commit b5967b13ac3e8515fec875fa52aa57434d248897 Author: Luiz F. Picolo Date: Wed Jun 5 20:46:09 2024 -0400 Commit inicial diff --git a/node_modules/.bin/proto-loader-gen-types b/node_modules/.bin/proto-loader-gen-types new file mode 120000 index 0000000..d677436 --- /dev/null +++ b/node_modules/.bin/proto-loader-gen-types @@ -0,0 +1 @@ +../@grpc/proto-loader/build/bin/proto-loader-gen-types.js \ No newline at end of file diff --git a/node_modules/.package-lock.json b/node_modules/.package-lock.json new file mode 100644 index 0000000..b0ab12b --- /dev/null +++ b/node_modules/.package-lock.json @@ -0,0 +1,307 @@ +{ + "name": "grpc", + "version": "1.0.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "node_modules/@grpc/grpc-js": { + "version": "1.10.8", + "resolved": "https://registry.npmjs.org/@grpc/grpc-js/-/grpc-js-1.10.8.tgz", + "integrity": "sha512-vYVqYzHicDqyKB+NQhAc54I1QWCBLCrYG6unqOIcBTHx+7x8C9lcoLj3KVJXs2VB4lUbpWY+Kk9NipcbXYWmvg==", + "dependencies": { + "@grpc/proto-loader": "^0.7.13", + "@js-sdsl/ordered-map": "^4.4.2" + }, + "engines": { + "node": ">=12.10.0" + } + }, + "node_modules/@grpc/proto-loader": { + "version": "0.7.13", + "resolved": "https://registry.npmjs.org/@grpc/proto-loader/-/proto-loader-0.7.13.tgz", + "integrity": "sha512-AiXO/bfe9bmxBjxxtYxFAXGZvMaN5s8kO+jBHAJCON8rJoB5YS/D6X7ZNc6XQkuHNmyl4CYaMI1fJ/Gn27RGGw==", + "dependencies": { + "lodash.camelcase": "^4.3.0", + "long": "^5.0.0", + "protobufjs": "^7.2.5", + "yargs": "^17.7.2" + }, + "bin": { + "proto-loader-gen-types": "build/bin/proto-loader-gen-types.js" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/@js-sdsl/ordered-map": { + "version": "4.4.2", + "resolved": "https://registry.npmjs.org/@js-sdsl/ordered-map/-/ordered-map-4.4.2.tgz", + "integrity": "sha512-iUKgm52T8HOE/makSxjqoWhe95ZJA1/G1sYsGev2JDKUSS14KAgg1LHb+Ba+IPow0xflbnSkOsZcO08C7w1gYw==", + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/js-sdsl" + } + }, + "node_modules/@protobufjs/aspromise": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/@protobufjs/aspromise/-/aspromise-1.1.2.tgz", + "integrity": "sha512-j+gKExEuLmKwvz3OgROXtrJ2UG2x8Ch2YZUxahh+s1F2HZ+wAceUNLkvy6zKCPVRkU++ZWQrdxsUeQXmcg4uoQ==" + }, + "node_modules/@protobufjs/base64": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/@protobufjs/base64/-/base64-1.1.2.tgz", + "integrity": "sha512-AZkcAA5vnN/v4PDqKyMR5lx7hZttPDgClv83E//FMNhR2TMcLUhfRUBHCmSl0oi9zMgDDqRUJkSxO3wm85+XLg==" + }, + "node_modules/@protobufjs/codegen": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/@protobufjs/codegen/-/codegen-2.0.4.tgz", + "integrity": "sha512-YyFaikqM5sH0ziFZCN3xDC7zeGaB/d0IUb9CATugHWbd1FRFwWwt4ld4OYMPWu5a3Xe01mGAULCdqhMlPl29Jg==" + }, + "node_modules/@protobufjs/eventemitter": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@protobufjs/eventemitter/-/eventemitter-1.1.0.tgz", + "integrity": "sha512-j9ednRT81vYJ9OfVuXG6ERSTdEL1xVsNgqpkxMsbIabzSo3goCjDIveeGv5d03om39ML71RdmrGNjG5SReBP/Q==" + }, + "node_modules/@protobufjs/fetch": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@protobufjs/fetch/-/fetch-1.1.0.tgz", + "integrity": "sha512-lljVXpqXebpsijW71PZaCYeIcE5on1w5DlQy5WH6GLbFryLUrBD4932W/E2BSpfRJWseIL4v/KPgBFxDOIdKpQ==", + "dependencies": { + "@protobufjs/aspromise": "^1.1.1", + "@protobufjs/inquire": "^1.1.0" + } + }, + "node_modules/@protobufjs/float": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/@protobufjs/float/-/float-1.0.2.tgz", + "integrity": "sha512-Ddb+kVXlXst9d+R9PfTIxh1EdNkgoRe5tOX6t01f1lYWOvJnSPDBlG241QLzcyPdoNTsblLUdujGSE4RzrTZGQ==" + }, + "node_modules/@protobufjs/inquire": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@protobufjs/inquire/-/inquire-1.1.0.tgz", + "integrity": "sha512-kdSefcPdruJiFMVSbn801t4vFK7KB/5gd2fYvrxhuJYg8ILrmn9SKSX2tZdV6V+ksulWqS7aXjBcRXl3wHoD9Q==" + }, + "node_modules/@protobufjs/path": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/@protobufjs/path/-/path-1.1.2.tgz", + "integrity": "sha512-6JOcJ5Tm08dOHAbdR3GrvP+yUUfkjG5ePsHYczMFLq3ZmMkAD98cDgcT2iA1lJ9NVwFd4tH/iSSoe44YWkltEA==" + }, + "node_modules/@protobufjs/pool": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@protobufjs/pool/-/pool-1.1.0.tgz", + "integrity": "sha512-0kELaGSIDBKvcgS4zkjz1PeddatrjYcmMWOlAuAPwAeccUrPHdUqo/J6LiymHHEiJT5NrF1UVwxY14f+fy4WQw==" + }, + "node_modules/@protobufjs/utf8": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@protobufjs/utf8/-/utf8-1.1.0.tgz", + "integrity": "sha512-Vvn3zZrhQZkkBE8LSuW3em98c0FwgO4nxzv6OdSxPKJIEKY2bGbHn+mhGIPerzI4twdxaP8/0+06HBpwf345Lw==" + }, + "node_modules/@types/node": { + "version": "20.14.1", + "resolved": "https://registry.npmjs.org/@types/node/-/node-20.14.1.tgz", + "integrity": "sha512-T2MzSGEu+ysB/FkWfqmhV3PLyQlowdptmmgD20C6QxsS8Fmv5SjpZ1ayXaEC0S21/h5UJ9iA6W/5vSNU5l00OA==", + "dependencies": { + "undici-types": "~5.26.4" + } + }, + "node_modules/ansi-regex": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", + "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", + "engines": { + "node": ">=8" + } + }, + "node_modules/ansi-styles": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", + "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", + "dependencies": { + "color-convert": "^2.0.1" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/chalk/ansi-styles?sponsor=1" + } + }, + "node_modules/cliui": { + "version": "8.0.1", + "resolved": "https://registry.npmjs.org/cliui/-/cliui-8.0.1.tgz", + "integrity": "sha512-BSeNnyus75C4//NQ9gQt1/csTXyo/8Sb+afLAkzAptFuMsod9HFokGNudZpi/oQV73hnVK+sR+5PVRMd+Dr7YQ==", + "dependencies": { + "string-width": "^4.2.0", + "strip-ansi": "^6.0.1", + "wrap-ansi": "^7.0.0" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/color-convert": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", + "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", + "dependencies": { + "color-name": "~1.1.4" + }, + "engines": { + "node": ">=7.0.0" + } + }, + "node_modules/color-name": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", + "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==" + }, + "node_modules/emoji-regex": { + "version": "8.0.0", + "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz", + "integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==" + }, + "node_modules/escalade": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/escalade/-/escalade-3.1.2.tgz", + "integrity": "sha512-ErCHMCae19vR8vQGe50xIsVomy19rg6gFu3+r3jkEO46suLMWBksvVyoGgQV+jOfl84ZSOSlmv6Gxa89PmTGmA==", + "engines": { + "node": ">=6" + } + }, + "node_modules/get-caller-file": { + "version": "2.0.5", + "resolved": "https://registry.npmjs.org/get-caller-file/-/get-caller-file-2.0.5.tgz", + "integrity": "sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg==", + "engines": { + "node": "6.* || 8.* || >= 10.*" + } + }, + "node_modules/is-fullwidth-code-point": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz", + "integrity": "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==", + "engines": { + "node": ">=8" + } + }, + "node_modules/lodash.camelcase": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/lodash.camelcase/-/lodash.camelcase-4.3.0.tgz", + "integrity": "sha512-TwuEnCnxbc3rAvhf/LbG7tJUDzhqXyFnv3dtzLOPgCG/hODL7WFnsbwktkD7yUV0RrreP/l1PALq/YSg6VvjlA==" + }, + "node_modules/long": { + "version": "5.2.3", + "resolved": "https://registry.npmjs.org/long/-/long-5.2.3.tgz", + "integrity": "sha512-lcHwpNoggQTObv5apGNCTdJrO69eHOZMi4BNC+rTLER8iHAqGrUVeLh/irVIM7zTw2bOXA8T6uNPeujwOLg/2Q==" + }, + "node_modules/protobufjs": { + "version": "7.3.0", + "resolved": "https://registry.npmjs.org/protobufjs/-/protobufjs-7.3.0.tgz", + "integrity": "sha512-YWD03n3shzV9ImZRX3ccbjqLxj7NokGN0V/ESiBV5xWqrommYHYiihuIyavq03pWSGqlyvYUFmfoMKd+1rPA/g==", + "hasInstallScript": true, + "dependencies": { + "@protobufjs/aspromise": "^1.1.2", + "@protobufjs/base64": "^1.1.2", + "@protobufjs/codegen": "^2.0.4", + "@protobufjs/eventemitter": "^1.1.0", + "@protobufjs/fetch": "^1.1.0", + "@protobufjs/float": "^1.0.2", + "@protobufjs/inquire": "^1.1.0", + "@protobufjs/path": "^1.1.2", + "@protobufjs/pool": "^1.1.0", + "@protobufjs/utf8": "^1.1.0", + "@types/node": ">=13.7.0", + "long": "^5.0.0" + }, + "engines": { + "node": ">=12.0.0" + } + }, + "node_modules/require-directory": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/require-directory/-/require-directory-2.1.1.tgz", + "integrity": "sha512-fGxEI7+wsG9xrvdjsrlmL22OMTTiHRwAMroiEeMgq8gzoLC/PQr7RsRDSTLUg/bZAZtF+TVIkHc6/4RIKrui+Q==", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/string-width": { + "version": "4.2.3", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz", + "integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==", + "dependencies": { + "emoji-regex": "^8.0.0", + "is-fullwidth-code-point": "^3.0.0", + "strip-ansi": "^6.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/strip-ansi": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", + "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", + "dependencies": { + "ansi-regex": "^5.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/undici-types": { + "version": "5.26.5", + "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-5.26.5.tgz", + "integrity": "sha512-JlCMO+ehdEIKqlFxk6IfVoAUVmgz7cU7zD/h9XZ0qzeosSHmUJVOzSQvvYSYWXkFXC+IfLKSIffhv0sVZup6pA==" + }, + "node_modules/wrap-ansi": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-7.0.0.tgz", + "integrity": "sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q==", + "dependencies": { + "ansi-styles": "^4.0.0", + "string-width": "^4.1.0", + "strip-ansi": "^6.0.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/chalk/wrap-ansi?sponsor=1" + } + }, + "node_modules/y18n": { + "version": "5.0.8", + "resolved": "https://registry.npmjs.org/y18n/-/y18n-5.0.8.tgz", + "integrity": "sha512-0pfFzegeDWJHJIAmTLRP2DwHjdF5s7jo9tuztdQxAhINCdvS+3nGINqPd00AphqJR/0LhANUS6/+7SCb98YOfA==", + "engines": { + "node": ">=10" + } + }, + "node_modules/yargs": { + "version": "17.7.2", + "resolved": "https://registry.npmjs.org/yargs/-/yargs-17.7.2.tgz", + "integrity": "sha512-7dSzzRQ++CKnNI/krKnYRV7JKKPUXMEh61soaHKg9mrWEhzFWhFnxPxGl+69cD1Ou63C13NUPCnmIcrvqCuM6w==", + "dependencies": { + "cliui": "^8.0.1", + "escalade": "^3.1.1", + "get-caller-file": "^2.0.5", + "require-directory": "^2.1.1", + "string-width": "^4.2.3", + "y18n": "^5.0.5", + "yargs-parser": "^21.1.1" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/yargs-parser": { + "version": "21.1.1", + "resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-21.1.1.tgz", + "integrity": "sha512-tVpsJW7DdjecAiFpbIB1e3qxIQsE6NoPc5/eTdrbbIC4h0LVsWhnoa3g+m2HclBIujHzsxZ4VJVA+GUuc2/LBw==", + "engines": { + "node": ">=12" + } + } + } +} diff --git a/node_modules/@grpc/grpc-js/LICENSE b/node_modules/@grpc/grpc-js/LICENSE new file mode 100644 index 0000000..8dada3e --- /dev/null +++ b/node_modules/@grpc/grpc-js/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright {yyyy} {name of copyright owner} + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/node_modules/@grpc/grpc-js/README.md b/node_modules/@grpc/grpc-js/README.md new file mode 100644 index 0000000..f3b682f --- /dev/null +++ b/node_modules/@grpc/grpc-js/README.md @@ -0,0 +1,82 @@ +# Pure JavaScript gRPC Client + +## Installation + +Node 12 is recommended. The exact set of compatible Node versions can be found in the `engines` field of the `package.json` file. + +```sh +npm install @grpc/grpc-js +``` + +## Documentation + +Documentation specifically for the `@grpc/grpc-js` package is currently not available. However, [documentation is available for the `grpc` package](https://grpc.github.io/grpc/node/grpc.html), and the two packages contain mostly the same interface. There are a few notable differences, however, and these differences are noted in the "Migrating from grpc" section below. + +## Features + +- Clients +- Automatic reconnection +- Servers +- Streaming +- Metadata +- Partial compression support: clients can compress and decompress messages, and servers can decompress request messages +- Pick first and round robin load balancing policies +- Client Interceptors +- Connection Keepalives +- HTTP Connect support (proxies) + +If you need a feature from the `grpc` package that is not provided by the `@grpc/grpc-js`, please file a feature request with that information. + +This library does not directly handle `.proto` files. To use `.proto` files with this library we recommend using the `@grpc/proto-loader` package. + +## Migrating from [`grpc`](https://www.npmjs.com/package/grpc) + +`@grpc/grpc-js` is almost a drop-in replacement for `grpc`, but you may need to make a few code changes to use it: + +- If you are currently loading `.proto` files using `grpc.load`, that function is not available in this library. You should instead load your `.proto` files using `@grpc/proto-loader` and load the resulting package definition objects into `@grpc/grpc-js` using `grpc.loadPackageDefinition`. +- If you are currently loading packages generated by `grpc-tools`, you should instead generate your files using the `generate_package_definition` option in `grpc-tools`, then load the object exported by the generated file into `@grpc/grpc-js` using `grpc.loadPackageDefinition`. +- If you have a server and you are using `Server#bind` to bind ports, you will need to use `Server#bindAsync` instead. +- If you are using any channel options supported in `grpc` but not supported in `@grpc/grpc-js`, you may need to adjust your code to handle the different behavior. Refer to [the list of supported options](#supported-channel-options) below. +- Refer to the [detailed package comparison](https://github.com/grpc/grpc-node/blob/master/PACKAGE-COMPARISON.md) for more details on the differences between `grpc` and `@grpc/grpc-js`. + +## Supported Channel Options +Many channel arguments supported in `grpc` are not supported in `@grpc/grpc-js`. The channel arguments supported by `@grpc/grpc-js` are: + - `grpc.ssl_target_name_override` + - `grpc.primary_user_agent` + - `grpc.secondary_user_agent` + - `grpc.default_authority` + - `grpc.keepalive_time_ms` + - `grpc.keepalive_timeout_ms` + - `grpc.keepalive_permit_without_calls` + - `grpc.service_config` + - `grpc.max_concurrent_streams` + - `grpc.initial_reconnect_backoff_ms` + - `grpc.max_reconnect_backoff_ms` + - `grpc.use_local_subchannel_pool` + - `grpc.max_send_message_length` + - `grpc.max_receive_message_length` + - `grpc.enable_http_proxy` + - `grpc.default_compression_algorithm` + - `grpc.enable_channelz` + - `grpc.dns_min_time_between_resolutions_ms` + - `grpc.enable_retries` + - `grpc.max_connection_age_ms` + - `grpc.max_connection_age_grace_ms` + - `grpc.max_connection_idle_ms` + - `grpc.per_rpc_retry_buffer_size` + - `grpc.retry_buffer_size` + - `grpc.service_config_disable_resolution` + - `grpc.client_idle_timeout_ms` + - `grpc-node.max_session_memory` + - `grpc-node.tls_enable_trace` + - `channelOverride` + - `channelFactoryOverride` + +## Some Notes on API Guarantees + +The public API of this library follows semantic versioning, with some caveats: + +- Some methods are prefixed with an underscore. These methods are internal and should not be considered part of the public API. +- The class `Call` is only exposed due to limitations of TypeScript. It should not be considered part of the public API. +- In general, any API that is exposed by this library but is not exposed by the `grpc` library is likely an error and should not be considered part of the public API. +- The `grpc.experimental` namespace contains APIs that have not stabilized. Any API in that namespace may break in any minor version update. diff --git a/node_modules/@grpc/grpc-js/build/src/admin.d.ts b/node_modules/@grpc/grpc-js/build/src/admin.d.ts new file mode 100644 index 0000000..92b9bba --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/admin.d.ts @@ -0,0 +1,11 @@ +import { ServiceDefinition } from './make-client'; +import { Server, UntypedServiceImplementation } from './server'; +interface GetServiceDefinition { + (): ServiceDefinition; +} +interface GetHandlers { + (): UntypedServiceImplementation; +} +export declare function registerAdminService(getServiceDefinition: GetServiceDefinition, getHandlers: GetHandlers): void; +export declare function addAdminServicesToServer(server: Server): void; +export {}; diff --git a/node_modules/@grpc/grpc-js/build/src/admin.js b/node_modules/@grpc/grpc-js/build/src/admin.js new file mode 100644 index 0000000..9fd8e64 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/admin.js @@ -0,0 +1,31 @@ +"use strict"; +/* + * Copyright 2021 gRPC authors. + * + * 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. + * + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.addAdminServicesToServer = exports.registerAdminService = void 0; +const registeredAdminServices = []; +function registerAdminService(getServiceDefinition, getHandlers) { + registeredAdminServices.push({ getServiceDefinition, getHandlers }); +} +exports.registerAdminService = registerAdminService; +function addAdminServicesToServer(server) { + for (const { getServiceDefinition, getHandlers } of registeredAdminServices) { + server.addService(getServiceDefinition(), getHandlers()); + } +} +exports.addAdminServicesToServer = addAdminServicesToServer; +//# sourceMappingURL=admin.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/admin.js.map b/node_modules/@grpc/grpc-js/build/src/admin.js.map new file mode 100644 index 0000000..e6e801a --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/admin.js.map @@ -0,0 +1 @@ +{"version":3,"file":"admin.js","sourceRoot":"","sources":["../../src/admin.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;GAeG;;;AAaH,MAAM,uBAAuB,GAGvB,EAAE,CAAC;AAET,SAAgB,oBAAoB,CAClC,oBAA0C,EAC1C,WAAwB;IAExB,uBAAuB,CAAC,IAAI,CAAC,EAAE,oBAAoB,EAAE,WAAW,EAAE,CAAC,CAAC;AACtE,CAAC;AALD,oDAKC;AAED,SAAgB,wBAAwB,CAAC,MAAc;IACrD,KAAK,MAAM,EAAE,oBAAoB,EAAE,WAAW,EAAE,IAAI,uBAAuB,EAAE,CAAC;QAC5E,MAAM,CAAC,UAAU,CAAC,oBAAoB,EAAE,EAAE,WAAW,EAAE,CAAC,CAAC;IAC3D,CAAC;AACH,CAAC;AAJD,4DAIC"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/backoff-timeout.d.ts b/node_modules/@grpc/grpc-js/build/src/backoff-timeout.d.ts new file mode 100644 index 0000000..c98e3a0 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/backoff-timeout.d.ts @@ -0,0 +1,90 @@ +export interface BackoffOptions { + initialDelay?: number; + multiplier?: number; + jitter?: number; + maxDelay?: number; +} +export declare class BackoffTimeout { + private callback; + /** + * The delay time at the start, and after each reset. + */ + private readonly initialDelay; + /** + * The exponential backoff multiplier. + */ + private readonly multiplier; + /** + * The maximum delay time + */ + private readonly maxDelay; + /** + * The maximum fraction by which the delay time can randomly vary after + * applying the multiplier. + */ + private readonly jitter; + /** + * The delay time for the next time the timer runs. + */ + private nextDelay; + /** + * The handle of the underlying timer. If running is false, this value refers + * to an object representing a timer that has ended, but it can still be + * interacted with without error. + */ + private timerId; + /** + * Indicates whether the timer is currently running. + */ + private running; + /** + * Indicates whether the timer should keep the Node process running if no + * other async operation is doing so. + */ + private hasRef; + /** + * The time that the currently running timer was started. Only valid if + * running is true. + */ + private startTime; + /** + * The approximate time that the currently running timer will end. Only valid + * if running is true. + */ + private endTime; + constructor(callback: () => void, options?: BackoffOptions); + private runTimer; + /** + * Call the callback after the current amount of delay time + */ + runOnce(): void; + /** + * Stop the timer. The callback will not be called until `runOnce` is called + * again. + */ + stop(): void; + /** + * Reset the delay time to its initial value. If the timer is still running, + * retroactively apply that reset to the current timer. + */ + reset(): void; + /** + * Check whether the timer is currently running. + */ + isRunning(): boolean; + /** + * Set that while the timer is running, it should keep the Node process + * running. + */ + ref(): void; + /** + * Set that while the timer is running, it should not keep the Node process + * running. + */ + unref(): void; + /** + * Get the approximate timestamp of when the timer will fire. Only valid if + * this.isRunning() is true. + */ + getEndTime(): Date; +} diff --git a/node_modules/@grpc/grpc-js/build/src/backoff-timeout.js b/node_modules/@grpc/grpc-js/build/src/backoff-timeout.js new file mode 100644 index 0000000..02762d5 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/backoff-timeout.js @@ -0,0 +1,174 @@ +"use strict"; +/* + * Copyright 2019 gRPC authors. + * + * 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. + * + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.BackoffTimeout = void 0; +const INITIAL_BACKOFF_MS = 1000; +const BACKOFF_MULTIPLIER = 1.6; +const MAX_BACKOFF_MS = 120000; +const BACKOFF_JITTER = 0.2; +/** + * Get a number uniformly at random in the range [min, max) + * @param min + * @param max + */ +function uniformRandom(min, max) { + return Math.random() * (max - min) + min; +} +class BackoffTimeout { + constructor(callback, options) { + this.callback = callback; + /** + * The delay time at the start, and after each reset. + */ + this.initialDelay = INITIAL_BACKOFF_MS; + /** + * The exponential backoff multiplier. + */ + this.multiplier = BACKOFF_MULTIPLIER; + /** + * The maximum delay time + */ + this.maxDelay = MAX_BACKOFF_MS; + /** + * The maximum fraction by which the delay time can randomly vary after + * applying the multiplier. + */ + this.jitter = BACKOFF_JITTER; + /** + * Indicates whether the timer is currently running. + */ + this.running = false; + /** + * Indicates whether the timer should keep the Node process running if no + * other async operation is doing so. + */ + this.hasRef = true; + /** + * The time that the currently running timer was started. Only valid if + * running is true. + */ + this.startTime = new Date(); + /** + * The approximate time that the currently running timer will end. Only valid + * if running is true. + */ + this.endTime = new Date(); + if (options) { + if (options.initialDelay) { + this.initialDelay = options.initialDelay; + } + if (options.multiplier) { + this.multiplier = options.multiplier; + } + if (options.jitter) { + this.jitter = options.jitter; + } + if (options.maxDelay) { + this.maxDelay = options.maxDelay; + } + } + this.nextDelay = this.initialDelay; + this.timerId = setTimeout(() => { }, 0); + clearTimeout(this.timerId); + } + runTimer(delay) { + var _a, _b; + this.endTime = this.startTime; + this.endTime.setMilliseconds(this.endTime.getMilliseconds() + this.nextDelay); + clearTimeout(this.timerId); + this.timerId = setTimeout(() => { + this.callback(); + this.running = false; + }, delay); + if (!this.hasRef) { + (_b = (_a = this.timerId).unref) === null || _b === void 0 ? void 0 : _b.call(_a); + } + } + /** + * Call the callback after the current amount of delay time + */ + runOnce() { + this.running = true; + this.startTime = new Date(); + this.runTimer(this.nextDelay); + const nextBackoff = Math.min(this.nextDelay * this.multiplier, this.maxDelay); + const jitterMagnitude = nextBackoff * this.jitter; + this.nextDelay = + nextBackoff + uniformRandom(-jitterMagnitude, jitterMagnitude); + } + /** + * Stop the timer. The callback will not be called until `runOnce` is called + * again. + */ + stop() { + clearTimeout(this.timerId); + this.running = false; + } + /** + * Reset the delay time to its initial value. If the timer is still running, + * retroactively apply that reset to the current timer. + */ + reset() { + this.nextDelay = this.initialDelay; + if (this.running) { + const now = new Date(); + const newEndTime = this.startTime; + newEndTime.setMilliseconds(newEndTime.getMilliseconds() + this.nextDelay); + clearTimeout(this.timerId); + if (now < newEndTime) { + this.runTimer(newEndTime.getTime() - now.getTime()); + } + else { + this.running = false; + } + } + } + /** + * Check whether the timer is currently running. + */ + isRunning() { + return this.running; + } + /** + * Set that while the timer is running, it should keep the Node process + * running. + */ + ref() { + var _a, _b; + this.hasRef = true; + (_b = (_a = this.timerId).ref) === null || _b === void 0 ? void 0 : _b.call(_a); + } + /** + * Set that while the timer is running, it should not keep the Node process + * running. + */ + unref() { + var _a, _b; + this.hasRef = false; + (_b = (_a = this.timerId).unref) === null || _b === void 0 ? void 0 : _b.call(_a); + } + /** + * Get the approximate timestamp of when the timer will fire. Only valid if + * this.isRunning() is true. + */ + getEndTime() { + return this.endTime; + } +} +exports.BackoffTimeout = BackoffTimeout; +//# sourceMappingURL=backoff-timeout.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/backoff-timeout.js.map b/node_modules/@grpc/grpc-js/build/src/backoff-timeout.js.map new file mode 100644 index 0000000..040b0ef --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/backoff-timeout.js.map @@ -0,0 +1 @@ +{"version":3,"file":"backoff-timeout.js","sourceRoot":"","sources":["../../src/backoff-timeout.ts"],"names":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line at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/call-credentials.d.ts b/node_modules/@grpc/grpc-js/build/src/call-credentials.d.ts new file mode 100644 index 0000000..1564eac --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/call-credentials.d.ts @@ -0,0 +1,56 @@ +import { Metadata } from './metadata'; +export interface CallMetadataOptions { + service_url: string; +} +export type CallMetadataGenerator = (options: CallMetadataOptions, cb: (err: Error | null, metadata?: Metadata) => void) => void; +export interface OldOAuth2Client { + getRequestMetadata: (url: string, callback: (err: Error | null, headers?: { + [index: string]: string; + }) => void) => void; +} +export interface CurrentOAuth2Client { + getRequestHeaders: (url?: string) => Promise<{ + [index: string]: string; + }>; +} +export type OAuth2Client = OldOAuth2Client | CurrentOAuth2Client; +/** + * A class that represents a generic method of adding authentication-related + * metadata on a per-request basis. + */ +export declare abstract class CallCredentials { + /** + * Asynchronously generates a new Metadata object. + * @param options Options used in generating the Metadata object. + */ + abstract generateMetadata(options: CallMetadataOptions): Promise; + /** + * Creates a new CallCredentials object from properties of both this and + * another CallCredentials object. This object's metadata generator will be + * called first. + * @param callCredentials The other CallCredentials object. + */ + abstract compose(callCredentials: CallCredentials): CallCredentials; + /** + * Check whether two call credentials objects are equal. Separate + * SingleCallCredentials with identical metadata generator functions are + * equal. + * @param other The other CallCredentials object to compare with. + */ + abstract _equals(other: CallCredentials): boolean; + /** + * Creates a new CallCredentials object from a given function that generates + * Metadata objects. + * @param metadataGenerator A function that accepts a set of options, and + * generates a Metadata object based on these options, which is passed back + * to the caller via a supplied (err, metadata) callback. + */ + static createFromMetadataGenerator(metadataGenerator: CallMetadataGenerator): CallCredentials; + /** + * Create a gRPC credential from a Google credential object. + * @param googleCredentials The authentication client to use. + * @return The resulting CallCredentials object. + */ + static createFromGoogleCredential(googleCredentials: OAuth2Client): CallCredentials; + static createEmpty(): CallCredentials; +} diff --git a/node_modules/@grpc/grpc-js/build/src/call-credentials.js b/node_modules/@grpc/grpc-js/build/src/call-credentials.js new file mode 100644 index 0000000..67b9266 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/call-credentials.js @@ -0,0 +1,153 @@ +"use strict"; +/* + * Copyright 2019 gRPC authors. + * + * 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. + * + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.CallCredentials = void 0; +const metadata_1 = require("./metadata"); +function isCurrentOauth2Client(client) { + return ('getRequestHeaders' in client && + typeof client.getRequestHeaders === 'function'); +} +/** + * A class that represents a generic method of adding authentication-related + * metadata on a per-request basis. + */ +class CallCredentials { + /** + * Creates a new CallCredentials object from a given function that generates + * Metadata objects. + * @param metadataGenerator A function that accepts a set of options, and + * generates a Metadata object based on these options, which is passed back + * to the caller via a supplied (err, metadata) callback. + */ + static createFromMetadataGenerator(metadataGenerator) { + return new SingleCallCredentials(metadataGenerator); + } + /** + * Create a gRPC credential from a Google credential object. + * @param googleCredentials The authentication client to use. + * @return The resulting CallCredentials object. + */ + static createFromGoogleCredential(googleCredentials) { + return CallCredentials.createFromMetadataGenerator((options, callback) => { + let getHeaders; + if (isCurrentOauth2Client(googleCredentials)) { + getHeaders = googleCredentials.getRequestHeaders(options.service_url); + } + else { + getHeaders = new Promise((resolve, reject) => { + googleCredentials.getRequestMetadata(options.service_url, (err, headers) => { + if (err) { + reject(err); + return; + } + if (!headers) { + reject(new Error('Headers not set by metadata plugin')); + return; + } + resolve(headers); + }); + }); + } + getHeaders.then(headers => { + const metadata = new metadata_1.Metadata(); + for (const key of Object.keys(headers)) { + metadata.add(key, headers[key]); + } + callback(null, metadata); + }, err => { + callback(err); + }); + }); + } + static createEmpty() { + return new EmptyCallCredentials(); + } +} +exports.CallCredentials = CallCredentials; +class ComposedCallCredentials extends CallCredentials { + constructor(creds) { + super(); + this.creds = creds; + } + async generateMetadata(options) { + const base = new metadata_1.Metadata(); + const generated = await Promise.all(this.creds.map(cred => cred.generateMetadata(options))); + for (const gen of generated) { + base.merge(gen); + } + return base; + } + compose(other) { + return new ComposedCallCredentials(this.creds.concat([other])); + } + _equals(other) { + if (this === other) { + return true; + } + if (other instanceof ComposedCallCredentials) { + return this.creds.every((value, index) => value._equals(other.creds[index])); + } + else { + return false; + } + } +} +class SingleCallCredentials extends CallCredentials { + constructor(metadataGenerator) { + super(); + this.metadataGenerator = metadataGenerator; + } + generateMetadata(options) { + return new Promise((resolve, reject) => { + this.metadataGenerator(options, (err, metadata) => { + if (metadata !== undefined) { + resolve(metadata); + } + else { + reject(err); + } + }); + }); + } + compose(other) { + return new ComposedCallCredentials([this, other]); + } + _equals(other) { + if (this === other) { + return true; + } + if (other instanceof SingleCallCredentials) { + return this.metadataGenerator === other.metadataGenerator; + } + else { + return false; + } + } +} +class EmptyCallCredentials extends CallCredentials { + generateMetadata(options) { + return Promise.resolve(new metadata_1.Metadata()); + } + compose(other) { + return other; + } + _equals(other) { + return other instanceof EmptyCallCredentials; + } +} +//# sourceMappingURL=call-credentials.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/call-credentials.js.map b/node_modules/@grpc/grpc-js/build/src/call-credentials.js.map new file mode 100644 index 0000000..8a4e9d6 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/call-credentials.js.map @@ -0,0 +1 @@ +{"version":3,"file":"call-credentials.js","sourceRoot":"","sources":["../../src/call-credentials.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;GAeG;;;AAEH,yCAAsC;AA+BtC,SAAS,qBAAqB,CAC5B,MAAoB;IAEpB,OAAO,CACL,mBAAmB,IAAI,MAAM;QAC7B,OAAO,MAAM,CAAC,iBAAiB,KAAK,UAAU,CAC/C,CAAC;AACJ,CAAC;AAED;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QAC5B,OAAO,KAAK,YAAY,oBAAoB,CAAC;IAC/C,CAAC;CACF"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/call-interface.d.ts b/node_modules/@grpc/grpc-js/build/src/call-interface.d.ts new file mode 100644 index 0000000..74581bf --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/call-interface.d.ts @@ -0,0 +1,89 @@ +/// +import { CallCredentials } from './call-credentials'; +import { Status } from './constants'; +import { Deadline } from './deadline'; +import { Metadata } from './metadata'; +import { ServerSurfaceCall } from './server-call'; +export interface CallStreamOptions { + deadline: Deadline; + flags: number; + host: string; + parentCall: ServerSurfaceCall | null; +} +export type PartialCallStreamOptions = Partial; +export interface StatusObject { + code: Status; + details: string; + metadata: Metadata; +} +export type PartialStatusObject = Pick & { + metadata?: Metadata | null | undefined; +}; +export declare const enum WriteFlags { + BufferHint = 1, + NoCompress = 2, + WriteThrough = 4 +} +export interface WriteObject { + message: Buffer; + flags?: number; +} +export interface MetadataListener { + (metadata: Metadata, next: (metadata: Metadata) => void): void; +} +export interface MessageListener { + (message: any, next: (message: any) => void): void; +} +export interface StatusListener { + (status: StatusObject, next: (status: StatusObject) => void): void; +} +export interface FullListener { + onReceiveMetadata: MetadataListener; + onReceiveMessage: MessageListener; + onReceiveStatus: StatusListener; +} +export type Listener = Partial; +/** + * An object with methods for handling the responses to a call. + */ +export interface InterceptingListener { + onReceiveMetadata(metadata: Metadata): void; + onReceiveMessage(message: any): void; + onReceiveStatus(status: StatusObject): void; +} +export declare function isInterceptingListener(listener: Listener | InterceptingListener): listener is InterceptingListener; +export declare class InterceptingListenerImpl implements InterceptingListener { + private listener; + private nextListener; + private processingMetadata; + private hasPendingMessage; + private pendingMessage; + private processingMessage; + private pendingStatus; + constructor(listener: FullListener, nextListener: InterceptingListener); + private processPendingMessage; + private processPendingStatus; + onReceiveMetadata(metadata: Metadata): void; + onReceiveMessage(message: any): void; + onReceiveStatus(status: StatusObject): void; +} +export interface WriteCallback { + (error?: Error | null): void; +} +export interface MessageContext { + callback?: WriteCallback; + flags?: number; +} +export interface Call { + cancelWithStatus(status: Status, details: string): void; + getPeer(): string; + start(metadata: Metadata, listener: InterceptingListener): void; + sendMessageWithContext(context: MessageContext, message: Buffer): void; + startRead(): void; + halfClose(): void; + getCallNumber(): number; + setCredentials(credentials: CallCredentials): void; +} +export interface DeadlineInfoProvider { + getDeadlineInfo(): string[]; +} diff --git a/node_modules/@grpc/grpc-js/build/src/call-interface.js b/node_modules/@grpc/grpc-js/build/src/call-interface.js new file mode 100644 index 0000000..cdef46f --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/call-interface.js @@ -0,0 +1,84 @@ +"use strict"; +/* + * Copyright 2022 gRPC authors. + * + * 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. + * + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.InterceptingListenerImpl = exports.isInterceptingListener = void 0; +function isInterceptingListener(listener) { + return (listener.onReceiveMetadata !== undefined && + listener.onReceiveMetadata.length === 1); +} +exports.isInterceptingListener = isInterceptingListener; +class InterceptingListenerImpl { + constructor(listener, nextListener) { + this.listener = listener; + this.nextListener = nextListener; + this.processingMetadata = false; + this.hasPendingMessage = false; + this.processingMessage = false; + this.pendingStatus = null; + } + processPendingMessage() { + if (this.hasPendingMessage) { + this.nextListener.onReceiveMessage(this.pendingMessage); + this.pendingMessage = null; + this.hasPendingMessage = false; + } + } + processPendingStatus() { + if (this.pendingStatus) { + this.nextListener.onReceiveStatus(this.pendingStatus); + } + } + onReceiveMetadata(metadata) { + this.processingMetadata = true; + this.listener.onReceiveMetadata(metadata, metadata => { + this.processingMetadata = false; + this.nextListener.onReceiveMetadata(metadata); + this.processPendingMessage(); + this.processPendingStatus(); + }); + } + // eslint-disable-next-line @typescript-eslint/no-explicit-any + onReceiveMessage(message) { + /* If this listener processes messages asynchronously, the last message may + * be reordered with respect to the status */ + this.processingMessage = true; + this.listener.onReceiveMessage(message, msg => { + this.processingMessage = false; + if (this.processingMetadata) { + this.pendingMessage = msg; + this.hasPendingMessage = true; + } + else { + this.nextListener.onReceiveMessage(msg); + this.processPendingStatus(); + } + }); + } + onReceiveStatus(status) { + this.listener.onReceiveStatus(status, processedStatus => { + if (this.processingMetadata || this.processingMessage) { + this.pendingStatus = processedStatus; + } + else { + this.nextListener.onReceiveStatus(processedStatus); + } + }); + } +} +exports.InterceptingListenerImpl = InterceptingListenerImpl; +//# sourceMappingURL=call-interface.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/call-interface.js.map b/node_modules/@grpc/grpc-js/build/src/call-interface.js.map new file mode 100644 index 0000000..9cb4c7e --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/call-interface.js.map @@ -0,0 +1 @@ +{"version":3,"file":"call-interface.js","sourceRoot":"","sources":["../../src/call-interface.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;GAeG;;;AAqEH,SAAgB,sBAAsB,CACpC,QAAyC;IAEzC,OAAO,CACL,QAAQ,CAAC,iBAAiB,KAAK,SAAS;QACxC,QAAQ,CAAC,iBAAiB,CAAC,MAAM,KAAK,CAAC,CACxC,CAAC;AACJ,CAAC;AAPD,wDAOC;AAED,MAAa,wBAAwB;IAMnC,YACU,QAAsB,EACtB,YAAkC;QADlC,aAAQ,GAAR,QAAQ,CAAc;QACtB,iBAAY,GAAZ,YAAY,CAAsB;QAPpC,uBAAkB,GAAG,KAAK,CAAC;QAC3B,sBAAiB,GAAG,KAAK,CAAC;QAE1B,sBAAiB,GAAG,KAAK,CAAC;QAC1B,kBAAa,GAAwB,IAAI,CAAC;IAI/C,CAAC;IAEI,qBAAqB;QAC3B,IAAI,IA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;YAC9B,CAAC;QACH,CAAC,CAAC,CAAC;IACL,CAAC;IACD,eAAe,CAAC,MAAoB;QAClC,IAAI,CAAC,QAAQ,CAAC,eAAe,CAAC,MAAM,EAAE,eAAe,CAAC,EAAE;YACtD,IAAI,IAAI,CAAC,kBAAkB,IAAI,IAAI,CAAC,iBAAiB,EAAE,CAAC;gBACtD,IAAI,CAAC,aAAa,GAAG,eAAe,CAAC;YACvC,CAAC;iBAAM,CAAC;gBACN,IAAI,CAAC,YAAY,CAAC,eAAe,CAAC,eAAe,CAAC,CAAC;YACrD,CAAC;QACH,CAAC,CAAC,CAAC;IACL,CAAC;CACF;AA3DD,4DA2DC"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/call-number.d.ts b/node_modules/@grpc/grpc-js/build/src/call-number.d.ts new file mode 100644 index 0000000..a679ff6 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/call-number.d.ts @@ -0,0 +1 @@ +export declare function getNextCallNumber(): number; diff --git a/node_modules/@grpc/grpc-js/build/src/call-number.js b/node_modules/@grpc/grpc-js/build/src/call-number.js new file mode 100644 index 0000000..a694f0f --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/call-number.js @@ -0,0 +1,25 @@ +"use strict"; +/* + * Copyright 2022 gRPC authors. + * + * 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. + * + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.getNextCallNumber = void 0; +let nextCallNumber = 0; +function getNextCallNumber() { + return nextCallNumber++; +} +exports.getNextCallNumber = getNextCallNumber; +//# sourceMappingURL=call-number.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/call-number.js.map b/node_modules/@grpc/grpc-js/build/src/call-number.js.map new file mode 100644 index 0000000..9a77ba9 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/call-number.js.map @@ -0,0 +1 @@ +{"version":3,"file":"call-number.js","sourceRoot":"","sources":["../../src/call-number.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;GAeG;;;AAEH,IAAI,cAAc,GAAG,CAAC,CAAC;AAEvB,SAAgB,iBAAiB;IAC/B,OAAO,cAAc,EAAE,CAAC;AAC1B,CAAC;AAFD,8CAEC"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/call.d.ts b/node_modules/@grpc/grpc-js/build/src/call.d.ts new file mode 100644 index 0000000..d223aa3 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/call.d.ts @@ -0,0 +1,83 @@ +/// +/// +/// +import { EventEmitter } from 'events'; +import { Duplex, Readable, Writable } from 'stream'; +import { StatusObject } from './call-interface'; +import { EmitterAugmentation1 } from './events'; +import { Metadata } from './metadata'; +import { ObjectReadable, ObjectWritable, WriteCallback } from './object-stream'; +import { InterceptingCallInterface } from './client-interceptors'; +/** + * A type extending the built-in Error object with additional fields. + */ +export type ServiceError = StatusObject & Error; +/** + * A base type for all user-facing values returned by client-side method calls. + */ +export type SurfaceCall = { + call?: InterceptingCallInterface; + cancel(): void; + getPeer(): string; +} & EmitterAugmentation1<'metadata', Metadata> & EmitterAugmentation1<'status', StatusObject> & EventEmitter; +/** + * A type representing the return value of a unary method call. + */ +export type ClientUnaryCall = SurfaceCall; +/** + * A type representing the return value of a server stream method call. + */ +export type ClientReadableStream = { + deserialize: (chunk: Buffer) => ResponseType; +} & SurfaceCall & ObjectReadable; +/** + * A type representing the return value of a client stream method call. + */ +export type ClientWritableStream = { + serialize: (value: RequestType) => Buffer; +} & SurfaceCall & ObjectWritable; +/** + * A type representing the return value of a bidirectional stream method call. + */ +export type ClientDuplexStream = ClientWritableStream & ClientReadableStream; +/** + * Construct a ServiceError from a StatusObject. This function exists primarily + * as an attempt to make the error stack trace clearly communicate that the + * error is not necessarily a problem in gRPC itself. + * @param status + */ +export declare function callErrorFromStatus(status: StatusObject, callerStack: string): ServiceError; +export declare class ClientUnaryCallImpl extends EventEmitter implements ClientUnaryCall { + call?: InterceptingCallInterface; + constructor(); + cancel(): void; + getPeer(): string; +} +export declare class ClientReadableStreamImpl extends Readable implements ClientReadableStream { + readonly deserialize: (chunk: Buffer) => ResponseType; + call?: InterceptingCallInterface; + constructor(deserialize: (chunk: Buffer) => ResponseType); + cancel(): void; + getPeer(): string; + _read(_size: number): void; +} +export declare class ClientWritableStreamImpl extends Writable implements ClientWritableStream { + readonly serialize: (value: RequestType) => Buffer; + call?: InterceptingCallInterface; + constructor(serialize: (value: RequestType) => Buffer); + cancel(): void; + getPeer(): string; + _write(chunk: RequestType, encoding: string, cb: WriteCallback): void; + _final(cb: Function): void; +} +export declare class ClientDuplexStreamImpl extends Duplex implements ClientDuplexStream { + readonly serialize: (value: RequestType) => Buffer; + readonly deserialize: (chunk: Buffer) => ResponseType; + call?: InterceptingCallInterface; + constructor(serialize: (value: RequestType) => Buffer, deserialize: (chunk: Buffer) => ResponseType); + cancel(): void; + getPeer(): string; + _read(_size: number): void; + _write(chunk: RequestType, encoding: string, cb: WriteCallback): void; + _final(cb: Function): void; +} diff --git a/node_modules/@grpc/grpc-js/build/src/call.js b/node_modules/@grpc/grpc-js/build/src/call.js new file mode 100644 index 0000000..029f679 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/call.js @@ -0,0 +1,136 @@ +"use strict"; +/* + * Copyright 2019 gRPC authors. + * + * 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. + * + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ClientDuplexStreamImpl = exports.ClientWritableStreamImpl = exports.ClientReadableStreamImpl = exports.ClientUnaryCallImpl = exports.callErrorFromStatus = void 0; +const events_1 = require("events"); +const stream_1 = require("stream"); +const constants_1 = require("./constants"); +/** + * Construct a ServiceError from a StatusObject. This function exists primarily + * as an attempt to make the error stack trace clearly communicate that the + * error is not necessarily a problem in gRPC itself. + * @param status + */ +function callErrorFromStatus(status, callerStack) { + const message = `${status.code} ${constants_1.Status[status.code]}: ${status.details}`; + const error = new Error(message); + const stack = `${error.stack}\nfor call at\n${callerStack}`; + return Object.assign(new Error(message), status, { stack }); +} +exports.callErrorFromStatus = callErrorFromStatus; +class ClientUnaryCallImpl extends events_1.EventEmitter { + constructor() { + super(); + } + cancel() { + var _a; + (_a = this.call) === null || _a === void 0 ? void 0 : _a.cancelWithStatus(constants_1.Status.CANCELLED, 'Cancelled on client'); + } + getPeer() { + var _a, _b; + return (_b = (_a = this.call) === null || _a === void 0 ? void 0 : _a.getPeer()) !== null && _b !== void 0 ? _b : 'unknown'; + } +} +exports.ClientUnaryCallImpl = ClientUnaryCallImpl; +class ClientReadableStreamImpl extends stream_1.Readable { + constructor(deserialize) { + super({ objectMode: true }); + this.deserialize = deserialize; + } + cancel() { + var _a; + (_a = this.call) === null || _a === void 0 ? void 0 : _a.cancelWithStatus(constants_1.Status.CANCELLED, 'Cancelled on client'); + } + getPeer() { + var _a, _b; + return (_b = (_a = this.call) === null || _a === void 0 ? void 0 : _a.getPeer()) !== null && _b !== void 0 ? _b : 'unknown'; + } + _read(_size) { + var _a; + (_a = this.call) === null || _a === void 0 ? void 0 : _a.startRead(); + } +} +exports.ClientReadableStreamImpl = ClientReadableStreamImpl; +class ClientWritableStreamImpl extends stream_1.Writable { + constructor(serialize) { + super({ objectMode: true }); + this.serialize = serialize; + } + cancel() { + var _a; + (_a = this.call) === null || _a === void 0 ? void 0 : _a.cancelWithStatus(constants_1.Status.CANCELLED, 'Cancelled on client'); + } + getPeer() { + var _a, _b; + return (_b = (_a = this.call) === null || _a === void 0 ? void 0 : _a.getPeer()) !== null && _b !== void 0 ? _b : 'unknown'; + } + _write(chunk, encoding, cb) { + var _a; + const context = { + callback: cb, + }; + const flags = Number(encoding); + if (!Number.isNaN(flags)) { + context.flags = flags; + } + (_a = this.call) === null || _a === void 0 ? void 0 : _a.sendMessageWithContext(context, chunk); + } + _final(cb) { + var _a; + (_a = this.call) === null || _a === void 0 ? void 0 : _a.halfClose(); + cb(); + } +} +exports.ClientWritableStreamImpl = ClientWritableStreamImpl; +class ClientDuplexStreamImpl extends stream_1.Duplex { + constructor(serialize, deserialize) { + super({ objectMode: true }); + this.serialize = serialize; + this.deserialize = deserialize; + } + cancel() { + var _a; + (_a = this.call) === null || _a === void 0 ? void 0 : _a.cancelWithStatus(constants_1.Status.CANCELLED, 'Cancelled on client'); + } + getPeer() { + var _a, _b; + return (_b = (_a = this.call) === null || _a === void 0 ? void 0 : _a.getPeer()) !== null && _b !== void 0 ? _b : 'unknown'; + } + _read(_size) { + var _a; + (_a = this.call) === null || _a === void 0 ? void 0 : _a.startRead(); + } + _write(chunk, encoding, cb) { + var _a; + const context = { + callback: cb, + }; + const flags = Number(encoding); + if (!Number.isNaN(flags)) { + context.flags = flags; + } + (_a = this.call) === null || _a === void 0 ? void 0 : _a.sendMessageWithContext(context, chunk); + } + _final(cb) { + var _a; + (_a = this.call) === null || _a === void 0 ? void 0 : _a.halfClose(); + cb(); + } +} +exports.ClientDuplexStreamImpl = ClientDuplexStreamImpl; +//# sourceMappingURL=call.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/call.js.map b/node_modules/@grpc/grpc-js/build/src/call.js.map new file mode 100644 index 0000000..ed4d096 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/call.js.map @@ -0,0 +1 @@ +{"version":3,"file":"call.js","sourceRoot":"","sources":["../../src/call.ts"],"names":[],"mappings":";AAAA;;;;;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;;QACJ,MAAA,IAAI,CAAC,IAAI,0CAAE,gBAAgB,CAAC,kBAAM,CAAC,SAAS,EAAE,qBAAqB,CAAC,CAAC;IACvE,CAAC;IAED,OAAO;;QACL,OAAO,MAAA,MAAA,IAAI,CAAC,IAAI,0CAAE,OAAO,EAAE,mCAAI,SAAS,CAAC;IAC3C,CAAC;IAED,KAAK,CAAC,KAAa;;QACjB,MAAA,IAAI,CAAC,IAAI,0CAAE,SAAS,EAAE,CAAC;IACzB,CAAC;IAED,MAAM,CAAC,KAAkB,EAAE,QAAgB,EAAE,EAAiB;;QAC5D,MAAM,OAAO,GAAmB;YAC9B,QAAQ,EAAE,EAAE;SACb,CAAC;QACF,MAAM,KAAK,GAAG,MAAM,CAAC,QAAQ,CAAC,CAAC;QAC/B,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,KAAK,CAAC,EAAE,CAAC;YACzB,OAAO,CAAC,KAAK,GAAG,KAAK,CAAC;QACxB,CAAC;QACD,MAAA,IAAI,CAAC,IAAI,0CAAE,sBAAsB,CAAC,OAAO,EAAE,KAAK,CAAC,CAAC;IACpD,CAAC;IAED,MAAM,CAAC,EAAY;;QACjB,MAAA,IAAI,CAAC,IAAI,0CAAE,SAAS,EAAE,CAAC;QACvB,EAAE,EAAE,CAAC;IACP,CAAC;CACF;AAvCD,wDAuCC"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/channel-credentials.d.ts b/node_modules/@grpc/grpc-js/build/src/channel-credentials.d.ts new file mode 100644 index 0000000..75b0312 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/channel-credentials.d.ts @@ -0,0 +1,83 @@ +/// +/// +import { ConnectionOptions, PeerCertificate, SecureContext } from 'tls'; +import { CallCredentials } from './call-credentials'; +/** + * A callback that will receive the expected hostname and presented peer + * certificate as parameters. The callback should return an error to + * indicate that the presented certificate is considered invalid and + * otherwise returned undefined. + */ +export type CheckServerIdentityCallback = (hostname: string, cert: PeerCertificate) => Error | undefined; +/** + * Additional peer verification options that can be set when creating + * SSL credentials. + */ +export interface VerifyOptions { + /** + * If set, this callback will be invoked after the usual hostname verification + * has been performed on the peer certificate. + */ + checkServerIdentity?: CheckServerIdentityCallback; +} +/** + * A class that contains credentials for communicating over a channel, as well + * as a set of per-call credentials, which are applied to every method call made + * over a channel initialized with an instance of this class. + */ +export declare abstract class ChannelCredentials { + protected callCredentials: CallCredentials; + protected constructor(callCredentials?: CallCredentials); + /** + * Returns a copy of this object with the included set of per-call credentials + * expanded to include callCredentials. + * @param callCredentials A CallCredentials object to associate with this + * instance. + */ + abstract compose(callCredentials: CallCredentials): ChannelCredentials; + /** + * Gets the set of per-call credentials associated with this instance. + */ + _getCallCredentials(): CallCredentials; + /** + * Gets a SecureContext object generated from input parameters if this + * instance was created with createSsl, or null if this instance was created + * with createInsecure. + */ + abstract _getConnectionOptions(): ConnectionOptions | null; + /** + * Indicates whether this credentials object creates a secure channel. + */ + abstract _isSecure(): boolean; + /** + * Check whether two channel credentials objects are equal. Two secure + * credentials are equal if they were constructed with the same parameters. + * @param other The other ChannelCredentials Object + */ + abstract _equals(other: ChannelCredentials): boolean; + /** + * Return a new ChannelCredentials instance with a given set of credentials. + * The resulting instance can be used to construct a Channel that communicates + * over TLS. + * @param rootCerts The root certificate data. + * @param privateKey The client certificate private key, if available. + * @param certChain The client certificate key chain, if available. + * @param verifyOptions Additional options to modify certificate verification + */ + static createSsl(rootCerts?: Buffer | null, privateKey?: Buffer | null, certChain?: Buffer | null, verifyOptions?: VerifyOptions): ChannelCredentials; + /** + * Return a new ChannelCredentials instance with credentials created using + * the provided secureContext. The resulting instances can be used to + * construct a Channel that communicates over TLS. gRPC will not override + * anything in the provided secureContext, so the environment variables + * GRPC_SSL_CIPHER_SUITES and GRPC_DEFAULT_SSL_ROOTS_FILE_PATH will + * not be applied. + * @param secureContext The return value of tls.createSecureContext() + * @param verifyOptions Additional options to modify certificate verification + */ + static createFromSecureContext(secureContext: SecureContext, verifyOptions?: VerifyOptions): ChannelCredentials; + /** + * Return a new ChannelCredentials instance with no credentials. + */ + static createInsecure(): ChannelCredentials; +} diff --git a/node_modules/@grpc/grpc-js/build/src/channel-credentials.js b/node_modules/@grpc/grpc-js/build/src/channel-credentials.js new file mode 100644 index 0000000..535ff07 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/channel-credentials.js @@ -0,0 +1,177 @@ +"use strict"; +/* + * Copyright 2019 gRPC authors. + * + * 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. + * + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ChannelCredentials = void 0; +const tls_1 = require("tls"); +const call_credentials_1 = require("./call-credentials"); +const tls_helpers_1 = require("./tls-helpers"); +// eslint-disable-next-line @typescript-eslint/no-explicit-any +function verifyIsBufferOrNull(obj, friendlyName) { + if (obj && !(obj instanceof Buffer)) { + throw new TypeError(`${friendlyName}, if provided, must be a Buffer.`); + } +} +/** + * A class that contains credentials for communicating over a channel, as well + * as a set of per-call credentials, which are applied to every method call made + * over a channel initialized with an instance of this class. + */ +class ChannelCredentials { + constructor(callCredentials) { + this.callCredentials = callCredentials || call_credentials_1.CallCredentials.createEmpty(); + } + /** + * Gets the set of per-call credentials associated with this instance. + */ + _getCallCredentials() { + return this.callCredentials; + } + /** + * Return a new ChannelCredentials instance with a given set of credentials. + * The resulting instance can be used to construct a Channel that communicates + * over TLS. + * @param rootCerts The root certificate data. + * @param privateKey The client certificate private key, if available. + * @param certChain The client certificate key chain, if available. + * @param verifyOptions Additional options to modify certificate verification + */ + static createSsl(rootCerts, privateKey, certChain, verifyOptions) { + var _a; + verifyIsBufferOrNull(rootCerts, 'Root certificate'); + verifyIsBufferOrNull(privateKey, 'Private key'); + verifyIsBufferOrNull(certChain, 'Certificate chain'); + if (privateKey && !certChain) { + throw new Error('Private key must be given with accompanying certificate chain'); + } + if (!privateKey && certChain) { + throw new Error('Certificate chain must be given with accompanying private key'); + } + const secureContext = (0, tls_1.createSecureContext)({ + ca: (_a = rootCerts !== null && rootCerts !== void 0 ? rootCerts : (0, tls_helpers_1.getDefaultRootsData)()) !== null && _a !== void 0 ? _a : undefined, + key: privateKey !== null && privateKey !== void 0 ? privateKey : undefined, + cert: certChain !== null && certChain !== void 0 ? certChain : undefined, + ciphers: tls_helpers_1.CIPHER_SUITES, + }); + return new SecureChannelCredentialsImpl(secureContext, verifyOptions !== null && verifyOptions !== void 0 ? verifyOptions : {}); + } + /** + * Return a new ChannelCredentials instance with credentials created using + * the provided secureContext. The resulting instances can be used to + * construct a Channel that communicates over TLS. gRPC will not override + * anything in the provided secureContext, so the environment variables + * GRPC_SSL_CIPHER_SUITES and GRPC_DEFAULT_SSL_ROOTS_FILE_PATH will + * not be applied. + * @param secureContext The return value of tls.createSecureContext() + * @param verifyOptions Additional options to modify certificate verification + */ + static createFromSecureContext(secureContext, verifyOptions) { + return new SecureChannelCredentialsImpl(secureContext, verifyOptions !== null && verifyOptions !== void 0 ? verifyOptions : {}); + } + /** + * Return a new ChannelCredentials instance with no credentials. + */ + static createInsecure() { + return new InsecureChannelCredentialsImpl(); + } +} +exports.ChannelCredentials = ChannelCredentials; +class InsecureChannelCredentialsImpl extends ChannelCredentials { + constructor() { + super(); + } + compose(callCredentials) { + throw new Error('Cannot compose insecure credentials'); + } + _getConnectionOptions() { + return null; + } + _isSecure() { + return false; + } + _equals(other) { + return other instanceof InsecureChannelCredentialsImpl; + } +} +class SecureChannelCredentialsImpl extends ChannelCredentials { + constructor(secureContext, verifyOptions) { + super(); + this.secureContext = secureContext; + this.verifyOptions = verifyOptions; + this.connectionOptions = { + secureContext, + }; + // Node asserts that this option is a function, so we cannot pass undefined + if (verifyOptions === null || verifyOptions === void 0 ? void 0 : verifyOptions.checkServerIdentity) { + this.connectionOptions.checkServerIdentity = + verifyOptions.checkServerIdentity; + } + } + compose(callCredentials) { + const combinedCallCredentials = this.callCredentials.compose(callCredentials); + return new ComposedChannelCredentialsImpl(this, combinedCallCredentials); + } + _getConnectionOptions() { + // Copy to prevent callers from mutating this.connectionOptions + return Object.assign({}, this.connectionOptions); + } + _isSecure() { + return true; + } + _equals(other) { + if (this === other) { + return true; + } + if (other instanceof SecureChannelCredentialsImpl) { + return (this.secureContext === other.secureContext && + this.verifyOptions.checkServerIdentity === + other.verifyOptions.checkServerIdentity); + } + else { + return false; + } + } +} +class ComposedChannelCredentialsImpl extends ChannelCredentials { + constructor(channelCredentials, callCreds) { + super(callCreds); + this.channelCredentials = channelCredentials; + } + compose(callCredentials) { + const combinedCallCredentials = this.callCredentials.compose(callCredentials); + return new ComposedChannelCredentialsImpl(this.channelCredentials, combinedCallCredentials); + } + _getConnectionOptions() { + return this.channelCredentials._getConnectionOptions(); + } + _isSecure() { + return true; + } + _equals(other) { + if (this === other) { + return true; + } + if (other instanceof ComposedChannelCredentialsImpl) { + return (this.channelCredentials._equals(other.channelCredentials) && + this.callCredentials._equals(other.callCredentials)); + } + else { + return false; + } + } +} +//# sourceMappingURL=channel-credentials.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/channel-credentials.js.map b/node_modules/@grpc/grpc-js/build/src/channel-credentials.js.map new file mode 100644 index 0000000..b945925 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/channel-credentials.js.map @@ -0,0 +1 @@ +{"version":3,"file":"channel-credentials.js","sourceRoot":"","sources":["../../src/channel-credentials.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;GAeG;;;AAEH,6BAKa;AAEb,yDAAqD;AACrD,+CAAmE;AAEnE,8DAA8D;AAC9D,SAAS,oBAAoB,CAAC,GAAQ,EAAE,YAAoB;IAC1D,IAAI,GAAG,IAAI,CAAC,CAAC,GAAG,YAAY,MA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AC,CACpD,CAAC;QACJ,CAAC;aAAM,CAAC;YACN,OAAO,KAAK,CAAC;QACf,CAAC;IACH,CAAC;CACF"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/channel-options.d.ts b/node_modules/@grpc/grpc-js/build/src/channel-options.d.ts new file mode 100644 index 0000000..54a007a --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/channel-options.d.ts @@ -0,0 +1,75 @@ +import { CompressionAlgorithms } from './compression-algorithms'; +/** + * An interface that contains options used when initializing a Channel instance. + */ +export interface ChannelOptions { + 'grpc.ssl_target_name_override'?: string; + 'grpc.primary_user_agent'?: string; + 'grpc.secondary_user_agent'?: string; + 'grpc.default_authority'?: string; + 'grpc.keepalive_time_ms'?: number; + 'grpc.keepalive_timeout_ms'?: number; + 'grpc.keepalive_permit_without_calls'?: number; + 'grpc.service_config'?: string; + 'grpc.max_concurrent_streams'?: number; + 'grpc.initial_reconnect_backoff_ms'?: number; + 'grpc.max_reconnect_backoff_ms'?: number; + 'grpc.use_local_subchannel_pool'?: number; + 'grpc.max_send_message_length'?: number; + 'grpc.max_receive_message_length'?: number; + 'grpc.enable_http_proxy'?: number; + 'grpc.http_connect_target'?: string; + 'grpc.http_connect_creds'?: string; + 'grpc.default_compression_algorithm'?: CompressionAlgorithms; + 'grpc.enable_channelz'?: number; + 'grpc.dns_min_time_between_resolutions_ms'?: number; + 'grpc.enable_retries'?: number; + 'grpc.per_rpc_retry_buffer_size'?: number; + 'grpc.retry_buffer_size'?: number; + 'grpc.max_connection_age_ms'?: number; + 'grpc.max_connection_age_grace_ms'?: number; + 'grpc.max_connection_idle_ms'?: number; + 'grpc-node.max_session_memory'?: number; + 'grpc.service_config_disable_resolution'?: number; + 'grpc.client_idle_timeout_ms'?: number; + /** + * Set the enableTrace option in TLS clients and servers + */ + 'grpc-node.tls_enable_trace'?: number; + 'grpc.lb.ring_hash.ring_size_cap'?: number; + [key: string]: any; +} +/** + * This is for checking provided options at runtime. This is an object for + * easier membership checking. + */ +export declare const recognizedOptions: { + 'grpc.ssl_target_name_override': boolean; + 'grpc.primary_user_agent': boolean; + 'grpc.secondary_user_agent': boolean; + 'grpc.default_authority': boolean; + 'grpc.keepalive_time_ms': boolean; + 'grpc.keepalive_timeout_ms': boolean; + 'grpc.keepalive_permit_without_calls': boolean; + 'grpc.service_config': boolean; + 'grpc.max_concurrent_streams': boolean; + 'grpc.initial_reconnect_backoff_ms': boolean; + 'grpc.max_reconnect_backoff_ms': boolean; + 'grpc.use_local_subchannel_pool': boolean; + 'grpc.max_send_message_length': boolean; + 'grpc.max_receive_message_length': boolean; + 'grpc.enable_http_proxy': boolean; + 'grpc.enable_channelz': boolean; + 'grpc.dns_min_time_between_resolutions_ms': boolean; + 'grpc.enable_retries': boolean; + 'grpc.per_rpc_retry_buffer_size': boolean; + 'grpc.retry_buffer_size': boolean; + 'grpc.max_connection_age_ms': boolean; + 'grpc.max_connection_age_grace_ms': boolean; + 'grpc-node.max_session_memory': boolean; + 'grpc.service_config_disable_resolution': boolean; + 'grpc.client_idle_timeout_ms': boolean; + 'grpc-node.tls_enable_trace': boolean; + 'grpc.lb.ring_hash.ring_size_cap': boolean; +}; +export declare function channelOptionsEqual(options1: ChannelOptions, options2: ChannelOptions): boolean; diff --git a/node_modules/@grpc/grpc-js/build/src/channel-options.js b/node_modules/@grpc/grpc-js/build/src/channel-options.js new file mode 100644 index 0000000..72ed599 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/channel-options.js @@ -0,0 +1,70 @@ +"use strict"; +/* + * Copyright 2019 gRPC authors. + * + * 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. + * + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.channelOptionsEqual = exports.recognizedOptions = void 0; +/** + * This is for checking provided options at runtime. This is an object for + * easier membership checking. + */ +exports.recognizedOptions = { + 'grpc.ssl_target_name_override': true, + 'grpc.primary_user_agent': true, + 'grpc.secondary_user_agent': true, + 'grpc.default_authority': true, + 'grpc.keepalive_time_ms': true, + 'grpc.keepalive_timeout_ms': true, + 'grpc.keepalive_permit_without_calls': true, + 'grpc.service_config': true, + 'grpc.max_concurrent_streams': true, + 'grpc.initial_reconnect_backoff_ms': true, + 'grpc.max_reconnect_backoff_ms': true, + 'grpc.use_local_subchannel_pool': true, + 'grpc.max_send_message_length': true, + 'grpc.max_receive_message_length': true, + 'grpc.enable_http_proxy': true, + 'grpc.enable_channelz': true, + 'grpc.dns_min_time_between_resolutions_ms': true, + 'grpc.enable_retries': true, + 'grpc.per_rpc_retry_buffer_size': true, + 'grpc.retry_buffer_size': true, + 'grpc.max_connection_age_ms': true, + 'grpc.max_connection_age_grace_ms': true, + 'grpc-node.max_session_memory': true, + 'grpc.service_config_disable_resolution': true, + 'grpc.client_idle_timeout_ms': true, + 'grpc-node.tls_enable_trace': true, + 'grpc.lb.ring_hash.ring_size_cap': true, +}; +function channelOptionsEqual(options1, options2) { + const keys1 = Object.keys(options1).sort(); + const keys2 = Object.keys(options2).sort(); + if (keys1.length !== keys2.length) { + return false; + } + for (let i = 0; i < keys1.length; i += 1) { + if (keys1[i] !== keys2[i]) { + return false; + } + if (options1[keys1[i]] !== options2[keys2[i]]) { + return false; + } + } + return true; +} +exports.channelOptionsEqual = channelOptionsEqual; +//# sourceMappingURL=channel-options.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/channel-options.js.map b/node_modules/@grpc/grpc-js/build/src/channel-options.js.map new file mode 100644 index 0000000..9961fd6 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/channel-options.js.map @@ -0,0 +1 @@ +{"version":3,"file":"channel-options.js","sourceRoot":"","sources":["../../src/channel-options.ts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,IAAI,CAAC,EAAE,CAAC;QACzC,IAAI,KAAK,CAAC,CAAC,CAAC,KAAK,KAAK,CAAC,CAAC,CAAC,EAAE,CAAC;YAC1B,OAAO,KAAK,CAAC;QACf,CAAC;QACD,IAAI,QAAQ,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,KAAK,QAAQ,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC;YAC9C,OAAO,KAAK,CAAC;QACf,CAAC;IACH,CAAC;IACD,OAAO,IAAI,CAAC;AACd,CAAC;AAlBD,kDAkBC"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/channel.d.ts b/node_modules/@grpc/grpc-js/build/src/channel.d.ts new file mode 100644 index 0000000..f4d646e --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/channel.d.ts @@ -0,0 +1,76 @@ +import { ChannelCredentials } from './channel-credentials'; +import { ChannelOptions } from './channel-options'; +import { ServerSurfaceCall } from './server-call'; +import { ConnectivityState } from './connectivity-state'; +import type { ChannelRef } from './channelz'; +import { Call } from './call-interface'; +import { Deadline } from './deadline'; +/** + * An interface that represents a communication channel to a server specified + * by a given address. + */ +export interface Channel { + /** + * Close the channel. This has the same functionality as the existing + * grpc.Client.prototype.close + */ + close(): void; + /** + * Return the target that this channel connects to + */ + getTarget(): string; + /** + * Get the channel's current connectivity state. This method is here mainly + * because it is in the existing internal Channel class, and there isn't + * another good place to put it. + * @param tryToConnect If true, the channel will start connecting if it is + * idle. Otherwise, idle channels will only start connecting when a + * call starts. + */ + getConnectivityState(tryToConnect: boolean): ConnectivityState; + /** + * Watch for connectivity state changes. This is also here mainly because + * it is in the existing external Channel class. + * @param currentState The state to watch for transitions from. This should + * always be populated by calling getConnectivityState immediately + * before. + * @param deadline A deadline for waiting for a state change + * @param callback Called with no error when a state change, or with an + * error if the deadline passes without a state change. + */ + watchConnectivityState(currentState: ConnectivityState, deadline: Date | number, callback: (error?: Error) => void): void; + /** + * Get the channelz reference object for this channel. A request to the + * channelz service for the id in this object will provide information + * about this channel. + */ + getChannelzRef(): ChannelRef; + /** + * Create a call object. Call is an opaque type that is used by the Client + * class. This function is called by the gRPC library when starting a + * request. Implementers should return an instance of Call that is returned + * from calling createCall on an instance of the provided Channel class. + * @param method The full method string to request. + * @param deadline The call deadline + * @param host A host string override for making the request + * @param parentCall A server call to propagate some information from + * @param propagateFlags A bitwise combination of elements of grpc.propagate + * that indicates what information to propagate from parentCall. + */ + createCall(method: string, deadline: Deadline, host: string | null | undefined, parentCall: ServerSurfaceCall | null, propagateFlags: number | null | undefined): Call; +} +export declare class ChannelImplementation implements Channel { + private internalChannel; + constructor(target: string, credentials: ChannelCredentials, options: ChannelOptions); + close(): void; + getTarget(): string; + getConnectivityState(tryToConnect: boolean): ConnectivityState; + watchConnectivityState(currentState: ConnectivityState, deadline: Date | number, callback: (error?: Error) => void): void; + /** + * Get the channelz reference object for this channel. The returned value is + * garbage if channelz is disabled for this channel. + * @returns + */ + getChannelzRef(): ChannelRef; + createCall(method: string, deadline: Deadline, host: string | null | undefined, parentCall: ServerSurfaceCall | null, propagateFlags: number | null | undefined): Call; +} diff --git a/node_modules/@grpc/grpc-js/build/src/channel.js b/node_modules/@grpc/grpc-js/build/src/channel.js new file mode 100644 index 0000000..49e8639 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/channel.js @@ -0,0 +1,68 @@ +"use strict"; +/* + * Copyright 2019 gRPC authors. + * + * 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. + * + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ChannelImplementation = void 0; +const channel_credentials_1 = require("./channel-credentials"); +const internal_channel_1 = require("./internal-channel"); +class ChannelImplementation { + constructor(target, credentials, options) { + if (typeof target !== 'string') { + throw new TypeError('Channel target must be a string'); + } + if (!(credentials instanceof channel_credentials_1.ChannelCredentials)) { + throw new TypeError('Channel credentials must be a ChannelCredentials object'); + } + if (options) { + if (typeof options !== 'object') { + throw new TypeError('Channel options must be an object'); + } + } + this.internalChannel = new internal_channel_1.InternalChannel(target, credentials, options); + } + close() { + this.internalChannel.close(); + } + getTarget() { + return this.internalChannel.getTarget(); + } + getConnectivityState(tryToConnect) { + return this.internalChannel.getConnectivityState(tryToConnect); + } + watchConnectivityState(currentState, deadline, callback) { + this.internalChannel.watchConnectivityState(currentState, deadline, callback); + } + /** + * Get the channelz reference object for this channel. The returned value is + * garbage if channelz is disabled for this channel. + * @returns + */ + getChannelzRef() { + return this.internalChannel.getChannelzRef(); + } + createCall(method, deadline, host, parentCall, propagateFlags) { + if (typeof method !== 'string') { + throw new TypeError('Channel#createCall: method must be a string'); + } + if (!(typeof deadline === 'number' || deadline instanceof Date)) { + throw new TypeError('Channel#createCall: deadline must be a number or Date'); + } + return this.internalChannel.createCall(method, deadline, host, parentCall, propagateFlags); + } +} +exports.ChannelImplementation = ChannelImplementation; +//# sourceMappingURL=channel.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/channel.js.map b/node_modules/@grpc/grpc-js/build/src/channel.js.map new file mode 100644 index 0000000..8758e84 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/channel.js.map @@ -0,0 +1 @@ +{"version":3,"file":"channel.js","sourceRoot":"","sources":["../../src/channel.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;GAeG;;;AAEH,+DAA2D;AAO3D,yDAAqD;AAoErD,MAAa,qBAAqB;IAGhC,YACE,MAAc,EACd,WAA+B,EAC/B,OAAuB;QAEvB,IAAI,OAAO,MAAM,KAAK,QAAQ,EAAE,CAAC;YAC/B,MAAM,IAAI,SAAS,CAAC,iCAAiC,CAAC,CAAC;QACzD,CAAC;QACD,I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,IAAI,CAAC,eAAe,CAAC,UAAU,CACpC,MAAM,EACN,QAAQ,EACR,IAAI,EACJ,UAAU,EACV,cAAc,CACf,CAAC;IACJ,CAAC;CACF;AAjFD,sDAiFC"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/channelz.d.ts b/node_modules/@grpc/grpc-js/build/src/channelz.d.ts new file mode 100644 index 0000000..1df4334 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/channelz.d.ts @@ -0,0 +1,159 @@ +/// +import { OrderedMap } from '@js-sdsl/ordered-map'; +import { ConnectivityState } from './connectivity-state'; +import { ChannelTrace } from './generated/grpc/channelz/v1/ChannelTrace'; +import { SubchannelAddress } from './subchannel-address'; +import { ChannelzDefinition, ChannelzHandlers } from './generated/grpc/channelz/v1/Channelz'; +export type TraceSeverity = 'CT_UNKNOWN' | 'CT_INFO' | 'CT_WARNING' | 'CT_ERROR'; +interface Ref { + kind: EntityTypes; + id: number; + name: string; +} +export interface ChannelRef extends Ref { + kind: EntityTypes.channel; +} +export interface SubchannelRef extends Ref { + kind: EntityTypes.subchannel; +} +export interface ServerRef extends Ref { + kind: EntityTypes.server; +} +export interface SocketRef extends Ref { + kind: EntityTypes.socket; +} +interface TraceEvent { + description: string; + severity: TraceSeverity; + timestamp: Date; + childChannel?: ChannelRef; + childSubchannel?: SubchannelRef; +} +export declare class ChannelzTraceStub { + readonly events: TraceEvent[]; + readonly creationTimestamp: Date; + readonly eventsLogged = 0; + addTrace(): void; + getTraceMessage(): ChannelTrace; +} +export declare class ChannelzTrace { + events: TraceEvent[]; + creationTimestamp: Date; + eventsLogged: number; + constructor(); + addTrace(severity: TraceSeverity, description: string, child?: ChannelRef | SubchannelRef): void; + getTraceMessage(): ChannelTrace; +} +export declare class ChannelzChildrenTracker { + private channelChildren; + private subchannelChildren; + private socketChildren; + private trackerMap; + refChild(child: ChannelRef | SubchannelRef | SocketRef): void; + unrefChild(child: ChannelRef | SubchannelRef | SocketRef): void; + getChildLists(): ChannelzChildren; +} +export declare class ChannelzChildrenTrackerStub extends ChannelzChildrenTracker { + refChild(): void; + unrefChild(): void; +} +export declare class ChannelzCallTracker { + callsStarted: number; + callsSucceeded: number; + callsFailed: number; + lastCallStartedTimestamp: Date | null; + addCallStarted(): void; + addCallSucceeded(): void; + addCallFailed(): void; +} +export declare class ChannelzCallTrackerStub extends ChannelzCallTracker { + addCallStarted(): void; + addCallSucceeded(): void; + addCallFailed(): void; +} +export interface ChannelzChildren { + channels: OrderedMap; + subchannels: OrderedMap; + sockets: OrderedMap; +} +export interface ChannelInfo { + target: string; + state: ConnectivityState; + trace: ChannelzTrace | ChannelzTraceStub; + callTracker: ChannelzCallTracker | ChannelzCallTrackerStub; + children: ChannelzChildren; +} +export type SubchannelInfo = ChannelInfo; +export interface ServerInfo { + trace: ChannelzTrace; + callTracker: ChannelzCallTracker; + listenerChildren: ChannelzChildren; + sessionChildren: ChannelzChildren; +} +export interface TlsInfo { + cipherSuiteStandardName: string | null; + cipherSuiteOtherName: string | null; + localCertificate: Buffer | null; + remoteCertificate: Buffer | null; +} +export interface SocketInfo { + localAddress: SubchannelAddress | null; + remoteAddress: SubchannelAddress | null; + security: TlsInfo | null; + remoteName: string | null; + streamsStarted: number; + streamsSucceeded: number; + streamsFailed: number; + messagesSent: number; + messagesReceived: number; + keepAlivesSent: number; + lastLocalStreamCreatedTimestamp: Date | null; + lastRemoteStreamCreatedTimestamp: Date | null; + lastMessageSentTimestamp: Date | null; + lastMessageReceivedTimestamp: Date | null; + localFlowControlWindow: number | null; + remoteFlowControlWindow: number | null; +} +interface ChannelEntry { + ref: ChannelRef; + getInfo(): ChannelInfo; +} +interface SubchannelEntry { + ref: SubchannelRef; + getInfo(): SubchannelInfo; +} +interface ServerEntry { + ref: ServerRef; + getInfo(): ServerInfo; +} +interface SocketEntry { + ref: SocketRef; + getInfo(): SocketInfo; +} +export declare const enum EntityTypes { + channel = "channel", + subchannel = "subchannel", + server = "server", + socket = "socket" +} +export type RefByType = T extends EntityTypes.channel ? ChannelRef : T extends EntityTypes.server ? ServerRef : T extends EntityTypes.socket ? SocketRef : T extends EntityTypes.subchannel ? SubchannelRef : never; +export type EntryByType = T extends EntityTypes.channel ? ChannelEntry : T extends EntityTypes.server ? ServerEntry : T extends EntityTypes.socket ? SocketEntry : T extends EntityTypes.subchannel ? SubchannelEntry : never; +export type InfoByType = T extends EntityTypes.channel ? ChannelInfo : T extends EntityTypes.subchannel ? SubchannelInfo : T extends EntityTypes.server ? ServerInfo : T extends EntityTypes.socket ? SocketInfo : never; +export declare const registerChannelzChannel: (name: string, getInfo: () => ChannelInfo, channelzEnabled: boolean) => ChannelRef; +export declare const registerChannelzSubchannel: (name: string, getInfo: () => ChannelInfo, channelzEnabled: boolean) => SubchannelRef; +export declare const registerChannelzServer: (name: string, getInfo: () => ServerInfo, channelzEnabled: boolean) => ServerRef; +export declare const registerChannelzSocket: (name: string, getInfo: () => SocketInfo, channelzEnabled: boolean) => SocketRef; +export declare function unregisterChannelzRef(ref: ChannelRef | SubchannelRef | ServerRef | SocketRef): void; +export declare function getChannelzHandlers(): ChannelzHandlers; +export declare function getChannelzServiceDefinition(): ChannelzDefinition; +export declare function setup(): void; +export {}; diff --git a/node_modules/@grpc/grpc-js/build/src/channelz.js b/node_modules/@grpc/grpc-js/build/src/channelz.js new file mode 100644 index 0000000..2c736c1 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/channelz.js @@ -0,0 +1,584 @@ +"use strict"; +/* + * Copyright 2021 gRPC authors. + * + * 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. + * + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.setup = exports.getChannelzServiceDefinition = exports.getChannelzHandlers = exports.unregisterChannelzRef = exports.registerChannelzSocket = exports.registerChannelzServer = exports.registerChannelzSubchannel = exports.registerChannelzChannel = exports.ChannelzCallTrackerStub = exports.ChannelzCallTracker = exports.ChannelzChildrenTrackerStub = exports.ChannelzChildrenTracker = exports.ChannelzTrace = exports.ChannelzTraceStub = void 0; +const net_1 = require("net"); +const ordered_map_1 = require("@js-sdsl/ordered-map"); +const connectivity_state_1 = require("./connectivity-state"); +const constants_1 = require("./constants"); +const subchannel_address_1 = require("./subchannel-address"); +const admin_1 = require("./admin"); +const make_client_1 = require("./make-client"); +function channelRefToMessage(ref) { + return { + channel_id: ref.id, + name: ref.name, + }; +} +function subchannelRefToMessage(ref) { + return { + subchannel_id: ref.id, + name: ref.name, + }; +} +function serverRefToMessage(ref) { + return { + server_id: ref.id, + }; +} +function socketRefToMessage(ref) { + return { + socket_id: ref.id, + name: ref.name, + }; +} +/** + * The loose upper bound on the number of events that should be retained in a + * trace. This may be exceeded by up to a factor of 2. Arbitrarily chosen as a + * number that should be large enough to contain the recent relevant + * information, but small enough to not use excessive memory. + */ +const TARGET_RETAINED_TRACES = 32; +/** + * Default number of sockets/servers/channels/subchannels to return + */ +const DEFAULT_MAX_RESULTS = 100; +class ChannelzTraceStub { + constructor() { + this.events = []; + this.creationTimestamp = new Date(); + this.eventsLogged = 0; + } + addTrace() { } + getTraceMessage() { + return { + creation_timestamp: dateToProtoTimestamp(this.creationTimestamp), + num_events_logged: this.eventsLogged, + events: [], + }; + } +} +exports.ChannelzTraceStub = ChannelzTraceStub; +class ChannelzTrace { + constructor() { + this.events = []; + this.eventsLogged = 0; + this.creationTimestamp = new Date(); + } + addTrace(severity, description, child) { + const timestamp = new Date(); + this.events.push({ + description: description, + severity: severity, + timestamp: timestamp, + childChannel: (child === null || child === void 0 ? void 0 : child.kind) === 'channel' ? child : undefined, + childSubchannel: (child === null || child === void 0 ? void 0 : child.kind) === 'subchannel' ? child : undefined, + }); + // Whenever the trace array gets too large, discard the first half + if (this.events.length >= TARGET_RETAINED_TRACES * 2) { + this.events = this.events.slice(TARGET_RETAINED_TRACES); + } + this.eventsLogged += 1; + } + getTraceMessage() { + return { + creation_timestamp: dateToProtoTimestamp(this.creationTimestamp), + num_events_logged: this.eventsLogged, + events: this.events.map(event => { + return { + description: event.description, + severity: event.severity, + timestamp: dateToProtoTimestamp(event.timestamp), + channel_ref: event.childChannel + ? channelRefToMessage(event.childChannel) + : null, + subchannel_ref: event.childSubchannel + ? subchannelRefToMessage(event.childSubchannel) + : null, + }; + }), + }; + } +} +exports.ChannelzTrace = ChannelzTrace; +class ChannelzChildrenTracker { + constructor() { + this.channelChildren = new ordered_map_1.OrderedMap(); + this.subchannelChildren = new ordered_map_1.OrderedMap(); + this.socketChildren = new ordered_map_1.OrderedMap(); + this.trackerMap = { + ["channel" /* EntityTypes.channel */]: this.channelChildren, + ["subchannel" /* EntityTypes.subchannel */]: this.subchannelChildren, + ["socket" /* EntityTypes.socket */]: this.socketChildren, + }; + } + refChild(child) { + const tracker = this.trackerMap[child.kind]; + const trackedChild = tracker.find(child.id); + if (trackedChild.equals(tracker.end())) { + tracker.setElement(child.id, { + ref: child, + count: 1, + }, trackedChild); + } + else { + trackedChild.pointer[1].count += 1; + } + } + unrefChild(child) { + const tracker = this.trackerMap[child.kind]; + const trackedChild = tracker.getElementByKey(child.id); + if (trackedChild !== undefined) { + trackedChild.count -= 1; + if (trackedChild.count === 0) { + tracker.eraseElementByKey(child.id); + } + } + } + getChildLists() { + return { + channels: this.channelChildren, + subchannels: this.subchannelChildren, + sockets: this.socketChildren, + }; + } +} +exports.ChannelzChildrenTracker = ChannelzChildrenTracker; +class ChannelzChildrenTrackerStub extends ChannelzChildrenTracker { + refChild() { } + unrefChild() { } +} +exports.ChannelzChildrenTrackerStub = ChannelzChildrenTrackerStub; +class ChannelzCallTracker { + constructor() { + this.callsStarted = 0; + this.callsSucceeded = 0; + this.callsFailed = 0; + this.lastCallStartedTimestamp = null; + } + addCallStarted() { + this.callsStarted += 1; + this.lastCallStartedTimestamp = new Date(); + } + addCallSucceeded() { + this.callsSucceeded += 1; + } + addCallFailed() { + this.callsFailed += 1; + } +} +exports.ChannelzCallTracker = ChannelzCallTracker; +class ChannelzCallTrackerStub extends ChannelzCallTracker { + addCallStarted() { } + addCallSucceeded() { } + addCallFailed() { } +} +exports.ChannelzCallTrackerStub = ChannelzCallTrackerStub; +const entityMaps = { + ["channel" /* EntityTypes.channel */]: new ordered_map_1.OrderedMap(), + ["subchannel" /* EntityTypes.subchannel */]: new ordered_map_1.OrderedMap(), + ["server" /* EntityTypes.server */]: new ordered_map_1.OrderedMap(), + ["socket" /* EntityTypes.socket */]: new ordered_map_1.OrderedMap(), +}; +const generateRegisterFn = (kind) => { + let nextId = 1; + function getNextId() { + return nextId++; + } + const entityMap = entityMaps[kind]; + return (name, getInfo, channelzEnabled) => { + const id = getNextId(); + const ref = { id, name, kind }; + if (channelzEnabled) { + entityMap.setElement(id, { ref, getInfo }); + } + return ref; + }; +}; +exports.registerChannelzChannel = generateRegisterFn("channel" /* EntityTypes.channel */); +exports.registerChannelzSubchannel = generateRegisterFn("subchannel" /* EntityTypes.subchannel */); +exports.registerChannelzServer = generateRegisterFn("server" /* EntityTypes.server */); +exports.registerChannelzSocket = generateRegisterFn("socket" /* EntityTypes.socket */); +function unregisterChannelzRef(ref) { + entityMaps[ref.kind].eraseElementByKey(ref.id); +} +exports.unregisterChannelzRef = unregisterChannelzRef; +/** + * Parse a single section of an IPv6 address as two bytes + * @param addressSection A hexadecimal string of length up to 4 + * @returns The pair of bytes representing this address section + */ +function parseIPv6Section(addressSection) { + const numberValue = Number.parseInt(addressSection, 16); + return [(numberValue / 256) | 0, numberValue % 256]; +} +/** + * Parse a chunk of an IPv6 address string to some number of bytes + * @param addressChunk Some number of segments of up to 4 hexadecimal + * characters each, joined by colons. + * @returns The list of bytes representing this address chunk + */ +function parseIPv6Chunk(addressChunk) { + if (addressChunk === '') { + return []; + } + const bytePairs = addressChunk + .split(':') + .map(section => parseIPv6Section(section)); + const result = []; + return result.concat(...bytePairs); +} +/** + * Converts an IPv4 or IPv6 address from string representation to binary + * representation + * @param ipAddress an IP address in standard IPv4 or IPv6 text format + * @returns + */ +function ipAddressStringToBuffer(ipAddress) { + if ((0, net_1.isIPv4)(ipAddress)) { + return Buffer.from(Uint8Array.from(ipAddress.split('.').map(segment => Number.parseInt(segment)))); + } + else if ((0, net_1.isIPv6)(ipAddress)) { + let leftSection; + let rightSection; + const doubleColonIndex = ipAddress.indexOf('::'); + if (doubleColonIndex === -1) { + leftSection = ipAddress; + rightSection = ''; + } + else { + leftSection = ipAddress.substring(0, doubleColonIndex); + rightSection = ipAddress.substring(doubleColonIndex + 2); + } + const leftBuffer = Buffer.from(parseIPv6Chunk(leftSection)); + const rightBuffer = Buffer.from(parseIPv6Chunk(rightSection)); + const middleBuffer = Buffer.alloc(16 - leftBuffer.length - rightBuffer.length, 0); + return Buffer.concat([leftBuffer, middleBuffer, rightBuffer]); + } + else { + return null; + } +} +function connectivityStateToMessage(state) { + switch (state) { + case connectivity_state_1.ConnectivityState.CONNECTING: + return { + state: 'CONNECTING', + }; + case connectivity_state_1.ConnectivityState.IDLE: + return { + state: 'IDLE', + }; + case connectivity_state_1.ConnectivityState.READY: + return { + state: 'READY', + }; + case connectivity_state_1.ConnectivityState.SHUTDOWN: + return { + state: 'SHUTDOWN', + }; + case connectivity_state_1.ConnectivityState.TRANSIENT_FAILURE: + return { + state: 'TRANSIENT_FAILURE', + }; + default: + return { + state: 'UNKNOWN', + }; + } +} +function dateToProtoTimestamp(date) { + if (!date) { + return null; + } + const millisSinceEpoch = date.getTime(); + return { + seconds: (millisSinceEpoch / 1000) | 0, + nanos: (millisSinceEpoch % 1000) * 1000000, + }; +} +function getChannelMessage(channelEntry) { + const resolvedInfo = channelEntry.getInfo(); + const channelRef = []; + const subchannelRef = []; + resolvedInfo.children.channels.forEach(el => { + channelRef.push(channelRefToMessage(el[1].ref)); + }); + resolvedInfo.children.subchannels.forEach(el => { + subchannelRef.push(subchannelRefToMessage(el[1].ref)); + }); + return { + ref: channelRefToMessage(channelEntry.ref), + data: { + target: resolvedInfo.target, + state: connectivityStateToMessage(resolvedInfo.state), + calls_started: resolvedInfo.callTracker.callsStarted, + calls_succeeded: resolvedInfo.callTracker.callsSucceeded, + calls_failed: resolvedInfo.callTracker.callsFailed, + last_call_started_timestamp: dateToProtoTimestamp(resolvedInfo.callTracker.lastCallStartedTimestamp), + trace: resolvedInfo.trace.getTraceMessage(), + }, + channel_ref: channelRef, + subchannel_ref: subchannelRef, + }; +} +function GetChannel(call, callback) { + const channelId = parseInt(call.request.channel_id, 10); + const channelEntry = entityMaps["channel" /* EntityTypes.channel */].getElementByKey(channelId); + if (channelEntry === undefined) { + callback({ + code: constants_1.Status.NOT_FOUND, + details: 'No channel data found for id ' + channelId, + }); + return; + } + callback(null, { channel: getChannelMessage(channelEntry) }); +} +function GetTopChannels(call, callback) { + const maxResults = parseInt(call.request.max_results, 10) || DEFAULT_MAX_RESULTS; + const resultList = []; + const startId = parseInt(call.request.start_channel_id, 10); + const channelEntries = entityMaps["channel" /* EntityTypes.channel */]; + let i; + for (i = channelEntries.lowerBound(startId); !i.equals(channelEntries.end()) && resultList.length < maxResults; i = i.next()) { + resultList.push(getChannelMessage(i.pointer[1])); + } + callback(null, { + channel: resultList, + end: i.equals(channelEntries.end()), + }); +} +function getServerMessage(serverEntry) { + const resolvedInfo = serverEntry.getInfo(); + const listenSocket = []; + resolvedInfo.listenerChildren.sockets.forEach(el => { + listenSocket.push(socketRefToMessage(el[1].ref)); + }); + return { + ref: serverRefToMessage(serverEntry.ref), + data: { + calls_started: resolvedInfo.callTracker.callsStarted, + calls_succeeded: resolvedInfo.callTracker.callsSucceeded, + calls_failed: resolvedInfo.callTracker.callsFailed, + last_call_started_timestamp: dateToProtoTimestamp(resolvedInfo.callTracker.lastCallStartedTimestamp), + trace: resolvedInfo.trace.getTraceMessage(), + }, + listen_socket: listenSocket, + }; +} +function GetServer(call, callback) { + const serverId = parseInt(call.request.server_id, 10); + const serverEntries = entityMaps["server" /* EntityTypes.server */]; + const serverEntry = serverEntries.getElementByKey(serverId); + if (serverEntry === undefined) { + callback({ + code: constants_1.Status.NOT_FOUND, + details: 'No server data found for id ' + serverId, + }); + return; + } + callback(null, { server: getServerMessage(serverEntry) }); +} +function GetServers(call, callback) { + const maxResults = parseInt(call.request.max_results, 10) || DEFAULT_MAX_RESULTS; + const startId = parseInt(call.request.start_server_id, 10); + const serverEntries = entityMaps["server" /* EntityTypes.server */]; + const resultList = []; + let i; + for (i = serverEntries.lowerBound(startId); !i.equals(serverEntries.end()) && resultList.length < maxResults; i = i.next()) { + resultList.push(getServerMessage(i.pointer[1])); + } + callback(null, { + server: resultList, + end: i.equals(serverEntries.end()), + }); +} +function GetSubchannel(call, callback) { + const subchannelId = parseInt(call.request.subchannel_id, 10); + const subchannelEntry = entityMaps["subchannel" /* EntityTypes.subchannel */].getElementByKey(subchannelId); + if (subchannelEntry === undefined) { + callback({ + code: constants_1.Status.NOT_FOUND, + details: 'No subchannel data found for id ' + subchannelId, + }); + return; + } + const resolvedInfo = subchannelEntry.getInfo(); + const listenSocket = []; + resolvedInfo.children.sockets.forEach(el => { + listenSocket.push(socketRefToMessage(el[1].ref)); + }); + const subchannelMessage = { + ref: subchannelRefToMessage(subchannelEntry.ref), + data: { + target: resolvedInfo.target, + state: connectivityStateToMessage(resolvedInfo.state), + calls_started: resolvedInfo.callTracker.callsStarted, + calls_succeeded: resolvedInfo.callTracker.callsSucceeded, + calls_failed: resolvedInfo.callTracker.callsFailed, + last_call_started_timestamp: dateToProtoTimestamp(resolvedInfo.callTracker.lastCallStartedTimestamp), + trace: resolvedInfo.trace.getTraceMessage(), + }, + socket_ref: listenSocket, + }; + callback(null, { subchannel: subchannelMessage }); +} +function subchannelAddressToAddressMessage(subchannelAddress) { + var _a; + if ((0, subchannel_address_1.isTcpSubchannelAddress)(subchannelAddress)) { + return { + address: 'tcpip_address', + tcpip_address: { + ip_address: (_a = ipAddressStringToBuffer(subchannelAddress.host)) !== null && _a !== void 0 ? _a : undefined, + port: subchannelAddress.port, + }, + }; + } + else { + return { + address: 'uds_address', + uds_address: { + filename: subchannelAddress.path, + }, + }; + } +} +function GetSocket(call, callback) { + var _a, _b, _c, _d, _e; + const socketId = parseInt(call.request.socket_id, 10); + const socketEntry = entityMaps["socket" /* EntityTypes.socket */].getElementByKey(socketId); + if (socketEntry === undefined) { + callback({ + code: constants_1.Status.NOT_FOUND, + details: 'No socket data found for id ' + socketId, + }); + return; + } + const resolvedInfo = socketEntry.getInfo(); + const securityMessage = resolvedInfo.security + ? { + model: 'tls', + tls: { + cipher_suite: resolvedInfo.security.cipherSuiteStandardName + ? 'standard_name' + : 'other_name', + standard_name: (_a = resolvedInfo.security.cipherSuiteStandardName) !== null && _a !== void 0 ? _a : undefined, + other_name: (_b = resolvedInfo.security.cipherSuiteOtherName) !== null && _b !== void 0 ? _b : undefined, + local_certificate: (_c = resolvedInfo.security.localCertificate) !== null && _c !== void 0 ? _c : undefined, + remote_certificate: (_d = resolvedInfo.security.remoteCertificate) !== null && _d !== void 0 ? _d : undefined, + }, + } + : null; + const socketMessage = { + ref: socketRefToMessage(socketEntry.ref), + local: resolvedInfo.localAddress + ? subchannelAddressToAddressMessage(resolvedInfo.localAddress) + : null, + remote: resolvedInfo.remoteAddress + ? subchannelAddressToAddressMessage(resolvedInfo.remoteAddress) + : null, + remote_name: (_e = resolvedInfo.remoteName) !== null && _e !== void 0 ? _e : undefined, + security: securityMessage, + data: { + keep_alives_sent: resolvedInfo.keepAlivesSent, + streams_started: resolvedInfo.streamsStarted, + streams_succeeded: resolvedInfo.streamsSucceeded, + streams_failed: resolvedInfo.streamsFailed, + last_local_stream_created_timestamp: dateToProtoTimestamp(resolvedInfo.lastLocalStreamCreatedTimestamp), + last_remote_stream_created_timestamp: dateToProtoTimestamp(resolvedInfo.lastRemoteStreamCreatedTimestamp), + messages_received: resolvedInfo.messagesReceived, + messages_sent: resolvedInfo.messagesSent, + last_message_received_timestamp: dateToProtoTimestamp(resolvedInfo.lastMessageReceivedTimestamp), + last_message_sent_timestamp: dateToProtoTimestamp(resolvedInfo.lastMessageSentTimestamp), + local_flow_control_window: resolvedInfo.localFlowControlWindow + ? { value: resolvedInfo.localFlowControlWindow } + : null, + remote_flow_control_window: resolvedInfo.remoteFlowControlWindow + ? { value: resolvedInfo.remoteFlowControlWindow } + : null, + }, + }; + callback(null, { socket: socketMessage }); +} +function GetServerSockets(call, callback) { + const serverId = parseInt(call.request.server_id, 10); + const serverEntry = entityMaps["server" /* EntityTypes.server */].getElementByKey(serverId); + if (serverEntry === undefined) { + callback({ + code: constants_1.Status.NOT_FOUND, + details: 'No server data found for id ' + serverId, + }); + return; + } + const startId = parseInt(call.request.start_socket_id, 10); + const maxResults = parseInt(call.request.max_results, 10) || DEFAULT_MAX_RESULTS; + const resolvedInfo = serverEntry.getInfo(); + // If we wanted to include listener sockets in the result, this line would + // instead say + // const allSockets = resolvedInfo.listenerChildren.sockets.concat(resolvedInfo.sessionChildren.sockets).sort((ref1, ref2) => ref1.id - ref2.id); + const allSockets = resolvedInfo.sessionChildren.sockets; + const resultList = []; + let i; + for (i = allSockets.lowerBound(startId); !i.equals(allSockets.end()) && resultList.length < maxResults; i = i.next()) { + resultList.push(socketRefToMessage(i.pointer[1].ref)); + } + callback(null, { + socket_ref: resultList, + end: i.equals(allSockets.end()), + }); +} +function getChannelzHandlers() { + return { + GetChannel, + GetTopChannels, + GetServer, + GetServers, + GetSubchannel, + GetSocket, + GetServerSockets, + }; +} +exports.getChannelzHandlers = getChannelzHandlers; +let loadedChannelzDefinition = null; +function getChannelzServiceDefinition() { + if (loadedChannelzDefinition) { + return loadedChannelzDefinition; + } + /* The purpose of this complexity is to avoid loading @grpc/proto-loader at + * runtime for users who will not use/enable channelz. */ + const loaderLoadSync = require('@grpc/proto-loader') + .loadSync; + const loadedProto = loaderLoadSync('channelz.proto', { + keepCase: true, + longs: String, + enums: String, + defaults: true, + oneofs: true, + includeDirs: [`${__dirname}/../../proto`], + }); + const channelzGrpcObject = (0, make_client_1.loadPackageDefinition)(loadedProto); + loadedChannelzDefinition = + channelzGrpcObject.grpc.channelz.v1.Channelz.service; + return loadedChannelzDefinition; +} +exports.getChannelzServiceDefinition = getChannelzServiceDefinition; +function setup() { + (0, admin_1.registerAdminService)(getChannelzServiceDefinition, getChannelzHandlers); +} +exports.setup = setup; +//# sourceMappingURL=channelz.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/channelz.js.map b/node_modules/@grpc/grpc-js/build/src/channelz.js.map new file mode 100644 index 0000000..77a723b --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/channelz.js.map @@ -0,0 +1 @@ +{"version":3,"file":"channelz.js","sourceRoot":"","sources":["../../src/channelz.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;GAeG;;;AAEH,6BAAqC;AACrC,sDAA2E;AAC3E,6DAAyD;AACzD,2CAAqC;AAWrC,6DAG8B;AAyB9B,mCAA+C;AAC/C,+CAAsD;AA8BtD,SAAS,mBAAmB,CAAC,GAAe;IAC1C,OAAO;QACL,UAAU,EAAE,GAAG,CAAC,EAAE;QAClB,IAAI,EAAE,GAAG,CAAC,IAAI;KACf,CAAC;AACJ,CAAC;AAED,SAAS,sBAAsB,CAAC,GAAkB;IAChD,OAAO;QACL,aAAa,EAAE,GAAG,CAAC,EAAE;QACrB,IAAI,EAAE,GAAG,CAAC,IAAI;KACf,CAAC;AACJ,CAAC;AAED,SAAS,kBAAkB,CAAC,GAAc;IACxC,OAAO;QACL,SAAS,EAAE,GAAG,CAAC,EAAE;KAClB,CAAC;AACJ,CAAC;AAED,SAAS,kBAAkB,CAAC,GAAc;IACxC,OAAO;QACL,SAAS,EAAE,GAAG,CAAC,EAAE;QACjB,IAAI,EAAE,GAAG,CAAC,IAAI;KACf,CAAC;AACJ,CAAC;AAUD;;;;;GAKG;AACH,MAAM,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CAAC;IACvD,OAAO,wBAAwB,CAAC;AAClC,CAAC;AAtBD,oEAsBC;AAED,SAAgB,KAAK;IACnB,IAAA,4BAAoB,EAAC,4BAA4B,EAAE,mBAAmB,CAAC,CAAC;AAC1E,CAAC;AAFD,sBAEC"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/client-interceptors.d.ts b/node_modules/@grpc/grpc-js/build/src/client-interceptors.d.ts new file mode 100644 index 0000000..1ecfb34 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/client-interceptors.d.ts @@ -0,0 +1,120 @@ +import { Metadata } from './metadata'; +import { Listener, MetadataListener, MessageListener, StatusListener, InterceptingListener, MessageContext } from './call-interface'; +import { Status } from './constants'; +import { Channel } from './channel'; +import { CallOptions } from './client'; +import { ClientMethodDefinition } from './make-client'; +/** + * Error class associated with passing both interceptors and interceptor + * providers to a client constructor or as call options. + */ +export declare class InterceptorConfigurationError extends Error { + constructor(message: string); +} +export interface MetadataRequester { + (metadata: Metadata, listener: InterceptingListener, next: (metadata: Metadata, listener: InterceptingListener | Listener) => void): void; +} +export interface MessageRequester { + (message: any, next: (message: any) => void): void; +} +export interface CloseRequester { + (next: () => void): void; +} +export interface CancelRequester { + (next: () => void): void; +} +/** + * An object with methods for intercepting and modifying outgoing call operations. + */ +export interface FullRequester { + start: MetadataRequester; + sendMessage: MessageRequester; + halfClose: CloseRequester; + cancel: CancelRequester; +} +export type Requester = Partial; +export declare class ListenerBuilder { + private metadata; + private message; + private status; + withOnReceiveMetadata(onReceiveMetadata: MetadataListener): this; + withOnReceiveMessage(onReceiveMessage: MessageListener): this; + withOnReceiveStatus(onReceiveStatus: StatusListener): this; + build(): Listener; +} +export declare class RequesterBuilder { + private start; + private message; + private halfClose; + private cancel; + withStart(start: MetadataRequester): this; + withSendMessage(sendMessage: MessageRequester): this; + withHalfClose(halfClose: CloseRequester): this; + withCancel(cancel: CancelRequester): this; + build(): Requester; +} +export interface InterceptorOptions extends CallOptions { + method_definition: ClientMethodDefinition; +} +export interface InterceptingCallInterface { + cancelWithStatus(status: Status, details: string): void; + getPeer(): string; + start(metadata: Metadata, listener?: Partial): void; + sendMessageWithContext(context: MessageContext, message: any): void; + sendMessage(message: any): void; + startRead(): void; + halfClose(): void; +} +export declare class InterceptingCall implements InterceptingCallInterface { + private nextCall; + /** + * The requester that this InterceptingCall uses to modify outgoing operations + */ + private requester; + /** + * Indicates that metadata has been passed to the requester's start + * method but it has not been passed to the corresponding next callback + */ + private processingMetadata; + /** + * Message context for a pending message that is waiting for + */ + private pendingMessageContext; + private pendingMessage; + /** + * Indicates that a message has been passed to the requester's sendMessage + * method but it has not been passed to the corresponding next callback + */ + private processingMessage; + /** + * Indicates that a status was received but could not be propagated because + * a message was still being processed. + */ + private pendingHalfClose; + constructor(nextCall: InterceptingCallInterface, requester?: Requester); + cancelWithStatus(status: Status, details: string): void; + getPeer(): string; + private processPendingMessage; + private processPendingHalfClose; + start(metadata: Metadata, interceptingListener?: Partial): void; + sendMessageWithContext(context: MessageContext, message: any): void; + sendMessage(message: any): void; + startRead(): void; + halfClose(): void; +} +export interface NextCall { + (options: InterceptorOptions): InterceptingCallInterface; +} +export interface Interceptor { + (options: InterceptorOptions, nextCall: NextCall): InterceptingCall; +} +export interface InterceptorProvider { + (methodDefinition: ClientMethodDefinition): Interceptor; +} +export interface InterceptorArguments { + clientInterceptors: Interceptor[]; + clientInterceptorProviders: InterceptorProvider[]; + callInterceptors: Interceptor[]; + callInterceptorProviders: InterceptorProvider[]; +} +export declare function getInterceptingCall(interceptorArgs: InterceptorArguments, methodDefinition: ClientMethodDefinition, options: CallOptions, channel: Channel): InterceptingCallInterface; diff --git a/node_modules/@grpc/grpc-js/build/src/client-interceptors.js b/node_modules/@grpc/grpc-js/build/src/client-interceptors.js new file mode 100644 index 0000000..76352e9 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/client-interceptors.js @@ -0,0 +1,428 @@ +"use strict"; +/* + * Copyright 2019 gRPC authors. + * + * 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. + * + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.getInterceptingCall = exports.InterceptingCall = exports.RequesterBuilder = exports.ListenerBuilder = exports.InterceptorConfigurationError = void 0; +const metadata_1 = require("./metadata"); +const call_interface_1 = require("./call-interface"); +const constants_1 = require("./constants"); +const error_1 = require("./error"); +/** + * Error class associated with passing both interceptors and interceptor + * providers to a client constructor or as call options. + */ +class InterceptorConfigurationError extends Error { + constructor(message) { + super(message); + this.name = 'InterceptorConfigurationError'; + Error.captureStackTrace(this, InterceptorConfigurationError); + } +} +exports.InterceptorConfigurationError = InterceptorConfigurationError; +class ListenerBuilder { + constructor() { + this.metadata = undefined; + this.message = undefined; + this.status = undefined; + } + withOnReceiveMetadata(onReceiveMetadata) { + this.metadata = onReceiveMetadata; + return this; + } + withOnReceiveMessage(onReceiveMessage) { + this.message = onReceiveMessage; + return this; + } + withOnReceiveStatus(onReceiveStatus) { + this.status = onReceiveStatus; + return this; + } + build() { + return { + onReceiveMetadata: this.metadata, + onReceiveMessage: this.message, + onReceiveStatus: this.status, + }; + } +} +exports.ListenerBuilder = ListenerBuilder; +class RequesterBuilder { + constructor() { + this.start = undefined; + this.message = undefined; + this.halfClose = undefined; + this.cancel = undefined; + } + withStart(start) { + this.start = start; + return this; + } + withSendMessage(sendMessage) { + this.message = sendMessage; + return this; + } + withHalfClose(halfClose) { + this.halfClose = halfClose; + return this; + } + withCancel(cancel) { + this.cancel = cancel; + return this; + } + build() { + return { + start: this.start, + sendMessage: this.message, + halfClose: this.halfClose, + cancel: this.cancel, + }; + } +} +exports.RequesterBuilder = RequesterBuilder; +/** + * A Listener with a default pass-through implementation of each method. Used + * for filling out Listeners with some methods omitted. + */ +const defaultListener = { + onReceiveMetadata: (metadata, next) => { + next(metadata); + }, + onReceiveMessage: (message, next) => { + next(message); + }, + onReceiveStatus: (status, next) => { + next(status); + }, +}; +/** + * A Requester with a default pass-through implementation of each method. Used + * for filling out Requesters with some methods omitted. + */ +const defaultRequester = { + start: (metadata, listener, next) => { + next(metadata, listener); + }, + sendMessage: (message, next) => { + next(message); + }, + halfClose: next => { + next(); + }, + cancel: next => { + next(); + }, +}; +class InterceptingCall { + constructor(nextCall, requester) { + var _a, _b, _c, _d; + this.nextCall = nextCall; + /** + * Indicates that metadata has been passed to the requester's start + * method but it has not been passed to the corresponding next callback + */ + this.processingMetadata = false; + /** + * Message context for a pending message that is waiting for + */ + this.pendingMessageContext = null; + /** + * Indicates that a message has been passed to the requester's sendMessage + * method but it has not been passed to the corresponding next callback + */ + this.processingMessage = false; + /** + * Indicates that a status was received but could not be propagated because + * a message was still being processed. + */ + this.pendingHalfClose = false; + if (requester) { + this.requester = { + start: (_a = requester.start) !== null && _a !== void 0 ? _a : defaultRequester.start, + sendMessage: (_b = requester.sendMessage) !== null && _b !== void 0 ? _b : defaultRequester.sendMessage, + halfClose: (_c = requester.halfClose) !== null && _c !== void 0 ? _c : defaultRequester.halfClose, + cancel: (_d = requester.cancel) !== null && _d !== void 0 ? _d : defaultRequester.cancel, + }; + } + else { + this.requester = defaultRequester; + } + } + cancelWithStatus(status, details) { + this.requester.cancel(() => { + this.nextCall.cancelWithStatus(status, details); + }); + } + getPeer() { + return this.nextCall.getPeer(); + } + processPendingMessage() { + if (this.pendingMessageContext) { + this.nextCall.sendMessageWithContext(this.pendingMessageContext, this.pendingMessage); + this.pendingMessageContext = null; + this.pendingMessage = null; + } + } + processPendingHalfClose() { + if (this.pendingHalfClose) { + this.nextCall.halfClose(); + } + } + start(metadata, interceptingListener) { + var _a, _b, _c, _d, _e, _f; + const fullInterceptingListener = { + onReceiveMetadata: (_b = (_a = interceptingListener === null || interceptingListener === void 0 ? void 0 : interceptingListener.onReceiveMetadata) === null || _a === void 0 ? void 0 : _a.bind(interceptingListener)) !== null && _b !== void 0 ? _b : (metadata => { }), + onReceiveMessage: (_d = (_c = interceptingListener === null || interceptingListener === void 0 ? void 0 : interceptingListener.onReceiveMessage) === null || _c === void 0 ? void 0 : _c.bind(interceptingListener)) !== null && _d !== void 0 ? _d : (message => { }), + onReceiveStatus: (_f = (_e = interceptingListener === null || interceptingListener === void 0 ? void 0 : interceptingListener.onReceiveStatus) === null || _e === void 0 ? void 0 : _e.bind(interceptingListener)) !== null && _f !== void 0 ? _f : (status => { }), + }; + this.processingMetadata = true; + this.requester.start(metadata, fullInterceptingListener, (md, listener) => { + var _a, _b, _c; + this.processingMetadata = false; + let finalInterceptingListener; + if ((0, call_interface_1.isInterceptingListener)(listener)) { + finalInterceptingListener = listener; + } + else { + const fullListener = { + onReceiveMetadata: (_a = listener.onReceiveMetadata) !== null && _a !== void 0 ? _a : defaultListener.onReceiveMetadata, + onReceiveMessage: (_b = listener.onReceiveMessage) !== null && _b !== void 0 ? _b : defaultListener.onReceiveMessage, + onReceiveStatus: (_c = listener.onReceiveStatus) !== null && _c !== void 0 ? _c : defaultListener.onReceiveStatus, + }; + finalInterceptingListener = new call_interface_1.InterceptingListenerImpl(fullListener, fullInterceptingListener); + } + this.nextCall.start(md, finalInterceptingListener); + this.processPendingMessage(); + this.processPendingHalfClose(); + }); + } + // eslint-disable-next-line @typescript-eslint/no-explicit-any + sendMessageWithContext(context, message) { + this.processingMessage = true; + this.requester.sendMessage(message, finalMessage => { + this.processingMessage = false; + if (this.processingMetadata) { + this.pendingMessageContext = context; + this.pendingMessage = message; + } + else { + this.nextCall.sendMessageWithContext(context, finalMessage); + this.processPendingHalfClose(); + } + }); + } + // eslint-disable-next-line @typescript-eslint/no-explicit-any + sendMessage(message) { + this.sendMessageWithContext({}, message); + } + startRead() { + this.nextCall.startRead(); + } + halfClose() { + this.requester.halfClose(() => { + if (this.processingMetadata || this.processingMessage) { + this.pendingHalfClose = true; + } + else { + this.nextCall.halfClose(); + } + }); + } +} +exports.InterceptingCall = InterceptingCall; +function getCall(channel, path, options) { + var _a, _b; + const deadline = (_a = options.deadline) !== null && _a !== void 0 ? _a : Infinity; + const host = options.host; + const parent = (_b = options.parent) !== null && _b !== void 0 ? _b : null; + const propagateFlags = options.propagate_flags; + const credentials = options.credentials; + const call = channel.createCall(path, deadline, host, parent, propagateFlags); + if (credentials) { + call.setCredentials(credentials); + } + return call; +} +/** + * InterceptingCall implementation that directly owns the underlying Call + * object and handles serialization and deseraizliation. + */ +class BaseInterceptingCall { + constructor(call, + // eslint-disable-next-line @typescript-eslint/no-explicit-any + methodDefinition) { + this.call = call; + this.methodDefinition = methodDefinition; + } + cancelWithStatus(status, details) { + this.call.cancelWithStatus(status, details); + } + getPeer() { + return this.call.getPeer(); + } + // eslint-disable-next-line @typescript-eslint/no-explicit-any + sendMessageWithContext(context, message) { + let serialized; + try { + serialized = this.methodDefinition.requestSerialize(message); + } + catch (e) { + this.call.cancelWithStatus(constants_1.Status.INTERNAL, `Request message serialization failure: ${(0, error_1.getErrorMessage)(e)}`); + return; + } + this.call.sendMessageWithContext(context, serialized); + } + // eslint-disable-next-line @typescript-eslint/no-explicit-any + sendMessage(message) { + this.sendMessageWithContext({}, message); + } + start(metadata, interceptingListener) { + let readError = null; + this.call.start(metadata, { + onReceiveMetadata: metadata => { + var _a; + (_a = interceptingListener === null || interceptingListener === void 0 ? void 0 : interceptingListener.onReceiveMetadata) === null || _a === void 0 ? void 0 : _a.call(interceptingListener, metadata); + }, + onReceiveMessage: message => { + var _a; + // eslint-disable-next-line @typescript-eslint/no-explicit-any + let deserialized; + try { + deserialized = this.methodDefinition.responseDeserialize(message); + } + catch (e) { + readError = { + code: constants_1.Status.INTERNAL, + details: `Response message parsing error: ${(0, error_1.getErrorMessage)(e)}`, + metadata: new metadata_1.Metadata(), + }; + this.call.cancelWithStatus(readError.code, readError.details); + return; + } + (_a = interceptingListener === null || interceptingListener === void 0 ? void 0 : interceptingListener.onReceiveMessage) === null || _a === void 0 ? void 0 : _a.call(interceptingListener, deserialized); + }, + onReceiveStatus: status => { + var _a, _b; + if (readError) { + (_a = interceptingListener === null || interceptingListener === void 0 ? void 0 : interceptingListener.onReceiveStatus) === null || _a === void 0 ? void 0 : _a.call(interceptingListener, readError); + } + else { + (_b = interceptingListener === null || interceptingListener === void 0 ? void 0 : interceptingListener.onReceiveStatus) === null || _b === void 0 ? void 0 : _b.call(interceptingListener, status); + } + }, + }); + } + startRead() { + this.call.startRead(); + } + halfClose() { + this.call.halfClose(); + } +} +/** + * BaseInterceptingCall with special-cased behavior for methods with unary + * responses. + */ +class BaseUnaryInterceptingCall extends BaseInterceptingCall { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + constructor(call, methodDefinition) { + super(call, methodDefinition); + } + start(metadata, listener) { + var _a, _b; + let receivedMessage = false; + const wrapperListener = { + onReceiveMetadata: (_b = (_a = listener === null || listener === void 0 ? void 0 : listener.onReceiveMetadata) === null || _a === void 0 ? void 0 : _a.bind(listener)) !== null && _b !== void 0 ? _b : (metadata => { }), + // eslint-disable-next-line @typescript-eslint/no-explicit-any + onReceiveMessage: (message) => { + var _a; + receivedMessage = true; + (_a = listener === null || listener === void 0 ? void 0 : listener.onReceiveMessage) === null || _a === void 0 ? void 0 : _a.call(listener, message); + }, + onReceiveStatus: (status) => { + var _a, _b; + if (!receivedMessage) { + (_a = listener === null || listener === void 0 ? void 0 : listener.onReceiveMessage) === null || _a === void 0 ? void 0 : _a.call(listener, null); + } + (_b = listener === null || listener === void 0 ? void 0 : listener.onReceiveStatus) === null || _b === void 0 ? void 0 : _b.call(listener, status); + }, + }; + super.start(metadata, wrapperListener); + this.call.startRead(); + } +} +/** + * BaseInterceptingCall with special-cased behavior for methods with streaming + * responses. + */ +class BaseStreamingInterceptingCall extends BaseInterceptingCall { +} +function getBottomInterceptingCall(channel, options, +// eslint-disable-next-line @typescript-eslint/no-explicit-any +methodDefinition) { + const call = getCall(channel, methodDefinition.path, options); + if (methodDefinition.responseStream) { + return new BaseStreamingInterceptingCall(call, methodDefinition); + } + else { + return new BaseUnaryInterceptingCall(call, methodDefinition); + } +} +function getInterceptingCall(interceptorArgs, +// eslint-disable-next-line @typescript-eslint/no-explicit-any +methodDefinition, options, channel) { + if (interceptorArgs.clientInterceptors.length > 0 && + interceptorArgs.clientInterceptorProviders.length > 0) { + throw new InterceptorConfigurationError('Both interceptors and interceptor_providers were passed as options ' + + 'to the client constructor. Only one of these is allowed.'); + } + if (interceptorArgs.callInterceptors.length > 0 && + interceptorArgs.callInterceptorProviders.length > 0) { + throw new InterceptorConfigurationError('Both interceptors and interceptor_providers were passed as call ' + + 'options. Only one of these is allowed.'); + } + let interceptors = []; + // Interceptors passed to the call override interceptors passed to the client constructor + if (interceptorArgs.callInterceptors.length > 0 || + interceptorArgs.callInterceptorProviders.length > 0) { + interceptors = [] + .concat(interceptorArgs.callInterceptors, interceptorArgs.callInterceptorProviders.map(provider => provider(methodDefinition))) + .filter(interceptor => interceptor); + // Filter out falsy values when providers return nothing + } + else { + interceptors = [] + .concat(interceptorArgs.clientInterceptors, interceptorArgs.clientInterceptorProviders.map(provider => provider(methodDefinition))) + .filter(interceptor => interceptor); + // Filter out falsy values when providers return nothing + } + const interceptorOptions = Object.assign({}, options, { + method_definition: methodDefinition, + }); + /* For each interceptor in the list, the nextCall function passed to it is + * based on the next interceptor in the list, using a nextCall function + * constructed with the following interceptor in the list, and so on. The + * initialValue, which is effectively at the end of the list, is a nextCall + * function that invokes getBottomInterceptingCall, the result of which + * handles (de)serialization and also gets the underlying call from the + * channel. */ + const getCall = interceptors.reduceRight((nextCall, nextInterceptor) => { + return currentOptions => nextInterceptor(currentOptions, nextCall); + }, (finalOptions) => getBottomInterceptingCall(channel, finalOptions, methodDefinition)); + return getCall(interceptorOptions); +} +exports.getInterceptingCall = getInterceptingCall; +//# sourceMappingURL=client-interceptors.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/client-interceptors.js.map b/node_modules/@grpc/grpc-js/build/src/client-interceptors.js.map new file mode 100644 index 0000000..e1dfd73 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/client-interceptors.js.map @@ -0,0 +1 @@ +{"version":3,"file":"client-interceptors.js","sourceRoot":"","sources":["../../src/client-interceptors.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;GAeG;;;AAEH,yCAAsC;AACtC,qDAY0B;AAC1B,2CAAqC;AAIrC,mCAA0C;AAE1C;;;GAGG;AACH,MAAa,6BAA8B,SAAQ,KAAK;IACtD,YAAY,OAAe;QACzB,KAAK,CAAC,OAAO,CAAC,CAAC;QACf,IAAI,CAAC,IAAI,GAAG,+BAA+B,CAAC;QAC5C,KAAK,CAAC,iBAAiB,CAAC,IAAI,EAAE,6BAA6B,CAAC,CAAC;IAC/D,CAAC;CACF;AAND,sEAMC;AAsCD,MAAa,eAAe;IAA5B;QACU,aAAQ,GAAiC,SAAS,CAAC;QACnD,YAAO,GAAgC,SAAS,CAAC;QACjD,WAAM,GAA+B,SAAS,CAAC;IAwBzD,CAAC;IAtBC,qBAAqB,CAAC,iBAAmC;QACvD,IAAI,CAAC,QAAQ,GAAG,iBAAiB,CAAC;QAClC,OAAO,IAAI,CAAC;IACd,CAAC;IAED,oBAAoB,CAAC,gBAAiC;QACpD,IAAI,CAAC,OAAO,GAAG,gBAAgB,CAAC;QAChC,OAAO,IAAI,CAAC;IACd,CAAC;IAED,mBAAmB,CAAC,eAA+B;QACjD,IAAI,CAAC,MAAM,GAAG,eAAe,CAAC;QAC9B,OAAO,IAAI,CAAC;IACd,CAAC;IAED,KAAK;QACH,OAAO;YACL,iBAAiB,EAAE,IAAI,CAAC,QAAQ;YAChC,gBAAgB,EAAE,IAAI,CAAC,OAAO;YAC9B,eAAe,EAAE,IAAI,CAAC,MAAM;SAC7B,CAAC;IACJ,CAAC;CACF;AA3BD,0CA2BC;AAED,MAAa,gB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O,EAAE;QACpD,iBAAiB,EAAE,gBAAgB;KACpC,CAAC,CAAC;IACH;;;;;;kBAMc;IACd,MAAM,OAAO,GAAa,YAAY,CAAC,WAAW,CAChD,CAAC,QAAkB,EAAE,eAA4B,EAAE,EAAE;QACnD,OAAO,cAAc,CAAC,EAAE,CAAC,eAAe,CAAC,cAAc,EAAE,QAAQ,CAAC,CAAC;IACrE,CAAC,EACD,CAAC,YAAgC,EAAE,EAAE,CACnC,yBAAyB,CAAC,OAAO,EAAE,YAAY,EAAE,gBAAgB,CAAC,CACrE,CAAC;IACF,OAAO,OAAO,CAAC,kBAAkB,CAAC,CAAC;AACrC,CAAC;AArED,kDAqEC"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/client.d.ts b/node_modules/@grpc/grpc-js/build/src/client.d.ts new file mode 100644 index 0000000..a57bfb5 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/client.d.ts @@ -0,0 +1,75 @@ +/// +import { ClientDuplexStream, ClientReadableStream, ClientUnaryCall, ClientWritableStream, ServiceError, SurfaceCall } from './call'; +import { CallCredentials } from './call-credentials'; +import { Channel } from './channel'; +import { ChannelCredentials } from './channel-credentials'; +import { ChannelOptions } from './channel-options'; +import { Metadata } from './metadata'; +import { ClientMethodDefinition } from './make-client'; +import { Interceptor, InterceptorProvider } from './client-interceptors'; +import { ServerUnaryCall, ServerReadableStream, ServerWritableStream, ServerDuplexStream } from './server-call'; +import { Deadline } from './deadline'; +declare const CHANNEL_SYMBOL: unique symbol; +declare const INTERCEPTOR_SYMBOL: unique symbol; +declare const INTERCEPTOR_PROVIDER_SYMBOL: unique symbol; +declare const CALL_INVOCATION_TRANSFORMER_SYMBOL: unique symbol; +export interface UnaryCallback { + (err: ServiceError | null, value?: ResponseType): void; +} +export interface CallOptions { + deadline?: Deadline; + host?: string; + parent?: ServerUnaryCall | ServerReadableStream | ServerWritableStream | ServerDuplexStream; + propagate_flags?: number; + credentials?: CallCredentials; + interceptors?: Interceptor[]; + interceptor_providers?: InterceptorProvider[]; +} +export interface CallProperties { + argument?: RequestType; + metadata: Metadata; + call: SurfaceCall; + channel: Channel; + methodDefinition: ClientMethodDefinition; + callOptions: CallOptions; + callback?: UnaryCallback; +} +export interface CallInvocationTransformer { + (callProperties: CallProperties): CallProperties; +} +export type ClientOptions = Partial & { + channelOverride?: Channel; + channelFactoryOverride?: (address: string, credentials: ChannelCredentials, options: ClientOptions) => Channel; + interceptors?: Interceptor[]; + interceptor_providers?: InterceptorProvider[]; + callInvocationTransformer?: CallInvocationTransformer; +}; +/** + * A generic gRPC client. Primarily useful as a base class for all generated + * clients. + */ +export declare class Client { + private readonly [CHANNEL_SYMBOL]; + private readonly [INTERCEPTOR_SYMBOL]; + private readonly [INTERCEPTOR_PROVIDER_SYMBOL]; + private readonly [CALL_INVOCATION_TRANSFORMER_SYMBOL]?; + constructor(address: string, credentials: ChannelCredentials, options?: ClientOptions); + close(): void; + getChannel(): Channel; + waitForReady(deadline: Deadline, callback: (error?: Error) => void): void; + private checkOptionalUnaryResponseArguments; + makeUnaryRequest(method: string, serialize: (value: RequestType) => Buffer, deserialize: (value: Buffer) => ResponseType, argument: RequestType, metadata: Metadata, options: CallOptions, callback: UnaryCallback): ClientUnaryCall; + makeUnaryRequest(method: string, serialize: (value: RequestType) => Buffer, deserialize: (value: Buffer) => ResponseType, argument: RequestType, metadata: Metadata, callback: UnaryCallback): ClientUnaryCall; + makeUnaryRequest(method: string, serialize: (value: RequestType) => Buffer, deserialize: (value: Buffer) => ResponseType, argument: RequestType, options: CallOptions, callback: UnaryCallback): ClientUnaryCall; + makeUnaryRequest(method: string, serialize: (value: RequestType) => Buffer, deserialize: (value: Buffer) => ResponseType, argument: RequestType, callback: UnaryCallback): ClientUnaryCall; + makeClientStreamRequest(method: string, serialize: (value: RequestType) => Buffer, deserialize: (value: Buffer) => ResponseType, metadata: Metadata, options: CallOptions, callback: UnaryCallback): ClientWritableStream; + makeClientStreamRequest(method: string, serialize: (value: RequestType) => Buffer, deserialize: (value: Buffer) => ResponseType, metadata: Metadata, callback: UnaryCallback): ClientWritableStream; + makeClientStreamRequest(method: string, serialize: (value: RequestType) => Buffer, deserialize: (value: Buffer) => ResponseType, options: CallOptions, callback: UnaryCallback): ClientWritableStream; + makeClientStreamRequest(method: string, serialize: (value: RequestType) => Buffer, deserialize: (value: Buffer) => ResponseType, callback: UnaryCallback): ClientWritableStream; + private checkMetadataAndOptions; + makeServerStreamRequest(method: string, serialize: (value: RequestType) => Buffer, deserialize: (value: Buffer) => ResponseType, argument: RequestType, metadata: Metadata, options?: CallOptions): ClientReadableStream; + makeServerStreamRequest(method: string, serialize: (value: RequestType) => Buffer, deserialize: (value: Buffer) => ResponseType, argument: RequestType, options?: CallOptions): ClientReadableStream; + makeBidiStreamRequest(method: string, serialize: (value: RequestType) => Buffer, deserialize: (value: Buffer) => ResponseType, metadata: Metadata, options?: CallOptions): ClientDuplexStream; + makeBidiStreamRequest(method: string, serialize: (value: RequestType) => Buffer, deserialize: (value: Buffer) => ResponseType, options?: CallOptions): ClientDuplexStream; +} +export {}; diff --git a/node_modules/@grpc/grpc-js/build/src/client.js b/node_modules/@grpc/grpc-js/build/src/client.js new file mode 100644 index 0000000..d20170c --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/client.js @@ -0,0 +1,432 @@ +"use strict"; +/* + * Copyright 2019 gRPC authors. + * + * 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. + * + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Client = void 0; +const call_1 = require("./call"); +const channel_1 = require("./channel"); +const connectivity_state_1 = require("./connectivity-state"); +const constants_1 = require("./constants"); +const metadata_1 = require("./metadata"); +const client_interceptors_1 = require("./client-interceptors"); +const CHANNEL_SYMBOL = Symbol(); +const INTERCEPTOR_SYMBOL = Symbol(); +const INTERCEPTOR_PROVIDER_SYMBOL = Symbol(); +const CALL_INVOCATION_TRANSFORMER_SYMBOL = Symbol(); +function isFunction(arg) { + return typeof arg === 'function'; +} +function getErrorStackString(error) { + var _a; + return ((_a = error.stack) === null || _a === void 0 ? void 0 : _a.split('\n').slice(1).join('\n')) || 'no stack trace available'; +} +/** + * A generic gRPC client. Primarily useful as a base class for all generated + * clients. + */ +class Client { + constructor(address, credentials, options = {}) { + var _a, _b; + options = Object.assign({}, options); + this[INTERCEPTOR_SYMBOL] = (_a = options.interceptors) !== null && _a !== void 0 ? _a : []; + delete options.interceptors; + this[INTERCEPTOR_PROVIDER_SYMBOL] = (_b = options.interceptor_providers) !== null && _b !== void 0 ? _b : []; + delete options.interceptor_providers; + if (this[INTERCEPTOR_SYMBOL].length > 0 && + this[INTERCEPTOR_PROVIDER_SYMBOL].length > 0) { + throw new Error('Both interceptors and interceptor_providers were passed as options ' + + 'to the client constructor. Only one of these is allowed.'); + } + this[CALL_INVOCATION_TRANSFORMER_SYMBOL] = + options.callInvocationTransformer; + delete options.callInvocationTransformer; + if (options.channelOverride) { + this[CHANNEL_SYMBOL] = options.channelOverride; + } + else if (options.channelFactoryOverride) { + const channelFactoryOverride = options.channelFactoryOverride; + delete options.channelFactoryOverride; + this[CHANNEL_SYMBOL] = channelFactoryOverride(address, credentials, options); + } + else { + this[CHANNEL_SYMBOL] = new channel_1.ChannelImplementation(address, credentials, options); + } + } + close() { + this[CHANNEL_SYMBOL].close(); + } + getChannel() { + return this[CHANNEL_SYMBOL]; + } + waitForReady(deadline, callback) { + const checkState = (err) => { + if (err) { + callback(new Error('Failed to connect before the deadline')); + return; + } + let newState; + try { + newState = this[CHANNEL_SYMBOL].getConnectivityState(true); + } + catch (e) { + callback(new Error('The channel has been closed')); + return; + } + if (newState === connectivity_state_1.ConnectivityState.READY) { + callback(); + } + else { + try { + this[CHANNEL_SYMBOL].watchConnectivityState(newState, deadline, checkState); + } + catch (e) { + callback(new Error('The channel has been closed')); + } + } + }; + setImmediate(checkState); + } + checkOptionalUnaryResponseArguments(arg1, arg2, arg3) { + if (isFunction(arg1)) { + return { metadata: new metadata_1.Metadata(), options: {}, callback: arg1 }; + } + else if (isFunction(arg2)) { + if (arg1 instanceof metadata_1.Metadata) { + return { metadata: arg1, options: {}, callback: arg2 }; + } + else { + return { metadata: new metadata_1.Metadata(), options: arg1, callback: arg2 }; + } + } + else { + if (!(arg1 instanceof metadata_1.Metadata && + arg2 instanceof Object && + isFunction(arg3))) { + throw new Error('Incorrect arguments passed'); + } + return { metadata: arg1, options: arg2, callback: arg3 }; + } + } + makeUnaryRequest(method, serialize, deserialize, argument, metadata, options, callback) { + var _a, _b; + const checkedArguments = this.checkOptionalUnaryResponseArguments(metadata, options, callback); + const methodDefinition = { + path: method, + requestStream: false, + responseStream: false, + requestSerialize: serialize, + responseDeserialize: deserialize, + }; + let callProperties = { + argument: argument, + metadata: checkedArguments.metadata, + call: new call_1.ClientUnaryCallImpl(), + channel: this[CHANNEL_SYMBOL], + methodDefinition: methodDefinition, + callOptions: checkedArguments.options, + callback: checkedArguments.callback, + }; + if (this[CALL_INVOCATION_TRANSFORMER_SYMBOL]) { + callProperties = this[CALL_INVOCATION_TRANSFORMER_SYMBOL](callProperties); + } + const emitter = callProperties.call; + const interceptorArgs = { + clientInterceptors: this[INTERCEPTOR_SYMBOL], + clientInterceptorProviders: this[INTERCEPTOR_PROVIDER_SYMBOL], + callInterceptors: (_a = callProperties.callOptions.interceptors) !== null && _a !== void 0 ? _a : [], + callInterceptorProviders: (_b = callProperties.callOptions.interceptor_providers) !== null && _b !== void 0 ? _b : [], + }; + const call = (0, client_interceptors_1.getInterceptingCall)(interceptorArgs, callProperties.methodDefinition, callProperties.callOptions, callProperties.channel); + /* This needs to happen before the emitter is used. Unfortunately we can't + * enforce this with the type system. We need to construct this emitter + * before calling the CallInvocationTransformer, and we need to create the + * call after that. */ + emitter.call = call; + let responseMessage = null; + let receivedStatus = false; + let callerStackError = new Error(); + call.start(callProperties.metadata, { + onReceiveMetadata: metadata => { + emitter.emit('metadata', metadata); + }, + // eslint-disable-next-line @typescript-eslint/no-explicit-any + onReceiveMessage(message) { + if (responseMessage !== null) { + call.cancelWithStatus(constants_1.Status.INTERNAL, 'Too many responses received'); + } + responseMessage = message; + }, + onReceiveStatus(status) { + if (receivedStatus) { + return; + } + receivedStatus = true; + if (status.code === constants_1.Status.OK) { + if (responseMessage === null) { + const callerStack = getErrorStackString(callerStackError); + callProperties.callback((0, call_1.callErrorFromStatus)({ + code: constants_1.Status.INTERNAL, + details: 'No message received', + metadata: status.metadata, + }, callerStack)); + } + else { + callProperties.callback(null, responseMessage); + } + } + else { + const callerStack = getErrorStackString(callerStackError); + callProperties.callback((0, call_1.callErrorFromStatus)(status, callerStack)); + } + /* Avoid retaining the callerStackError object in the call context of + * the status event handler. */ + callerStackError = null; + emitter.emit('status', status); + }, + }); + call.sendMessage(argument); + call.halfClose(); + return emitter; + } + makeClientStreamRequest(method, serialize, deserialize, metadata, options, callback) { + var _a, _b; + const checkedArguments = this.checkOptionalUnaryResponseArguments(metadata, options, callback); + const methodDefinition = { + path: method, + requestStream: true, + responseStream: false, + requestSerialize: serialize, + responseDeserialize: deserialize, + }; + let callProperties = { + metadata: checkedArguments.metadata, + call: new call_1.ClientWritableStreamImpl(serialize), + channel: this[CHANNEL_SYMBOL], + methodDefinition: methodDefinition, + callOptions: checkedArguments.options, + callback: checkedArguments.callback, + }; + if (this[CALL_INVOCATION_TRANSFORMER_SYMBOL]) { + callProperties = this[CALL_INVOCATION_TRANSFORMER_SYMBOL](callProperties); + } + const emitter = callProperties.call; + const interceptorArgs = { + clientInterceptors: this[INTERCEPTOR_SYMBOL], + clientInterceptorProviders: this[INTERCEPTOR_PROVIDER_SYMBOL], + callInterceptors: (_a = callProperties.callOptions.interceptors) !== null && _a !== void 0 ? _a : [], + callInterceptorProviders: (_b = callProperties.callOptions.interceptor_providers) !== null && _b !== void 0 ? _b : [], + }; + const call = (0, client_interceptors_1.getInterceptingCall)(interceptorArgs, callProperties.methodDefinition, callProperties.callOptions, callProperties.channel); + /* This needs to happen before the emitter is used. Unfortunately we can't + * enforce this with the type system. We need to construct this emitter + * before calling the CallInvocationTransformer, and we need to create the + * call after that. */ + emitter.call = call; + let responseMessage = null; + let receivedStatus = false; + let callerStackError = new Error(); + call.start(callProperties.metadata, { + onReceiveMetadata: metadata => { + emitter.emit('metadata', metadata); + }, + // eslint-disable-next-line @typescript-eslint/no-explicit-any + onReceiveMessage(message) { + if (responseMessage !== null) { + call.cancelWithStatus(constants_1.Status.INTERNAL, 'Too many responses received'); + } + responseMessage = message; + }, + onReceiveStatus(status) { + if (receivedStatus) { + return; + } + receivedStatus = true; + if (status.code === constants_1.Status.OK) { + if (responseMessage === null) { + const callerStack = getErrorStackString(callerStackError); + callProperties.callback((0, call_1.callErrorFromStatus)({ + code: constants_1.Status.INTERNAL, + details: 'No message received', + metadata: status.metadata, + }, callerStack)); + } + else { + callProperties.callback(null, responseMessage); + } + } + else { + const callerStack = getErrorStackString(callerStackError); + callProperties.callback((0, call_1.callErrorFromStatus)(status, callerStack)); + } + /* Avoid retaining the callerStackError object in the call context of + * the status event handler. */ + callerStackError = null; + emitter.emit('status', status); + }, + }); + return emitter; + } + checkMetadataAndOptions(arg1, arg2) { + let metadata; + let options; + if (arg1 instanceof metadata_1.Metadata) { + metadata = arg1; + if (arg2) { + options = arg2; + } + else { + options = {}; + } + } + else { + if (arg1) { + options = arg1; + } + else { + options = {}; + } + metadata = new metadata_1.Metadata(); + } + return { metadata, options }; + } + makeServerStreamRequest(method, serialize, deserialize, argument, metadata, options) { + var _a, _b; + const checkedArguments = this.checkMetadataAndOptions(metadata, options); + const methodDefinition = { + path: method, + requestStream: false, + responseStream: true, + requestSerialize: serialize, + responseDeserialize: deserialize, + }; + let callProperties = { + argument: argument, + metadata: checkedArguments.metadata, + call: new call_1.ClientReadableStreamImpl(deserialize), + channel: this[CHANNEL_SYMBOL], + methodDefinition: methodDefinition, + callOptions: checkedArguments.options, + }; + if (this[CALL_INVOCATION_TRANSFORMER_SYMBOL]) { + callProperties = this[CALL_INVOCATION_TRANSFORMER_SYMBOL](callProperties); + } + const stream = callProperties.call; + const interceptorArgs = { + clientInterceptors: this[INTERCEPTOR_SYMBOL], + clientInterceptorProviders: this[INTERCEPTOR_PROVIDER_SYMBOL], + callInterceptors: (_a = callProperties.callOptions.interceptors) !== null && _a !== void 0 ? _a : [], + callInterceptorProviders: (_b = callProperties.callOptions.interceptor_providers) !== null && _b !== void 0 ? _b : [], + }; + const call = (0, client_interceptors_1.getInterceptingCall)(interceptorArgs, callProperties.methodDefinition, callProperties.callOptions, callProperties.channel); + /* This needs to happen before the emitter is used. Unfortunately we can't + * enforce this with the type system. We need to construct this emitter + * before calling the CallInvocationTransformer, and we need to create the + * call after that. */ + stream.call = call; + let receivedStatus = false; + let callerStackError = new Error(); + call.start(callProperties.metadata, { + onReceiveMetadata(metadata) { + stream.emit('metadata', metadata); + }, + // eslint-disable-next-line @typescript-eslint/no-explicit-any + onReceiveMessage(message) { + stream.push(message); + }, + onReceiveStatus(status) { + if (receivedStatus) { + return; + } + receivedStatus = true; + stream.push(null); + if (status.code !== constants_1.Status.OK) { + const callerStack = getErrorStackString(callerStackError); + stream.emit('error', (0, call_1.callErrorFromStatus)(status, callerStack)); + } + /* Avoid retaining the callerStackError object in the call context of + * the status event handler. */ + callerStackError = null; + stream.emit('status', status); + }, + }); + call.sendMessage(argument); + call.halfClose(); + return stream; + } + makeBidiStreamRequest(method, serialize, deserialize, metadata, options) { + var _a, _b; + const checkedArguments = this.checkMetadataAndOptions(metadata, options); + const methodDefinition = { + path: method, + requestStream: true, + responseStream: true, + requestSerialize: serialize, + responseDeserialize: deserialize, + }; + let callProperties = { + metadata: checkedArguments.metadata, + call: new call_1.ClientDuplexStreamImpl(serialize, deserialize), + channel: this[CHANNEL_SYMBOL], + methodDefinition: methodDefinition, + callOptions: checkedArguments.options, + }; + if (this[CALL_INVOCATION_TRANSFORMER_SYMBOL]) { + callProperties = this[CALL_INVOCATION_TRANSFORMER_SYMBOL](callProperties); + } + const stream = callProperties.call; + const interceptorArgs = { + clientInterceptors: this[INTERCEPTOR_SYMBOL], + clientInterceptorProviders: this[INTERCEPTOR_PROVIDER_SYMBOL], + callInterceptors: (_a = callProperties.callOptions.interceptors) !== null && _a !== void 0 ? _a : [], + callInterceptorProviders: (_b = callProperties.callOptions.interceptor_providers) !== null && _b !== void 0 ? _b : [], + }; + const call = (0, client_interceptors_1.getInterceptingCall)(interceptorArgs, callProperties.methodDefinition, callProperties.callOptions, callProperties.channel); + /* This needs to happen before the emitter is used. Unfortunately we can't + * enforce this with the type system. We need to construct this emitter + * before calling the CallInvocationTransformer, and we need to create the + * call after that. */ + stream.call = call; + let receivedStatus = false; + let callerStackError = new Error(); + call.start(callProperties.metadata, { + onReceiveMetadata(metadata) { + stream.emit('metadata', metadata); + }, + onReceiveMessage(message) { + stream.push(message); + }, + onReceiveStatus(status) { + if (receivedStatus) { + return; + } + receivedStatus = true; + stream.push(null); + if (status.code !== constants_1.Status.OK) { + const callerStack = getErrorStackString(callerStackError); + stream.emit('error', (0, call_1.callErrorFromStatus)(status, callerStack)); + } + /* Avoid retaining the callerStackError object in the call context of + * the status event handler. */ + callerStackError = null; + stream.emit('status', status); + }, + }); + return stream; + } +} +exports.Client = Client; +//# sourceMappingURL=client.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/client.js.map b/node_modules/@grpc/grpc-js/build/src/client.js.map new file mode 100644 index 0000000..ee2adba --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/client.js.map @@ -0,0 +1 @@ +{"version":3,"file":"client.js","sourceRoot":"","sources":["../../src/client.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;GAeG;;;AAEH,iCAYgB;AAGhB,uCAA2D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C,CAAC;YACpC,CAAC;YACD,gBAAgB,CAAC,OAAe;gBAC9B,MAAM,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;YACvB,CAAC;YACD,eAAe,CAAC,MAAoB;gBAClC,IAAI,cAAc,EAAE,CAAC;oBACnB,OAAO;gBACT,CAAC;gBACD,cAAc,GAAG,IAAI,CAAC;gBACtB,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;gBAClB,IAAI,MAAM,CAAC,IAAI,KAAK,kBAAM,CAAC,EAAE,EAAE,CAAC;oBAC9B,MAAM,WAAW,GAAG,mBAAmB,CAAC,gBAAiB,CAAC,CAAC;oBAC3D,MAAM,CAAC,IAAI,CAAC,OAAO,EAAE,IAAA,0BAAmB,EAAC,MAAM,EAAE,WAAW,CAAC,CAAC,CAAC;gBACjE,CAAC;gBACD;+CAC+B;gBAC/B,gBAAgB,GAAG,IAAI,CAAC;gBACxB,MAAM,CAAC,IAAI,CAAC,QAAQ,EAAE,MAAM,CAAC,CAAC;YAChC,CAAC;SACF,CAAC,CAAC;QACH,OAAO,MAAM,CAAC;IAChB,CAAC;CACF;AAnlBD,wBAmlBC"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/compression-algorithms.d.ts b/node_modules/@grpc/grpc-js/build/src/compression-algorithms.d.ts new file mode 100644 index 0000000..555b222 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/compression-algorithms.d.ts @@ -0,0 +1,5 @@ +export declare enum CompressionAlgorithms { + identity = 0, + deflate = 1, + gzip = 2 +} diff --git a/node_modules/@grpc/grpc-js/build/src/compression-algorithms.js b/node_modules/@grpc/grpc-js/build/src/compression-algorithms.js new file mode 100644 index 0000000..15a4f00 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/compression-algorithms.js @@ -0,0 +1,26 @@ +"use strict"; +/* + * Copyright 2021 gRPC authors. + * + * 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. + * + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.CompressionAlgorithms = void 0; +var CompressionAlgorithms; +(function (CompressionAlgorithms) { + CompressionAlgorithms[CompressionAlgorithms["identity"] = 0] = "identity"; + CompressionAlgorithms[CompressionAlgorithms["deflate"] = 1] = "deflate"; + CompressionAlgorithms[CompressionAlgorithms["gzip"] = 2] = "gzip"; +})(CompressionAlgorithms || (exports.CompressionAlgorithms = CompressionAlgorithms = {})); +//# sourceMappingURL=compression-algorithms.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/compression-algorithms.js.map b/node_modules/@grpc/grpc-js/build/src/compression-algorithms.js.map new file mode 100644 index 0000000..760772f --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/compression-algorithms.js.map @@ -0,0 +1 @@ +{"version":3,"file":"compression-algorithms.js","sourceRoot":"","sources":["../../src/compression-algorithms.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;GAeG;;;AAEH,IAAY,qBAIX;AAJD,WAAY,qBAAqB;IAC/B,yEAAY,CAAA;IACZ,uEAAW,CAAA;IACX,iEAAQ,CAAA;AACV,CAAC,EAJW,qBAAqB,qCAArB,qBAAqB,QAIhC"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/compression-filter.d.ts b/node_modules/@grpc/grpc-js/build/src/compression-filter.d.ts new file mode 100644 index 0000000..87926f5 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/compression-filter.d.ts @@ -0,0 +1,27 @@ +/// +import { WriteObject } from './call-interface'; +import { Channel } from './channel'; +import { ChannelOptions } from './channel-options'; +import { BaseFilter, Filter, FilterFactory } from './filter'; +import { Metadata } from './metadata'; +type SharedCompressionFilterConfig = { + serverSupportedEncodingHeader?: string; +}; +export declare class CompressionFilter extends BaseFilter implements Filter { + private sharedFilterConfig; + private sendCompression; + private receiveCompression; + private currentCompressionAlgorithm; + constructor(channelOptions: ChannelOptions, sharedFilterConfig: SharedCompressionFilterConfig); + sendMetadata(metadata: Promise): Promise; + receiveMetadata(metadata: Metadata): Metadata; + sendMessage(message: Promise): Promise; + receiveMessage(message: Promise): Promise; +} +export declare class CompressionFilterFactory implements FilterFactory { + private readonly options; + private sharedFilterConfig; + constructor(channel: Channel, options: ChannelOptions); + createFilter(): CompressionFilter; +} +export {}; diff --git a/node_modules/@grpc/grpc-js/build/src/compression-filter.js b/node_modules/@grpc/grpc-js/build/src/compression-filter.js new file mode 100644 index 0000000..483b153 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/compression-filter.js @@ -0,0 +1,257 @@ +"use strict"; +/* + * Copyright 2019 gRPC authors. + * + * 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. + * + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.CompressionFilterFactory = exports.CompressionFilter = void 0; +const zlib = require("zlib"); +const compression_algorithms_1 = require("./compression-algorithms"); +const constants_1 = require("./constants"); +const filter_1 = require("./filter"); +const logging = require("./logging"); +const isCompressionAlgorithmKey = (key) => { + return (typeof key === 'number' && typeof compression_algorithms_1.CompressionAlgorithms[key] === 'string'); +}; +class CompressionHandler { + /** + * @param message Raw uncompressed message bytes + * @param compress Indicates whether the message should be compressed + * @return Framed message, compressed if applicable + */ + async writeMessage(message, compress) { + let messageBuffer = message; + if (compress) { + messageBuffer = await this.compressMessage(messageBuffer); + } + const output = Buffer.allocUnsafe(messageBuffer.length + 5); + output.writeUInt8(compress ? 1 : 0, 0); + output.writeUInt32BE(messageBuffer.length, 1); + messageBuffer.copy(output, 5); + return output; + } + /** + * @param data Framed message, possibly compressed + * @return Uncompressed message + */ + async readMessage(data) { + const compressed = data.readUInt8(0) === 1; + let messageBuffer = data.slice(5); + if (compressed) { + messageBuffer = await this.decompressMessage(messageBuffer); + } + return messageBuffer; + } +} +class IdentityHandler extends CompressionHandler { + async compressMessage(message) { + return message; + } + async writeMessage(message, compress) { + const output = Buffer.allocUnsafe(message.length + 5); + /* With "identity" compression, messages should always be marked as + * uncompressed */ + output.writeUInt8(0, 0); + output.writeUInt32BE(message.length, 1); + message.copy(output, 5); + return output; + } + decompressMessage(message) { + return Promise.reject(new Error('Received compressed message but "grpc-encoding" header was identity')); + } +} +class DeflateHandler extends CompressionHandler { + compressMessage(message) { + return new Promise((resolve, reject) => { + zlib.deflate(message, (err, output) => { + if (err) { + reject(err); + } + else { + resolve(output); + } + }); + }); + } + decompressMessage(message) { + return new Promise((resolve, reject) => { + zlib.inflate(message, (err, output) => { + if (err) { + reject(err); + } + else { + resolve(output); + } + }); + }); + } +} +class GzipHandler extends CompressionHandler { + compressMessage(message) { + return new Promise((resolve, reject) => { + zlib.gzip(message, (err, output) => { + if (err) { + reject(err); + } + else { + resolve(output); + } + }); + }); + } + decompressMessage(message) { + return new Promise((resolve, reject) => { + zlib.unzip(message, (err, output) => { + if (err) { + reject(err); + } + else { + resolve(output); + } + }); + }); + } +} +class UnknownHandler extends CompressionHandler { + constructor(compressionName) { + super(); + this.compressionName = compressionName; + } + compressMessage(message) { + return Promise.reject(new Error(`Received message compressed with unsupported compression method ${this.compressionName}`)); + } + decompressMessage(message) { + // This should be unreachable + return Promise.reject(new Error(`Compression method not supported: ${this.compressionName}`)); + } +} +function getCompressionHandler(compressionName) { + switch (compressionName) { + case 'identity': + return new IdentityHandler(); + case 'deflate': + return new DeflateHandler(); + case 'gzip': + return new GzipHandler(); + default: + return new UnknownHandler(compressionName); + } +} +class CompressionFilter extends filter_1.BaseFilter { + constructor(channelOptions, sharedFilterConfig) { + var _a; + super(); + this.sharedFilterConfig = sharedFilterConfig; + this.sendCompression = new IdentityHandler(); + this.receiveCompression = new IdentityHandler(); + this.currentCompressionAlgorithm = 'identity'; + const compressionAlgorithmKey = channelOptions['grpc.default_compression_algorithm']; + if (compressionAlgorithmKey !== undefined) { + if (isCompressionAlgorithmKey(compressionAlgorithmKey)) { + const clientSelectedEncoding = compression_algorithms_1.CompressionAlgorithms[compressionAlgorithmKey]; + const serverSupportedEncodings = (_a = sharedFilterConfig.serverSupportedEncodingHeader) === null || _a === void 0 ? void 0 : _a.split(','); + /** + * There are two possible situations here: + * 1) We don't have any info yet from the server about what compression it supports + * In that case we should just use what the client tells us to use + * 2) We've previously received a response from the server including a grpc-accept-encoding header + * In that case we only want to use the encoding chosen by the client if the server supports it + */ + if (!serverSupportedEncodings || + serverSupportedEncodings.includes(clientSelectedEncoding)) { + this.currentCompressionAlgorithm = clientSelectedEncoding; + this.sendCompression = getCompressionHandler(this.currentCompressionAlgorithm); + } + } + else { + logging.log(constants_1.LogVerbosity.ERROR, `Invalid value provided for grpc.default_compression_algorithm option: ${compressionAlgorithmKey}`); + } + } + } + async sendMetadata(metadata) { + const headers = await metadata; + headers.set('grpc-accept-encoding', 'identity,deflate,gzip'); + headers.set('accept-encoding', 'identity'); + // No need to send the header if it's "identity" - behavior is identical; save the bandwidth + if (this.currentCompressionAlgorithm === 'identity') { + headers.remove('grpc-encoding'); + } + else { + headers.set('grpc-encoding', this.currentCompressionAlgorithm); + } + return headers; + } + receiveMetadata(metadata) { + const receiveEncoding = metadata.get('grpc-encoding'); + if (receiveEncoding.length > 0) { + const encoding = receiveEncoding[0]; + if (typeof encoding === 'string') { + this.receiveCompression = getCompressionHandler(encoding); + } + } + metadata.remove('grpc-encoding'); + /* Check to see if the compression we're using to send messages is supported by the server + * If not, reset the sendCompression filter and have it use the default IdentityHandler */ + const serverSupportedEncodingsHeader = metadata.get('grpc-accept-encoding')[0]; + if (serverSupportedEncodingsHeader) { + this.sharedFilterConfig.serverSupportedEncodingHeader = + serverSupportedEncodingsHeader; + const serverSupportedEncodings = serverSupportedEncodingsHeader.split(','); + if (!serverSupportedEncodings.includes(this.currentCompressionAlgorithm)) { + this.sendCompression = new IdentityHandler(); + this.currentCompressionAlgorithm = 'identity'; + } + } + metadata.remove('grpc-accept-encoding'); + return metadata; + } + async sendMessage(message) { + var _a; + /* This filter is special. The input message is the bare message bytes, + * and the output is a framed and possibly compressed message. For this + * reason, this filter should be at the bottom of the filter stack */ + const resolvedMessage = await message; + let compress; + if (this.sendCompression instanceof IdentityHandler) { + compress = false; + } + else { + compress = (((_a = resolvedMessage.flags) !== null && _a !== void 0 ? _a : 0) & 2 /* WriteFlags.NoCompress */) === 0; + } + return { + message: await this.sendCompression.writeMessage(resolvedMessage.message, compress), + flags: resolvedMessage.flags, + }; + } + async receiveMessage(message) { + /* This filter is also special. The input message is framed and possibly + * compressed, and the output message is deframed and uncompressed. So + * this is another reason that this filter should be at the bottom of the + * filter stack. */ + return this.receiveCompression.readMessage(await message); + } +} +exports.CompressionFilter = CompressionFilter; +class CompressionFilterFactory { + constructor(channel, options) { + this.options = options; + this.sharedFilterConfig = {}; + } + createFilter() { + return new CompressionFilter(this.options, this.sharedFilterConfig); + } +} +exports.CompressionFilterFactory = CompressionFilterFactory; +//# sourceMappingURL=compression-filter.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/compression-filter.js.map b/node_modules/@grpc/grpc-js/build/src/compression-filter.js.map new file mode 100644 index 0000000..2c94620 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/compression-filter.js.map @@ -0,0 +1 @@ +{"version":3,"file":"compression-filter.js","sourceRoot":"","sources":["../../src/compression-filter.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;GAeG;;;AAEH,6BAA6B;AAK7B,qEAAiE;AACjE,2CAA2C;AAC3C,qCAA6D;AAC7D,qCAAqC;A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git a/node_modules/@grpc/grpc-js/build/src/connectivity-state.d.ts b/node_modules/@grpc/grpc-js/build/src/connectivity-state.d.ts new file mode 100644 index 0000000..048ea39 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/connectivity-state.d.ts @@ -0,0 +1,7 @@ +export declare enum ConnectivityState { + IDLE = 0, + CONNECTING = 1, + READY = 2, + TRANSIENT_FAILURE = 3, + SHUTDOWN = 4 +} diff --git a/node_modules/@grpc/grpc-js/build/src/connectivity-state.js b/node_modules/@grpc/grpc-js/build/src/connectivity-state.js new file mode 100644 index 0000000..c8540b0 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/connectivity-state.js @@ -0,0 +1,28 @@ +"use strict"; +/* + * Copyright 2021 gRPC authors. + * + * 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. + * + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ConnectivityState = void 0; +var ConnectivityState; +(function (ConnectivityState) { + ConnectivityState[ConnectivityState["IDLE"] = 0] = "IDLE"; + ConnectivityState[ConnectivityState["CONNECTING"] = 1] = "CONNECTING"; + ConnectivityState[ConnectivityState["READY"] = 2] = "READY"; + ConnectivityState[ConnectivityState["TRANSIENT_FAILURE"] = 3] = "TRANSIENT_FAILURE"; + ConnectivityState[ConnectivityState["SHUTDOWN"] = 4] = "SHUTDOWN"; +})(ConnectivityState || (exports.ConnectivityState = ConnectivityState = {})); +//# sourceMappingURL=connectivity-state.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/connectivity-state.js.map b/node_modules/@grpc/grpc-js/build/src/connectivity-state.js.map new file mode 100644 index 0000000..1afc24d --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/connectivity-state.js.map @@ -0,0 +1 @@ +{"version":3,"file":"connectivity-state.js","sourceRoot":"","sources":["../../src/connectivity-state.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;GAeG;;;AAEH,IAAY,iBAMX;AAND,WAAY,iBAAiB;IAC3B,yDAAI,CAAA;IACJ,qEAAU,CAAA;IACV,2DAAK,CAAA;IACL,mFAAiB,CAAA;IACjB,iEAAQ,CAAA;AACV,CAAC,EANW,iBAAiB,iCAAjB,iBAAiB,QAM5B"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/constants.d.ts b/node_modules/@grpc/grpc-js/build/src/constants.d.ts new file mode 100644 index 0000000..43ec358 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/constants.d.ts @@ -0,0 +1,38 @@ +export declare enum Status { + OK = 0, + CANCELLED = 1, + UNKNOWN = 2, + INVALID_ARGUMENT = 3, + DEADLINE_EXCEEDED = 4, + NOT_FOUND = 5, + ALREADY_EXISTS = 6, + PERMISSION_DENIED = 7, + RESOURCE_EXHAUSTED = 8, + FAILED_PRECONDITION = 9, + ABORTED = 10, + OUT_OF_RANGE = 11, + UNIMPLEMENTED = 12, + INTERNAL = 13, + UNAVAILABLE = 14, + DATA_LOSS = 15, + UNAUTHENTICATED = 16 +} +export declare enum LogVerbosity { + DEBUG = 0, + INFO = 1, + ERROR = 2, + NONE = 3 +} +/** + * NOTE: This enum is not currently used in any implemented API in this + * library. It is included only for type parity with the other implementation. + */ +export declare enum Propagate { + DEADLINE = 1, + CENSUS_STATS_CONTEXT = 2, + CENSUS_TRACING_CONTEXT = 4, + CANCELLATION = 8, + DEFAULTS = 65535 +} +export declare const DEFAULT_MAX_SEND_MESSAGE_LENGTH = -1; +export declare const DEFAULT_MAX_RECEIVE_MESSAGE_LENGTH: number; diff --git a/node_modules/@grpc/grpc-js/build/src/constants.js b/node_modules/@grpc/grpc-js/build/src/constants.js new file mode 100644 index 0000000..6e6b8ed --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/constants.js @@ -0,0 +1,64 @@ +"use strict"; +/* + * Copyright 2019 gRPC authors. + * + * 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. + * + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.DEFAULT_MAX_RECEIVE_MESSAGE_LENGTH = exports.DEFAULT_MAX_SEND_MESSAGE_LENGTH = exports.Propagate = exports.LogVerbosity = exports.Status = void 0; +var Status; +(function (Status) { + Status[Status["OK"] = 0] = "OK"; + Status[Status["CANCELLED"] = 1] = "CANCELLED"; + Status[Status["UNKNOWN"] = 2] = "UNKNOWN"; + Status[Status["INVALID_ARGUMENT"] = 3] = "INVALID_ARGUMENT"; + Status[Status["DEADLINE_EXCEEDED"] = 4] = "DEADLINE_EXCEEDED"; + Status[Status["NOT_FOUND"] = 5] = "NOT_FOUND"; + Status[Status["ALREADY_EXISTS"] = 6] = "ALREADY_EXISTS"; + Status[Status["PERMISSION_DENIED"] = 7] = "PERMISSION_DENIED"; + Status[Status["RESOURCE_EXHAUSTED"] = 8] = "RESOURCE_EXHAUSTED"; + Status[Status["FAILED_PRECONDITION"] = 9] = "FAILED_PRECONDITION"; + Status[Status["ABORTED"] = 10] = "ABORTED"; + Status[Status["OUT_OF_RANGE"] = 11] = "OUT_OF_RANGE"; + Status[Status["UNIMPLEMENTED"] = 12] = "UNIMPLEMENTED"; + Status[Status["INTERNAL"] = 13] = "INTERNAL"; + Status[Status["UNAVAILABLE"] = 14] = "UNAVAILABLE"; + Status[Status["DATA_LOSS"] = 15] = "DATA_LOSS"; + Status[Status["UNAUTHENTICATED"] = 16] = "UNAUTHENTICATED"; +})(Status || (exports.Status = Status = {})); +var LogVerbosity; +(function (LogVerbosity) { + LogVerbosity[LogVerbosity["DEBUG"] = 0] = "DEBUG"; + LogVerbosity[LogVerbosity["INFO"] = 1] = "INFO"; + LogVerbosity[LogVerbosity["ERROR"] = 2] = "ERROR"; + LogVerbosity[LogVerbosity["NONE"] = 3] = "NONE"; +})(LogVerbosity || (exports.LogVerbosity = LogVerbosity = {})); +/** + * NOTE: This enum is not currently used in any implemented API in this + * library. It is included only for type parity with the other implementation. + */ +var Propagate; +(function (Propagate) { + Propagate[Propagate["DEADLINE"] = 1] = "DEADLINE"; + Propagate[Propagate["CENSUS_STATS_CONTEXT"] = 2] = "CENSUS_STATS_CONTEXT"; + Propagate[Propagate["CENSUS_TRACING_CONTEXT"] = 4] = "CENSUS_TRACING_CONTEXT"; + Propagate[Propagate["CANCELLATION"] = 8] = "CANCELLATION"; + // https://github.com/grpc/grpc/blob/master/include/grpc/impl/codegen/propagation_bits.h#L43 + Propagate[Propagate["DEFAULTS"] = 65535] = "DEFAULTS"; +})(Propagate || (exports.Propagate = Propagate = {})); +// -1 means unlimited +exports.DEFAULT_MAX_SEND_MESSAGE_LENGTH = -1; +// 4 MB default +exports.DEFAULT_MAX_RECEIVE_MESSAGE_LENGTH = 4 * 1024 * 1024; +//# sourceMappingURL=constants.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/constants.js.map b/node_modules/@grpc/grpc-js/build/src/constants.js.map new file mode 100644 index 0000000..a3c5c87 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/constants.js.map @@ -0,0 +1 @@ +{"version":3,"file":"constants.js","sourceRoot":"","sources":["../../src/constants.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;GAeG;;;AAEH,IAAY,MAkBX;AAlBD,WAAY,MAAM;IAChB,+BAAM,CAAA;IACN,6CAAS,CAAA;IACT,yCAAO,CAAA;IACP,2DAAgB,CAAA;IAChB,6DAAiB,CAAA;IACjB,6CAAS,CAAA;IACT,uDAAc,CAAA;IACd,6DAAiB,CAAA;IACjB,+DAAkB,CAAA;IAClB,iEAAmB,CAAA;IACnB,0CAAO,CAAA;IACP,oDAAY,CAAA;IACZ,sDAAa,CAAA;IACb,4CAAQ,CAAA;IACR,kDAAW,CAAA;IACX,8CAAS,CAAA;IACT,0DAAe,CAAA;AACjB,CAAC,EAlBW,MAAM,sBAAN,MAAM,QAkBjB;AAED,IAAY,YAKX;AALD,WAAY,YAAY;IACtB,iDAAS,CAAA;IACT,+CAAI,CAAA;IACJ,iDAAK,CAAA;IACL,+CAAI,CAAA;AACN,CAAC,EALW,YAAY,4BAAZ,YAAY,QAKvB;AAED;;;GAGG;AACH,IAAY,SAWX;AAXD,WAAY,SAAS;IACnB,iDAAY,CAAA;IACZ,yEAAwB,CAAA;IACxB,6EAA0B,CAAA;IAC1B,yDAAgB,CAAA;IAChB,4FAA4F;IAC5F,qDAIwB,CAAA;AAC1B,CAAC,EAXW,SAAS,yBAAT,SAAS,QAWpB;AAED,qBAAqB;AACR,QAAA,+BAA+B,GAAG,CAAC,CAAC,CAAC;AAElD,eAAe;AACF,QAAA,kCAAkC,GAAG,CAAC,GAAG,IAAI,GAAG,IAAI,CAAC"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/control-plane-status.d.ts b/node_modules/@grpc/grpc-js/build/src/control-plane-status.d.ts new file mode 100644 index 0000000..a137cab --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/control-plane-status.d.ts @@ -0,0 +1,5 @@ +import { Status } from './constants'; +export declare function restrictControlPlaneStatusCode(code: Status, details: string): { + code: Status; + details: string; +}; diff --git a/node_modules/@grpc/grpc-js/build/src/control-plane-status.js b/node_modules/@grpc/grpc-js/build/src/control-plane-status.js new file mode 100644 index 0000000..dc41cb2 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/control-plane-status.js @@ -0,0 +1,43 @@ +"use strict"; +/* + * Copyright 2022 gRPC authors. + * + * 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. + * + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.restrictControlPlaneStatusCode = void 0; +const constants_1 = require("./constants"); +const INAPPROPRIATE_CONTROL_PLANE_CODES = [ + constants_1.Status.OK, + constants_1.Status.INVALID_ARGUMENT, + constants_1.Status.NOT_FOUND, + constants_1.Status.ALREADY_EXISTS, + constants_1.Status.FAILED_PRECONDITION, + constants_1.Status.ABORTED, + constants_1.Status.OUT_OF_RANGE, + constants_1.Status.DATA_LOSS, +]; +function restrictControlPlaneStatusCode(code, details) { + if (INAPPROPRIATE_CONTROL_PLANE_CODES.includes(code)) { + return { + code: constants_1.Status.INTERNAL, + details: `Invalid status from control plane: ${code} ${constants_1.Status[code]} ${details}`, + }; + } + else { + return { code, details }; + } +} +exports.restrictControlPlaneStatusCode = restrictControlPlaneStatusCode; +//# sourceMappingURL=control-plane-status.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/control-plane-status.js.map b/node_modules/@grpc/grpc-js/build/src/control-plane-status.js.map new file mode 100644 index 0000000..297ca91 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/control-plane-status.js.map @@ -0,0 +1 @@ +{"version":3,"file":"control-plane-status.js","sourceRoot":"","sources":["../../src/control-plane-status.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;GAeG;;;AAEH,2CAAqC;AAErC,MAAM,iCAAiC,GAAa;IAClD,kBAAM,CAAC,EAAE;IACT,kBAAM,CAAC,gBAAgB;IACvB,kBAAM,CAAC,SAAS;IAChB,kBAAM,CAAC,cAAc;IACrB,kBAAM,CAAC,mBAAmB;IAC1B,kBAAM,CAAC,OAAO;IACd,kBAAM,CAAC,YAAY;IACnB,kBAAM,CAAC,SAAS;CACjB,CAAC;AAEF,SAAgB,8BAA8B,CAC5C,IAAY,EACZ,OAAe;IAEf,IAAI,iCAAiC,CAAC,QAAQ,CAAC,IAAI,CAAC,EAAE,CAAC;QACrD,OAAO;YACL,IAAI,EAAE,kBAAM,CAAC,QAAQ;YACrB,OAAO,EAAE,sCAAsC,IAAI,IAAI,kBAAM,CAAC,IAAI,CAAC,IAAI,OAAO,EAAE;SACjF,CAAC;IACJ,CAAC;SAAM,CAAC;QACN,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,CAAC;IAC3B,CAAC;AACH,CAAC;AAZD,wEAYC"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/deadline.d.ts b/node_modules/@grpc/grpc-js/build/src/deadline.d.ts new file mode 100644 index 0000000..63db6af --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/deadline.d.ts @@ -0,0 +1,22 @@ +export type Deadline = Date | number; +export declare function minDeadline(...deadlineList: Deadline[]): Deadline; +export declare function getDeadlineTimeoutString(deadline: Deadline): string; +/** + * Get the timeout value that should be passed to setTimeout now for the timer + * to end at the deadline. For any deadline before now, the timer should end + * immediately, represented by a value of 0. For any deadline more than + * MAX_TIMEOUT_TIME milliseconds in the future, a timer cannot be set that will + * end at that time, so it is treated as infinitely far in the future. + * @param deadline + * @returns + */ +export declare function getRelativeTimeout(deadline: Deadline): number; +export declare function deadlineToString(deadline: Deadline): string; +/** + * Calculate the difference between two dates as a number of seconds and format + * it as a string. + * @param startDate + * @param endDate + * @returns + */ +export declare function formatDateDifference(startDate: Date, endDate: Date): string; diff --git a/node_modules/@grpc/grpc-js/build/src/deadline.js b/node_modules/@grpc/grpc-js/build/src/deadline.js new file mode 100644 index 0000000..3468c7c --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/deadline.js @@ -0,0 +1,109 @@ +"use strict"; +/* + * Copyright 2019 gRPC authors. + * + * 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. + * + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.formatDateDifference = exports.deadlineToString = exports.getRelativeTimeout = exports.getDeadlineTimeoutString = exports.minDeadline = void 0; +function minDeadline(...deadlineList) { + let minValue = Infinity; + for (const deadline of deadlineList) { + const deadlineMsecs = deadline instanceof Date ? deadline.getTime() : deadline; + if (deadlineMsecs < minValue) { + minValue = deadlineMsecs; + } + } + return minValue; +} +exports.minDeadline = minDeadline; +const units = [ + ['m', 1], + ['S', 1000], + ['M', 60 * 1000], + ['H', 60 * 60 * 1000], +]; +function getDeadlineTimeoutString(deadline) { + const now = new Date().getTime(); + if (deadline instanceof Date) { + deadline = deadline.getTime(); + } + const timeoutMs = Math.max(deadline - now, 0); + for (const [unit, factor] of units) { + const amount = timeoutMs / factor; + if (amount < 1e8) { + return String(Math.ceil(amount)) + unit; + } + } + throw new Error('Deadline is too far in the future'); +} +exports.getDeadlineTimeoutString = getDeadlineTimeoutString; +/** + * See https://nodejs.org/api/timers.html#settimeoutcallback-delay-args + * In particular, "When delay is larger than 2147483647 or less than 1, the + * delay will be set to 1. Non-integer delays are truncated to an integer." + * This number of milliseconds is almost 25 days. + */ +const MAX_TIMEOUT_TIME = 2147483647; +/** + * Get the timeout value that should be passed to setTimeout now for the timer + * to end at the deadline. For any deadline before now, the timer should end + * immediately, represented by a value of 0. For any deadline more than + * MAX_TIMEOUT_TIME milliseconds in the future, a timer cannot be set that will + * end at that time, so it is treated as infinitely far in the future. + * @param deadline + * @returns + */ +function getRelativeTimeout(deadline) { + const deadlineMs = deadline instanceof Date ? deadline.getTime() : deadline; + const now = new Date().getTime(); + const timeout = deadlineMs - now; + if (timeout < 0) { + return 0; + } + else if (timeout > MAX_TIMEOUT_TIME) { + return Infinity; + } + else { + return timeout; + } +} +exports.getRelativeTimeout = getRelativeTimeout; +function deadlineToString(deadline) { + if (deadline instanceof Date) { + return deadline.toISOString(); + } + else { + const dateDeadline = new Date(deadline); + if (Number.isNaN(dateDeadline.getTime())) { + return '' + deadline; + } + else { + return dateDeadline.toISOString(); + } + } +} +exports.deadlineToString = deadlineToString; +/** + * Calculate the difference between two dates as a number of seconds and format + * it as a string. + * @param startDate + * @param endDate + * @returns + */ +function formatDateDifference(startDate, endDate) { + return ((endDate.getTime() - startDate.getTime()) / 1000).toFixed(3) + 's'; +} +exports.formatDateDifference = formatDateDifference; +//# sourceMappingURL=deadline.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/deadline.js.map b/node_modules/@grpc/grpc-js/build/src/deadline.js.map new file mode 100644 index 0000000..b02fad9 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/deadline.js.map @@ -0,0 +1 @@ +{"version":3,"file":"deadline.js","sourceRoot":"","sources":["../../src/deadline.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;GAeG;;;AAIH,SAAgB,WAAW,CAAC,GAAG,YAAwB;IACrD,IAAI,QAAQ,GAAG,QAAQ,CAAC;IACxB,KAAK,MAAM,QAAQ,IAAI,YAAY,EAAE,CAAC;QACpC,MAAM,aAAa,GACjB,QAAQ,YAAY,IAAI,CAAC,CAAC,CAAC,QAAQ,CAAC,OAAO,EAAE,CAAC,CAAC,CAAC,QAAQ,CAAC;QAC3D,IAAI,aAAa,GAAG,QAAQ,EAAE,CAAC;YAC7B,QAAQ,GAAG,aAAa,CAAC;QAC3B,CAAC;IACH,CAAC;IACD,OAAO,QAAQ,CAAC;AAClB,CAAC;AAVD,kCAUC;AAED,MAAM,KAAK,GAA4B;IACrC,CAAC,GAAG,EAAE,CAAC,CAAC;IACR,CAAC,GAAG,EAAE,IAAI,CAAC;IACX,CAAC,GAAG,EAAE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AClB,CAAC;SAAM,CAAC;QACN,OAAO,OAAO,CAAC;IACjB,CAAC;AACH,CAAC;AAXD,gDAWC;AAED,SAAgB,gBAAgB,CAAC,QAAkB;IACjD,IAAI,QAAQ,YAAY,IAAI,EAAE,CAAC;QAC7B,OAAO,QAAQ,CAAC,WAAW,EAAE,CAAC;IAChC,CAAC;SAAM,CAAC;QACN,MAAM,YAAY,GAAG,IAAI,IAAI,CAAC,QAAQ,CAAC,CAAC;QACxC,IAAI,MAAM,CAAC,KAAK,CAAC,YAAY,CAAC,OAAO,EAAE,CAAC,EAAE,CAAC;YACzC,OAAO,EAAE,GAAG,QAAQ,CAAC;QACvB,CAAC;aAAM,CAAC;YACN,OAAO,YAAY,CAAC,WAAW,EAAE,CAAC;QACpC,CAAC;IACH,CAAC;AACH,CAAC;AAXD,4CAWC;AAED;;;;;;GAMG;AACH,SAAgB,oBAAoB,CAAC,SAAe,EAAE,OAAa;IACjE,OAAO,CAAC,CAAC,OAAO,CAAC,OAAO,EAAE,GAAG,SAAS,CAAC,OAAO,EAAE,CAAC,GAAG,IAAI,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,GAAG,GAAG,CAAC;AAC7E,CAAC;AAFD,oDAEC"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/duration.d.ts b/node_modules/@grpc/grpc-js/build/src/duration.d.ts new file mode 100644 index 0000000..923159b --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/duration.d.ts @@ -0,0 +1,7 @@ +export interface Duration { + seconds: number; + nanos: number; +} +export declare function msToDuration(millis: number): Duration; +export declare function durationToMs(duration: Duration): number; +export declare function isDuration(value: any): value is Duration; diff --git a/node_modules/@grpc/grpc-js/build/src/duration.js b/node_modules/@grpc/grpc-js/build/src/duration.js new file mode 100644 index 0000000..3ac1d21 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/duration.js @@ -0,0 +1,35 @@ +"use strict"; +/* + * Copyright 2022 gRPC authors. + * + * 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. + * + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.isDuration = exports.durationToMs = exports.msToDuration = void 0; +function msToDuration(millis) { + return { + seconds: (millis / 1000) | 0, + nanos: ((millis % 1000) * 1000000) | 0, + }; +} +exports.msToDuration = msToDuration; +function durationToMs(duration) { + return (duration.seconds * 1000 + duration.nanos / 1000000) | 0; +} +exports.durationToMs = durationToMs; +function isDuration(value) { + return typeof value.seconds === 'number' && typeof value.nanos === 'number'; +} +exports.isDuration = isDuration; +//# sourceMappingURL=duration.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/duration.js.map b/node_modules/@grpc/grpc-js/build/src/duration.js.map new file mode 100644 index 0000000..3be3631 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/duration.js.map @@ -0,0 +1 @@ +{"version":3,"file":"duration.js","sourceRoot":"","sources":["../../src/duration.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;GAeG;;;AAOH,SAAgB,YAAY,CAAC,MAAc;IACzC,OAAO;QACL,OAAO,EAAE,CAAC,MAAM,GAAG,IAAI,CAAC,GAAG,CAAC;QAC5B,KAAK,EAAE,CAAC,CAAC,MAAM,GAAG,IAAI,CAAC,GAAG,OAAS,CAAC,GAAG,CAAC;KACzC,CAAC;AACJ,CAAC;AALD,oCAKC;AAED,SAAgB,YAAY,CAAC,QAAkB;IAC7C,OAAO,CAAC,QAAQ,CAAC,OAAO,GAAG,IAAI,GAAG,QAAQ,CAAC,KAAK,GAAG,OAAS,CAAC,GAAG,CAAC,CAAC;AACpE,CAAC;AAFD,oCAEC;AAED,SAAgB,UAAU,CAAC,KAAU;IACnC,OAAO,OAAO,KAAK,CAAC,OAAO,KAAK,QAAQ,IAAI,OAAO,KAAK,CAAC,KAAK,KAAK,QAAQ,CAAC;AAC9E,CAAC;AAFD,gCAEC"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/error.d.ts b/node_modules/@grpc/grpc-js/build/src/error.d.ts new file mode 100644 index 0000000..fd4cc77 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/error.d.ts @@ -0,0 +1,2 @@ +export declare function getErrorMessage(error: unknown): string; +export declare function getErrorCode(error: unknown): number | null; diff --git a/node_modules/@grpc/grpc-js/build/src/error.js b/node_modules/@grpc/grpc-js/build/src/error.js new file mode 100644 index 0000000..c842333 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/error.js @@ -0,0 +1,41 @@ +"use strict"; +/* + * Copyright 2022 gRPC authors. + * + * 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. + * + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.getErrorCode = exports.getErrorMessage = void 0; +function getErrorMessage(error) { + if (error instanceof Error) { + return error.message; + } + else { + return String(error); + } +} +exports.getErrorMessage = getErrorMessage; +function getErrorCode(error) { + if (typeof error === 'object' && + error !== null && + 'code' in error && + typeof error.code === 'number') { + return error.code; + } + else { + return null; + } +} +exports.getErrorCode = getErrorCode; +//# sourceMappingURL=error.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/error.js.map b/node_modules/@grpc/grpc-js/build/src/error.js.map new file mode 100644 index 0000000..192891c --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/error.js.map @@ -0,0 +1 @@ +{"version":3,"file":"error.js","sourceRoot":"","sources":["../../src/error.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;GAeG;;;AAEH,SAAgB,eAAe,CAAC,KAAc;IAC5C,IAAI,KAAK,YAAY,KAAK,EAAE,CAAC;QAC3B,OAAO,KAAK,CAAC,OAAO,CAAC;IACvB,CAAC;SAAM,CAAC;QACN,OAAO,MAAM,CAAC,KAAK,CAAC,CAAC;IACvB,CAAC;AACH,CAAC;AAND,0CAMC;AAED,SAAgB,YAAY,CAAC,KAAc;IACzC,IACE,OAAO,KAAK,KAAK,QAAQ;QACzB,KAAK,KAAK,IAAI;QACd,MAAM,IAAI,KAAK;QACf,OAAQ,KAAiC,CAAC,IAAI,KAAK,QAAQ,EAC3D,CAAC;QACD,OAAQ,KAAgC,CAAC,IAAI,CAAC;IAChD,CAAC;SAAM,CAAC;QACN,OAAO,IAAI,CAAC;IACd,CAAC;AACH,CAAC;AAXD,oCAWC"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/events.d.ts b/node_modules/@grpc/grpc-js/build/src/events.d.ts new file mode 100644 index 0000000..d1a764e --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/events.d.ts @@ -0,0 +1,9 @@ +export interface EmitterAugmentation1 { + addListener(event: Name, listener: (arg1: Arg) => void): this; + emit(event: Name, arg1: Arg): boolean; + on(event: Name, listener: (arg1: Arg) => void): this; + once(event: Name, listener: (arg1: Arg) => void): this; + prependListener(event: Name, listener: (arg1: Arg) => void): this; + prependOnceListener(event: Name, listener: (arg1: Arg) => void): this; + removeListener(event: Name, listener: (arg1: Arg) => void): this; +} diff --git a/node_modules/@grpc/grpc-js/build/src/events.js b/node_modules/@grpc/grpc-js/build/src/events.js new file mode 100644 index 0000000..082ed9b --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/events.js @@ -0,0 +1,19 @@ +"use strict"; +/* + * Copyright 2019 gRPC authors. + * + * 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. + * + */ +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=events.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/events.js.map b/node_modules/@grpc/grpc-js/build/src/events.js.map new file mode 100644 index 0000000..ba39b5d --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/events.js.map @@ -0,0 +1 @@ +{"version":3,"file":"events.js","sourceRoot":"","sources":["../../src/events.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;GAeG"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/experimental.d.ts b/node_modules/@grpc/grpc-js/build/src/experimental.d.ts new file mode 100644 index 0000000..8abaec6 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/experimental.d.ts @@ -0,0 +1,16 @@ +export { trace, log } from './logging'; +export { Resolver, ResolverListener, registerResolver, ConfigSelector, createResolver, } from './resolver'; +export { GrpcUri, uriToString } from './uri-parser'; +export { Duration, durationToMs } from './duration'; +export { BackoffTimeout } from './backoff-timeout'; +export { LoadBalancer, TypedLoadBalancingConfig, ChannelControlHelper, createChildChannelControlHelper, registerLoadBalancerType, selectLbConfigFromList, parseLoadBalancingConfig, isLoadBalancerNameRegistered, } from './load-balancer'; +export { LeafLoadBalancer } from './load-balancer-pick-first'; +export { SubchannelAddress, subchannelAddressToString, Endpoint, endpointToString, endpointHasAddress, EndpointMap, } from './subchannel-address'; +export { ChildLoadBalancerHandler } from './load-balancer-child-handler'; +export { Picker, UnavailablePicker, QueuePicker, PickResult, PickArgs, PickResultType, } from './picker'; +export { Call as CallStream } from './call-interface'; +export { Filter, BaseFilter, FilterFactory } from './filter'; +export { FilterStackFactory } from './filter-stack'; +export { registerAdminService } from './admin'; +export { SubchannelInterface, BaseSubchannelWrapper, ConnectivityStateListener, HealthListener, } from './subchannel-interface'; +export { OutlierDetectionRawConfig, SuccessRateEjectionConfig, FailurePercentageEjectionConfig, } from './load-balancer-outlier-detection'; diff --git a/node_modules/@grpc/grpc-js/build/src/experimental.js b/node_modules/@grpc/grpc-js/build/src/experimental.js new file mode 100644 index 0000000..caeb023 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/experimental.js @@ -0,0 +1,43 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.BaseSubchannelWrapper = exports.registerAdminService = exports.FilterStackFactory = exports.BaseFilter = exports.PickResultType = exports.QueuePicker = exports.UnavailablePicker = exports.ChildLoadBalancerHandler = exports.EndpointMap = exports.endpointHasAddress = exports.endpointToString = exports.subchannelAddressToString = exports.LeafLoadBalancer = exports.isLoadBalancerNameRegistered = exports.parseLoadBalancingConfig = exports.selectLbConfigFromList = exports.registerLoadBalancerType = exports.createChildChannelControlHelper = exports.BackoffTimeout = exports.durationToMs = exports.uriToString = exports.createResolver = exports.registerResolver = exports.log = exports.trace = void 0; +var logging_1 = require("./logging"); +Object.defineProperty(exports, "trace", { enumerable: true, get: function () { return logging_1.trace; } }); +Object.defineProperty(exports, "log", { enumerable: true, get: function () { return logging_1.log; } }); +var resolver_1 = require("./resolver"); +Object.defineProperty(exports, "registerResolver", { enumerable: true, get: function () { return resolver_1.registerResolver; } }); +Object.defineProperty(exports, "createResolver", { enumerable: true, get: function () { return resolver_1.createResolver; } }); +var uri_parser_1 = require("./uri-parser"); +Object.defineProperty(exports, "uriToString", { enumerable: true, get: function () { return uri_parser_1.uriToString; } }); +var duration_1 = require("./duration"); +Object.defineProperty(exports, "durationToMs", { enumerable: true, get: function () { return duration_1.durationToMs; } }); +var backoff_timeout_1 = require("./backoff-timeout"); +Object.defineProperty(exports, "BackoffTimeout", { enumerable: true, get: function () { return backoff_timeout_1.BackoffTimeout; } }); +var load_balancer_1 = require("./load-balancer"); +Object.defineProperty(exports, "createChildChannelControlHelper", { enumerable: true, get: function () { return load_balancer_1.createChildChannelControlHelper; } }); +Object.defineProperty(exports, "registerLoadBalancerType", { enumerable: true, get: function () { return load_balancer_1.registerLoadBalancerType; } }); +Object.defineProperty(exports, "selectLbConfigFromList", { enumerable: true, get: function () { return load_balancer_1.selectLbConfigFromList; } }); +Object.defineProperty(exports, "parseLoadBalancingConfig", { enumerable: true, get: function () { return load_balancer_1.parseLoadBalancingConfig; } }); +Object.defineProperty(exports, "isLoadBalancerNameRegistered", { enumerable: true, get: function () { return load_balancer_1.isLoadBalancerNameRegistered; } }); +var load_balancer_pick_first_1 = require("./load-balancer-pick-first"); +Object.defineProperty(exports, "LeafLoadBalancer", { enumerable: true, get: function () { return load_balancer_pick_first_1.LeafLoadBalancer; } }); +var subchannel_address_1 = require("./subchannel-address"); +Object.defineProperty(exports, "subchannelAddressToString", { enumerable: true, get: function () { return subchannel_address_1.subchannelAddressToString; } }); +Object.defineProperty(exports, "endpointToString", { enumerable: true, get: function () { return subchannel_address_1.endpointToString; } }); +Object.defineProperty(exports, "endpointHasAddress", { enumerable: true, get: function () { return subchannel_address_1.endpointHasAddress; } }); +Object.defineProperty(exports, "EndpointMap", { enumerable: true, get: function () { return subchannel_address_1.EndpointMap; } }); +var load_balancer_child_handler_1 = require("./load-balancer-child-handler"); +Object.defineProperty(exports, "ChildLoadBalancerHandler", { enumerable: true, get: function () { return load_balancer_child_handler_1.ChildLoadBalancerHandler; } }); +var picker_1 = require("./picker"); +Object.defineProperty(exports, "UnavailablePicker", { enumerable: true, get: function () { return picker_1.UnavailablePicker; } }); +Object.defineProperty(exports, "QueuePicker", { enumerable: true, get: function () { return picker_1.QueuePicker; } }); +Object.defineProperty(exports, "PickResultType", { enumerable: true, get: function () { return picker_1.PickResultType; } }); +var filter_1 = require("./filter"); +Object.defineProperty(exports, "BaseFilter", { enumerable: true, get: function () { return filter_1.BaseFilter; } }); +var filter_stack_1 = require("./filter-stack"); +Object.defineProperty(exports, "FilterStackFactory", { enumerable: true, get: function () { return filter_stack_1.FilterStackFactory; } }); +var admin_1 = require("./admin"); +Object.defineProperty(exports, "registerAdminService", { enumerable: true, get: function () { return admin_1.registerAdminService; } }); +var subchannel_interface_1 = require("./subchannel-interface"); +Object.defineProperty(exports, "BaseSubchannelWrapper", { enumerable: true, get: function () { return subchannel_interface_1.BaseSubchannelWrapper; } }); +//# sourceMappingURL=experimental.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/experimental.js.map b/node_modules/@grpc/grpc-js/build/src/experimental.js.map new file mode 100644 index 0000000..13a74bb --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/experimental.js.map @@ -0,0 +1 @@ +{"version":3,"file":"experimental.js","sourceRoot":"","sources":["../../src/experimental.ts"],"names":[],"mappings":";;;AAAA,qCAAuC;AAA9B,gGAAA,KAAK,OAAA;AAAE,8FAAA,GAAG,OAAA;AACnB,uCAMoB;AAHlB,4GAAA,gBAAgB,OAAA;AAEhB,0GAAA,cAAc,OAAA;AAEhB,2CAAoD;AAAlC,yGAAA,WAAW,OAAA;AAC7B,uCAAoD;AAAjC,wGAAA,YAAY,OAAA;AAC/B,qDAAmD;AAA1C,iHAAA,cAAc,OAAA;AACvB,iDASyB;AALvB,gIAAA,+BAA+B,OAAA;AAC/B,yHAAA,wBAAwB,OAAA;AACxB,uHAAA,sBAAsB,OAAA;AACtB,yHAAA,wBAAwB,OAAA;AACxB,6HAAA,4BAA4B,OAAA;AAE9B,uEAA8D;AAArD,4HAAA,gBAAgB,OAAA;AACzB,2DAO8B;AAL5B,+HAAA,yBAAyB,OAAA;AAEzB,sHAAA,gBAAgB,OAAA;AAChB,wHAAA,kBAAkB,OAAA;AAClB,iHAAA,WAAW,OAAA;AAEb,6EAAyE;AAAhE,uIAAA,wBAAwB,OAAA;AACjC,mCAOkB;AALhB,2GAAA,iBAAiB,OAAA;AACjB,qGAAA,WAAW,OAAA;AAGX,wGAAA,cAAc,OAAA;AAGhB,mCAA6D;AAA5C,oGAAA,UAAU,OAAA;AAC3B,+CAAoD;AAA3C,kHAAA,kBAAkB,OAAA;AAC3B,iCAA+C;AAAtC,6GAAA,oBAAoB,OAAA;AAC7B,+DAKgC;AAH9B,6HAAA,qBAAqB,OAAA"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/filter-stack.d.ts b/node_modules/@grpc/grpc-js/build/src/filter-stack.d.ts new file mode 100644 index 0000000..c3f55cc --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/filter-stack.d.ts @@ -0,0 +1,22 @@ +/// +import { StatusObject, WriteObject } from './call-interface'; +import { Filter, FilterFactory } from './filter'; +import { Metadata } from './metadata'; +export declare class FilterStack implements Filter { + private readonly filters; + constructor(filters: Filter[]); + sendMetadata(metadata: Promise): Promise; + receiveMetadata(metadata: Metadata): Metadata; + sendMessage(message: Promise): Promise; + receiveMessage(message: Promise): Promise; + receiveTrailers(status: StatusObject): StatusObject; + push(filters: Filter[]): void; + getFilters(): Filter[]; +} +export declare class FilterStackFactory implements FilterFactory { + private readonly factories; + constructor(factories: Array>); + push(filterFactories: FilterFactory[]): void; + clone(): FilterStackFactory; + createFilter(): FilterStack; +} diff --git a/node_modules/@grpc/grpc-js/build/src/filter-stack.js b/node_modules/@grpc/grpc-js/build/src/filter-stack.js new file mode 100644 index 0000000..6cf2e1a --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/filter-stack.js @@ -0,0 +1,82 @@ +"use strict"; +/* + * Copyright 2019 gRPC authors. + * + * 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. + * + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.FilterStackFactory = exports.FilterStack = void 0; +class FilterStack { + constructor(filters) { + this.filters = filters; + } + sendMetadata(metadata) { + let result = metadata; + for (let i = 0; i < this.filters.length; i++) { + result = this.filters[i].sendMetadata(result); + } + return result; + } + receiveMetadata(metadata) { + let result = metadata; + for (let i = this.filters.length - 1; i >= 0; i--) { + result = this.filters[i].receiveMetadata(result); + } + return result; + } + sendMessage(message) { + let result = message; + for (let i = 0; i < this.filters.length; i++) { + result = this.filters[i].sendMessage(result); + } + return result; + } + receiveMessage(message) { + let result = message; + for (let i = this.filters.length - 1; i >= 0; i--) { + result = this.filters[i].receiveMessage(result); + } + return result; + } + receiveTrailers(status) { + let result = status; + for (let i = this.filters.length - 1; i >= 0; i--) { + result = this.filters[i].receiveTrailers(result); + } + return result; + } + push(filters) { + this.filters.unshift(...filters); + } + getFilters() { + return this.filters; + } +} +exports.FilterStack = FilterStack; +class FilterStackFactory { + constructor(factories) { + this.factories = factories; + } + push(filterFactories) { + this.factories.unshift(...filterFactories); + } + clone() { + return new FilterStackFactory([...this.factories]); + } + createFilter() { + return new FilterStack(this.factories.map(factory => factory.createFilter())); + } +} +exports.FilterStackFactory = FilterStackFactory; +//# sourceMappingURL=filter-stack.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/filter-stack.js.map b/node_modules/@grpc/grpc-js/build/src/filter-stack.js.map new file mode 100644 index 0000000..ffbeadf --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/filter-stack.js.map @@ -0,0 +1 @@ +{"version":3,"file":"filter-stack.js","sourceRoot":"","sources":["../../src/filter-stack.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;GAeG;;;AAMH,MAAa,WAAW;IACtB,YAA6B,OAAiB;QAAjB,YAAO,GAAP,OAAO,CAAU;IAAG,CAAC;IAElD,YAAY,CAAC,QAA2B;QACtC,IAAI,MAAM,GAAsB,QAAQ,CAAC;QAEzC,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,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C,KAAK,IAAI,CAAC,GAAG,IAAI,CAAC,OAAO,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC,IAAI,CAAC,EAAE,CAAC,EAAE,EAAE,CAAC;YAClD,MAAM,GAAG,IAAI,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,eAAe,CAAC,MAAM,CAAC,CAAC;QACnD,CAAC;QAED,OAAO,MAAM,CAAC;IAChB,CAAC;IAED,IAAI,CAAC,OAAiB;QACpB,IAAI,CAAC,OAAO,CAAC,OAAO,CAAC,GAAG,OAAO,CAAC,CAAC;IACnC,CAAC;IAED,UAAU;QACR,OAAO,IAAI,CAAC,OAAO,CAAC;IACtB,CAAC;CACF;AA5DD,kCA4DC;AAED,MAAa,kBAAkB;IAC7B,YAA6B,SAAuC;QAAvC,cAAS,GAAT,SAAS,CAA8B;IAAG,CAAC;IAExE,IAAI,CAAC,eAAwC;QAC3C,IAAI,CAAC,SAAS,CAAC,OAAO,CAAC,GAAG,eAAe,CAAC,CAAC;IAC7C,CAAC;IAED,KAAK;QACH,OAAO,IAAI,kBAAkB,CAAC,CAAC,GAAG,IAAI,CAAC,SAAS,CAAC,CAAC,CAAC;IACrD,CAAC;IAED,YAAY;QACV,OAAO,IAAI,WAAW,CACpB,IAAI,CAAC,SAAS,CAAC,GAAG,CAAC,OAAO,CAAC,EAAE,CAAC,OAAO,CAAC,YAAY,EAAE,CAAC,CACtD,CAAC;IACJ,CAAC;CACF;AAhBD,gDAgBC"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/filter.d.ts b/node_modules/@grpc/grpc-js/build/src/filter.d.ts new file mode 100644 index 0000000..f7e382a --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/filter.d.ts @@ -0,0 +1,26 @@ +/// +import { StatusObject, WriteObject } from './call-interface'; +import { Metadata } from './metadata'; +/** + * Filter classes represent related per-call logic and state that is primarily + * used to modify incoming and outgoing data. All async filters can be + * rejected. The rejection error must be a StatusObject, and a rejection will + * cause the call to end with that status. + */ +export interface Filter { + sendMetadata(metadata: Promise): Promise; + receiveMetadata(metadata: Metadata): Metadata; + sendMessage(message: Promise): Promise; + receiveMessage(message: Promise): Promise; + receiveTrailers(status: StatusObject): StatusObject; +} +export declare abstract class BaseFilter implements Filter { + sendMetadata(metadata: Promise): Promise; + receiveMetadata(metadata: Metadata): Metadata; + sendMessage(message: Promise): Promise; + receiveMessage(message: Promise): Promise; + receiveTrailers(status: StatusObject): StatusObject; +} +export interface FilterFactory { + createFilter(): T; +} diff --git a/node_modules/@grpc/grpc-js/build/src/filter.js b/node_modules/@grpc/grpc-js/build/src/filter.js new file mode 100644 index 0000000..d888a82 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/filter.js @@ -0,0 +1,38 @@ +"use strict"; +/* + * Copyright 2019 gRPC authors. + * + * 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. + * + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.BaseFilter = void 0; +class BaseFilter { + async sendMetadata(metadata) { + return metadata; + } + receiveMetadata(metadata) { + return metadata; + } + async sendMessage(message) { + return message; + } + async receiveMessage(message) { + return message; + } + receiveTrailers(status) { + return status; + } +} +exports.BaseFilter = BaseFilter; +//# sourceMappingURL=filter.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/filter.js.map b/node_modules/@grpc/grpc-js/build/src/filter.js.map new file mode 100644 index 0000000..1ddf110 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/filter.js.map @@ -0,0 +1 @@ +{"version":3,"file":"filter.js","sourceRoot":"","sources":["../../src/filter.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;GAeG;;;AAuBH,MAAsB,UAAU;IAC9B,KAAK,CAAC,YAAY,CAAC,QAA2B;QAC5C,OAAO,QAAQ,CAAC;IAClB,CAAC;IAED,eAAe,CAAC,QAAkB;QAChC,OAAO,QAAQ,CAAC;IAClB,CAAC;IAED,KAAK,CAAC,WAAW,CAAC,OAA6B;QAC7C,OAAO,OAAO,CAAC;IACjB,CAAC;IAED,KAAK,CAAC,cAAc,CAAC,OAAwB;QAC3C,OAAO,OAAO,CAAC;IACjB,CAAC;IAED,eAAe,CAAC,MAAoB;QAClC,OAAO,MAAM,CAAC;IAChB,CAAC;CACF;AApBD,gCAoBC"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/channelz.d.ts b/node_modules/@grpc/grpc-js/build/src/generated/channelz.d.ts new file mode 100644 index 0000000..d311c65 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/channelz.d.ts @@ -0,0 +1,72 @@ +import type * as grpc from '../index'; +import type { MessageTypeDefinition } from '@grpc/proto-loader'; +import type { ChannelzClient as _grpc_channelz_v1_ChannelzClient, ChannelzDefinition as _grpc_channelz_v1_ChannelzDefinition } from './grpc/channelz/v1/Channelz'; +type SubtypeConstructor any, Subtype> = { + new (...args: ConstructorParameters): Subtype; +}; +export interface ProtoGrpcType { + google: { + protobuf: { + Any: MessageTypeDefinition; + BoolValue: MessageTypeDefinition; + BytesValue: MessageTypeDefinition; + DoubleValue: MessageTypeDefinition; + Duration: MessageTypeDefinition; + FloatValue: MessageTypeDefinition; + Int32Value: MessageTypeDefinition; + Int64Value: MessageTypeDefinition; + StringValue: MessageTypeDefinition; + Timestamp: MessageTypeDefinition; + UInt32Value: MessageTypeDefinition; + UInt64Value: MessageTypeDefinition; + }; + }; + grpc: { + channelz: { + v1: { + Address: MessageTypeDefinition; + Channel: MessageTypeDefinition; + ChannelConnectivityState: MessageTypeDefinition; + ChannelData: MessageTypeDefinition; + ChannelRef: MessageTypeDefinition; + ChannelTrace: MessageTypeDefinition; + ChannelTraceEvent: MessageTypeDefinition; + /** + * Channelz is a service exposed by gRPC servers that provides detailed debug + * information. + */ + Channelz: SubtypeConstructor & { + service: _grpc_channelz_v1_ChannelzDefinition; + }; + GetChannelRequest: MessageTypeDefinition; + GetChannelResponse: MessageTypeDefinition; + GetServerRequest: MessageTypeDefinition; + GetServerResponse: MessageTypeDefinition; + GetServerSocketsRequest: MessageTypeDefinition; + GetServerSocketsResponse: MessageTypeDefinition; + GetServersRequest: MessageTypeDefinition; + GetServersResponse: MessageTypeDefinition; + GetSocketRequest: MessageTypeDefinition; + GetSocketResponse: MessageTypeDefinition; + GetSubchannelRequest: MessageTypeDefinition; + GetSubchannelResponse: MessageTypeDefinition; + GetTopChannelsRequest: MessageTypeDefinition; + GetTopChannelsResponse: MessageTypeDefinition; + Security: MessageTypeDefinition; + Server: MessageTypeDefinition; + ServerData: MessageTypeDefinition; + ServerRef: MessageTypeDefinition; + Socket: MessageTypeDefinition; + SocketData: MessageTypeDefinition; + SocketOption: MessageTypeDefinition; + SocketOptionLinger: MessageTypeDefinition; + SocketOptionTcpInfo: MessageTypeDefinition; + SocketOptionTimeout: MessageTypeDefinition; + SocketRef: MessageTypeDefinition; + Subchannel: MessageTypeDefinition; + SubchannelRef: MessageTypeDefinition; + }; + }; + }; +} +export {}; diff --git a/node_modules/@grpc/grpc-js/build/src/generated/channelz.js b/node_modules/@grpc/grpc-js/build/src/generated/channelz.js new file mode 100644 index 0000000..0c2cf67 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/channelz.js @@ -0,0 +1,3 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=channelz.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/channelz.js.map b/node_modules/@grpc/grpc-js/build/src/generated/channelz.js.map new file mode 100644 index 0000000..af4016b --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/channelz.js.map @@ -0,0 +1 @@ +{"version":3,"file":"channelz.js","sourceRoot":"","sources":["../../../src/generated/channelz.ts"],"names":[],"mappings":""} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/Any.d.ts b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/Any.d.ts new file mode 100644 index 0000000..e8c0607 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/Any.d.ts @@ -0,0 +1,10 @@ +/// +import type { AnyExtension } from '@grpc/proto-loader'; +export type Any = AnyExtension | { + type_url: string; + value: Buffer | Uint8Array | string; +}; +export interface Any__Output { + 'type_url': (string); + 'value': (Buffer); +} diff --git a/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/Any.js b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/Any.js new file mode 100644 index 0000000..f9651f8 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/Any.js @@ -0,0 +1,4 @@ +"use strict"; +// Original file: null +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=Any.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/Any.js.map b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/Any.js.map new file mode 100644 index 0000000..2e75474 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/Any.js.map @@ -0,0 +1 @@ +{"version":3,"file":"Any.js","sourceRoot":"","sources":["../../../../../src/generated/google/protobuf/Any.ts"],"names":[],"mappings":";AAAA,sBAAsB"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/BoolValue.d.ts b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/BoolValue.d.ts new file mode 100644 index 0000000..b7235a7 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/BoolValue.d.ts @@ -0,0 +1,6 @@ +export interface BoolValue { + 'value'?: (boolean); +} +export interface BoolValue__Output { + 'value': (boolean); +} diff --git a/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/BoolValue.js b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/BoolValue.js new file mode 100644 index 0000000..f893f74 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/BoolValue.js @@ -0,0 +1,4 @@ +"use strict"; +// Original file: null +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=BoolValue.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/BoolValue.js.map b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/BoolValue.js.map new file mode 100644 index 0000000..3573853 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/BoolValue.js.map @@ -0,0 +1 @@ +{"version":3,"file":"BoolValue.js","sourceRoot":"","sources":["../../../../../src/generated/google/protobuf/BoolValue.ts"],"names":[],"mappings":";AAAA,sBAAsB"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/BytesValue.d.ts b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/BytesValue.d.ts new file mode 100644 index 0000000..2c77f9d --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/BytesValue.d.ts @@ -0,0 +1,7 @@ +/// +export interface BytesValue { + 'value'?: (Buffer | Uint8Array | string); +} +export interface BytesValue__Output { + 'value': (Buffer); +} diff --git a/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/BytesValue.js b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/BytesValue.js new file mode 100644 index 0000000..4cac93e --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/BytesValue.js @@ -0,0 +1,4 @@ +"use strict"; +// Original file: null +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=BytesValue.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/BytesValue.js.map b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/BytesValue.js.map new file mode 100644 index 0000000..a589ea5 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/BytesValue.js.map @@ -0,0 +1 @@ +{"version":3,"file":"BytesValue.js","sourceRoot":"","sources":["../../../../../src/generated/google/protobuf/BytesValue.ts"],"names":[],"mappings":";AAAA,sBAAsB"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/DoubleValue.d.ts b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/DoubleValue.d.ts new file mode 100644 index 0000000..e4e2204 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/DoubleValue.d.ts @@ -0,0 +1,6 @@ +export interface DoubleValue { + 'value'?: (number | string); +} +export interface DoubleValue__Output { + 'value': (number); +} diff --git a/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/DoubleValue.js b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/DoubleValue.js new file mode 100644 index 0000000..133e011 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/DoubleValue.js @@ -0,0 +1,4 @@ +"use strict"; +// Original file: null +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=DoubleValue.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/DoubleValue.js.map b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/DoubleValue.js.map new file mode 100644 index 0000000..7f28720 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/DoubleValue.js.map @@ -0,0 +1 @@ +{"version":3,"file":"DoubleValue.js","sourceRoot":"","sources":["../../../../../src/generated/google/protobuf/DoubleValue.ts"],"names":[],"mappings":";AAAA,sBAAsB"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/Duration.d.ts b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/Duration.d.ts new file mode 100644 index 0000000..7e04ea6 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/Duration.d.ts @@ -0,0 +1,9 @@ +import type { Long } from '@grpc/proto-loader'; +export interface Duration { + 'seconds'?: (number | string | Long); + 'nanos'?: (number); +} +export interface Duration__Output { + 'seconds': (string); + 'nanos': (number); +} diff --git a/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/Duration.js b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/Duration.js new file mode 100644 index 0000000..b071b70 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/Duration.js @@ -0,0 +1,4 @@ +"use strict"; +// Original file: null +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=Duration.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/Duration.js.map b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/Duration.js.map new file mode 100644 index 0000000..3fc8fe8 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/Duration.js.map @@ -0,0 +1 @@ +{"version":3,"file":"Duration.js","sourceRoot":"","sources":["../../../../../src/generated/google/protobuf/Duration.ts"],"names":[],"mappings":";AAAA,sBAAsB"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/FloatValue.d.ts b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/FloatValue.d.ts new file mode 100644 index 0000000..33bd60b --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/FloatValue.d.ts @@ -0,0 +1,6 @@ +export interface FloatValue { + 'value'?: (number | string); +} +export interface FloatValue__Output { + 'value': (number); +} diff --git a/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/FloatValue.js b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/FloatValue.js new file mode 100644 index 0000000..17290a2 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/FloatValue.js @@ -0,0 +1,4 @@ +"use strict"; +// Original file: null +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=FloatValue.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/FloatValue.js.map b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/FloatValue.js.map new file mode 100644 index 0000000..bf27b78 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/FloatValue.js.map @@ -0,0 +1 @@ +{"version":3,"file":"FloatValue.js","sourceRoot":"","sources":["../../../../../src/generated/google/protobuf/FloatValue.ts"],"names":[],"mappings":";AAAA,sBAAsB"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/Int32Value.d.ts b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/Int32Value.d.ts new file mode 100644 index 0000000..895fb9d --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/Int32Value.d.ts @@ -0,0 +1,6 @@ +export interface Int32Value { + 'value'?: (number); +} +export interface Int32Value__Output { + 'value': (number); +} diff --git a/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/Int32Value.js b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/Int32Value.js new file mode 100644 index 0000000..dc46343 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/Int32Value.js @@ -0,0 +1,4 @@ +"use strict"; +// Original file: null +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=Int32Value.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/Int32Value.js.map b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/Int32Value.js.map new file mode 100644 index 0000000..157e73a --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/Int32Value.js.map @@ -0,0 +1 @@ +{"version":3,"file":"Int32Value.js","sourceRoot":"","sources":["../../../../../src/generated/google/protobuf/Int32Value.ts"],"names":[],"mappings":";AAAA,sBAAsB"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/Int64Value.d.ts b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/Int64Value.d.ts new file mode 100644 index 0000000..00bd119 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/Int64Value.d.ts @@ -0,0 +1,7 @@ +import type { Long } from '@grpc/proto-loader'; +export interface Int64Value { + 'value'?: (number | string | Long); +} +export interface Int64Value__Output { + 'value': (string); +} diff --git a/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/Int64Value.js b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/Int64Value.js new file mode 100644 index 0000000..a77bc96 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/Int64Value.js @@ -0,0 +1,4 @@ +"use strict"; +// Original file: null +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=Int64Value.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/Int64Value.js.map b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/Int64Value.js.map new file mode 100644 index 0000000..b8894b1 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/Int64Value.js.map @@ -0,0 +1 @@ +{"version":3,"file":"Int64Value.js","sourceRoot":"","sources":["../../../../../src/generated/google/protobuf/Int64Value.ts"],"names":[],"mappings":";AAAA,sBAAsB"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/StringValue.d.ts b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/StringValue.d.ts new file mode 100644 index 0000000..74230c9 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/StringValue.d.ts @@ -0,0 +1,6 @@ +export interface StringValue { + 'value'?: (string); +} +export interface StringValue__Output { + 'value': (string); +} diff --git a/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/StringValue.js b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/StringValue.js new file mode 100644 index 0000000..0836e97 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/StringValue.js @@ -0,0 +1,4 @@ +"use strict"; +// Original file: null +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=StringValue.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/StringValue.js.map b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/StringValue.js.map new file mode 100644 index 0000000..bc05ddc --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/StringValue.js.map @@ -0,0 +1 @@ +{"version":3,"file":"StringValue.js","sourceRoot":"","sources":["../../../../../src/generated/google/protobuf/StringValue.ts"],"names":[],"mappings":";AAAA,sBAAsB"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/Timestamp.d.ts b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/Timestamp.d.ts new file mode 100644 index 0000000..900ff5a --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/Timestamp.d.ts @@ -0,0 +1,9 @@ +import type { Long } from '@grpc/proto-loader'; +export interface Timestamp { + 'seconds'?: (number | string | Long); + 'nanos'?: (number); +} +export interface Timestamp__Output { + 'seconds': (string); + 'nanos': (number); +} diff --git a/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/Timestamp.js b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/Timestamp.js new file mode 100644 index 0000000..dcca213 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/Timestamp.js @@ -0,0 +1,4 @@ +"use strict"; +// Original file: null +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=Timestamp.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/Timestamp.js.map b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/Timestamp.js.map new file mode 100644 index 0000000..e90342e --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/Timestamp.js.map @@ -0,0 +1 @@ +{"version":3,"file":"Timestamp.js","sourceRoot":"","sources":["../../../../../src/generated/google/protobuf/Timestamp.ts"],"names":[],"mappings":";AAAA,sBAAsB"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/UInt32Value.d.ts b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/UInt32Value.d.ts new file mode 100644 index 0000000..d7e185f --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/UInt32Value.d.ts @@ -0,0 +1,6 @@ +export interface UInt32Value { + 'value'?: (number); +} +export interface UInt32Value__Output { + 'value': (number); +} diff --git a/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/UInt32Value.js b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/UInt32Value.js new file mode 100644 index 0000000..889cd2e --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/UInt32Value.js @@ -0,0 +1,4 @@ +"use strict"; +// Original file: null +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=UInt32Value.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/UInt32Value.js.map b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/UInt32Value.js.map new file mode 100644 index 0000000..2a0420f --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/UInt32Value.js.map @@ -0,0 +1 @@ +{"version":3,"file":"UInt32Value.js","sourceRoot":"","sources":["../../../../../src/generated/google/protobuf/UInt32Value.ts"],"names":[],"mappings":";AAAA,sBAAsB"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/UInt64Value.d.ts b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/UInt64Value.d.ts new file mode 100644 index 0000000..fe94d29 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/UInt64Value.d.ts @@ -0,0 +1,7 @@ +import type { Long } from '@grpc/proto-loader'; +export interface UInt64Value { + 'value'?: (number | string | Long); +} +export interface UInt64Value__Output { + 'value': (string); +} diff --git a/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/UInt64Value.js b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/UInt64Value.js new file mode 100644 index 0000000..2a06a69 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/UInt64Value.js @@ -0,0 +1,4 @@ +"use strict"; +// Original file: null +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=UInt64Value.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/UInt64Value.js.map b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/UInt64Value.js.map new file mode 100644 index 0000000..4ea43ca --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/google/protobuf/UInt64Value.js.map @@ -0,0 +1 @@ +{"version":3,"file":"UInt64Value.js","sourceRoot":"","sources":["../../../../../src/generated/google/protobuf/UInt64Value.ts"],"names":[],"mappings":";AAAA,sBAAsB"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/Address.d.ts b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/Address.d.ts new file mode 100644 index 0000000..0676367 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/Address.d.ts @@ -0,0 +1,80 @@ +/// +import type { Any as _google_protobuf_Any, Any__Output as _google_protobuf_Any__Output } from '../../../google/protobuf/Any'; +/** + * An address type not included above. + */ +export interface _grpc_channelz_v1_Address_OtherAddress { + /** + * The human readable version of the value. This value should be set. + */ + 'name'?: (string); + /** + * The actual address message. + */ + 'value'?: (_google_protobuf_Any | null); +} +/** + * An address type not included above. + */ +export interface _grpc_channelz_v1_Address_OtherAddress__Output { + /** + * The human readable version of the value. This value should be set. + */ + 'name': (string); + /** + * The actual address message. + */ + 'value': (_google_protobuf_Any__Output | null); +} +export interface _grpc_channelz_v1_Address_TcpIpAddress { + /** + * Either the IPv4 or IPv6 address in bytes. Will be either 4 bytes or 16 + * bytes in length. + */ + 'ip_address'?: (Buffer | Uint8Array | string); + /** + * 0-64k, or -1 if not appropriate. + */ + 'port'?: (number); +} +export interface _grpc_channelz_v1_Address_TcpIpAddress__Output { + /** + * Either the IPv4 or IPv6 address in bytes. Will be either 4 bytes or 16 + * bytes in length. + */ + 'ip_address': (Buffer); + /** + * 0-64k, or -1 if not appropriate. + */ + 'port': (number); +} +/** + * A Unix Domain Socket address. + */ +export interface _grpc_channelz_v1_Address_UdsAddress { + 'filename'?: (string); +} +/** + * A Unix Domain Socket address. + */ +export interface _grpc_channelz_v1_Address_UdsAddress__Output { + 'filename': (string); +} +/** + * Address represents the address used to create the socket. + */ +export interface Address { + 'tcpip_address'?: (_grpc_channelz_v1_Address_TcpIpAddress | null); + 'uds_address'?: (_grpc_channelz_v1_Address_UdsAddress | null); + 'other_address'?: (_grpc_channelz_v1_Address_OtherAddress | null); + 'address'?: "tcpip_address" | "uds_address" | "other_address"; +} +/** + * Address represents the address used to create the socket. + */ +export interface Address__Output { + 'tcpip_address'?: (_grpc_channelz_v1_Address_TcpIpAddress__Output | null); + 'uds_address'?: (_grpc_channelz_v1_Address_UdsAddress__Output | null); + 'other_address'?: (_grpc_channelz_v1_Address_OtherAddress__Output | null); + 'address': "tcpip_address" | "uds_address" | "other_address"; +} diff --git a/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/Address.js b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/Address.js new file mode 100644 index 0000000..6f15b91 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/Address.js @@ -0,0 +1,4 @@ +"use strict"; +// Original file: proto/channelz.proto +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=Address.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/Address.js.map b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/Address.js.map new file mode 100644 index 0000000..554d6da --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/Address.js.map @@ -0,0 +1 @@ +{"version":3,"file":"Address.js","sourceRoot":"","sources":["../../../../../../src/generated/grpc/channelz/v1/Address.ts"],"names":[],"mappings":";AAAA,sCAAsC"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/Channel.d.ts b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/Channel.d.ts new file mode 100644 index 0000000..3bd11ca --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/Channel.d.ts @@ -0,0 +1,64 @@ +import type { ChannelRef as _grpc_channelz_v1_ChannelRef, ChannelRef__Output as _grpc_channelz_v1_ChannelRef__Output } from '../../../grpc/channelz/v1/ChannelRef'; +import type { ChannelData as _grpc_channelz_v1_ChannelData, ChannelData__Output as _grpc_channelz_v1_ChannelData__Output } from '../../../grpc/channelz/v1/ChannelData'; +import type { SubchannelRef as _grpc_channelz_v1_SubchannelRef, SubchannelRef__Output as _grpc_channelz_v1_SubchannelRef__Output } from '../../../grpc/channelz/v1/SubchannelRef'; +import type { SocketRef as _grpc_channelz_v1_SocketRef, SocketRef__Output as _grpc_channelz_v1_SocketRef__Output } from '../../../grpc/channelz/v1/SocketRef'; +/** + * Channel is a logical grouping of channels, subchannels, and sockets. + */ +export interface Channel { + /** + * The identifier for this channel. This should bet set. + */ + 'ref'?: (_grpc_channelz_v1_ChannelRef | null); + /** + * Data specific to this channel. + */ + 'data'?: (_grpc_channelz_v1_ChannelData | null); + /** + * There are no ordering guarantees on the order of channel refs. + * There may not be cycles in the ref graph. + * A channel ref may be present in more than one channel or subchannel. + */ + 'channel_ref'?: (_grpc_channelz_v1_ChannelRef)[]; + /** + * At most one of 'channel_ref+subchannel_ref' and 'socket' is set. + * There are no ordering guarantees on the order of subchannel refs. + * There may not be cycles in the ref graph. + * A sub channel ref may be present in more than one channel or subchannel. + */ + 'subchannel_ref'?: (_grpc_channelz_v1_SubchannelRef)[]; + /** + * There are no ordering guarantees on the order of sockets. + */ + 'socket_ref'?: (_grpc_channelz_v1_SocketRef)[]; +} +/** + * Channel is a logical grouping of channels, subchannels, and sockets. + */ +export interface Channel__Output { + /** + * The identifier for this channel. This should bet set. + */ + 'ref': (_grpc_channelz_v1_ChannelRef__Output | null); + /** + * Data specific to this channel. + */ + 'data': (_grpc_channelz_v1_ChannelData__Output | null); + /** + * There are no ordering guarantees on the order of channel refs. + * There may not be cycles in the ref graph. + * A channel ref may be present in more than one channel or subchannel. + */ + 'channel_ref': (_grpc_channelz_v1_ChannelRef__Output)[]; + /** + * At most one of 'channel_ref+subchannel_ref' and 'socket' is set. + * There are no ordering guarantees on the order of subchannel refs. + * There may not be cycles in the ref graph. + * A sub channel ref may be present in more than one channel or subchannel. + */ + 'subchannel_ref': (_grpc_channelz_v1_SubchannelRef__Output)[]; + /** + * There are no ordering guarantees on the order of sockets. + */ + 'socket_ref': (_grpc_channelz_v1_SocketRef__Output)[]; +} diff --git a/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/Channel.js b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/Channel.js new file mode 100644 index 0000000..d9bc55a --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/Channel.js @@ -0,0 +1,4 @@ +"use strict"; +// Original file: proto/channelz.proto +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=Channel.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/Channel.js.map b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/Channel.js.map new file mode 100644 index 0000000..5dd6b69 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/Channel.js.map @@ -0,0 +1 @@ +{"version":3,"file":"Channel.js","sourceRoot":"","sources":["../../../../../../src/generated/grpc/channelz/v1/Channel.ts"],"names":[],"mappings":";AAAA,sCAAsC"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/ChannelConnectivityState.d.ts b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/ChannelConnectivityState.d.ts new file mode 100644 index 0000000..2ea3833 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/ChannelConnectivityState.d.ts @@ -0,0 +1,24 @@ +export declare const _grpc_channelz_v1_ChannelConnectivityState_State: { + readonly UNKNOWN: "UNKNOWN"; + readonly IDLE: "IDLE"; + readonly CONNECTING: "CONNECTING"; + readonly READY: "READY"; + readonly TRANSIENT_FAILURE: "TRANSIENT_FAILURE"; + readonly SHUTDOWN: "SHUTDOWN"; +}; +export type _grpc_channelz_v1_ChannelConnectivityState_State = 'UNKNOWN' | 0 | 'IDLE' | 1 | 'CONNECTING' | 2 | 'READY' | 3 | 'TRANSIENT_FAILURE' | 4 | 'SHUTDOWN' | 5; +export type _grpc_channelz_v1_ChannelConnectivityState_State__Output = typeof _grpc_channelz_v1_ChannelConnectivityState_State[keyof typeof _grpc_channelz_v1_ChannelConnectivityState_State]; +/** + * These come from the specified states in this document: + * https://github.com/grpc/grpc/blob/master/doc/connectivity-semantics-and-api.md + */ +export interface ChannelConnectivityState { + 'state'?: (_grpc_channelz_v1_ChannelConnectivityState_State); +} +/** + * These come from the specified states in this document: + * https://github.com/grpc/grpc/blob/master/doc/connectivity-semantics-and-api.md + */ +export interface ChannelConnectivityState__Output { + 'state': (_grpc_channelz_v1_ChannelConnectivityState_State__Output); +} diff --git a/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/ChannelConnectivityState.js b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/ChannelConnectivityState.js new file mode 100644 index 0000000..2a783d9 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/ChannelConnectivityState.js @@ -0,0 +1,14 @@ +"use strict"; +// Original file: proto/channelz.proto +Object.defineProperty(exports, "__esModule", { value: true }); +exports._grpc_channelz_v1_ChannelConnectivityState_State = void 0; +// Original file: proto/channelz.proto +exports._grpc_channelz_v1_ChannelConnectivityState_State = { + UNKNOWN: 'UNKNOWN', + IDLE: 'IDLE', + CONNECTING: 'CONNECTING', + READY: 'READY', + TRANSIENT_FAILURE: 'TRANSIENT_FAILURE', + SHUTDOWN: 'SHUTDOWN', +}; +//# sourceMappingURL=ChannelConnectivityState.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/ChannelConnectivityState.js.map b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/ChannelConnectivityState.js.map new file mode 100644 index 0000000..d4b2567 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/ChannelConnectivityState.js.map @@ -0,0 +1 @@ +{"version":3,"file":"ChannelConnectivityState.js","sourceRoot":"","sources":["../../../../../../src/generated/grpc/channelz/v1/ChannelConnectivityState.ts"],"names":[],"mappings":";AAAA,sCAAsC;;;AAGtC,sCAAsC;AAEzB,QAAA,gDAAgD,GAAG;IAC9D,OAAO,EAAE,SAAS;IAClB,IAAI,EAAE,MAAM;IACZ,UAAU,EAAE,YAAY;IACxB,KAAK,EAAE,OAAO;IACd,iBAAiB,EAAE,mBAAmB;IACtC,QAAQ,EAAE,UAAU;CACZ,CAAC"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/ChannelData.d.ts b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/ChannelData.d.ts new file mode 100644 index 0000000..3d9716a --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/ChannelData.d.ts @@ -0,0 +1,72 @@ +import type { ChannelConnectivityState as _grpc_channelz_v1_ChannelConnectivityState, ChannelConnectivityState__Output as _grpc_channelz_v1_ChannelConnectivityState__Output } from '../../../grpc/channelz/v1/ChannelConnectivityState'; +import type { ChannelTrace as _grpc_channelz_v1_ChannelTrace, ChannelTrace__Output as _grpc_channelz_v1_ChannelTrace__Output } from '../../../grpc/channelz/v1/ChannelTrace'; +import type { Timestamp as _google_protobuf_Timestamp, Timestamp__Output as _google_protobuf_Timestamp__Output } from '../../../google/protobuf/Timestamp'; +import type { Long } from '@grpc/proto-loader'; +/** + * Channel data is data related to a specific Channel or Subchannel. + */ +export interface ChannelData { + /** + * The connectivity state of the channel or subchannel. Implementations + * should always set this. + */ + 'state'?: (_grpc_channelz_v1_ChannelConnectivityState | null); + /** + * The target this channel originally tried to connect to. May be absent + */ + 'target'?: (string); + /** + * A trace of recent events on the channel. May be absent. + */ + 'trace'?: (_grpc_channelz_v1_ChannelTrace | null); + /** + * The number of calls started on the channel + */ + 'calls_started'?: (number | string | Long); + /** + * The number of calls that have completed with an OK status + */ + 'calls_succeeded'?: (number | string | Long); + /** + * The number of calls that have completed with a non-OK status + */ + 'calls_failed'?: (number | string | Long); + /** + * The last time a call was started on the channel. + */ + 'last_call_started_timestamp'?: (_google_protobuf_Timestamp | null); +} +/** + * Channel data is data related to a specific Channel or Subchannel. + */ +export interface ChannelData__Output { + /** + * The connectivity state of the channel or subchannel. Implementations + * should always set this. + */ + 'state': (_grpc_channelz_v1_ChannelConnectivityState__Output | null); + /** + * The target this channel originally tried to connect to. May be absent + */ + 'target': (string); + /** + * A trace of recent events on the channel. May be absent. + */ + 'trace': (_grpc_channelz_v1_ChannelTrace__Output | null); + /** + * The number of calls started on the channel + */ + 'calls_started': (string); + /** + * The number of calls that have completed with an OK status + */ + 'calls_succeeded': (string); + /** + * The number of calls that have completed with a non-OK status + */ + 'calls_failed': (string); + /** + * The last time a call was started on the channel. + */ + 'last_call_started_timestamp': (_google_protobuf_Timestamp__Output | null); +} diff --git a/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/ChannelData.js b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/ChannelData.js new file mode 100644 index 0000000..dffbd45 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/ChannelData.js @@ -0,0 +1,4 @@ +"use strict"; +// Original file: proto/channelz.proto +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=ChannelData.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/ChannelData.js.map b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/ChannelData.js.map new file mode 100644 index 0000000..bb2b4c4 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/ChannelData.js.map @@ -0,0 +1 @@ +{"version":3,"file":"ChannelData.js","sourceRoot":"","sources":["../../../../../../src/generated/grpc/channelz/v1/ChannelData.ts"],"names":[],"mappings":";AAAA,sCAAsC"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/ChannelRef.d.ts b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/ChannelRef.d.ts new file mode 100644 index 0000000..29deef9 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/ChannelRef.d.ts @@ -0,0 +1,27 @@ +import type { Long } from '@grpc/proto-loader'; +/** + * ChannelRef is a reference to a Channel. + */ +export interface ChannelRef { + /** + * The globally unique id for this channel. Must be a positive number. + */ + 'channel_id'?: (number | string | Long); + /** + * An optional name associated with the channel. + */ + 'name'?: (string); +} +/** + * ChannelRef is a reference to a Channel. + */ +export interface ChannelRef__Output { + /** + * The globally unique id for this channel. Must be a positive number. + */ + 'channel_id': (string); + /** + * An optional name associated with the channel. + */ + 'name': (string); +} diff --git a/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/ChannelRef.js b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/ChannelRef.js new file mode 100644 index 0000000..d239819 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/ChannelRef.js @@ -0,0 +1,4 @@ +"use strict"; +// Original file: proto/channelz.proto +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=ChannelRef.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/ChannelRef.js.map b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/ChannelRef.js.map new file mode 100644 index 0000000..1030ded --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/ChannelRef.js.map @@ -0,0 +1 @@ +{"version":3,"file":"ChannelRef.js","sourceRoot":"","sources":["../../../../../../src/generated/grpc/channelz/v1/ChannelRef.ts"],"names":[],"mappings":";AAAA,sCAAsC"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/ChannelTrace.d.ts b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/ChannelTrace.d.ts new file mode 100644 index 0000000..5b6170a --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/ChannelTrace.d.ts @@ -0,0 +1,41 @@ +import type { Timestamp as _google_protobuf_Timestamp, Timestamp__Output as _google_protobuf_Timestamp__Output } from '../../../google/protobuf/Timestamp'; +import type { ChannelTraceEvent as _grpc_channelz_v1_ChannelTraceEvent, ChannelTraceEvent__Output as _grpc_channelz_v1_ChannelTraceEvent__Output } from '../../../grpc/channelz/v1/ChannelTraceEvent'; +import type { Long } from '@grpc/proto-loader'; +/** + * ChannelTrace represents the recent events that have occurred on the channel. + */ +export interface ChannelTrace { + /** + * Number of events ever logged in this tracing object. This can differ from + * events.size() because events can be overwritten or garbage collected by + * implementations. + */ + 'num_events_logged'?: (number | string | Long); + /** + * Time that this channel was created. + */ + 'creation_timestamp'?: (_google_protobuf_Timestamp | null); + /** + * List of events that have occurred on this channel. + */ + 'events'?: (_grpc_channelz_v1_ChannelTraceEvent)[]; +} +/** + * ChannelTrace represents the recent events that have occurred on the channel. + */ +export interface ChannelTrace__Output { + /** + * Number of events ever logged in this tracing object. This can differ from + * events.size() because events can be overwritten or garbage collected by + * implementations. + */ + 'num_events_logged': (string); + /** + * Time that this channel was created. + */ + 'creation_timestamp': (_google_protobuf_Timestamp__Output | null); + /** + * List of events that have occurred on this channel. + */ + 'events': (_grpc_channelz_v1_ChannelTraceEvent__Output)[]; +} diff --git a/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/ChannelTrace.js b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/ChannelTrace.js new file mode 100644 index 0000000..112069c --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/ChannelTrace.js @@ -0,0 +1,4 @@ +"use strict"; +// Original file: proto/channelz.proto +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=ChannelTrace.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/ChannelTrace.js.map b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/ChannelTrace.js.map new file mode 100644 index 0000000..2f665dc --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/ChannelTrace.js.map @@ -0,0 +1 @@ +{"version":3,"file":"ChannelTrace.js","sourceRoot":"","sources":["../../../../../../src/generated/grpc/channelz/v1/ChannelTrace.ts"],"names":[],"mappings":";AAAA,sCAAsC"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/ChannelTraceEvent.d.ts b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/ChannelTraceEvent.d.ts new file mode 100644 index 0000000..6ff7e30 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/ChannelTraceEvent.d.ts @@ -0,0 +1,74 @@ +import type { Timestamp as _google_protobuf_Timestamp, Timestamp__Output as _google_protobuf_Timestamp__Output } from '../../../google/protobuf/Timestamp'; +import type { ChannelRef as _grpc_channelz_v1_ChannelRef, ChannelRef__Output as _grpc_channelz_v1_ChannelRef__Output } from '../../../grpc/channelz/v1/ChannelRef'; +import type { SubchannelRef as _grpc_channelz_v1_SubchannelRef, SubchannelRef__Output as _grpc_channelz_v1_SubchannelRef__Output } from '../../../grpc/channelz/v1/SubchannelRef'; +/** + * The supported severity levels of trace events. + */ +export declare const _grpc_channelz_v1_ChannelTraceEvent_Severity: { + readonly CT_UNKNOWN: "CT_UNKNOWN"; + readonly CT_INFO: "CT_INFO"; + readonly CT_WARNING: "CT_WARNING"; + readonly CT_ERROR: "CT_ERROR"; +}; +/** + * The supported severity levels of trace events. + */ +export type _grpc_channelz_v1_ChannelTraceEvent_Severity = 'CT_UNKNOWN' | 0 | 'CT_INFO' | 1 | 'CT_WARNING' | 2 | 'CT_ERROR' | 3; +/** + * The supported severity levels of trace events. + */ +export type _grpc_channelz_v1_ChannelTraceEvent_Severity__Output = typeof _grpc_channelz_v1_ChannelTraceEvent_Severity[keyof typeof _grpc_channelz_v1_ChannelTraceEvent_Severity]; +/** + * A trace event is an interesting thing that happened to a channel or + * subchannel, such as creation, address resolution, subchannel creation, etc. + */ +export interface ChannelTraceEvent { + /** + * High level description of the event. + */ + 'description'?: (string); + /** + * the severity of the trace event + */ + 'severity'?: (_grpc_channelz_v1_ChannelTraceEvent_Severity); + /** + * When this event occurred. + */ + 'timestamp'?: (_google_protobuf_Timestamp | null); + 'channel_ref'?: (_grpc_channelz_v1_ChannelRef | null); + 'subchannel_ref'?: (_grpc_channelz_v1_SubchannelRef | null); + /** + * ref of referenced channel or subchannel. + * Optional, only present if this event refers to a child object. For example, + * this field would be filled if this trace event was for a subchannel being + * created. + */ + 'child_ref'?: "channel_ref" | "subchannel_ref"; +} +/** + * A trace event is an interesting thing that happened to a channel or + * subchannel, such as creation, address resolution, subchannel creation, etc. + */ +export interface ChannelTraceEvent__Output { + /** + * High level description of the event. + */ + 'description': (string); + /** + * the severity of the trace event + */ + 'severity': (_grpc_channelz_v1_ChannelTraceEvent_Severity__Output); + /** + * When this event occurred. + */ + 'timestamp': (_google_protobuf_Timestamp__Output | null); + 'channel_ref'?: (_grpc_channelz_v1_ChannelRef__Output | null); + 'subchannel_ref'?: (_grpc_channelz_v1_SubchannelRef__Output | null); + /** + * ref of referenced channel or subchannel. + * Optional, only present if this event refers to a child object. For example, + * this field would be filled if this trace event was for a subchannel being + * created. + */ + 'child_ref': "channel_ref" | "subchannel_ref"; +} diff --git a/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/ChannelTraceEvent.js b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/ChannelTraceEvent.js new file mode 100644 index 0000000..ae9981b --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/ChannelTraceEvent.js @@ -0,0 +1,15 @@ +"use strict"; +// Original file: proto/channelz.proto +Object.defineProperty(exports, "__esModule", { value: true }); +exports._grpc_channelz_v1_ChannelTraceEvent_Severity = void 0; +// Original file: proto/channelz.proto +/** + * The supported severity levels of trace events. + */ +exports._grpc_channelz_v1_ChannelTraceEvent_Severity = { + CT_UNKNOWN: 'CT_UNKNOWN', + CT_INFO: 'CT_INFO', + CT_WARNING: 'CT_WARNING', + CT_ERROR: 'CT_ERROR', +}; +//# sourceMappingURL=ChannelTraceEvent.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/ChannelTraceEvent.js.map b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/ChannelTraceEvent.js.map new file mode 100644 index 0000000..2ed003c --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/ChannelTraceEvent.js.map @@ -0,0 +1 @@ +{"version":3,"file":"ChannelTraceEvent.js","sourceRoot":"","sources":["../../../../../../src/generated/grpc/channelz/v1/ChannelTraceEvent.ts"],"names":[],"mappings":";AAAA,sCAAsC;;;AAMtC,sCAAsC;AAEtC;;GAEG;AACU,QAAA,4CAA4C,GAAG;IAC1D,UAAU,EAAE,YAAY;IACxB,OAAO,EAAE,SAAS;IAClB,UAAU,EAAE,YAAY;IACxB,QAAQ,EAAE,UAAU;CACZ,CAAC"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/Channelz.d.ts b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/Channelz.d.ts new file mode 100644 index 0000000..3e9eb98 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/Channelz.d.ts @@ -0,0 +1,159 @@ +import type * as grpc from '../../../../index'; +import type { MethodDefinition } from '@grpc/proto-loader'; +import type { GetChannelRequest as _grpc_channelz_v1_GetChannelRequest, GetChannelRequest__Output as _grpc_channelz_v1_GetChannelRequest__Output } from '../../../grpc/channelz/v1/GetChannelRequest'; +import type { GetChannelResponse as _grpc_channelz_v1_GetChannelResponse, GetChannelResponse__Output as _grpc_channelz_v1_GetChannelResponse__Output } from '../../../grpc/channelz/v1/GetChannelResponse'; +import type { GetServerRequest as _grpc_channelz_v1_GetServerRequest, GetServerRequest__Output as _grpc_channelz_v1_GetServerRequest__Output } from '../../../grpc/channelz/v1/GetServerRequest'; +import type { GetServerResponse as _grpc_channelz_v1_GetServerResponse, GetServerResponse__Output as _grpc_channelz_v1_GetServerResponse__Output } from '../../../grpc/channelz/v1/GetServerResponse'; +import type { GetServerSocketsRequest as _grpc_channelz_v1_GetServerSocketsRequest, GetServerSocketsRequest__Output as _grpc_channelz_v1_GetServerSocketsRequest__Output } from '../../../grpc/channelz/v1/GetServerSocketsRequest'; +import type { GetServerSocketsResponse as _grpc_channelz_v1_GetServerSocketsResponse, GetServerSocketsResponse__Output as _grpc_channelz_v1_GetServerSocketsResponse__Output } from '../../../grpc/channelz/v1/GetServerSocketsResponse'; +import type { GetServersRequest as _grpc_channelz_v1_GetServersRequest, GetServersRequest__Output as _grpc_channelz_v1_GetServersRequest__Output } from '../../../grpc/channelz/v1/GetServersRequest'; +import type { GetServersResponse as _grpc_channelz_v1_GetServersResponse, GetServersResponse__Output as _grpc_channelz_v1_GetServersResponse__Output } from '../../../grpc/channelz/v1/GetServersResponse'; +import type { GetSocketRequest as _grpc_channelz_v1_GetSocketRequest, GetSocketRequest__Output as _grpc_channelz_v1_GetSocketRequest__Output } from '../../../grpc/channelz/v1/GetSocketRequest'; +import type { GetSocketResponse as _grpc_channelz_v1_GetSocketResponse, GetSocketResponse__Output as _grpc_channelz_v1_GetSocketResponse__Output } from '../../../grpc/channelz/v1/GetSocketResponse'; +import type { GetSubchannelRequest as _grpc_channelz_v1_GetSubchannelRequest, GetSubchannelRequest__Output as _grpc_channelz_v1_GetSubchannelRequest__Output } from '../../../grpc/channelz/v1/GetSubchannelRequest'; +import type { GetSubchannelResponse as _grpc_channelz_v1_GetSubchannelResponse, GetSubchannelResponse__Output as _grpc_channelz_v1_GetSubchannelResponse__Output } from '../../../grpc/channelz/v1/GetSubchannelResponse'; +import type { GetTopChannelsRequest as _grpc_channelz_v1_GetTopChannelsRequest, GetTopChannelsRequest__Output as _grpc_channelz_v1_GetTopChannelsRequest__Output } from '../../../grpc/channelz/v1/GetTopChannelsRequest'; +import type { GetTopChannelsResponse as _grpc_channelz_v1_GetTopChannelsResponse, GetTopChannelsResponse__Output as _grpc_channelz_v1_GetTopChannelsResponse__Output } from '../../../grpc/channelz/v1/GetTopChannelsResponse'; +/** + * Channelz is a service exposed by gRPC servers that provides detailed debug + * information. + */ +export interface ChannelzClient extends grpc.Client { + /** + * Returns a single Channel, or else a NOT_FOUND code. + */ + GetChannel(argument: _grpc_channelz_v1_GetChannelRequest, metadata: grpc.Metadata, options: grpc.CallOptions, callback: grpc.requestCallback<_grpc_channelz_v1_GetChannelResponse__Output>): grpc.ClientUnaryCall; + GetChannel(argument: _grpc_channelz_v1_GetChannelRequest, metadata: grpc.Metadata, callback: grpc.requestCallback<_grpc_channelz_v1_GetChannelResponse__Output>): grpc.ClientUnaryCall; + GetChannel(argument: _grpc_channelz_v1_GetChannelRequest, options: grpc.CallOptions, callback: grpc.requestCallback<_grpc_channelz_v1_GetChannelResponse__Output>): grpc.ClientUnaryCall; + GetChannel(argument: _grpc_channelz_v1_GetChannelRequest, callback: grpc.requestCallback<_grpc_channelz_v1_GetChannelResponse__Output>): grpc.ClientUnaryCall; + /** + * Returns a single Server, or else a NOT_FOUND code. + */ + GetServer(argument: _grpc_channelz_v1_GetServerRequest, metadata: grpc.Metadata, options: grpc.CallOptions, callback: grpc.requestCallback<_grpc_channelz_v1_GetServerResponse__Output>): grpc.ClientUnaryCall; + GetServer(argument: _grpc_channelz_v1_GetServerRequest, metadata: grpc.Metadata, callback: grpc.requestCallback<_grpc_channelz_v1_GetServerResponse__Output>): grpc.ClientUnaryCall; + GetServer(argument: _grpc_channelz_v1_GetServerRequest, options: grpc.CallOptions, callback: grpc.requestCallback<_grpc_channelz_v1_GetServerResponse__Output>): grpc.ClientUnaryCall; + GetServer(argument: _grpc_channelz_v1_GetServerRequest, callback: grpc.requestCallback<_grpc_channelz_v1_GetServerResponse__Output>): grpc.ClientUnaryCall; + /** + * Returns a single Server, or else a NOT_FOUND code. + */ + getServer(argument: _grpc_channelz_v1_GetServerRequest, metadata: grpc.Metadata, options: grpc.CallOptions, callback: grpc.requestCallback<_grpc_channelz_v1_GetServerResponse__Output>): grpc.ClientUnaryCall; + getServer(argument: _grpc_channelz_v1_GetServerRequest, metadata: grpc.Metadata, callback: grpc.requestCallback<_grpc_channelz_v1_GetServerResponse__Output>): grpc.ClientUnaryCall; + getServer(argument: _grpc_channelz_v1_GetServerRequest, options: grpc.CallOptions, callback: grpc.requestCallback<_grpc_channelz_v1_GetServerResponse__Output>): grpc.ClientUnaryCall; + getServer(argument: _grpc_channelz_v1_GetServerRequest, callback: grpc.requestCallback<_grpc_channelz_v1_GetServerResponse__Output>): grpc.ClientUnaryCall; + /** + * Gets all server sockets that exist in the process. + */ + GetServerSockets(argument: _grpc_channelz_v1_GetServerSocketsRequest, metadata: grpc.Metadata, options: grpc.CallOptions, callback: grpc.requestCallback<_grpc_channelz_v1_GetServerSocketsResponse__Output>): grpc.ClientUnaryCall; + GetServerSockets(argument: _grpc_channelz_v1_GetServerSocketsRequest, metadata: grpc.Metadata, callback: grpc.requestCallback<_grpc_channelz_v1_GetServerSocketsResponse__Output>): grpc.ClientUnaryCall; + GetServerSockets(argument: _grpc_channelz_v1_GetServerSocketsRequest, options: grpc.CallOptions, callback: grpc.requestCallback<_grpc_channelz_v1_GetServerSocketsResponse__Output>): grpc.ClientUnaryCall; + GetServerSockets(argument: _grpc_channelz_v1_GetServerSocketsRequest, callback: grpc.requestCallback<_grpc_channelz_v1_GetServerSocketsResponse__Output>): grpc.ClientUnaryCall; + /** + * Gets all server sockets that exist in the process. + */ + getServerSockets(argument: _grpc_channelz_v1_GetServerSocketsRequest, metadata: grpc.Metadata, options: grpc.CallOptions, callback: grpc.requestCallback<_grpc_channelz_v1_GetServerSocketsResponse__Output>): grpc.ClientUnaryCall; + getServerSockets(argument: _grpc_channelz_v1_GetServerSocketsRequest, metadata: grpc.Metadata, callback: grpc.requestCallback<_grpc_channelz_v1_GetServerSocketsResponse__Output>): grpc.ClientUnaryCall; + getServerSockets(argument: _grpc_channelz_v1_GetServerSocketsRequest, options: grpc.CallOptions, callback: grpc.requestCallback<_grpc_channelz_v1_GetServerSocketsResponse__Output>): grpc.ClientUnaryCall; + getServerSockets(argument: _grpc_channelz_v1_GetServerSocketsRequest, callback: grpc.requestCallback<_grpc_channelz_v1_GetServerSocketsResponse__Output>): grpc.ClientUnaryCall; + /** + * Gets all servers that exist in the process. + */ + GetServers(argument: _grpc_channelz_v1_GetServersRequest, metadata: grpc.Metadata, options: grpc.CallOptions, callback: grpc.requestCallback<_grpc_channelz_v1_GetServersResponse__Output>): grpc.ClientUnaryCall; + GetServers(argument: _grpc_channelz_v1_GetServersRequest, metadata: grpc.Metadata, callback: grpc.requestCallback<_grpc_channelz_v1_GetServersResponse__Output>): grpc.ClientUnaryCall; + GetServers(argument: _grpc_channelz_v1_GetServersRequest, options: grpc.CallOptions, callback: grpc.requestCallback<_grpc_channelz_v1_GetServersResponse__Output>): grpc.ClientUnaryCall; + GetServers(argument: _grpc_channelz_v1_GetServersRequest, callback: grpc.requestCallback<_grpc_channelz_v1_GetServersResponse__Output>): grpc.ClientUnaryCall; + /** + * Gets all servers that exist in the process. + */ + getServers(argument: _grpc_channelz_v1_GetServersRequest, metadata: grpc.Metadata, options: grpc.CallOptions, callback: grpc.requestCallback<_grpc_channelz_v1_GetServersResponse__Output>): grpc.ClientUnaryCall; + getServers(argument: _grpc_channelz_v1_GetServersRequest, metadata: grpc.Metadata, callback: grpc.requestCallback<_grpc_channelz_v1_GetServersResponse__Output>): grpc.ClientUnaryCall; + getServers(argument: _grpc_channelz_v1_GetServersRequest, options: grpc.CallOptions, callback: grpc.requestCallback<_grpc_channelz_v1_GetServersResponse__Output>): grpc.ClientUnaryCall; + getServers(argument: _grpc_channelz_v1_GetServersRequest, callback: grpc.requestCallback<_grpc_channelz_v1_GetServersResponse__Output>): grpc.ClientUnaryCall; + /** + * Returns a single Socket or else a NOT_FOUND code. + */ + GetSocket(argument: _grpc_channelz_v1_GetSocketRequest, metadata: grpc.Metadata, options: grpc.CallOptions, callback: grpc.requestCallback<_grpc_channelz_v1_GetSocketResponse__Output>): grpc.ClientUnaryCall; + GetSocket(argument: _grpc_channelz_v1_GetSocketRequest, metadata: grpc.Metadata, callback: grpc.requestCallback<_grpc_channelz_v1_GetSocketResponse__Output>): grpc.ClientUnaryCall; + GetSocket(argument: _grpc_channelz_v1_GetSocketRequest, options: grpc.CallOptions, callback: grpc.requestCallback<_grpc_channelz_v1_GetSocketResponse__Output>): grpc.ClientUnaryCall; + GetSocket(argument: _grpc_channelz_v1_GetSocketRequest, callback: grpc.requestCallback<_grpc_channelz_v1_GetSocketResponse__Output>): grpc.ClientUnaryCall; + /** + * Returns a single Socket or else a NOT_FOUND code. + */ + getSocket(argument: _grpc_channelz_v1_GetSocketRequest, metadata: grpc.Metadata, options: grpc.CallOptions, callback: grpc.requestCallback<_grpc_channelz_v1_GetSocketResponse__Output>): grpc.ClientUnaryCall; + getSocket(argument: _grpc_channelz_v1_GetSocketRequest, metadata: grpc.Metadata, callback: grpc.requestCallback<_grpc_channelz_v1_GetSocketResponse__Output>): grpc.ClientUnaryCall; + getSocket(argument: _grpc_channelz_v1_GetSocketRequest, options: grpc.CallOptions, callback: grpc.requestCallback<_grpc_channelz_v1_GetSocketResponse__Output>): grpc.ClientUnaryCall; + getSocket(argument: _grpc_channelz_v1_GetSocketRequest, callback: grpc.requestCallback<_grpc_channelz_v1_GetSocketResponse__Output>): grpc.ClientUnaryCall; + /** + * Returns a single Subchannel, or else a NOT_FOUND code. + */ + GetSubchannel(argument: _grpc_channelz_v1_GetSubchannelRequest, metadata: grpc.Metadata, options: grpc.CallOptions, callback: grpc.requestCallback<_grpc_channelz_v1_GetSubchannelResponse__Output>): grpc.ClientUnaryCall; + GetSubchannel(argument: _grpc_channelz_v1_GetSubchannelRequest, metadata: grpc.Metadata, callback: grpc.requestCallback<_grpc_channelz_v1_GetSubchannelResponse__Output>): grpc.ClientUnaryCall; + GetSubchannel(argument: _grpc_channelz_v1_GetSubchannelRequest, options: grpc.CallOptions, callback: grpc.requestCallback<_grpc_channelz_v1_GetSubchannelResponse__Output>): grpc.ClientUnaryCall; + GetSubchannel(argument: _grpc_channelz_v1_GetSubchannelRequest, callback: grpc.requestCallback<_grpc_channelz_v1_GetSubchannelResponse__Output>): grpc.ClientUnaryCall; + /** + * Returns a single Subchannel, or else a NOT_FOUND code. + */ + getSubchannel(argument: _grpc_channelz_v1_GetSubchannelRequest, metadata: grpc.Metadata, options: grpc.CallOptions, callback: grpc.requestCallback<_grpc_channelz_v1_GetSubchannelResponse__Output>): grpc.ClientUnaryCall; + getSubchannel(argument: _grpc_channelz_v1_GetSubchannelRequest, metadata: grpc.Metadata, callback: grpc.requestCallback<_grpc_channelz_v1_GetSubchannelResponse__Output>): grpc.ClientUnaryCall; + getSubchannel(argument: _grpc_channelz_v1_GetSubchannelRequest, options: grpc.CallOptions, callback: grpc.requestCallback<_grpc_channelz_v1_GetSubchannelResponse__Output>): grpc.ClientUnaryCall; + getSubchannel(argument: _grpc_channelz_v1_GetSubchannelRequest, callback: grpc.requestCallback<_grpc_channelz_v1_GetSubchannelResponse__Output>): grpc.ClientUnaryCall; + /** + * Gets all root channels (i.e. channels the application has directly + * created). This does not include subchannels nor non-top level channels. + */ + GetTopChannels(argument: _grpc_channelz_v1_GetTopChannelsRequest, metadata: grpc.Metadata, options: grpc.CallOptions, callback: grpc.requestCallback<_grpc_channelz_v1_GetTopChannelsResponse__Output>): grpc.ClientUnaryCall; + GetTopChannels(argument: _grpc_channelz_v1_GetTopChannelsRequest, metadata: grpc.Metadata, callback: grpc.requestCallback<_grpc_channelz_v1_GetTopChannelsResponse__Output>): grpc.ClientUnaryCall; + GetTopChannels(argument: _grpc_channelz_v1_GetTopChannelsRequest, options: grpc.CallOptions, callback: grpc.requestCallback<_grpc_channelz_v1_GetTopChannelsResponse__Output>): grpc.ClientUnaryCall; + GetTopChannels(argument: _grpc_channelz_v1_GetTopChannelsRequest, callback: grpc.requestCallback<_grpc_channelz_v1_GetTopChannelsResponse__Output>): grpc.ClientUnaryCall; + /** + * Gets all root channels (i.e. channels the application has directly + * created). This does not include subchannels nor non-top level channels. + */ + getTopChannels(argument: _grpc_channelz_v1_GetTopChannelsRequest, metadata: grpc.Metadata, options: grpc.CallOptions, callback: grpc.requestCallback<_grpc_channelz_v1_GetTopChannelsResponse__Output>): grpc.ClientUnaryCall; + getTopChannels(argument: _grpc_channelz_v1_GetTopChannelsRequest, metadata: grpc.Metadata, callback: grpc.requestCallback<_grpc_channelz_v1_GetTopChannelsResponse__Output>): grpc.ClientUnaryCall; + getTopChannels(argument: _grpc_channelz_v1_GetTopChannelsRequest, options: grpc.CallOptions, callback: grpc.requestCallback<_grpc_channelz_v1_GetTopChannelsResponse__Output>): grpc.ClientUnaryCall; + getTopChannels(argument: _grpc_channelz_v1_GetTopChannelsRequest, callback: grpc.requestCallback<_grpc_channelz_v1_GetTopChannelsResponse__Output>): grpc.ClientUnaryCall; +} +/** + * Channelz is a service exposed by gRPC servers that provides detailed debug + * information. + */ +export interface ChannelzHandlers extends grpc.UntypedServiceImplementation { + /** + * Returns a single Channel, or else a NOT_FOUND code. + */ + GetChannel: grpc.handleUnaryCall<_grpc_channelz_v1_GetChannelRequest__Output, _grpc_channelz_v1_GetChannelResponse>; + /** + * Returns a single Server, or else a NOT_FOUND code. + */ + GetServer: grpc.handleUnaryCall<_grpc_channelz_v1_GetServerRequest__Output, _grpc_channelz_v1_GetServerResponse>; + /** + * Gets all server sockets that exist in the process. + */ + GetServerSockets: grpc.handleUnaryCall<_grpc_channelz_v1_GetServerSocketsRequest__Output, _grpc_channelz_v1_GetServerSocketsResponse>; + /** + * Gets all servers that exist in the process. + */ + GetServers: grpc.handleUnaryCall<_grpc_channelz_v1_GetServersRequest__Output, _grpc_channelz_v1_GetServersResponse>; + /** + * Returns a single Socket or else a NOT_FOUND code. + */ + GetSocket: grpc.handleUnaryCall<_grpc_channelz_v1_GetSocketRequest__Output, _grpc_channelz_v1_GetSocketResponse>; + /** + * Returns a single Subchannel, or else a NOT_FOUND code. + */ + GetSubchannel: grpc.handleUnaryCall<_grpc_channelz_v1_GetSubchannelRequest__Output, _grpc_channelz_v1_GetSubchannelResponse>; + /** + * Gets all root channels (i.e. channels the application has directly + * created). This does not include subchannels nor non-top level channels. + */ + GetTopChannels: grpc.handleUnaryCall<_grpc_channelz_v1_GetTopChannelsRequest__Output, _grpc_channelz_v1_GetTopChannelsResponse>; +} +export interface ChannelzDefinition extends grpc.ServiceDefinition { + GetChannel: MethodDefinition<_grpc_channelz_v1_GetChannelRequest, _grpc_channelz_v1_GetChannelResponse, _grpc_channelz_v1_GetChannelRequest__Output, _grpc_channelz_v1_GetChannelResponse__Output>; + GetServer: MethodDefinition<_grpc_channelz_v1_GetServerRequest, _grpc_channelz_v1_GetServerResponse, _grpc_channelz_v1_GetServerRequest__Output, _grpc_channelz_v1_GetServerResponse__Output>; + GetServerSockets: MethodDefinition<_grpc_channelz_v1_GetServerSocketsRequest, _grpc_channelz_v1_GetServerSocketsResponse, _grpc_channelz_v1_GetServerSocketsRequest__Output, _grpc_channelz_v1_GetServerSocketsResponse__Output>; + GetServers: MethodDefinition<_grpc_channelz_v1_GetServersRequest, _grpc_channelz_v1_GetServersResponse, _grpc_channelz_v1_GetServersRequest__Output, _grpc_channelz_v1_GetServersResponse__Output>; + GetSocket: MethodDefinition<_grpc_channelz_v1_GetSocketRequest, _grpc_channelz_v1_GetSocketResponse, _grpc_channelz_v1_GetSocketRequest__Output, _grpc_channelz_v1_GetSocketResponse__Output>; + GetSubchannel: MethodDefinition<_grpc_channelz_v1_GetSubchannelRequest, _grpc_channelz_v1_GetSubchannelResponse, _grpc_channelz_v1_GetSubchannelRequest__Output, _grpc_channelz_v1_GetSubchannelResponse__Output>; + GetTopChannels: MethodDefinition<_grpc_channelz_v1_GetTopChannelsRequest, _grpc_channelz_v1_GetTopChannelsResponse, _grpc_channelz_v1_GetTopChannelsRequest__Output, _grpc_channelz_v1_GetTopChannelsResponse__Output>; +} diff --git a/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/Channelz.js b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/Channelz.js new file mode 100644 index 0000000..9fdf9fc --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/Channelz.js @@ -0,0 +1,4 @@ +"use strict"; +// Original file: proto/channelz.proto +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=Channelz.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/Channelz.js.map b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/Channelz.js.map new file mode 100644 index 0000000..86fafec --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/Channelz.js.map @@ -0,0 +1 @@ +{"version":3,"file":"Channelz.js","sourceRoot":"","sources":["../../../../../../src/generated/grpc/channelz/v1/Channelz.ts"],"names":[],"mappings":";AAAA,sCAAsC"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetChannelRequest.d.ts b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetChannelRequest.d.ts new file mode 100644 index 0000000..4956cfa --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetChannelRequest.d.ts @@ -0,0 +1,13 @@ +import type { Long } from '@grpc/proto-loader'; +export interface GetChannelRequest { + /** + * channel_id is the identifier of the specific channel to get. + */ + 'channel_id'?: (number | string | Long); +} +export interface GetChannelRequest__Output { + /** + * channel_id is the identifier of the specific channel to get. + */ + 'channel_id': (string); +} diff --git a/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetChannelRequest.js b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetChannelRequest.js new file mode 100644 index 0000000..10948d4 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetChannelRequest.js @@ -0,0 +1,4 @@ +"use strict"; +// Original file: proto/channelz.proto +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=GetChannelRequest.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetChannelRequest.js.map b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetChannelRequest.js.map new file mode 100644 index 0000000..0ae3f26 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetChannelRequest.js.map @@ -0,0 +1 @@ +{"version":3,"file":"GetChannelRequest.js","sourceRoot":"","sources":["../../../../../../src/generated/grpc/channelz/v1/GetChannelRequest.ts"],"names":[],"mappings":";AAAA,sCAAsC"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetChannelResponse.d.ts b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetChannelResponse.d.ts new file mode 100644 index 0000000..2fbab92 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetChannelResponse.d.ts @@ -0,0 +1,15 @@ +import type { Channel as _grpc_channelz_v1_Channel, Channel__Output as _grpc_channelz_v1_Channel__Output } from '../../../grpc/channelz/v1/Channel'; +export interface GetChannelResponse { + /** + * The Channel that corresponds to the requested channel_id. This field + * should be set. + */ + 'channel'?: (_grpc_channelz_v1_Channel | null); +} +export interface GetChannelResponse__Output { + /** + * The Channel that corresponds to the requested channel_id. This field + * should be set. + */ + 'channel': (_grpc_channelz_v1_Channel__Output | null); +} diff --git a/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetChannelResponse.js b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetChannelResponse.js new file mode 100644 index 0000000..02a4426 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetChannelResponse.js @@ -0,0 +1,4 @@ +"use strict"; +// Original file: proto/channelz.proto +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=GetChannelResponse.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetChannelResponse.js.map b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetChannelResponse.js.map new file mode 100644 index 0000000..a3cfefb --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetChannelResponse.js.map @@ -0,0 +1 @@ +{"version":3,"file":"GetChannelResponse.js","sourceRoot":"","sources":["../../../../../../src/generated/grpc/channelz/v1/GetChannelResponse.ts"],"names":[],"mappings":";AAAA,sCAAsC"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetServerRequest.d.ts b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetServerRequest.d.ts new file mode 100644 index 0000000..1df8503 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetServerRequest.d.ts @@ -0,0 +1,13 @@ +import type { Long } from '@grpc/proto-loader'; +export interface GetServerRequest { + /** + * server_id is the identifier of the specific server to get. + */ + 'server_id'?: (number | string | Long); +} +export interface GetServerRequest__Output { + /** + * server_id is the identifier of the specific server to get. + */ + 'server_id': (string); +} diff --git a/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetServerRequest.js b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetServerRequest.js new file mode 100644 index 0000000..77717b4 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetServerRequest.js @@ -0,0 +1,4 @@ +"use strict"; +// Original file: proto/channelz.proto +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=GetServerRequest.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetServerRequest.js.map b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetServerRequest.js.map new file mode 100644 index 0000000..86fbba6 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetServerRequest.js.map @@ -0,0 +1 @@ +{"version":3,"file":"GetServerRequest.js","sourceRoot":"","sources":["../../../../../../src/generated/grpc/channelz/v1/GetServerRequest.ts"],"names":[],"mappings":";AAAA,sCAAsC"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetServerResponse.d.ts b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetServerResponse.d.ts new file mode 100644 index 0000000..2da13dd --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetServerResponse.d.ts @@ -0,0 +1,15 @@ +import type { Server as _grpc_channelz_v1_Server, Server__Output as _grpc_channelz_v1_Server__Output } from '../../../grpc/channelz/v1/Server'; +export interface GetServerResponse { + /** + * The Server that corresponds to the requested server_id. This field + * should be set. + */ + 'server'?: (_grpc_channelz_v1_Server | null); +} +export interface GetServerResponse__Output { + /** + * The Server that corresponds to the requested server_id. This field + * should be set. + */ + 'server': (_grpc_channelz_v1_Server__Output | null); +} diff --git a/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetServerResponse.js b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetServerResponse.js new file mode 100644 index 0000000..130eb1b --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetServerResponse.js @@ -0,0 +1,4 @@ +"use strict"; +// Original file: proto/channelz.proto +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=GetServerResponse.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetServerResponse.js.map b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetServerResponse.js.map new file mode 100644 index 0000000..f4b16ff --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetServerResponse.js.map @@ -0,0 +1 @@ +{"version":3,"file":"GetServerResponse.js","sourceRoot":"","sources":["../../../../../../src/generated/grpc/channelz/v1/GetServerResponse.ts"],"names":[],"mappings":";AAAA,sCAAsC"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetServerSocketsRequest.d.ts b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetServerSocketsRequest.d.ts new file mode 100644 index 0000000..d810b92 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetServerSocketsRequest.d.ts @@ -0,0 +1,35 @@ +import type { Long } from '@grpc/proto-loader'; +export interface GetServerSocketsRequest { + 'server_id'?: (number | string | Long); + /** + * start_socket_id indicates that only sockets at or above this id should be + * included in the results. + * To request the first page, this must be set to 0. To request + * subsequent pages, the client generates this value by adding 1 to + * the highest seen result ID. + */ + 'start_socket_id'?: (number | string | Long); + /** + * If non-zero, the server will return a page of results containing + * at most this many items. If zero, the server will choose a + * reasonable page size. Must never be negative. + */ + 'max_results'?: (number | string | Long); +} +export interface GetServerSocketsRequest__Output { + 'server_id': (string); + /** + * start_socket_id indicates that only sockets at or above this id should be + * included in the results. + * To request the first page, this must be set to 0. To request + * subsequent pages, the client generates this value by adding 1 to + * the highest seen result ID. + */ + 'start_socket_id': (string); + /** + * If non-zero, the server will return a page of results containing + * at most this many items. If zero, the server will choose a + * reasonable page size. Must never be negative. + */ + 'max_results': (string); +} diff --git a/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetServerSocketsRequest.js b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetServerSocketsRequest.js new file mode 100644 index 0000000..1a15183 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetServerSocketsRequest.js @@ -0,0 +1,4 @@ +"use strict"; +// Original file: proto/channelz.proto +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=GetServerSocketsRequest.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetServerSocketsRequest.js.map b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetServerSocketsRequest.js.map new file mode 100644 index 0000000..458dd98 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetServerSocketsRequest.js.map @@ -0,0 +1 @@ +{"version":3,"file":"GetServerSocketsRequest.js","sourceRoot":"","sources":["../../../../../../src/generated/grpc/channelz/v1/GetServerSocketsRequest.ts"],"names":[],"mappings":";AAAA,sCAAsC"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetServerSocketsResponse.d.ts b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetServerSocketsResponse.d.ts new file mode 100644 index 0000000..4c329ae --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetServerSocketsResponse.d.ts @@ -0,0 +1,29 @@ +import type { SocketRef as _grpc_channelz_v1_SocketRef, SocketRef__Output as _grpc_channelz_v1_SocketRef__Output } from '../../../grpc/channelz/v1/SocketRef'; +export interface GetServerSocketsResponse { + /** + * list of socket refs that the connection detail service knows about. Sorted in + * ascending socket_id order. + * Must contain at least 1 result, otherwise 'end' must be true. + */ + 'socket_ref'?: (_grpc_channelz_v1_SocketRef)[]; + /** + * If set, indicates that the list of sockets is the final list. Requesting + * more sockets will only return more if they are created after this RPC + * completes. + */ + 'end'?: (boolean); +} +export interface GetServerSocketsResponse__Output { + /** + * list of socket refs that the connection detail service knows about. Sorted in + * ascending socket_id order. + * Must contain at least 1 result, otherwise 'end' must be true. + */ + 'socket_ref': (_grpc_channelz_v1_SocketRef__Output)[]; + /** + * If set, indicates that the list of sockets is the final list. Requesting + * more sockets will only return more if they are created after this RPC + * completes. + */ + 'end': (boolean); +} diff --git a/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetServerSocketsResponse.js b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetServerSocketsResponse.js new file mode 100644 index 0000000..29e424f --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetServerSocketsResponse.js @@ -0,0 +1,4 @@ +"use strict"; +// Original file: proto/channelz.proto +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=GetServerSocketsResponse.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetServerSocketsResponse.js.map b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetServerSocketsResponse.js.map new file mode 100644 index 0000000..dc99923 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetServerSocketsResponse.js.map @@ -0,0 +1 @@ +{"version":3,"file":"GetServerSocketsResponse.js","sourceRoot":"","sources":["../../../../../../src/generated/grpc/channelz/v1/GetServerSocketsResponse.ts"],"names":[],"mappings":";AAAA,sCAAsC"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetServersRequest.d.ts b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetServersRequest.d.ts new file mode 100644 index 0000000..64ace6e --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetServersRequest.d.ts @@ -0,0 +1,33 @@ +import type { Long } from '@grpc/proto-loader'; +export interface GetServersRequest { + /** + * start_server_id indicates that only servers at or above this id should be + * included in the results. + * To request the first page, this must be set to 0. To request + * subsequent pages, the client generates this value by adding 1 to + * the highest seen result ID. + */ + 'start_server_id'?: (number | string | Long); + /** + * If non-zero, the server will return a page of results containing + * at most this many items. If zero, the server will choose a + * reasonable page size. Must never be negative. + */ + 'max_results'?: (number | string | Long); +} +export interface GetServersRequest__Output { + /** + * start_server_id indicates that only servers at or above this id should be + * included in the results. + * To request the first page, this must be set to 0. To request + * subsequent pages, the client generates this value by adding 1 to + * the highest seen result ID. + */ + 'start_server_id': (string); + /** + * If non-zero, the server will return a page of results containing + * at most this many items. If zero, the server will choose a + * reasonable page size. Must never be negative. + */ + 'max_results': (string); +} diff --git a/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetServersRequest.js b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetServersRequest.js new file mode 100644 index 0000000..7371813 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetServersRequest.js @@ -0,0 +1,4 @@ +"use strict"; +// Original file: proto/channelz.proto +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=GetServersRequest.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetServersRequest.js.map b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetServersRequest.js.map new file mode 100644 index 0000000..db7c710 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetServersRequest.js.map @@ -0,0 +1 @@ +{"version":3,"file":"GetServersRequest.js","sourceRoot":"","sources":["../../../../../../src/generated/grpc/channelz/v1/GetServersRequest.ts"],"names":[],"mappings":";AAAA,sCAAsC"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetServersResponse.d.ts b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetServersResponse.d.ts new file mode 100644 index 0000000..d3840cd --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetServersResponse.d.ts @@ -0,0 +1,29 @@ +import type { Server as _grpc_channelz_v1_Server, Server__Output as _grpc_channelz_v1_Server__Output } from '../../../grpc/channelz/v1/Server'; +export interface GetServersResponse { + /** + * list of servers that the connection detail service knows about. Sorted in + * ascending server_id order. + * Must contain at least 1 result, otherwise 'end' must be true. + */ + 'server'?: (_grpc_channelz_v1_Server)[]; + /** + * If set, indicates that the list of servers is the final list. Requesting + * more servers will only return more if they are created after this RPC + * completes. + */ + 'end'?: (boolean); +} +export interface GetServersResponse__Output { + /** + * list of servers that the connection detail service knows about. Sorted in + * ascending server_id order. + * Must contain at least 1 result, otherwise 'end' must be true. + */ + 'server': (_grpc_channelz_v1_Server__Output)[]; + /** + * If set, indicates that the list of servers is the final list. Requesting + * more servers will only return more if they are created after this RPC + * completes. + */ + 'end': (boolean); +} diff --git a/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetServersResponse.js b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetServersResponse.js new file mode 100644 index 0000000..5124298 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetServersResponse.js @@ -0,0 +1,4 @@ +"use strict"; +// Original file: proto/channelz.proto +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=GetServersResponse.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetServersResponse.js.map b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetServersResponse.js.map new file mode 100644 index 0000000..74e4bba --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetServersResponse.js.map @@ -0,0 +1 @@ +{"version":3,"file":"GetServersResponse.js","sourceRoot":"","sources":["../../../../../../src/generated/grpc/channelz/v1/GetServersResponse.ts"],"names":[],"mappings":";AAAA,sCAAsC"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetSocketRequest.d.ts b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetSocketRequest.d.ts new file mode 100644 index 0000000..f80615c --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetSocketRequest.d.ts @@ -0,0 +1,25 @@ +import type { Long } from '@grpc/proto-loader'; +export interface GetSocketRequest { + /** + * socket_id is the identifier of the specific socket to get. + */ + 'socket_id'?: (number | string | Long); + /** + * If true, the response will contain only high level information + * that is inexpensive to obtain. Fields thay may be omitted are + * documented. + */ + 'summary'?: (boolean); +} +export interface GetSocketRequest__Output { + /** + * socket_id is the identifier of the specific socket to get. + */ + 'socket_id': (string); + /** + * If true, the response will contain only high level information + * that is inexpensive to obtain. Fields thay may be omitted are + * documented. + */ + 'summary': (boolean); +} diff --git a/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetSocketRequest.js b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetSocketRequest.js new file mode 100644 index 0000000..40ad25b --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetSocketRequest.js @@ -0,0 +1,4 @@ +"use strict"; +// Original file: proto/channelz.proto +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=GetSocketRequest.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetSocketRequest.js.map b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetSocketRequest.js.map new file mode 100644 index 0000000..3b4c180 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetSocketRequest.js.map @@ -0,0 +1 @@ +{"version":3,"file":"GetSocketRequest.js","sourceRoot":"","sources":["../../../../../../src/generated/grpc/channelz/v1/GetSocketRequest.ts"],"names":[],"mappings":";AAAA,sCAAsC"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetSocketResponse.d.ts b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetSocketResponse.d.ts new file mode 100644 index 0000000..a9795d3 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetSocketResponse.d.ts @@ -0,0 +1,15 @@ +import type { Socket as _grpc_channelz_v1_Socket, Socket__Output as _grpc_channelz_v1_Socket__Output } from '../../../grpc/channelz/v1/Socket'; +export interface GetSocketResponse { + /** + * The Socket that corresponds to the requested socket_id. This field + * should be set. + */ + 'socket'?: (_grpc_channelz_v1_Socket | null); +} +export interface GetSocketResponse__Output { + /** + * The Socket that corresponds to the requested socket_id. This field + * should be set. + */ + 'socket': (_grpc_channelz_v1_Socket__Output | null); +} diff --git a/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetSocketResponse.js b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetSocketResponse.js new file mode 100644 index 0000000..ace0ef2 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetSocketResponse.js @@ -0,0 +1,4 @@ +"use strict"; +// Original file: proto/channelz.proto +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=GetSocketResponse.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetSocketResponse.js.map b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetSocketResponse.js.map new file mode 100644 index 0000000..90fada3 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetSocketResponse.js.map @@ -0,0 +1 @@ +{"version":3,"file":"GetSocketResponse.js","sourceRoot":"","sources":["../../../../../../src/generated/grpc/channelz/v1/GetSocketResponse.ts"],"names":[],"mappings":";AAAA,sCAAsC"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetSubchannelRequest.d.ts b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetSubchannelRequest.d.ts new file mode 100644 index 0000000..114a91f --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetSubchannelRequest.d.ts @@ -0,0 +1,13 @@ +import type { Long } from '@grpc/proto-loader'; +export interface GetSubchannelRequest { + /** + * subchannel_id is the identifier of the specific subchannel to get. + */ + 'subchannel_id'?: (number | string | Long); +} +export interface GetSubchannelRequest__Output { + /** + * subchannel_id is the identifier of the specific subchannel to get. + */ + 'subchannel_id': (string); +} diff --git a/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetSubchannelRequest.js b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetSubchannelRequest.js new file mode 100644 index 0000000..90f45ea --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetSubchannelRequest.js @@ -0,0 +1,4 @@ +"use strict"; +// Original file: proto/channelz.proto +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=GetSubchannelRequest.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetSubchannelRequest.js.map b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetSubchannelRequest.js.map new file mode 100644 index 0000000..b8f8f62 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetSubchannelRequest.js.map @@ -0,0 +1 @@ +{"version":3,"file":"GetSubchannelRequest.js","sourceRoot":"","sources":["../../../../../../src/generated/grpc/channelz/v1/GetSubchannelRequest.ts"],"names":[],"mappings":";AAAA,sCAAsC"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetSubchannelResponse.d.ts b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetSubchannelResponse.d.ts new file mode 100644 index 0000000..455639f --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetSubchannelResponse.d.ts @@ -0,0 +1,15 @@ +import type { Subchannel as _grpc_channelz_v1_Subchannel, Subchannel__Output as _grpc_channelz_v1_Subchannel__Output } from '../../../grpc/channelz/v1/Subchannel'; +export interface GetSubchannelResponse { + /** + * The Subchannel that corresponds to the requested subchannel_id. This + * field should be set. + */ + 'subchannel'?: (_grpc_channelz_v1_Subchannel | null); +} +export interface GetSubchannelResponse__Output { + /** + * The Subchannel that corresponds to the requested subchannel_id. This + * field should be set. + */ + 'subchannel': (_grpc_channelz_v1_Subchannel__Output | null); +} diff --git a/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetSubchannelResponse.js b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetSubchannelResponse.js new file mode 100644 index 0000000..52d4111 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetSubchannelResponse.js @@ -0,0 +1,4 @@ +"use strict"; +// Original file: proto/channelz.proto +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=GetSubchannelResponse.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetSubchannelResponse.js.map b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetSubchannelResponse.js.map new file mode 100644 index 0000000..b39861f --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetSubchannelResponse.js.map @@ -0,0 +1 @@ +{"version":3,"file":"GetSubchannelResponse.js","sourceRoot":"","sources":["../../../../../../src/generated/grpc/channelz/v1/GetSubchannelResponse.ts"],"names":[],"mappings":";AAAA,sCAAsC"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetTopChannelsRequest.d.ts b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetTopChannelsRequest.d.ts new file mode 100644 index 0000000..43049af --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetTopChannelsRequest.d.ts @@ -0,0 +1,33 @@ +import type { Long } from '@grpc/proto-loader'; +export interface GetTopChannelsRequest { + /** + * start_channel_id indicates that only channels at or above this id should be + * included in the results. + * To request the first page, this should be set to 0. To request + * subsequent pages, the client generates this value by adding 1 to + * the highest seen result ID. + */ + 'start_channel_id'?: (number | string | Long); + /** + * If non-zero, the server will return a page of results containing + * at most this many items. If zero, the server will choose a + * reasonable page size. Must never be negative. + */ + 'max_results'?: (number | string | Long); +} +export interface GetTopChannelsRequest__Output { + /** + * start_channel_id indicates that only channels at or above this id should be + * included in the results. + * To request the first page, this should be set to 0. To request + * subsequent pages, the client generates this value by adding 1 to + * the highest seen result ID. + */ + 'start_channel_id': (string); + /** + * If non-zero, the server will return a page of results containing + * at most this many items. If zero, the server will choose a + * reasonable page size. Must never be negative. + */ + 'max_results': (string); +} diff --git a/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetTopChannelsRequest.js b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetTopChannelsRequest.js new file mode 100644 index 0000000..8b3e023 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetTopChannelsRequest.js @@ -0,0 +1,4 @@ +"use strict"; +// Original file: proto/channelz.proto +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=GetTopChannelsRequest.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetTopChannelsRequest.js.map b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetTopChannelsRequest.js.map new file mode 100644 index 0000000..c4ffc68 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetTopChannelsRequest.js.map @@ -0,0 +1 @@ +{"version":3,"file":"GetTopChannelsRequest.js","sourceRoot":"","sources":["../../../../../../src/generated/grpc/channelz/v1/GetTopChannelsRequest.ts"],"names":[],"mappings":";AAAA,sCAAsC"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetTopChannelsResponse.d.ts b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetTopChannelsResponse.d.ts new file mode 100644 index 0000000..03f282f --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetTopChannelsResponse.d.ts @@ -0,0 +1,29 @@ +import type { Channel as _grpc_channelz_v1_Channel, Channel__Output as _grpc_channelz_v1_Channel__Output } from '../../../grpc/channelz/v1/Channel'; +export interface GetTopChannelsResponse { + /** + * list of channels that the connection detail service knows about. Sorted in + * ascending channel_id order. + * Must contain at least 1 result, otherwise 'end' must be true. + */ + 'channel'?: (_grpc_channelz_v1_Channel)[]; + /** + * If set, indicates that the list of channels is the final list. Requesting + * more channels can only return more if they are created after this RPC + * completes. + */ + 'end'?: (boolean); +} +export interface GetTopChannelsResponse__Output { + /** + * list of channels that the connection detail service knows about. Sorted in + * ascending channel_id order. + * Must contain at least 1 result, otherwise 'end' must be true. + */ + 'channel': (_grpc_channelz_v1_Channel__Output)[]; + /** + * If set, indicates that the list of channels is the final list. Requesting + * more channels can only return more if they are created after this RPC + * completes. + */ + 'end': (boolean); +} diff --git a/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetTopChannelsResponse.js b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetTopChannelsResponse.js new file mode 100644 index 0000000..44f1c91 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetTopChannelsResponse.js @@ -0,0 +1,4 @@ +"use strict"; +// Original file: proto/channelz.proto +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=GetTopChannelsResponse.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetTopChannelsResponse.js.map b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetTopChannelsResponse.js.map new file mode 100644 index 0000000..b691e5e --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/GetTopChannelsResponse.js.map @@ -0,0 +1 @@ +{"version":3,"file":"GetTopChannelsResponse.js","sourceRoot":"","sources":["../../../../../../src/generated/grpc/channelz/v1/GetTopChannelsResponse.ts"],"names":[],"mappings":";AAAA,sCAAsC"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/Security.d.ts b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/Security.d.ts new file mode 100644 index 0000000..a78e8f8 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/Security.d.ts @@ -0,0 +1,80 @@ +/// +import type { Any as _google_protobuf_Any, Any__Output as _google_protobuf_Any__Output } from '../../../google/protobuf/Any'; +export interface _grpc_channelz_v1_Security_OtherSecurity { + /** + * The human readable version of the value. + */ + 'name'?: (string); + /** + * The actual security details message. + */ + 'value'?: (_google_protobuf_Any | null); +} +export interface _grpc_channelz_v1_Security_OtherSecurity__Output { + /** + * The human readable version of the value. + */ + 'name': (string); + /** + * The actual security details message. + */ + 'value': (_google_protobuf_Any__Output | null); +} +export interface _grpc_channelz_v1_Security_Tls { + /** + * The cipher suite name in the RFC 4346 format: + * https://tools.ietf.org/html/rfc4346#appendix-C + */ + 'standard_name'?: (string); + /** + * Some other way to describe the cipher suite if + * the RFC 4346 name is not available. + */ + 'other_name'?: (string); + /** + * the certificate used by this endpoint. + */ + 'local_certificate'?: (Buffer | Uint8Array | string); + /** + * the certificate used by the remote endpoint. + */ + 'remote_certificate'?: (Buffer | Uint8Array | string); + 'cipher_suite'?: "standard_name" | "other_name"; +} +export interface _grpc_channelz_v1_Security_Tls__Output { + /** + * The cipher suite name in the RFC 4346 format: + * https://tools.ietf.org/html/rfc4346#appendix-C + */ + 'standard_name'?: (string); + /** + * Some other way to describe the cipher suite if + * the RFC 4346 name is not available. + */ + 'other_name'?: (string); + /** + * the certificate used by this endpoint. + */ + 'local_certificate': (Buffer); + /** + * the certificate used by the remote endpoint. + */ + 'remote_certificate': (Buffer); + 'cipher_suite': "standard_name" | "other_name"; +} +/** + * Security represents details about how secure the socket is. + */ +export interface Security { + 'tls'?: (_grpc_channelz_v1_Security_Tls | null); + 'other'?: (_grpc_channelz_v1_Security_OtherSecurity | null); + 'model'?: "tls" | "other"; +} +/** + * Security represents details about how secure the socket is. + */ +export interface Security__Output { + 'tls'?: (_grpc_channelz_v1_Security_Tls__Output | null); + 'other'?: (_grpc_channelz_v1_Security_OtherSecurity__Output | null); + 'model': "tls" | "other"; +} diff --git a/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/Security.js b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/Security.js new file mode 100644 index 0000000..022b367 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/Security.js @@ -0,0 +1,4 @@ +"use strict"; +// Original file: proto/channelz.proto +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=Security.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/Security.js.map b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/Security.js.map new file mode 100644 index 0000000..3243c97 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/Security.js.map @@ -0,0 +1 @@ +{"version":3,"file":"Security.js","sourceRoot":"","sources":["../../../../../../src/generated/grpc/channelz/v1/Security.ts"],"names":[],"mappings":";AAAA,sCAAsC"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/Server.d.ts b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/Server.d.ts new file mode 100644 index 0000000..8d984af --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/Server.d.ts @@ -0,0 +1,41 @@ +import type { ServerRef as _grpc_channelz_v1_ServerRef, ServerRef__Output as _grpc_channelz_v1_ServerRef__Output } from '../../../grpc/channelz/v1/ServerRef'; +import type { ServerData as _grpc_channelz_v1_ServerData, ServerData__Output as _grpc_channelz_v1_ServerData__Output } from '../../../grpc/channelz/v1/ServerData'; +import type { SocketRef as _grpc_channelz_v1_SocketRef, SocketRef__Output as _grpc_channelz_v1_SocketRef__Output } from '../../../grpc/channelz/v1/SocketRef'; +/** + * Server represents a single server. There may be multiple servers in a single + * program. + */ +export interface Server { + /** + * The identifier for a Server. This should be set. + */ + 'ref'?: (_grpc_channelz_v1_ServerRef | null); + /** + * The associated data of the Server. + */ + 'data'?: (_grpc_channelz_v1_ServerData | null); + /** + * The sockets that the server is listening on. There are no ordering + * guarantees. This may be absent. + */ + 'listen_socket'?: (_grpc_channelz_v1_SocketRef)[]; +} +/** + * Server represents a single server. There may be multiple servers in a single + * program. + */ +export interface Server__Output { + /** + * The identifier for a Server. This should be set. + */ + 'ref': (_grpc_channelz_v1_ServerRef__Output | null); + /** + * The associated data of the Server. + */ + 'data': (_grpc_channelz_v1_ServerData__Output | null); + /** + * The sockets that the server is listening on. There are no ordering + * guarantees. This may be absent. + */ + 'listen_socket': (_grpc_channelz_v1_SocketRef__Output)[]; +} diff --git a/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/Server.js b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/Server.js new file mode 100644 index 0000000..b230e4d --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/Server.js @@ -0,0 +1,4 @@ +"use strict"; +// Original file: proto/channelz.proto +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=Server.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/Server.js.map b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/Server.js.map new file mode 100644 index 0000000..522934d --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/Server.js.map @@ -0,0 +1 @@ +{"version":3,"file":"Server.js","sourceRoot":"","sources":["../../../../../../src/generated/grpc/channelz/v1/Server.ts"],"names":[],"mappings":";AAAA,sCAAsC"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/ServerData.d.ts b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/ServerData.d.ts new file mode 100644 index 0000000..7a2de0f --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/ServerData.d.ts @@ -0,0 +1,53 @@ +import type { ChannelTrace as _grpc_channelz_v1_ChannelTrace, ChannelTrace__Output as _grpc_channelz_v1_ChannelTrace__Output } from '../../../grpc/channelz/v1/ChannelTrace'; +import type { Timestamp as _google_protobuf_Timestamp, Timestamp__Output as _google_protobuf_Timestamp__Output } from '../../../google/protobuf/Timestamp'; +import type { Long } from '@grpc/proto-loader'; +/** + * ServerData is data for a specific Server. + */ +export interface ServerData { + /** + * A trace of recent events on the server. May be absent. + */ + 'trace'?: (_grpc_channelz_v1_ChannelTrace | null); + /** + * The number of incoming calls started on the server + */ + 'calls_started'?: (number | string | Long); + /** + * The number of incoming calls that have completed with an OK status + */ + 'calls_succeeded'?: (number | string | Long); + /** + * The number of incoming calls that have a completed with a non-OK status + */ + 'calls_failed'?: (number | string | Long); + /** + * The last time a call was started on the server. + */ + 'last_call_started_timestamp'?: (_google_protobuf_Timestamp | null); +} +/** + * ServerData is data for a specific Server. + */ +export interface ServerData__Output { + /** + * A trace of recent events on the server. May be absent. + */ + 'trace': (_grpc_channelz_v1_ChannelTrace__Output | null); + /** + * The number of incoming calls started on the server + */ + 'calls_started': (string); + /** + * The number of incoming calls that have completed with an OK status + */ + 'calls_succeeded': (string); + /** + * The number of incoming calls that have a completed with a non-OK status + */ + 'calls_failed': (string); + /** + * The last time a call was started on the server. + */ + 'last_call_started_timestamp': (_google_protobuf_Timestamp__Output | null); +} diff --git a/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/ServerData.js b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/ServerData.js new file mode 100644 index 0000000..53d92a6 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/ServerData.js @@ -0,0 +1,4 @@ +"use strict"; +// Original file: proto/channelz.proto +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=ServerData.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/ServerData.js.map b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/ServerData.js.map new file mode 100644 index 0000000..b78c5b4 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/ServerData.js.map @@ -0,0 +1 @@ +{"version":3,"file":"ServerData.js","sourceRoot":"","sources":["../../../../../../src/generated/grpc/channelz/v1/ServerData.ts"],"names":[],"mappings":";AAAA,sCAAsC"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/ServerRef.d.ts b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/ServerRef.d.ts new file mode 100644 index 0000000..778b87d --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/ServerRef.d.ts @@ -0,0 +1,27 @@ +import type { Long } from '@grpc/proto-loader'; +/** + * ServerRef is a reference to a Server. + */ +export interface ServerRef { + /** + * A globally unique identifier for this server. Must be a positive number. + */ + 'server_id'?: (number | string | Long); + /** + * An optional name associated with the server. + */ + 'name'?: (string); +} +/** + * ServerRef is a reference to a Server. + */ +export interface ServerRef__Output { + /** + * A globally unique identifier for this server. Must be a positive number. + */ + 'server_id': (string); + /** + * An optional name associated with the server. + */ + 'name': (string); +} diff --git a/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/ServerRef.js b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/ServerRef.js new file mode 100644 index 0000000..9a623c7 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/ServerRef.js @@ -0,0 +1,4 @@ +"use strict"; +// Original file: proto/channelz.proto +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=ServerRef.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/ServerRef.js.map b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/ServerRef.js.map new file mode 100644 index 0000000..75f5aad --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/ServerRef.js.map @@ -0,0 +1 @@ +{"version":3,"file":"ServerRef.js","sourceRoot":"","sources":["../../../../../../src/generated/grpc/channelz/v1/ServerRef.ts"],"names":[],"mappings":";AAAA,sCAAsC"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/Socket.d.ts b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/Socket.d.ts new file mode 100644 index 0000000..91d4ad8 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/Socket.d.ts @@ -0,0 +1,66 @@ +import type { SocketRef as _grpc_channelz_v1_SocketRef, SocketRef__Output as _grpc_channelz_v1_SocketRef__Output } from '../../../grpc/channelz/v1/SocketRef'; +import type { SocketData as _grpc_channelz_v1_SocketData, SocketData__Output as _grpc_channelz_v1_SocketData__Output } from '../../../grpc/channelz/v1/SocketData'; +import type { Address as _grpc_channelz_v1_Address, Address__Output as _grpc_channelz_v1_Address__Output } from '../../../grpc/channelz/v1/Address'; +import type { Security as _grpc_channelz_v1_Security, Security__Output as _grpc_channelz_v1_Security__Output } from '../../../grpc/channelz/v1/Security'; +/** + * Information about an actual connection. Pronounced "sock-ay". + */ +export interface Socket { + /** + * The identifier for the Socket. + */ + 'ref'?: (_grpc_channelz_v1_SocketRef | null); + /** + * Data specific to this Socket. + */ + 'data'?: (_grpc_channelz_v1_SocketData | null); + /** + * The locally bound address. + */ + 'local'?: (_grpc_channelz_v1_Address | null); + /** + * The remote bound address. May be absent. + */ + 'remote'?: (_grpc_channelz_v1_Address | null); + /** + * Security details for this socket. May be absent if not available, or + * there is no security on the socket. + */ + 'security'?: (_grpc_channelz_v1_Security | null); + /** + * Optional, represents the name of the remote endpoint, if different than + * the original target name. + */ + 'remote_name'?: (string); +} +/** + * Information about an actual connection. Pronounced "sock-ay". + */ +export interface Socket__Output { + /** + * The identifier for the Socket. + */ + 'ref': (_grpc_channelz_v1_SocketRef__Output | null); + /** + * Data specific to this Socket. + */ + 'data': (_grpc_channelz_v1_SocketData__Output | null); + /** + * The locally bound address. + */ + 'local': (_grpc_channelz_v1_Address__Output | null); + /** + * The remote bound address. May be absent. + */ + 'remote': (_grpc_channelz_v1_Address__Output | null); + /** + * Security details for this socket. May be absent if not available, or + * there is no security on the socket. + */ + 'security': (_grpc_channelz_v1_Security__Output | null); + /** + * Optional, represents the name of the remote endpoint, if different than + * the original target name. + */ + 'remote_name': (string); +} diff --git a/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/Socket.js b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/Socket.js new file mode 100644 index 0000000..c1e5004 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/Socket.js @@ -0,0 +1,4 @@ +"use strict"; +// Original file: proto/channelz.proto +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=Socket.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/Socket.js.map b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/Socket.js.map new file mode 100644 index 0000000..d49d9df --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/Socket.js.map @@ -0,0 +1 @@ +{"version":3,"file":"Socket.js","sourceRoot":"","sources":["../../../../../../src/generated/grpc/channelz/v1/Socket.ts"],"names":[],"mappings":";AAAA,sCAAsC"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/SocketData.d.ts b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/SocketData.d.ts new file mode 100644 index 0000000..5553cb2 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/SocketData.d.ts @@ -0,0 +1,146 @@ +import type { Timestamp as _google_protobuf_Timestamp, Timestamp__Output as _google_protobuf_Timestamp__Output } from '../../../google/protobuf/Timestamp'; +import type { Int64Value as _google_protobuf_Int64Value, Int64Value__Output as _google_protobuf_Int64Value__Output } from '../../../google/protobuf/Int64Value'; +import type { SocketOption as _grpc_channelz_v1_SocketOption, SocketOption__Output as _grpc_channelz_v1_SocketOption__Output } from '../../../grpc/channelz/v1/SocketOption'; +import type { Long } from '@grpc/proto-loader'; +/** + * SocketData is data associated for a specific Socket. The fields present + * are specific to the implementation, so there may be minor differences in + * the semantics. (e.g. flow control windows) + */ +export interface SocketData { + /** + * The number of streams that have been started. + */ + 'streams_started'?: (number | string | Long); + /** + * The number of streams that have ended successfully: + * On client side, received frame with eos bit set; + * On server side, sent frame with eos bit set. + */ + 'streams_succeeded'?: (number | string | Long); + /** + * The number of streams that have ended unsuccessfully: + * On client side, ended without receiving frame with eos bit set; + * On server side, ended without sending frame with eos bit set. + */ + 'streams_failed'?: (number | string | Long); + /** + * The number of grpc messages successfully sent on this socket. + */ + 'messages_sent'?: (number | string | Long); + /** + * The number of grpc messages received on this socket. + */ + 'messages_received'?: (number | string | Long); + /** + * The number of keep alives sent. This is typically implemented with HTTP/2 + * ping messages. + */ + 'keep_alives_sent'?: (number | string | Long); + /** + * The last time a stream was created by this endpoint. Usually unset for + * servers. + */ + 'last_local_stream_created_timestamp'?: (_google_protobuf_Timestamp | null); + /** + * The last time a stream was created by the remote endpoint. Usually unset + * for clients. + */ + 'last_remote_stream_created_timestamp'?: (_google_protobuf_Timestamp | null); + /** + * The last time a message was sent by this endpoint. + */ + 'last_message_sent_timestamp'?: (_google_protobuf_Timestamp | null); + /** + * The last time a message was received by this endpoint. + */ + 'last_message_received_timestamp'?: (_google_protobuf_Timestamp | null); + /** + * The amount of window, granted to the local endpoint by the remote endpoint. + * This may be slightly out of date due to network latency. This does NOT + * include stream level or TCP level flow control info. + */ + 'local_flow_control_window'?: (_google_protobuf_Int64Value | null); + /** + * The amount of window, granted to the remote endpoint by the local endpoint. + * This may be slightly out of date due to network latency. This does NOT + * include stream level or TCP level flow control info. + */ + 'remote_flow_control_window'?: (_google_protobuf_Int64Value | null); + /** + * Socket options set on this socket. May be absent if 'summary' is set + * on GetSocketRequest. + */ + 'option'?: (_grpc_channelz_v1_SocketOption)[]; +} +/** + * SocketData is data associated for a specific Socket. The fields present + * are specific to the implementation, so there may be minor differences in + * the semantics. (e.g. flow control windows) + */ +export interface SocketData__Output { + /** + * The number of streams that have been started. + */ + 'streams_started': (string); + /** + * The number of streams that have ended successfully: + * On client side, received frame with eos bit set; + * On server side, sent frame with eos bit set. + */ + 'streams_succeeded': (string); + /** + * The number of streams that have ended unsuccessfully: + * On client side, ended without receiving frame with eos bit set; + * On server side, ended without sending frame with eos bit set. + */ + 'streams_failed': (string); + /** + * The number of grpc messages successfully sent on this socket. + */ + 'messages_sent': (string); + /** + * The number of grpc messages received on this socket. + */ + 'messages_received': (string); + /** + * The number of keep alives sent. This is typically implemented with HTTP/2 + * ping messages. + */ + 'keep_alives_sent': (string); + /** + * The last time a stream was created by this endpoint. Usually unset for + * servers. + */ + 'last_local_stream_created_timestamp': (_google_protobuf_Timestamp__Output | null); + /** + * The last time a stream was created by the remote endpoint. Usually unset + * for clients. + */ + 'last_remote_stream_created_timestamp': (_google_protobuf_Timestamp__Output | null); + /** + * The last time a message was sent by this endpoint. + */ + 'last_message_sent_timestamp': (_google_protobuf_Timestamp__Output | null); + /** + * The last time a message was received by this endpoint. + */ + 'last_message_received_timestamp': (_google_protobuf_Timestamp__Output | null); + /** + * The amount of window, granted to the local endpoint by the remote endpoint. + * This may be slightly out of date due to network latency. This does NOT + * include stream level or TCP level flow control info. + */ + 'local_flow_control_window': (_google_protobuf_Int64Value__Output | null); + /** + * The amount of window, granted to the remote endpoint by the local endpoint. + * This may be slightly out of date due to network latency. This does NOT + * include stream level or TCP level flow control info. + */ + 'remote_flow_control_window': (_google_protobuf_Int64Value__Output | null); + /** + * Socket options set on this socket. May be absent if 'summary' is set + * on GetSocketRequest. + */ + 'option': (_grpc_channelz_v1_SocketOption__Output)[]; +} diff --git a/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/SocketData.js b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/SocketData.js new file mode 100644 index 0000000..40638de --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/SocketData.js @@ -0,0 +1,4 @@ +"use strict"; +// Original file: proto/channelz.proto +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=SocketData.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/SocketData.js.map b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/SocketData.js.map new file mode 100644 index 0000000..c17becd --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/SocketData.js.map @@ -0,0 +1 @@ +{"version":3,"file":"SocketData.js","sourceRoot":"","sources":["../../../../../../src/generated/grpc/channelz/v1/SocketData.ts"],"names":[],"mappings":";AAAA,sCAAsC"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/SocketOption.d.ts b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/SocketOption.d.ts new file mode 100644 index 0000000..53c23a2 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/SocketOption.d.ts @@ -0,0 +1,43 @@ +import type { Any as _google_protobuf_Any, Any__Output as _google_protobuf_Any__Output } from '../../../google/protobuf/Any'; +/** + * SocketOption represents socket options for a socket. Specifically, these + * are the options returned by getsockopt(). + */ +export interface SocketOption { + /** + * The full name of the socket option. Typically this will be the upper case + * name, such as "SO_REUSEPORT". + */ + 'name'?: (string); + /** + * The human readable value of this socket option. At least one of value or + * additional will be set. + */ + 'value'?: (string); + /** + * Additional data associated with the socket option. At least one of value + * or additional will be set. + */ + 'additional'?: (_google_protobuf_Any | null); +} +/** + * SocketOption represents socket options for a socket. Specifically, these + * are the options returned by getsockopt(). + */ +export interface SocketOption__Output { + /** + * The full name of the socket option. Typically this will be the upper case + * name, such as "SO_REUSEPORT". + */ + 'name': (string); + /** + * The human readable value of this socket option. At least one of value or + * additional will be set. + */ + 'value': (string); + /** + * Additional data associated with the socket option. At least one of value + * or additional will be set. + */ + 'additional': (_google_protobuf_Any__Output | null); +} diff --git a/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/SocketOption.js b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/SocketOption.js new file mode 100644 index 0000000..c459962 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/SocketOption.js @@ -0,0 +1,4 @@ +"use strict"; +// Original file: proto/channelz.proto +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=SocketOption.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/SocketOption.js.map b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/SocketOption.js.map new file mode 100644 index 0000000..6b8bf59 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/SocketOption.js.map @@ -0,0 +1 @@ +{"version":3,"file":"SocketOption.js","sourceRoot":"","sources":["../../../../../../src/generated/grpc/channelz/v1/SocketOption.ts"],"names":[],"mappings":";AAAA,sCAAsC"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/SocketOptionLinger.d.ts b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/SocketOptionLinger.d.ts new file mode 100644 index 0000000..d0fd4b0 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/SocketOptionLinger.d.ts @@ -0,0 +1,29 @@ +import type { Duration as _google_protobuf_Duration, Duration__Output as _google_protobuf_Duration__Output } from '../../../google/protobuf/Duration'; +/** + * For use with SocketOption's additional field. This is primarily used for + * SO_LINGER. + */ +export interface SocketOptionLinger { + /** + * active maps to `struct linger.l_onoff` + */ + 'active'?: (boolean); + /** + * duration maps to `struct linger.l_linger` + */ + 'duration'?: (_google_protobuf_Duration | null); +} +/** + * For use with SocketOption's additional field. This is primarily used for + * SO_LINGER. + */ +export interface SocketOptionLinger__Output { + /** + * active maps to `struct linger.l_onoff` + */ + 'active': (boolean); + /** + * duration maps to `struct linger.l_linger` + */ + 'duration': (_google_protobuf_Duration__Output | null); +} diff --git a/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/SocketOptionLinger.js b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/SocketOptionLinger.js new file mode 100644 index 0000000..01028c8 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/SocketOptionLinger.js @@ -0,0 +1,4 @@ +"use strict"; +// Original file: proto/channelz.proto +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=SocketOptionLinger.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/SocketOptionLinger.js.map b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/SocketOptionLinger.js.map new file mode 100644 index 0000000..a5283ab --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/SocketOptionLinger.js.map @@ -0,0 +1 @@ +{"version":3,"file":"SocketOptionLinger.js","sourceRoot":"","sources":["../../../../../../src/generated/grpc/channelz/v1/SocketOptionLinger.ts"],"names":[],"mappings":";AAAA,sCAAsC"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/SocketOptionTcpInfo.d.ts b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/SocketOptionTcpInfo.d.ts new file mode 100644 index 0000000..d2457e1 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/SocketOptionTcpInfo.d.ts @@ -0,0 +1,70 @@ +/** + * For use with SocketOption's additional field. Tcp info for + * SOL_TCP and TCP_INFO. + */ +export interface SocketOptionTcpInfo { + 'tcpi_state'?: (number); + 'tcpi_ca_state'?: (number); + 'tcpi_retransmits'?: (number); + 'tcpi_probes'?: (number); + 'tcpi_backoff'?: (number); + 'tcpi_options'?: (number); + 'tcpi_snd_wscale'?: (number); + 'tcpi_rcv_wscale'?: (number); + 'tcpi_rto'?: (number); + 'tcpi_ato'?: (number); + 'tcpi_snd_mss'?: (number); + 'tcpi_rcv_mss'?: (number); + 'tcpi_unacked'?: (number); + 'tcpi_sacked'?: (number); + 'tcpi_lost'?: (number); + 'tcpi_retrans'?: (number); + 'tcpi_fackets'?: (number); + 'tcpi_last_data_sent'?: (number); + 'tcpi_last_ack_sent'?: (number); + 'tcpi_last_data_recv'?: (number); + 'tcpi_last_ack_recv'?: (number); + 'tcpi_pmtu'?: (number); + 'tcpi_rcv_ssthresh'?: (number); + 'tcpi_rtt'?: (number); + 'tcpi_rttvar'?: (number); + 'tcpi_snd_ssthresh'?: (number); + 'tcpi_snd_cwnd'?: (number); + 'tcpi_advmss'?: (number); + 'tcpi_reordering'?: (number); +} +/** + * For use with SocketOption's additional field. Tcp info for + * SOL_TCP and TCP_INFO. + */ +export interface SocketOptionTcpInfo__Output { + 'tcpi_state': (number); + 'tcpi_ca_state': (number); + 'tcpi_retransmits': (number); + 'tcpi_probes': (number); + 'tcpi_backoff': (number); + 'tcpi_options': (number); + 'tcpi_snd_wscale': (number); + 'tcpi_rcv_wscale': (number); + 'tcpi_rto': (number); + 'tcpi_ato': (number); + 'tcpi_snd_mss': (number); + 'tcpi_rcv_mss': (number); + 'tcpi_unacked': (number); + 'tcpi_sacked': (number); + 'tcpi_lost': (number); + 'tcpi_retrans': (number); + 'tcpi_fackets': (number); + 'tcpi_last_data_sent': (number); + 'tcpi_last_ack_sent': (number); + 'tcpi_last_data_recv': (number); + 'tcpi_last_ack_recv': (number); + 'tcpi_pmtu': (number); + 'tcpi_rcv_ssthresh': (number); + 'tcpi_rtt': (number); + 'tcpi_rttvar': (number); + 'tcpi_snd_ssthresh': (number); + 'tcpi_snd_cwnd': (number); + 'tcpi_advmss': (number); + 'tcpi_reordering': (number); +} diff --git a/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/SocketOptionTcpInfo.js b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/SocketOptionTcpInfo.js new file mode 100644 index 0000000..b663a2e --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/SocketOptionTcpInfo.js @@ -0,0 +1,4 @@ +"use strict"; +// Original file: proto/channelz.proto +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=SocketOptionTcpInfo.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/SocketOptionTcpInfo.js.map b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/SocketOptionTcpInfo.js.map new file mode 100644 index 0000000..cb68a32 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/SocketOptionTcpInfo.js.map @@ -0,0 +1 @@ +{"version":3,"file":"SocketOptionTcpInfo.js","sourceRoot":"","sources":["../../../../../../src/generated/grpc/channelz/v1/SocketOptionTcpInfo.ts"],"names":[],"mappings":";AAAA,sCAAsC"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/SocketOptionTimeout.d.ts b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/SocketOptionTimeout.d.ts new file mode 100644 index 0000000..b102a34 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/SocketOptionTimeout.d.ts @@ -0,0 +1,15 @@ +import type { Duration as _google_protobuf_Duration, Duration__Output as _google_protobuf_Duration__Output } from '../../../google/protobuf/Duration'; +/** + * For use with SocketOption's additional field. This is primarily used for + * SO_RCVTIMEO and SO_SNDTIMEO + */ +export interface SocketOptionTimeout { + 'duration'?: (_google_protobuf_Duration | null); +} +/** + * For use with SocketOption's additional field. This is primarily used for + * SO_RCVTIMEO and SO_SNDTIMEO + */ +export interface SocketOptionTimeout__Output { + 'duration': (_google_protobuf_Duration__Output | null); +} diff --git a/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/SocketOptionTimeout.js b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/SocketOptionTimeout.js new file mode 100644 index 0000000..bcef7f5 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/SocketOptionTimeout.js @@ -0,0 +1,4 @@ +"use strict"; +// Original file: proto/channelz.proto +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=SocketOptionTimeout.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/SocketOptionTimeout.js.map b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/SocketOptionTimeout.js.map new file mode 100644 index 0000000..73c8085 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/SocketOptionTimeout.js.map @@ -0,0 +1 @@ +{"version":3,"file":"SocketOptionTimeout.js","sourceRoot":"","sources":["../../../../../../src/generated/grpc/channelz/v1/SocketOptionTimeout.ts"],"names":[],"mappings":";AAAA,sCAAsC"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/SocketRef.d.ts b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/SocketRef.d.ts new file mode 100644 index 0000000..2f34d65 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/SocketRef.d.ts @@ -0,0 +1,27 @@ +import type { Long } from '@grpc/proto-loader'; +/** + * SocketRef is a reference to a Socket. + */ +export interface SocketRef { + /** + * The globally unique id for this socket. Must be a positive number. + */ + 'socket_id'?: (number | string | Long); + /** + * An optional name associated with the socket. + */ + 'name'?: (string); +} +/** + * SocketRef is a reference to a Socket. + */ +export interface SocketRef__Output { + /** + * The globally unique id for this socket. Must be a positive number. + */ + 'socket_id': (string); + /** + * An optional name associated with the socket. + */ + 'name': (string); +} diff --git a/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/SocketRef.js b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/SocketRef.js new file mode 100644 index 0000000..a73587f --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/SocketRef.js @@ -0,0 +1,4 @@ +"use strict"; +// Original file: proto/channelz.proto +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=SocketRef.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/SocketRef.js.map b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/SocketRef.js.map new file mode 100644 index 0000000..d970f9c --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/SocketRef.js.map @@ -0,0 +1 @@ +{"version":3,"file":"SocketRef.js","sourceRoot":"","sources":["../../../../../../src/generated/grpc/channelz/v1/SocketRef.ts"],"names":[],"mappings":";AAAA,sCAAsC"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/Subchannel.d.ts b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/Subchannel.d.ts new file mode 100644 index 0000000..1222cb5 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/Subchannel.d.ts @@ -0,0 +1,66 @@ +import type { SubchannelRef as _grpc_channelz_v1_SubchannelRef, SubchannelRef__Output as _grpc_channelz_v1_SubchannelRef__Output } from '../../../grpc/channelz/v1/SubchannelRef'; +import type { ChannelData as _grpc_channelz_v1_ChannelData, ChannelData__Output as _grpc_channelz_v1_ChannelData__Output } from '../../../grpc/channelz/v1/ChannelData'; +import type { ChannelRef as _grpc_channelz_v1_ChannelRef, ChannelRef__Output as _grpc_channelz_v1_ChannelRef__Output } from '../../../grpc/channelz/v1/ChannelRef'; +import type { SocketRef as _grpc_channelz_v1_SocketRef, SocketRef__Output as _grpc_channelz_v1_SocketRef__Output } from '../../../grpc/channelz/v1/SocketRef'; +/** + * Subchannel is a logical grouping of channels, subchannels, and sockets. + * A subchannel is load balanced over by it's ancestor + */ +export interface Subchannel { + /** + * The identifier for this channel. + */ + 'ref'?: (_grpc_channelz_v1_SubchannelRef | null); + /** + * Data specific to this channel. + */ + 'data'?: (_grpc_channelz_v1_ChannelData | null); + /** + * There are no ordering guarantees on the order of channel refs. + * There may not be cycles in the ref graph. + * A channel ref may be present in more than one channel or subchannel. + */ + 'channel_ref'?: (_grpc_channelz_v1_ChannelRef)[]; + /** + * At most one of 'channel_ref+subchannel_ref' and 'socket' is set. + * There are no ordering guarantees on the order of subchannel refs. + * There may not be cycles in the ref graph. + * A sub channel ref may be present in more than one channel or subchannel. + */ + 'subchannel_ref'?: (_grpc_channelz_v1_SubchannelRef)[]; + /** + * There are no ordering guarantees on the order of sockets. + */ + 'socket_ref'?: (_grpc_channelz_v1_SocketRef)[]; +} +/** + * Subchannel is a logical grouping of channels, subchannels, and sockets. + * A subchannel is load balanced over by it's ancestor + */ +export interface Subchannel__Output { + /** + * The identifier for this channel. + */ + 'ref': (_grpc_channelz_v1_SubchannelRef__Output | null); + /** + * Data specific to this channel. + */ + 'data': (_grpc_channelz_v1_ChannelData__Output | null); + /** + * There are no ordering guarantees on the order of channel refs. + * There may not be cycles in the ref graph. + * A channel ref may be present in more than one channel or subchannel. + */ + 'channel_ref': (_grpc_channelz_v1_ChannelRef__Output)[]; + /** + * At most one of 'channel_ref+subchannel_ref' and 'socket' is set. + * There are no ordering guarantees on the order of subchannel refs. + * There may not be cycles in the ref graph. + * A sub channel ref may be present in more than one channel or subchannel. + */ + 'subchannel_ref': (_grpc_channelz_v1_SubchannelRef__Output)[]; + /** + * There are no ordering guarantees on the order of sockets. + */ + 'socket_ref': (_grpc_channelz_v1_SocketRef__Output)[]; +} diff --git a/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/Subchannel.js b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/Subchannel.js new file mode 100644 index 0000000..6a5e543 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/Subchannel.js @@ -0,0 +1,4 @@ +"use strict"; +// Original file: proto/channelz.proto +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=Subchannel.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/Subchannel.js.map b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/Subchannel.js.map new file mode 100644 index 0000000..6441346 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/Subchannel.js.map @@ -0,0 +1 @@ +{"version":3,"file":"Subchannel.js","sourceRoot":"","sources":["../../../../../../src/generated/grpc/channelz/v1/Subchannel.ts"],"names":[],"mappings":";AAAA,sCAAsC"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/SubchannelRef.d.ts b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/SubchannelRef.d.ts new file mode 100644 index 0000000..290fc85 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/SubchannelRef.d.ts @@ -0,0 +1,27 @@ +import type { Long } from '@grpc/proto-loader'; +/** + * SubchannelRef is a reference to a Subchannel. + */ +export interface SubchannelRef { + /** + * The globally unique id for this subchannel. Must be a positive number. + */ + 'subchannel_id'?: (number | string | Long); + /** + * An optional name associated with the subchannel. + */ + 'name'?: (string); +} +/** + * SubchannelRef is a reference to a Subchannel. + */ +export interface SubchannelRef__Output { + /** + * The globally unique id for this subchannel. Must be a positive number. + */ + 'subchannel_id': (string); + /** + * An optional name associated with the subchannel. + */ + 'name': (string); +} diff --git a/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/SubchannelRef.js b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/SubchannelRef.js new file mode 100644 index 0000000..68520f9 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/SubchannelRef.js @@ -0,0 +1,4 @@ +"use strict"; +// Original file: proto/channelz.proto +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=SubchannelRef.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/SubchannelRef.js.map b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/SubchannelRef.js.map new file mode 100644 index 0000000..1e4b009 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/generated/grpc/channelz/v1/SubchannelRef.js.map @@ -0,0 +1 @@ +{"version":3,"file":"SubchannelRef.js","sourceRoot":"","sources":["../../../../../../src/generated/grpc/channelz/v1/SubchannelRef.ts"],"names":[],"mappings":";AAAA,sCAAsC"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/http_proxy.d.ts b/node_modules/@grpc/grpc-js/build/src/http_proxy.d.ts new file mode 100644 index 0000000..345e42c --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/http_proxy.d.ts @@ -0,0 +1,17 @@ +/// +/// +import { Socket } from 'net'; +import * as tls from 'tls'; +import { SubchannelAddress } from './subchannel-address'; +import { ChannelOptions } from './channel-options'; +import { GrpcUri } from './uri-parser'; +export interface ProxyMapResult { + target: GrpcUri; + extraOptions: ChannelOptions; +} +export declare function mapProxyName(target: GrpcUri, options: ChannelOptions): ProxyMapResult; +export interface ProxyConnectionResult { + socket?: Socket; + realTarget?: GrpcUri; +} +export declare function getProxiedConnection(address: SubchannelAddress, channelOptions: ChannelOptions, connectionOptions: tls.ConnectionOptions): Promise; diff --git a/node_modules/@grpc/grpc-js/build/src/http_proxy.js b/node_modules/@grpc/grpc-js/build/src/http_proxy.js new file mode 100644 index 0000000..67fc1e2 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/http_proxy.js @@ -0,0 +1,260 @@ +"use strict"; +/* + * Copyright 2019 gRPC authors. + * + * 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. + * + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.getProxiedConnection = exports.mapProxyName = void 0; +const logging_1 = require("./logging"); +const constants_1 = require("./constants"); +const resolver_1 = require("./resolver"); +const http = require("http"); +const tls = require("tls"); +const logging = require("./logging"); +const subchannel_address_1 = require("./subchannel-address"); +const uri_parser_1 = require("./uri-parser"); +const url_1 = require("url"); +const resolver_dns_1 = require("./resolver-dns"); +const TRACER_NAME = 'proxy'; +function trace(text) { + logging.trace(constants_1.LogVerbosity.DEBUG, TRACER_NAME, text); +} +function getProxyInfo() { + let proxyEnv = ''; + let envVar = ''; + /* Prefer using 'grpc_proxy'. Fallback on 'http_proxy' if it is not set. + * Also prefer using 'https_proxy' with fallback on 'http_proxy'. The + * fallback behavior can be removed if there's a demand for it. + */ + if (process.env.grpc_proxy) { + envVar = 'grpc_proxy'; + proxyEnv = process.env.grpc_proxy; + } + else if (process.env.https_proxy) { + envVar = 'https_proxy'; + proxyEnv = process.env.https_proxy; + } + else if (process.env.http_proxy) { + envVar = 'http_proxy'; + proxyEnv = process.env.http_proxy; + } + else { + return {}; + } + let proxyUrl; + try { + proxyUrl = new url_1.URL(proxyEnv); + } + catch (e) { + (0, logging_1.log)(constants_1.LogVerbosity.ERROR, `cannot parse value of "${envVar}" env var`); + return {}; + } + if (proxyUrl.protocol !== 'http:') { + (0, logging_1.log)(constants_1.LogVerbosity.ERROR, `"${proxyUrl.protocol}" scheme not supported in proxy URI`); + return {}; + } + let userCred = null; + if (proxyUrl.username) { + if (proxyUrl.password) { + (0, logging_1.log)(constants_1.LogVerbosity.INFO, 'userinfo found in proxy URI'); + userCred = `${proxyUrl.username}:${proxyUrl.password}`; + } + else { + userCred = proxyUrl.username; + } + } + const hostname = proxyUrl.hostname; + let port = proxyUrl.port; + /* The proxy URL uses the scheme "http:", which has a default port number of + * 80. We need to set that explicitly here if it is omitted because otherwise + * it will use gRPC's default port 443. */ + if (port === '') { + port = '80'; + } + const result = { + address: `${hostname}:${port}`, + }; + if (userCred) { + result.creds = userCred; + } + trace('Proxy server ' + result.address + ' set by environment variable ' + envVar); + return result; +} +function getNoProxyHostList() { + /* Prefer using 'no_grpc_proxy'. Fallback on 'no_proxy' if it is not set. */ + let noProxyStr = process.env.no_grpc_proxy; + let envVar = 'no_grpc_proxy'; + if (!noProxyStr) { + noProxyStr = process.env.no_proxy; + envVar = 'no_proxy'; + } + if (noProxyStr) { + trace('No proxy server list set by environment variable ' + envVar); + return noProxyStr.split(','); + } + else { + return []; + } +} +function mapProxyName(target, options) { + var _a; + const noProxyResult = { + target: target, + extraOptions: {}, + }; + if (((_a = options['grpc.enable_http_proxy']) !== null && _a !== void 0 ? _a : 1) === 0) { + return noProxyResult; + } + if (target.scheme === 'unix') { + return noProxyResult; + } + const proxyInfo = getProxyInfo(); + if (!proxyInfo.address) { + return noProxyResult; + } + const hostPort = (0, uri_parser_1.splitHostPort)(target.path); + if (!hostPort) { + return noProxyResult; + } + const serverHost = hostPort.host; + for (const host of getNoProxyHostList()) { + if (host === serverHost) { + trace('Not using proxy for target in no_proxy list: ' + (0, uri_parser_1.uriToString)(target)); + return noProxyResult; + } + } + const extraOptions = { + 'grpc.http_connect_target': (0, uri_parser_1.uriToString)(target), + }; + if (proxyInfo.creds) { + extraOptions['grpc.http_connect_creds'] = proxyInfo.creds; + } + return { + target: { + scheme: 'dns', + path: proxyInfo.address, + }, + extraOptions: extraOptions, + }; +} +exports.mapProxyName = mapProxyName; +function getProxiedConnection(address, channelOptions, connectionOptions) { + var _a; + if (!('grpc.http_connect_target' in channelOptions)) { + return Promise.resolve({}); + } + const realTarget = channelOptions['grpc.http_connect_target']; + const parsedTarget = (0, uri_parser_1.parseUri)(realTarget); + if (parsedTarget === null) { + return Promise.resolve({}); + } + const splitHostPost = (0, uri_parser_1.splitHostPort)(parsedTarget.path); + if (splitHostPost === null) { + return Promise.resolve({}); + } + const hostPort = `${splitHostPost.host}:${(_a = splitHostPost.port) !== null && _a !== void 0 ? _a : resolver_dns_1.DEFAULT_PORT}`; + const options = { + method: 'CONNECT', + path: hostPort, + }; + const headers = { + Host: hostPort, + }; + // Connect to the subchannel address as a proxy + if ((0, subchannel_address_1.isTcpSubchannelAddress)(address)) { + options.host = address.host; + options.port = address.port; + } + else { + options.socketPath = address.path; + } + if ('grpc.http_connect_creds' in channelOptions) { + headers['Proxy-Authorization'] = + 'Basic ' + + Buffer.from(channelOptions['grpc.http_connect_creds']).toString('base64'); + } + options.headers = headers; + const proxyAddressString = (0, subchannel_address_1.subchannelAddressToString)(address); + trace('Using proxy ' + proxyAddressString + ' to connect to ' + options.path); + return new Promise((resolve, reject) => { + const request = http.request(options); + request.once('connect', (res, socket, head) => { + var _a; + request.removeAllListeners(); + socket.removeAllListeners(); + if (res.statusCode === 200) { + trace('Successfully connected to ' + + options.path + + ' through proxy ' + + proxyAddressString); + if ('secureContext' in connectionOptions) { + /* The proxy is connecting to a TLS server, so upgrade this socket + * connection to a TLS connection. + * This is a workaround for https://github.com/nodejs/node/issues/32922 + * See https://github.com/grpc/grpc-node/pull/1369 for more info. */ + const targetPath = (0, resolver_1.getDefaultAuthority)(parsedTarget); + const hostPort = (0, uri_parser_1.splitHostPort)(targetPath); + const remoteHost = (_a = hostPort === null || hostPort === void 0 ? void 0 : hostPort.host) !== null && _a !== void 0 ? _a : targetPath; + const cts = tls.connect(Object.assign({ host: remoteHost, servername: remoteHost, socket: socket }, connectionOptions), () => { + trace('Successfully established a TLS connection to ' + + options.path + + ' through proxy ' + + proxyAddressString); + resolve({ socket: cts, realTarget: parsedTarget }); + }); + cts.on('error', (error) => { + trace('Failed to establish a TLS connection to ' + + options.path + + ' through proxy ' + + proxyAddressString + + ' with error ' + + error.message); + reject(); + }); + } + else { + trace('Successfully established a plaintext connection to ' + + options.path + + ' through proxy ' + + proxyAddressString); + resolve({ + socket, + realTarget: parsedTarget, + }); + } + } + else { + (0, logging_1.log)(constants_1.LogVerbosity.ERROR, 'Failed to connect to ' + + options.path + + ' through proxy ' + + proxyAddressString + + ' with status ' + + res.statusCode); + reject(); + } + }); + request.once('error', err => { + request.removeAllListeners(); + (0, logging_1.log)(constants_1.LogVerbosity.ERROR, 'Failed to connect to proxy ' + + proxyAddressString + + ' with error ' + + err.message); + reject(); + }); + request.end(); + }); +} +exports.getProxiedConnection = getProxiedConnection; +//# sourceMappingURL=http_proxy.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/http_proxy.js.map b/node_modules/@grpc/grpc-js/build/src/http_proxy.js.map new file mode 100644 index 0000000..82df262 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/http_proxy.js.map @@ -0,0 +1 @@ +{"version":3,"file":"http_proxy.js","sourceRoot":"","sources":["../../src/http_proxy.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;GAeG;;;AAEH,uCAAgC;AAChC,2CAA2C;AAC3C,yCAAiD;AAEjD,6BAA6B;AAC7B,2BAA2B;AAC3B,qCAAqC;AACrC,6DAI8B;AAE9B,6CAA6E;AAC7E,6BAA0B;AAC1B,iDAA8C;AAE9C,MAAM,WAAW,GAAG,OAAO,CAAC;AAE5B,SAAS,KAAK,CAAC,IAAY;IACzB,OAAO,CAAC,KAAK,CAAC,wBAAY,CAAC,KAAK,EAAE,WAAW,EAAE,IAAI,CAAC,CAAC;AACvD,CAAC;AAOD,SAAS,YAAY;IACnB,IAAI,QAAQ,GAAG,EAAE,CAAC;IAClB,IAAI,MAAM,GAAG,EAAE,CAAC;IAChB;;;OAGG;IACH,IAAI,OAAO,CAAC,GAAG,CAAC,UAAU,EAAE,CAAC;QAC3B,MAAM,GAAG,YAAY,CAAC;QACtB,QAAQ,GAAG,OAAO,CAAC,GAAG,CAAC,UAAU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;4BACjB,kBAAkB;4BAClB,cAAc;4BACd,KAAK,CAAC,OAAO,CAChB,CAAC;wBACF,MAAM,EAAE,CAAC;oBACX,CAAC,CAAC,CAAC;gBACL,CAAC;qBAAM,CAAC;oBACN,KAAK,CACH,qDAAqD;wBACnD,OAAO,CAAC,IAAI;wBACZ,iBAAiB;wBACjB,kBAAkB,CACrB,CAAC;oBACF,OAAO,CAAC;wBACN,MAAM;wBACN,UAAU,EAAE,YAAY;qBACzB,CAAC,CAAC;gBACL,CAAC;YACH,CAAC;iBAAM,CAAC;gBACN,IAAA,aAAG,EACD,wBAAY,CAAC,KAAK,EAClB,uBAAuB;oBACrB,OAAO,CAAC,IAAI;oBACZ,iBAAiB;oBACjB,kBAAkB;oBAClB,eAAe;oBACf,GAAG,CAAC,UAAU,CACjB,CAAC;gBACF,MAAM,EAAE,CAAC;YACX,CAAC;QACH,CAAC,CAAC,CAAC;QACH,OAAO,CAAC,IAAI,CAAC,OAAO,EAAE,GAAG,CAAC,EAAE;YAC1B,OAAO,CAAC,kBAAkB,EAAE,CAAC;YAC7B,IAAA,aAAG,EACD,wBAAY,CAAC,KAAK,EAClB,6BAA6B;gBAC3B,kBAAkB;gBAClB,cAAc;gBACd,GAAG,CAAC,OAAO,CACd,CAAC;YACF,MAAM,EAAE,CAAC;QACX,CAAC,CAAC,CAAC;QACH,OAAO,CAAC,GAAG,EAAE,CAAC;IAChB,CAAC,CAAC,CAAC;AACL,CAAC;AAnID,oDAmIC"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/index.d.ts b/node_modules/@grpc/grpc-js/build/src/index.d.ts new file mode 100644 index 0000000..fece45a --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/index.d.ts @@ -0,0 +1,79 @@ +/// +import { ClientDuplexStream, ClientReadableStream, ClientUnaryCall, ClientWritableStream, ServiceError } from './call'; +import { CallCredentials, OAuth2Client } from './call-credentials'; +import { StatusObject } from './call-interface'; +import { Channel, ChannelImplementation } from './channel'; +import { CompressionAlgorithms } from './compression-algorithms'; +import { ConnectivityState } from './connectivity-state'; +import { ChannelCredentials, VerifyOptions } from './channel-credentials'; +import { CallOptions, Client, ClientOptions, CallInvocationTransformer, CallProperties, UnaryCallback } from './client'; +import { LogVerbosity, Status, Propagate } from './constants'; +import { Deserialize, loadPackageDefinition, makeClientConstructor, MethodDefinition, Serialize, ServiceDefinition } from './make-client'; +import { Metadata, MetadataOptions, MetadataValue } from './metadata'; +import { Server, ServerOptions, UntypedHandleCall, UntypedServiceImplementation } from './server'; +import { KeyCertPair, ServerCredentials } from './server-credentials'; +import { StatusBuilder } from './status-builder'; +import { handleBidiStreamingCall, handleServerStreamingCall, handleClientStreamingCall, handleUnaryCall, sendUnaryData, ServerUnaryCall, ServerReadableStream, ServerWritableStream, ServerDuplexStream, ServerErrorResponse } from './server-call'; +export { OAuth2Client }; +/**** Client Credentials ****/ +export declare const credentials: { + /** + * Combine a ChannelCredentials with any number of CallCredentials into a + * single ChannelCredentials object. + * @param channelCredentials The ChannelCredentials object. + * @param callCredentials Any number of CallCredentials objects. + * @return The resulting ChannelCredentials object. + */ + combineChannelCredentials: (channelCredentials: ChannelCredentials, ...callCredentials: CallCredentials[]) => ChannelCredentials; + /** + * Combine any number of CallCredentials into a single CallCredentials + * object. + * @param first The first CallCredentials object. + * @param additional Any number of additional CallCredentials objects. + * @return The resulting CallCredentials object. + */ + combineCallCredentials: (first: CallCredentials, ...additional: CallCredentials[]) => CallCredentials; + createInsecure: typeof ChannelCredentials.createInsecure; + createSsl: typeof ChannelCredentials.createSsl; + createFromSecureContext: typeof ChannelCredentials.createFromSecureContext; + createFromMetadataGenerator: typeof CallCredentials.createFromMetadataGenerator; + createFromGoogleCredential: typeof CallCredentials.createFromGoogleCredential; + createEmpty: typeof CallCredentials.createEmpty; +}; +/**** Metadata ****/ +export { Metadata, MetadataOptions, MetadataValue }; +/**** Constants ****/ +export { LogVerbosity as logVerbosity, Status as status, ConnectivityState as connectivityState, Propagate as propagate, CompressionAlgorithms as compressionAlgorithms, }; +/**** Client ****/ +export { Client, ClientOptions, loadPackageDefinition, makeClientConstructor, makeClientConstructor as makeGenericClientConstructor, CallProperties, CallInvocationTransformer, ChannelImplementation as Channel, Channel as ChannelInterface, UnaryCallback as requestCallback, }; +/** + * Close a Client object. + * @param client The client to close. + */ +export declare const closeClient: (client: Client) => void; +export declare const waitForClientReady: (client: Client, deadline: Date | number, callback: (error?: Error) => void) => void; +export { sendUnaryData, ChannelCredentials, CallCredentials, Deadline, Serialize as serialize, Deserialize as deserialize, ClientUnaryCall, ClientReadableStream, ClientWritableStream, ClientDuplexStream, CallOptions, MethodDefinition, StatusObject, ServiceError, ServerUnaryCall, ServerReadableStream, ServerWritableStream, ServerDuplexStream, ServerErrorResponse, ServiceDefinition, UntypedHandleCall, UntypedServiceImplementation, VerifyOptions, }; +/**** Server ****/ +export { handleBidiStreamingCall, handleServerStreamingCall, handleUnaryCall, handleClientStreamingCall, }; +export type Call = ClientUnaryCall | ClientReadableStream | ClientWritableStream | ClientDuplexStream; +/**** Unimplemented function stubs ****/ +export declare const loadObject: (value: any, options: any) => never; +export declare const load: (filename: any, format: any, options: any) => never; +export declare const setLogger: (logger: Partial) => void; +export declare const setLogVerbosity: (verbosity: LogVerbosity) => void; +export { Server, ServerOptions }; +export { ServerCredentials }; +export { KeyCertPair }; +export declare const getClientChannel: (client: Client) => Channel; +export { StatusBuilder }; +export { Listener, InterceptingListener } from './call-interface'; +export { Requester, ListenerBuilder, RequesterBuilder, Interceptor, InterceptorOptions, InterceptorProvider, InterceptingCall, InterceptorConfigurationError, NextCall, } from './client-interceptors'; +export { GrpcObject, ServiceClientConstructor, ProtobufTypeDefinition, } from './make-client'; +export { ChannelOptions } from './channel-options'; +export { getChannelzServiceDefinition, getChannelzHandlers } from './channelz'; +export { addAdminServicesToServer } from './admin'; +export { ServiceConfig, LoadBalancingConfig, MethodConfig, RetryPolicy, } from './service-config'; +export { ServerListener, FullServerListener, ServerListenerBuilder, Responder, FullResponder, ResponderBuilder, ServerInterceptingCallInterface, ServerInterceptingCall, ServerInterceptor, } from './server-interceptors'; +import * as experimental from './experimental'; +export { experimental }; +import { Deadline } from './deadline'; diff --git a/node_modules/@grpc/grpc-js/build/src/index.js b/node_modules/@grpc/grpc-js/build/src/index.js new file mode 100644 index 0000000..09aeae9 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/index.js @@ -0,0 +1,144 @@ +"use strict"; +/* + * Copyright 2019 gRPC authors. + * + * 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. + * + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.experimental = exports.ServerInterceptingCall = exports.ResponderBuilder = exports.ServerListenerBuilder = exports.addAdminServicesToServer = exports.getChannelzHandlers = exports.getChannelzServiceDefinition = exports.InterceptorConfigurationError = exports.InterceptingCall = exports.RequesterBuilder = exports.ListenerBuilder = exports.StatusBuilder = exports.getClientChannel = exports.ServerCredentials = exports.Server = exports.setLogVerbosity = exports.setLogger = exports.load = exports.loadObject = exports.CallCredentials = exports.ChannelCredentials = exports.waitForClientReady = exports.closeClient = exports.Channel = exports.makeGenericClientConstructor = exports.makeClientConstructor = exports.loadPackageDefinition = exports.Client = exports.compressionAlgorithms = exports.propagate = exports.connectivityState = exports.status = exports.logVerbosity = exports.Metadata = exports.credentials = void 0; +const call_credentials_1 = require("./call-credentials"); +Object.defineProperty(exports, "CallCredentials", { enumerable: true, get: function () { return call_credentials_1.CallCredentials; } }); +const channel_1 = require("./channel"); +Object.defineProperty(exports, "Channel", { enumerable: true, get: function () { return channel_1.ChannelImplementation; } }); +const compression_algorithms_1 = require("./compression-algorithms"); +Object.defineProperty(exports, "compressionAlgorithms", { enumerable: true, get: function () { return compression_algorithms_1.CompressionAlgorithms; } }); +const connectivity_state_1 = require("./connectivity-state"); +Object.defineProperty(exports, "connectivityState", { enumerable: true, get: function () { return connectivity_state_1.ConnectivityState; } }); +const channel_credentials_1 = require("./channel-credentials"); +Object.defineProperty(exports, "ChannelCredentials", { enumerable: true, get: function () { return channel_credentials_1.ChannelCredentials; } }); +const client_1 = require("./client"); +Object.defineProperty(exports, "Client", { enumerable: true, get: function () { return client_1.Client; } }); +const constants_1 = require("./constants"); +Object.defineProperty(exports, "logVerbosity", { enumerable: true, get: function () { return constants_1.LogVerbosity; } }); +Object.defineProperty(exports, "status", { enumerable: true, get: function () { return constants_1.Status; } }); +Object.defineProperty(exports, "propagate", { enumerable: true, get: function () { return constants_1.Propagate; } }); +const logging = require("./logging"); +const make_client_1 = require("./make-client"); +Object.defineProperty(exports, "loadPackageDefinition", { enumerable: true, get: function () { return make_client_1.loadPackageDefinition; } }); +Object.defineProperty(exports, "makeClientConstructor", { enumerable: true, get: function () { return make_client_1.makeClientConstructor; } }); +Object.defineProperty(exports, "makeGenericClientConstructor", { enumerable: true, get: function () { return make_client_1.makeClientConstructor; } }); +const metadata_1 = require("./metadata"); +Object.defineProperty(exports, "Metadata", { enumerable: true, get: function () { return metadata_1.Metadata; } }); +const server_1 = require("./server"); +Object.defineProperty(exports, "Server", { enumerable: true, get: function () { return server_1.Server; } }); +const server_credentials_1 = require("./server-credentials"); +Object.defineProperty(exports, "ServerCredentials", { enumerable: true, get: function () { return server_credentials_1.ServerCredentials; } }); +const status_builder_1 = require("./status-builder"); +Object.defineProperty(exports, "StatusBuilder", { enumerable: true, get: function () { return status_builder_1.StatusBuilder; } }); +/**** Client Credentials ****/ +// Using assign only copies enumerable properties, which is what we want +exports.credentials = { + /** + * Combine a ChannelCredentials with any number of CallCredentials into a + * single ChannelCredentials object. + * @param channelCredentials The ChannelCredentials object. + * @param callCredentials Any number of CallCredentials objects. + * @return The resulting ChannelCredentials object. + */ + combineChannelCredentials: (channelCredentials, ...callCredentials) => { + return callCredentials.reduce((acc, other) => acc.compose(other), channelCredentials); + }, + /** + * Combine any number of CallCredentials into a single CallCredentials + * object. + * @param first The first CallCredentials object. + * @param additional Any number of additional CallCredentials objects. + * @return The resulting CallCredentials object. + */ + combineCallCredentials: (first, ...additional) => { + return additional.reduce((acc, other) => acc.compose(other), first); + }, + // from channel-credentials.ts + createInsecure: channel_credentials_1.ChannelCredentials.createInsecure, + createSsl: channel_credentials_1.ChannelCredentials.createSsl, + createFromSecureContext: channel_credentials_1.ChannelCredentials.createFromSecureContext, + // from call-credentials.ts + createFromMetadataGenerator: call_credentials_1.CallCredentials.createFromMetadataGenerator, + createFromGoogleCredential: call_credentials_1.CallCredentials.createFromGoogleCredential, + createEmpty: call_credentials_1.CallCredentials.createEmpty, +}; +/** + * Close a Client object. + * @param client The client to close. + */ +const closeClient = (client) => client.close(); +exports.closeClient = closeClient; +const waitForClientReady = (client, deadline, callback) => client.waitForReady(deadline, callback); +exports.waitForClientReady = waitForClientReady; +/* eslint-enable @typescript-eslint/no-explicit-any */ +/**** Unimplemented function stubs ****/ +/* eslint-disable @typescript-eslint/no-explicit-any */ +const loadObject = (value, options) => { + throw new Error('Not available in this library. Use @grpc/proto-loader and loadPackageDefinition instead'); +}; +exports.loadObject = loadObject; +const load = (filename, format, options) => { + throw new Error('Not available in this library. Use @grpc/proto-loader and loadPackageDefinition instead'); +}; +exports.load = load; +const setLogger = (logger) => { + logging.setLogger(logger); +}; +exports.setLogger = setLogger; +const setLogVerbosity = (verbosity) => { + logging.setLoggerVerbosity(verbosity); +}; +exports.setLogVerbosity = setLogVerbosity; +const getClientChannel = (client) => { + return client_1.Client.prototype.getChannel.call(client); +}; +exports.getClientChannel = getClientChannel; +var client_interceptors_1 = require("./client-interceptors"); +Object.defineProperty(exports, "ListenerBuilder", { enumerable: true, get: function () { return client_interceptors_1.ListenerBuilder; } }); +Object.defineProperty(exports, "RequesterBuilder", { enumerable: true, get: function () { return client_interceptors_1.RequesterBuilder; } }); +Object.defineProperty(exports, "InterceptingCall", { enumerable: true, get: function () { return client_interceptors_1.InterceptingCall; } }); +Object.defineProperty(exports, "InterceptorConfigurationError", { enumerable: true, get: function () { return client_interceptors_1.InterceptorConfigurationError; } }); +var channelz_1 = require("./channelz"); +Object.defineProperty(exports, "getChannelzServiceDefinition", { enumerable: true, get: function () { return channelz_1.getChannelzServiceDefinition; } }); +Object.defineProperty(exports, "getChannelzHandlers", { enumerable: true, get: function () { return channelz_1.getChannelzHandlers; } }); +var admin_1 = require("./admin"); +Object.defineProperty(exports, "addAdminServicesToServer", { enumerable: true, get: function () { return admin_1.addAdminServicesToServer; } }); +var server_interceptors_1 = require("./server-interceptors"); +Object.defineProperty(exports, "ServerListenerBuilder", { enumerable: true, get: function () { return server_interceptors_1.ServerListenerBuilder; } }); +Object.defineProperty(exports, "ResponderBuilder", { enumerable: true, get: function () { return server_interceptors_1.ResponderBuilder; } }); +Object.defineProperty(exports, "ServerInterceptingCall", { enumerable: true, get: function () { return server_interceptors_1.ServerInterceptingCall; } }); +const experimental = require("./experimental"); +exports.experimental = experimental; +const resolver_dns = require("./resolver-dns"); +const resolver_uds = require("./resolver-uds"); +const resolver_ip = require("./resolver-ip"); +const load_balancer_pick_first = require("./load-balancer-pick-first"); +const load_balancer_round_robin = require("./load-balancer-round-robin"); +const load_balancer_outlier_detection = require("./load-balancer-outlier-detection"); +const channelz = require("./channelz"); +(() => { + resolver_dns.setup(); + resolver_uds.setup(); + resolver_ip.setup(); + load_balancer_pick_first.setup(); + load_balancer_round_robin.setup(); + load_balancer_outlier_detection.setup(); + channelz.setup(); +})(); +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/index.js.map b/node_modules/@grpc/grpc-js/build/src/index.js.map new file mode 100644 index 0000000..6db9ba7 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js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,CAAC,kBAAkB,CAAC,SAAS,CAAC,CAAC;AACxC,CAAC,CAAC;AAFW,QAAA,eAAe,mBAE1B;AAMK,MAAM,gBAAgB,GAAG,CAAC,MAAc,EAAE,EAAE;IACjD,OAAO,eAAM,CAAC,SAAS,CAAC,UAAU,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;AAClD,CAAC,CAAC;AAFW,QAAA,gBAAgB,oBAE3B;AAMF,6DAU+B;AAR7B,sHAAA,eAAe,OAAA;AACf,uHAAA,gBAAgB,OAAA;AAIhB,uHAAA,gBAAgB,OAAA;AAChB,oIAAA,6BAA6B,OAAA;AAY/B,uCAA+E;AAAtE,wHAAA,4BAA4B,OAAA;AAAE,+GAAA,mBAAmB,OAAA;AAE1D,iCAAmD;AAA1C,iHAAA,wBAAwB,OAAA;AASjC,6DAU+B;AAP7B,4HAAA,qBAAqB,OAAA;AAGrB,uHAAA,gBAAgB,OAAA;AAEhB,6HAAA,sBAAsB,OAAA;AAIxB,+CAA+C;AACtC,oCAAY;AAErB,+CAA+C;AAC/C,+CAA+C;AAC/C,6CAA6C;AAC7C,uEAAuE;AACvE,yEAAyE;AACzE,qFAAqF;AACrF,uCAAuC;AAGvC,CAAC,GAAG,EAAE;IACJ,YAAY,CAAC,KAAK,EAAE,CAAC;IACrB,YAAY,CAAC,KAAK,EAAE,CAAC;IACrB,WAAW,CAAC,KAAK,EAAE,CAAC;IACpB,wBAAwB,CAAC,KAAK,EAAE,CAAC;IACjC,yBAAyB,CAAC,KAAK,EAAE,CAAC;IAClC,+BAA+B,CAAC,KAAK,EAAE,CAAC;IACxC,QAAQ,CAAC,KAAK,EAAE,CAAC;AACnB,CAAC,CAAC,EAAE,CAAC"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/internal-channel.d.ts b/node_modules/@grpc/grpc-js/build/src/internal-channel.d.ts new file mode 100644 index 0000000..b7785c8 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/internal-channel.d.ts @@ -0,0 +1,124 @@ +import { ChannelCredentials } from './channel-credentials'; +import { ChannelOptions } from './channel-options'; +import { Metadata } from './metadata'; +import { CallConfig } from './resolver'; +import { ServerSurfaceCall } from './server-call'; +import { ConnectivityState } from './connectivity-state'; +import { ChannelRef } from './channelz'; +import { LoadBalancingCall } from './load-balancing-call'; +import { CallCredentials } from './call-credentials'; +import { Call, StatusObject } from './call-interface'; +import { Deadline } from './deadline'; +import { ResolvingCall } from './resolving-call'; +import { RetryingCall } from './retrying-call'; +import { BaseSubchannelWrapper, SubchannelInterface } from './subchannel-interface'; +interface NoneConfigResult { + type: 'NONE'; +} +interface SuccessConfigResult { + type: 'SUCCESS'; + config: CallConfig; +} +interface ErrorConfigResult { + type: 'ERROR'; + error: StatusObject; +} +type GetConfigResult = NoneConfigResult | SuccessConfigResult | ErrorConfigResult; +declare class ChannelSubchannelWrapper extends BaseSubchannelWrapper implements SubchannelInterface { + private channel; + private refCount; + private subchannelStateListener; + constructor(childSubchannel: SubchannelInterface, channel: InternalChannel); + ref(): void; + unref(): void; +} +export declare class InternalChannel { + private readonly credentials; + private readonly options; + private readonly resolvingLoadBalancer; + private readonly subchannelPool; + private connectivityState; + private currentPicker; + /** + * Calls queued up to get a call config. Should only be populated before the + * first time the resolver returns a result, which includes the ConfigSelector. + */ + private configSelectionQueue; + private pickQueue; + private connectivityStateWatchers; + private readonly defaultAuthority; + private readonly filterStackFactory; + private readonly target; + /** + * This timer does not do anything on its own. Its purpose is to hold the + * event loop open while there are any pending calls for the channel that + * have not yet been assigned to specific subchannels. In other words, + * the invariant is that callRefTimer is reffed if and only if pickQueue + * is non-empty. + */ + private readonly callRefTimer; + private configSelector; + /** + * This is the error from the name resolver if it failed most recently. It + * is only used to end calls that start while there is no config selector + * and the name resolver is in backoff, so it should be nulled if + * configSelector becomes set or the channel state becomes anything other + * than TRANSIENT_FAILURE. + */ + private currentResolutionError; + private readonly retryBufferTracker; + private keepaliveTime; + private readonly wrappedSubchannels; + private callCount; + private idleTimer; + private readonly idleTimeoutMs; + private lastActivityTimestamp; + private readonly channelzEnabled; + private readonly originalTarget; + private readonly channelzRef; + private readonly channelzTrace; + private readonly callTracker; + private readonly childrenTracker; + /** + * Randomly generated ID to be passed to the config selector, for use by + * ring_hash in xDS. An integer distributed approximately uniformly between + * 0 and MAX_SAFE_INTEGER. + */ + private readonly randomChannelId; + constructor(target: string, credentials: ChannelCredentials, options: ChannelOptions); + private getChannelzInfo; + private trace; + private callRefTimerRef; + private callRefTimerUnref; + private removeConnectivityStateWatcher; + private updateState; + throttleKeepalive(newKeepaliveTime: number): void; + removeWrappedSubchannel(wrappedSubchannel: ChannelSubchannelWrapper): void; + doPick(metadata: Metadata, extraPickInfo: { + [key: string]: string; + }): import("./picker").PickResult; + queueCallForPick(call: LoadBalancingCall): void; + getConfig(method: string, metadata: Metadata): GetConfigResult; + queueCallForConfig(call: ResolvingCall): void; + private enterIdle; + private startIdleTimeout; + private maybeStartIdleTimer; + private onCallStart; + private onCallEnd; + createLoadBalancingCall(callConfig: CallConfig, method: string, host: string, credentials: CallCredentials, deadline: Deadline): LoadBalancingCall; + createRetryingCall(callConfig: CallConfig, method: string, host: string, credentials: CallCredentials, deadline: Deadline): RetryingCall; + createInnerCall(callConfig: CallConfig, method: string, host: string, credentials: CallCredentials, deadline: Deadline): LoadBalancingCall | RetryingCall; + createResolvingCall(method: string, deadline: Deadline, host: string | null | undefined, parentCall: ServerSurfaceCall | null, propagateFlags: number | null | undefined): ResolvingCall; + close(): void; + getTarget(): string; + getConnectivityState(tryToConnect: boolean): ConnectivityState; + watchConnectivityState(currentState: ConnectivityState, deadline: Date | number, callback: (error?: Error) => void): void; + /** + * Get the channelz reference object for this channel. The returned value is + * garbage if channelz is disabled for this channel. + * @returns + */ + getChannelzRef(): ChannelRef; + createCall(method: string, deadline: Deadline, host: string | null | undefined, parentCall: ServerSurfaceCall | null, propagateFlags: number | null | undefined): Call; +} +export {}; diff --git a/node_modules/@grpc/grpc-js/build/src/internal-channel.js b/node_modules/@grpc/grpc-js/build/src/internal-channel.js new file mode 100644 index 0000000..f6dce2c --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/internal-channel.js @@ -0,0 +1,542 @@ +"use strict"; +/* + * Copyright 2019 gRPC authors. + * + * 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. + * + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.InternalChannel = void 0; +const channel_credentials_1 = require("./channel-credentials"); +const resolving_load_balancer_1 = require("./resolving-load-balancer"); +const subchannel_pool_1 = require("./subchannel-pool"); +const picker_1 = require("./picker"); +const constants_1 = require("./constants"); +const filter_stack_1 = require("./filter-stack"); +const compression_filter_1 = require("./compression-filter"); +const resolver_1 = require("./resolver"); +const logging_1 = require("./logging"); +const max_message_size_filter_1 = require("./max-message-size-filter"); +const http_proxy_1 = require("./http_proxy"); +const uri_parser_1 = require("./uri-parser"); +const connectivity_state_1 = require("./connectivity-state"); +const channelz_1 = require("./channelz"); +const load_balancing_call_1 = require("./load-balancing-call"); +const deadline_1 = require("./deadline"); +const resolving_call_1 = require("./resolving-call"); +const call_number_1 = require("./call-number"); +const control_plane_status_1 = require("./control-plane-status"); +const retrying_call_1 = require("./retrying-call"); +const subchannel_interface_1 = require("./subchannel-interface"); +/** + * See https://nodejs.org/api/timers.html#timers_setinterval_callback_delay_args + */ +const MAX_TIMEOUT_TIME = 2147483647; +const MIN_IDLE_TIMEOUT_MS = 1000; +// 30 minutes +const DEFAULT_IDLE_TIMEOUT_MS = 30 * 60 * 1000; +const RETRY_THROTTLER_MAP = new Map(); +const DEFAULT_RETRY_BUFFER_SIZE_BYTES = 1 << 24; // 16 MB +const DEFAULT_PER_RPC_RETRY_BUFFER_SIZE_BYTES = 1 << 20; // 1 MB +class ChannelSubchannelWrapper extends subchannel_interface_1.BaseSubchannelWrapper { + constructor(childSubchannel, channel) { + super(childSubchannel); + this.channel = channel; + this.refCount = 0; + this.subchannelStateListener = (subchannel, previousState, newState, keepaliveTime) => { + channel.throttleKeepalive(keepaliveTime); + }; + childSubchannel.addConnectivityStateListener(this.subchannelStateListener); + } + ref() { + this.child.ref(); + this.refCount += 1; + } + unref() { + this.child.unref(); + this.refCount -= 1; + if (this.refCount <= 0) { + this.child.removeConnectivityStateListener(this.subchannelStateListener); + this.channel.removeWrappedSubchannel(this); + } + } +} +class InternalChannel { + constructor(target, credentials, options) { + var _a, _b, _c, _d, _e, _f, _g, _h; + this.credentials = credentials; + this.options = options; + this.connectivityState = connectivity_state_1.ConnectivityState.IDLE; + this.currentPicker = new picker_1.UnavailablePicker(); + /** + * Calls queued up to get a call config. Should only be populated before the + * first time the resolver returns a result, which includes the ConfigSelector. + */ + this.configSelectionQueue = []; + this.pickQueue = []; + this.connectivityStateWatchers = []; + this.configSelector = null; + /** + * This is the error from the name resolver if it failed most recently. It + * is only used to end calls that start while there is no config selector + * and the name resolver is in backoff, so it should be nulled if + * configSelector becomes set or the channel state becomes anything other + * than TRANSIENT_FAILURE. + */ + this.currentResolutionError = null; + this.wrappedSubchannels = new Set(); + this.callCount = 0; + this.idleTimer = null; + // Channelz info + this.channelzEnabled = true; + this.callTracker = new channelz_1.ChannelzCallTracker(); + this.childrenTracker = new channelz_1.ChannelzChildrenTracker(); + /** + * Randomly generated ID to be passed to the config selector, for use by + * ring_hash in xDS. An integer distributed approximately uniformly between + * 0 and MAX_SAFE_INTEGER. + */ + this.randomChannelId = Math.floor(Math.random() * Number.MAX_SAFE_INTEGER); + if (typeof target !== 'string') { + throw new TypeError('Channel target must be a string'); + } + if (!(credentials instanceof channel_credentials_1.ChannelCredentials)) { + throw new TypeError('Channel credentials must be a ChannelCredentials object'); + } + if (options) { + if (typeof options !== 'object') { + throw new TypeError('Channel options must be an object'); + } + } + this.originalTarget = target; + const originalTargetUri = (0, uri_parser_1.parseUri)(target); + if (originalTargetUri === null) { + throw new Error(`Could not parse target name "${target}"`); + } + /* This ensures that the target has a scheme that is registered with the + * resolver */ + const defaultSchemeMapResult = (0, resolver_1.mapUriDefaultScheme)(originalTargetUri); + if (defaultSchemeMapResult === null) { + throw new Error(`Could not find a default scheme for target name "${target}"`); + } + this.callRefTimer = setInterval(() => { }, MAX_TIMEOUT_TIME); + (_b = (_a = this.callRefTimer).unref) === null || _b === void 0 ? void 0 : _b.call(_a); + if (this.options['grpc.enable_channelz'] === 0) { + this.channelzEnabled = false; + } + this.channelzTrace = new channelz_1.ChannelzTrace(); + this.channelzRef = (0, channelz_1.registerChannelzChannel)(target, () => this.getChannelzInfo(), this.channelzEnabled); + if (this.channelzEnabled) { + this.channelzTrace.addTrace('CT_INFO', 'Channel created'); + } + if (this.options['grpc.default_authority']) { + this.defaultAuthority = this.options['grpc.default_authority']; + } + else { + this.defaultAuthority = (0, resolver_1.getDefaultAuthority)(defaultSchemeMapResult); + } + const proxyMapResult = (0, http_proxy_1.mapProxyName)(defaultSchemeMapResult, options); + this.target = proxyMapResult.target; + this.options = Object.assign({}, this.options, proxyMapResult.extraOptions); + /* The global boolean parameter to getSubchannelPool has the inverse meaning to what + * the grpc.use_local_subchannel_pool channel option means. */ + this.subchannelPool = (0, subchannel_pool_1.getSubchannelPool)(((_c = options['grpc.use_local_subchannel_pool']) !== null && _c !== void 0 ? _c : 0) === 0); + this.retryBufferTracker = new retrying_call_1.MessageBufferTracker((_d = options['grpc.retry_buffer_size']) !== null && _d !== void 0 ? _d : DEFAULT_RETRY_BUFFER_SIZE_BYTES, (_e = options['grpc.per_rpc_retry_buffer_size']) !== null && _e !== void 0 ? _e : DEFAULT_PER_RPC_RETRY_BUFFER_SIZE_BYTES); + this.keepaliveTime = (_f = options['grpc.keepalive_time_ms']) !== null && _f !== void 0 ? _f : -1; + this.idleTimeoutMs = Math.max((_g = options['grpc.client_idle_timeout_ms']) !== null && _g !== void 0 ? _g : DEFAULT_IDLE_TIMEOUT_MS, MIN_IDLE_TIMEOUT_MS); + const channelControlHelper = { + createSubchannel: (subchannelAddress, subchannelArgs) => { + const subchannel = this.subchannelPool.getOrCreateSubchannel(this.target, subchannelAddress, Object.assign({}, this.options, subchannelArgs), this.credentials); + subchannel.throttleKeepalive(this.keepaliveTime); + if (this.channelzEnabled) { + this.channelzTrace.addTrace('CT_INFO', 'Created subchannel or used existing subchannel', subchannel.getChannelzRef()); + } + const wrappedSubchannel = new ChannelSubchannelWrapper(subchannel, this); + this.wrappedSubchannels.add(wrappedSubchannel); + return wrappedSubchannel; + }, + updateState: (connectivityState, picker) => { + this.currentPicker = picker; + const queueCopy = this.pickQueue.slice(); + this.pickQueue = []; + if (queueCopy.length > 0) { + this.callRefTimerUnref(); + } + for (const call of queueCopy) { + call.doPick(); + } + this.updateState(connectivityState); + }, + requestReresolution: () => { + // This should never be called. + throw new Error('Resolving load balancer should never call requestReresolution'); + }, + addChannelzChild: (child) => { + if (this.channelzEnabled) { + this.childrenTracker.refChild(child); + } + }, + removeChannelzChild: (child) => { + if (this.channelzEnabled) { + this.childrenTracker.unrefChild(child); + } + }, + }; + this.resolvingLoadBalancer = new resolving_load_balancer_1.ResolvingLoadBalancer(this.target, channelControlHelper, options, (serviceConfig, configSelector) => { + if (serviceConfig.retryThrottling) { + RETRY_THROTTLER_MAP.set(this.getTarget(), new retrying_call_1.RetryThrottler(serviceConfig.retryThrottling.maxTokens, serviceConfig.retryThrottling.tokenRatio, RETRY_THROTTLER_MAP.get(this.getTarget()))); + } + else { + RETRY_THROTTLER_MAP.delete(this.getTarget()); + } + if (this.channelzEnabled) { + this.channelzTrace.addTrace('CT_INFO', 'Address resolution succeeded'); + } + this.configSelector = configSelector; + this.currentResolutionError = null; + /* We process the queue asynchronously to ensure that the corresponding + * load balancer update has completed. */ + process.nextTick(() => { + const localQueue = this.configSelectionQueue; + this.configSelectionQueue = []; + if (localQueue.length > 0) { + this.callRefTimerUnref(); + } + for (const call of localQueue) { + call.getConfig(); + } + }); + }, status => { + if (this.channelzEnabled) { + this.channelzTrace.addTrace('CT_WARNING', 'Address resolution failed with code ' + + status.code + + ' and details "' + + status.details + + '"'); + } + if (this.configSelectionQueue.length > 0) { + this.trace('Name resolution failed with calls queued for config selection'); + } + if (this.configSelector === null) { + this.currentResolutionError = Object.assign(Object.assign({}, (0, control_plane_status_1.restrictControlPlaneStatusCode)(status.code, status.details)), { metadata: status.metadata }); + } + const localQueue = this.configSelectionQueue; + this.configSelectionQueue = []; + if (localQueue.length > 0) { + this.callRefTimerUnref(); + } + for (const call of localQueue) { + call.reportResolverError(status); + } + }); + this.filterStackFactory = new filter_stack_1.FilterStackFactory([ + new max_message_size_filter_1.MaxMessageSizeFilterFactory(this.options), + new compression_filter_1.CompressionFilterFactory(this, this.options), + ]); + this.trace('Channel constructed with options ' + + JSON.stringify(options, undefined, 2)); + const error = new Error(); + (0, logging_1.trace)(constants_1.LogVerbosity.DEBUG, 'channel_stacktrace', '(' + + this.channelzRef.id + + ') ' + + 'Channel constructed \n' + + ((_h = error.stack) === null || _h === void 0 ? void 0 : _h.substring(error.stack.indexOf('\n') + 1))); + this.lastActivityTimestamp = new Date(); + } + getChannelzInfo() { + return { + target: this.originalTarget, + state: this.connectivityState, + trace: this.channelzTrace, + callTracker: this.callTracker, + children: this.childrenTracker.getChildLists(), + }; + } + trace(text, verbosityOverride) { + (0, logging_1.trace)(verbosityOverride !== null && verbosityOverride !== void 0 ? verbosityOverride : constants_1.LogVerbosity.DEBUG, 'channel', '(' + this.channelzRef.id + ') ' + (0, uri_parser_1.uriToString)(this.target) + ' ' + text); + } + callRefTimerRef() { + var _a, _b, _c, _d; + // If the hasRef function does not exist, always run the code + if (!((_b = (_a = this.callRefTimer).hasRef) === null || _b === void 0 ? void 0 : _b.call(_a))) { + this.trace('callRefTimer.ref | configSelectionQueue.length=' + + this.configSelectionQueue.length + + ' pickQueue.length=' + + this.pickQueue.length); + (_d = (_c = this.callRefTimer).ref) === null || _d === void 0 ? void 0 : _d.call(_c); + } + } + callRefTimerUnref() { + var _a, _b; + // If the hasRef function does not exist, always run the code + if (!this.callRefTimer.hasRef || this.callRefTimer.hasRef()) { + this.trace('callRefTimer.unref | configSelectionQueue.length=' + + this.configSelectionQueue.length + + ' pickQueue.length=' + + this.pickQueue.length); + (_b = (_a = this.callRefTimer).unref) === null || _b === void 0 ? void 0 : _b.call(_a); + } + } + removeConnectivityStateWatcher(watcherObject) { + const watcherIndex = this.connectivityStateWatchers.findIndex(value => value === watcherObject); + if (watcherIndex >= 0) { + this.connectivityStateWatchers.splice(watcherIndex, 1); + } + } + updateState(newState) { + (0, logging_1.trace)(constants_1.LogVerbosity.DEBUG, 'connectivity_state', '(' + + this.channelzRef.id + + ') ' + + (0, uri_parser_1.uriToString)(this.target) + + ' ' + + connectivity_state_1.ConnectivityState[this.connectivityState] + + ' -> ' + + connectivity_state_1.ConnectivityState[newState]); + if (this.channelzEnabled) { + this.channelzTrace.addTrace('CT_INFO', 'Connectivity state change to ' + connectivity_state_1.ConnectivityState[newState]); + } + this.connectivityState = newState; + const watchersCopy = this.connectivityStateWatchers.slice(); + for (const watcherObject of watchersCopy) { + if (newState !== watcherObject.currentState) { + if (watcherObject.timer) { + clearTimeout(watcherObject.timer); + } + this.removeConnectivityStateWatcher(watcherObject); + watcherObject.callback(); + } + } + if (newState !== connectivity_state_1.ConnectivityState.TRANSIENT_FAILURE) { + this.currentResolutionError = null; + } + } + throttleKeepalive(newKeepaliveTime) { + if (newKeepaliveTime > this.keepaliveTime) { + this.keepaliveTime = newKeepaliveTime; + for (const wrappedSubchannel of this.wrappedSubchannels) { + wrappedSubchannel.throttleKeepalive(newKeepaliveTime); + } + } + } + removeWrappedSubchannel(wrappedSubchannel) { + this.wrappedSubchannels.delete(wrappedSubchannel); + } + doPick(metadata, extraPickInfo) { + return this.currentPicker.pick({ + metadata: metadata, + extraPickInfo: extraPickInfo, + }); + } + queueCallForPick(call) { + this.pickQueue.push(call); + this.callRefTimerRef(); + } + getConfig(method, metadata) { + this.resolvingLoadBalancer.exitIdle(); + if (this.configSelector) { + return { + type: 'SUCCESS', + config: this.configSelector(method, metadata, this.randomChannelId), + }; + } + else { + if (this.currentResolutionError) { + return { + type: 'ERROR', + error: this.currentResolutionError, + }; + } + else { + return { + type: 'NONE', + }; + } + } + } + queueCallForConfig(call) { + this.configSelectionQueue.push(call); + this.callRefTimerRef(); + } + enterIdle() { + this.resolvingLoadBalancer.destroy(); + this.updateState(connectivity_state_1.ConnectivityState.IDLE); + this.currentPicker = new picker_1.QueuePicker(this.resolvingLoadBalancer); + if (this.idleTimer) { + clearTimeout(this.idleTimer); + this.idleTimer = null; + } + } + startIdleTimeout(timeoutMs) { + var _a, _b; + this.idleTimer = setTimeout(() => { + if (this.callCount > 0) { + /* If there is currently a call, the channel will not go idle for a + * period of at least idleTimeoutMs, so check again after that time. + */ + this.startIdleTimeout(this.idleTimeoutMs); + return; + } + const now = new Date(); + const timeSinceLastActivity = now.valueOf() - this.lastActivityTimestamp.valueOf(); + if (timeSinceLastActivity >= this.idleTimeoutMs) { + this.trace('Idle timer triggered after ' + + this.idleTimeoutMs + + 'ms of inactivity'); + this.enterIdle(); + } + else { + /* Whenever the timer fires with the latest activity being too recent, + * set the timer again for the time when the time since the last + * activity is equal to the timeout. This should result in the timer + * firing no more than once every idleTimeoutMs/2 on average. */ + this.startIdleTimeout(this.idleTimeoutMs - timeSinceLastActivity); + } + }, timeoutMs); + (_b = (_a = this.idleTimer).unref) === null || _b === void 0 ? void 0 : _b.call(_a); + } + maybeStartIdleTimer() { + if (this.connectivityState !== connectivity_state_1.ConnectivityState.SHUTDOWN && + !this.idleTimer) { + this.startIdleTimeout(this.idleTimeoutMs); + } + } + onCallStart() { + if (this.channelzEnabled) { + this.callTracker.addCallStarted(); + } + this.callCount += 1; + } + onCallEnd(status) { + if (this.channelzEnabled) { + if (status.code === constants_1.Status.OK) { + this.callTracker.addCallSucceeded(); + } + else { + this.callTracker.addCallFailed(); + } + } + this.callCount -= 1; + this.lastActivityTimestamp = new Date(); + this.maybeStartIdleTimer(); + } + createLoadBalancingCall(callConfig, method, host, credentials, deadline) { + const callNumber = (0, call_number_1.getNextCallNumber)(); + this.trace('createLoadBalancingCall [' + callNumber + '] method="' + method + '"'); + return new load_balancing_call_1.LoadBalancingCall(this, callConfig, method, host, credentials, deadline, callNumber); + } + createRetryingCall(callConfig, method, host, credentials, deadline) { + const callNumber = (0, call_number_1.getNextCallNumber)(); + this.trace('createRetryingCall [' + callNumber + '] method="' + method + '"'); + return new retrying_call_1.RetryingCall(this, callConfig, method, host, credentials, deadline, callNumber, this.retryBufferTracker, RETRY_THROTTLER_MAP.get(this.getTarget())); + } + createInnerCall(callConfig, method, host, credentials, deadline) { + // Create a RetryingCall if retries are enabled + if (this.options['grpc.enable_retries'] === 0) { + return this.createLoadBalancingCall(callConfig, method, host, credentials, deadline); + } + else { + return this.createRetryingCall(callConfig, method, host, credentials, deadline); + } + } + createResolvingCall(method, deadline, host, parentCall, propagateFlags) { + const callNumber = (0, call_number_1.getNextCallNumber)(); + this.trace('createResolvingCall [' + + callNumber + + '] method="' + + method + + '", deadline=' + + (0, deadline_1.deadlineToString)(deadline)); + const finalOptions = { + deadline: deadline, + flags: propagateFlags !== null && propagateFlags !== void 0 ? propagateFlags : constants_1.Propagate.DEFAULTS, + host: host !== null && host !== void 0 ? host : this.defaultAuthority, + parentCall: parentCall, + }; + const call = new resolving_call_1.ResolvingCall(this, method, finalOptions, this.filterStackFactory.clone(), this.credentials._getCallCredentials(), callNumber); + this.onCallStart(); + call.addStatusWatcher(status => { + this.onCallEnd(status); + }); + return call; + } + close() { + this.resolvingLoadBalancer.destroy(); + this.updateState(connectivity_state_1.ConnectivityState.SHUTDOWN); + clearInterval(this.callRefTimer); + if (this.idleTimer) { + clearTimeout(this.idleTimer); + } + if (this.channelzEnabled) { + (0, channelz_1.unregisterChannelzRef)(this.channelzRef); + } + this.subchannelPool.unrefUnusedSubchannels(); + } + getTarget() { + return (0, uri_parser_1.uriToString)(this.target); + } + getConnectivityState(tryToConnect) { + const connectivityState = this.connectivityState; + if (tryToConnect) { + this.resolvingLoadBalancer.exitIdle(); + this.lastActivityTimestamp = new Date(); + this.maybeStartIdleTimer(); + } + return connectivityState; + } + watchConnectivityState(currentState, deadline, callback) { + if (this.connectivityState === connectivity_state_1.ConnectivityState.SHUTDOWN) { + throw new Error('Channel has been shut down'); + } + let timer = null; + if (deadline !== Infinity) { + const deadlineDate = deadline instanceof Date ? deadline : new Date(deadline); + const now = new Date(); + if (deadline === -Infinity || deadlineDate <= now) { + process.nextTick(callback, new Error('Deadline passed without connectivity state change')); + return; + } + timer = setTimeout(() => { + this.removeConnectivityStateWatcher(watcherObject); + callback(new Error('Deadline passed without connectivity state change')); + }, deadlineDate.getTime() - now.getTime()); + } + const watcherObject = { + currentState, + callback, + timer, + }; + this.connectivityStateWatchers.push(watcherObject); + } + /** + * Get the channelz reference object for this channel. The returned value is + * garbage if channelz is disabled for this channel. + * @returns + */ + getChannelzRef() { + return this.channelzRef; + } + createCall(method, deadline, host, parentCall, propagateFlags) { + if (typeof method !== 'string') { + throw new TypeError('Channel#createCall: method must be a string'); + } + if (!(typeof deadline === 'number' || deadline instanceof Date)) { + throw new TypeError('Channel#createCall: deadline must be a number or Date'); + } + if (this.connectivityState === connectivity_state_1.ConnectivityState.SHUTDOWN) { + throw new Error('Channel has been shut down'); + } + return this.createResolvingCall(method, deadline, host, parentCall, propagateFlags); + } +} +exports.InternalChannel = InternalChannel; +//# sourceMappingURL=internal-channel.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/internal-channel.js.map b/node_modules/@grpc/grpc-js/build/src/internal-channel.js.map new file mode 100644 index 0000000..d6843a5 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/internal-channel.js.map @@ -0,0 +1 @@ +{"version":3,"file":"internal-channel.js","sourceR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EACR,IAAI,EACJ,UAAU,EACV,cAAc,CACf,CAAC;IACJ,CAAC;CACF;AA1rBD,0CA0rBC"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/load-balancer-child-handler.d.ts b/node_modules/@grpc/grpc-js/build/src/load-balancer-child-handler.d.ts new file mode 100644 index 0000000..ca484c8 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/load-balancer-child-handler.d.ts @@ -0,0 +1,26 @@ +import { LoadBalancer, ChannelControlHelper, TypedLoadBalancingConfig } from './load-balancer'; +import { Endpoint } from './subchannel-address'; +import { ChannelOptions } from './channel-options'; +export declare class ChildLoadBalancerHandler implements LoadBalancer { + private readonly channelControlHelper; + private readonly options; + private currentChild; + private pendingChild; + private latestConfig; + private ChildPolicyHelper; + constructor(channelControlHelper: ChannelControlHelper, options: ChannelOptions); + protected configUpdateRequiresNewPolicyInstance(oldConfig: TypedLoadBalancingConfig, newConfig: TypedLoadBalancingConfig): boolean; + /** + * Prerequisites: lbConfig !== null and lbConfig.name is registered + * @param endpointList + * @param lbConfig + * @param attributes + */ + updateAddressList(endpointList: Endpoint[], lbConfig: TypedLoadBalancingConfig, attributes: { + [key: string]: unknown; + }): void; + exitIdle(): void; + resetBackoff(): void; + destroy(): void; + getTypeName(): string; +} diff --git a/node_modules/@grpc/grpc-js/build/src/load-balancer-child-handler.js b/node_modules/@grpc/grpc-js/build/src/load-balancer-child-handler.js new file mode 100644 index 0000000..76db257 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/load-balancer-child-handler.js @@ -0,0 +1,152 @@ +"use strict"; +/* + * Copyright 2020 gRPC authors. + * + * 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. + * + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ChildLoadBalancerHandler = void 0; +const load_balancer_1 = require("./load-balancer"); +const connectivity_state_1 = require("./connectivity-state"); +const TYPE_NAME = 'child_load_balancer_helper'; +class ChildLoadBalancerHandler { + constructor(channelControlHelper, options) { + this.channelControlHelper = channelControlHelper; + this.options = options; + this.currentChild = null; + this.pendingChild = null; + this.latestConfig = null; + this.ChildPolicyHelper = class { + constructor(parent) { + this.parent = parent; + this.child = null; + } + createSubchannel(subchannelAddress, subchannelArgs) { + return this.parent.channelControlHelper.createSubchannel(subchannelAddress, subchannelArgs); + } + updateState(connectivityState, picker) { + var _a; + if (this.calledByPendingChild()) { + if (connectivityState === connectivity_state_1.ConnectivityState.CONNECTING) { + return; + } + (_a = this.parent.currentChild) === null || _a === void 0 ? void 0 : _a.destroy(); + this.parent.currentChild = this.parent.pendingChild; + this.parent.pendingChild = null; + } + else if (!this.calledByCurrentChild()) { + return; + } + this.parent.channelControlHelper.updateState(connectivityState, picker); + } + requestReresolution() { + var _a; + const latestChild = (_a = this.parent.pendingChild) !== null && _a !== void 0 ? _a : this.parent.currentChild; + if (this.child === latestChild) { + this.parent.channelControlHelper.requestReresolution(); + } + } + setChild(newChild) { + this.child = newChild; + } + addChannelzChild(child) { + this.parent.channelControlHelper.addChannelzChild(child); + } + removeChannelzChild(child) { + this.parent.channelControlHelper.removeChannelzChild(child); + } + calledByPendingChild() { + return this.child === this.parent.pendingChild; + } + calledByCurrentChild() { + return this.child === this.parent.currentChild; + } + }; + } + configUpdateRequiresNewPolicyInstance(oldConfig, newConfig) { + return oldConfig.getLoadBalancerName() !== newConfig.getLoadBalancerName(); + } + /** + * Prerequisites: lbConfig !== null and lbConfig.name is registered + * @param endpointList + * @param lbConfig + * @param attributes + */ + updateAddressList(endpointList, lbConfig, attributes) { + let childToUpdate; + if (this.currentChild === null || + this.latestConfig === null || + this.configUpdateRequiresNewPolicyInstance(this.latestConfig, lbConfig)) { + const newHelper = new this.ChildPolicyHelper(this); + const newChild = (0, load_balancer_1.createLoadBalancer)(lbConfig, newHelper, this.options); + newHelper.setChild(newChild); + if (this.currentChild === null) { + this.currentChild = newChild; + childToUpdate = this.currentChild; + } + else { + if (this.pendingChild) { + this.pendingChild.destroy(); + } + this.pendingChild = newChild; + childToUpdate = this.pendingChild; + } + } + else { + if (this.pendingChild === null) { + childToUpdate = this.currentChild; + } + else { + childToUpdate = this.pendingChild; + } + } + this.latestConfig = lbConfig; + childToUpdate.updateAddressList(endpointList, lbConfig, attributes); + } + exitIdle() { + if (this.currentChild) { + this.currentChild.exitIdle(); + if (this.pendingChild) { + this.pendingChild.exitIdle(); + } + } + } + resetBackoff() { + if (this.currentChild) { + this.currentChild.resetBackoff(); + if (this.pendingChild) { + this.pendingChild.resetBackoff(); + } + } + } + destroy() { + /* Note: state updates are only propagated from the child balancer if that + * object is equal to this.currentChild or this.pendingChild. Since this + * function sets both of those to null, no further state updates will + * occur after this function returns. */ + if (this.currentChild) { + this.currentChild.destroy(); + this.currentChild = null; + } + if (this.pendingChild) { + this.pendingChild.destroy(); + this.pendingChild = null; + } + } + getTypeName() { + return TYPE_NAME; + } +} +exports.ChildLoadBalancerHandler = ChildLoadBalancerHandler; +//# sourceMappingURL=load-balancer-child-handler.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/load-balancer-child-handler.js.map b/node_modules/@grpc/grpc-js/build/src/load-balancer-child-handler.js.map new file mode 100644 index 0000000..f4c6fca --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/load-balancer-child-handler.js.map @@ -0,0 +1 @@ +{"version":3,"file":"load-balancer-child-handler.js","sourceRoot":"","sources":["../../src/load-balancer-child-handler.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;GAeG;;;AAEH,mDAKyB;AAGzB,6DAAyD;AAKzD,MAAM,SAAS,GAAG,4BAA4B,CAAC;AAE/C,MAAa,wBAAwB;IAsDnC,YACmB,oBAA0C,EA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ACtB,IAAI,CAAC,YAAY,CAAC,OAAO,EAAE,CAAC;YAC5B,IAAI,CAAC,YAAY,GAAG,IAAI,CAAC;QAC3B,CAAC;QACD,IAAI,IAAI,CAAC,YAAY,EAAE,CAAC;YACtB,IAAI,CAAC,YAAY,CAAC,OAAO,EAAE,CAAC;YAC5B,IAAI,CAAC,YAAY,GAAG,IAAI,CAAC;QAC3B,CAAC;IACH,CAAC;IACD,WAAW;QACT,OAAO,SAAS,CAAC;IACnB,CAAC;CACF;AA3ID,4DA2IC"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/load-balancer-outlier-detection.d.ts b/node_modules/@grpc/grpc-js/build/src/load-balancer-outlier-detection.d.ts new file mode 100644 index 0000000..eab8d2b --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/load-balancer-outlier-detection.d.ts @@ -0,0 +1,72 @@ +import { ChannelOptions } from './channel-options'; +import { Duration } from './duration'; +import { ChannelControlHelper } from './experimental'; +import { LoadBalancer, TypedLoadBalancingConfig } from './load-balancer'; +import { Endpoint } from './subchannel-address'; +import { LoadBalancingConfig } from './service-config'; +export interface SuccessRateEjectionConfig { + readonly stdev_factor: number; + readonly enforcement_percentage: number; + readonly minimum_hosts: number; + readonly request_volume: number; +} +export interface FailurePercentageEjectionConfig { + readonly threshold: number; + readonly enforcement_percentage: number; + readonly minimum_hosts: number; + readonly request_volume: number; +} +export interface OutlierDetectionRawConfig { + interval?: Duration; + base_ejection_time?: Duration; + max_ejection_time?: Duration; + max_ejection_percent?: number; + success_rate_ejection?: Partial; + failure_percentage_ejection?: Partial; + child_policy: LoadBalancingConfig[]; +} +export declare class OutlierDetectionLoadBalancingConfig implements TypedLoadBalancingConfig { + private readonly childPolicy; + private readonly intervalMs; + private readonly baseEjectionTimeMs; + private readonly maxEjectionTimeMs; + private readonly maxEjectionPercent; + private readonly successRateEjection; + private readonly failurePercentageEjection; + constructor(intervalMs: number | null, baseEjectionTimeMs: number | null, maxEjectionTimeMs: number | null, maxEjectionPercent: number | null, successRateEjection: Partial | null, failurePercentageEjection: Partial | null, childPolicy: TypedLoadBalancingConfig); + getLoadBalancerName(): string; + toJsonObject(): object; + getIntervalMs(): number; + getBaseEjectionTimeMs(): number; + getMaxEjectionTimeMs(): number; + getMaxEjectionPercent(): number; + getSuccessRateEjectionConfig(): SuccessRateEjectionConfig | null; + getFailurePercentageEjectionConfig(): FailurePercentageEjectionConfig | null; + getChildPolicy(): TypedLoadBalancingConfig; + static createFromJson(obj: any): OutlierDetectionLoadBalancingConfig; +} +export declare class OutlierDetectionLoadBalancer implements LoadBalancer { + private childBalancer; + private entryMap; + private latestConfig; + private ejectionTimer; + private timerStartTime; + constructor(channelControlHelper: ChannelControlHelper, options: ChannelOptions); + private isCountingEnabled; + private getCurrentEjectionPercent; + private runSuccessRateCheck; + private runFailurePercentageCheck; + private eject; + private uneject; + private switchAllBuckets; + private startTimer; + private runChecks; + updateAddressList(endpointList: Endpoint[], lbConfig: TypedLoadBalancingConfig, attributes: { + [key: string]: unknown; + }): void; + exitIdle(): void; + resetBackoff(): void; + destroy(): void; + getTypeName(): string; +} +export declare function setup(): void; diff --git a/node_modules/@grpc/grpc-js/build/src/load-balancer-outlier-detection.js b/node_modules/@grpc/grpc-js/build/src/load-balancer-outlier-detection.js new file mode 100644 index 0000000..7f2c15a --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/load-balancer-outlier-detection.js @@ -0,0 +1,567 @@ +"use strict"; +/* + * Copyright 2022 gRPC authors. + * + * 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 _a; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.setup = exports.OutlierDetectionLoadBalancer = exports.OutlierDetectionLoadBalancingConfig = void 0; +const connectivity_state_1 = require("./connectivity-state"); +const constants_1 = require("./constants"); +const duration_1 = require("./duration"); +const experimental_1 = require("./experimental"); +const load_balancer_1 = require("./load-balancer"); +const load_balancer_child_handler_1 = require("./load-balancer-child-handler"); +const picker_1 = require("./picker"); +const subchannel_address_1 = require("./subchannel-address"); +const subchannel_interface_1 = require("./subchannel-interface"); +const logging = require("./logging"); +const TRACER_NAME = 'outlier_detection'; +function trace(text) { + logging.trace(constants_1.LogVerbosity.DEBUG, TRACER_NAME, text); +} +const TYPE_NAME = 'outlier_detection'; +const OUTLIER_DETECTION_ENABLED = ((_a = process.env.GRPC_EXPERIMENTAL_ENABLE_OUTLIER_DETECTION) !== null && _a !== void 0 ? _a : 'true') === 'true'; +const defaultSuccessRateEjectionConfig = { + stdev_factor: 1900, + enforcement_percentage: 100, + minimum_hosts: 5, + request_volume: 100, +}; +const defaultFailurePercentageEjectionConfig = { + threshold: 85, + enforcement_percentage: 100, + minimum_hosts: 5, + request_volume: 50, +}; +function validateFieldType(obj, fieldName, expectedType, objectName) { + if (fieldName in obj && + obj[fieldName] !== undefined && + typeof obj[fieldName] !== expectedType) { + const fullFieldName = objectName ? `${objectName}.${fieldName}` : fieldName; + throw new Error(`outlier detection config ${fullFieldName} parse error: expected ${expectedType}, got ${typeof obj[fieldName]}`); + } +} +function validatePositiveDuration(obj, fieldName, objectName) { + const fullFieldName = objectName ? `${objectName}.${fieldName}` : fieldName; + if (fieldName in obj && obj[fieldName] !== undefined) { + if (!(0, duration_1.isDuration)(obj[fieldName])) { + throw new Error(`outlier detection config ${fullFieldName} parse error: expected Duration, got ${typeof obj[fieldName]}`); + } + if (!(obj[fieldName].seconds >= 0 && + obj[fieldName].seconds <= 315576000000 && + obj[fieldName].nanos >= 0 && + obj[fieldName].nanos <= 999999999)) { + throw new Error(`outlier detection config ${fullFieldName} parse error: values out of range for non-negative Duaration`); + } + } +} +function validatePercentage(obj, fieldName, objectName) { + const fullFieldName = objectName ? `${objectName}.${fieldName}` : fieldName; + validateFieldType(obj, fieldName, 'number', objectName); + if (fieldName in obj && + obj[fieldName] !== undefined && + !(obj[fieldName] >= 0 && obj[fieldName] <= 100)) { + throw new Error(`outlier detection config ${fullFieldName} parse error: value out of range for percentage (0-100)`); + } +} +class OutlierDetectionLoadBalancingConfig { + constructor(intervalMs, baseEjectionTimeMs, maxEjectionTimeMs, maxEjectionPercent, successRateEjection, failurePercentageEjection, childPolicy) { + this.childPolicy = childPolicy; + if (childPolicy.getLoadBalancerName() === 'pick_first') { + throw new Error('outlier_detection LB policy cannot have a pick_first child policy'); + } + this.intervalMs = intervalMs !== null && intervalMs !== void 0 ? intervalMs : 10000; + this.baseEjectionTimeMs = baseEjectionTimeMs !== null && baseEjectionTimeMs !== void 0 ? baseEjectionTimeMs : 30000; + this.maxEjectionTimeMs = maxEjectionTimeMs !== null && maxEjectionTimeMs !== void 0 ? maxEjectionTimeMs : 300000; + this.maxEjectionPercent = maxEjectionPercent !== null && maxEjectionPercent !== void 0 ? maxEjectionPercent : 10; + this.successRateEjection = successRateEjection + ? Object.assign(Object.assign({}, defaultSuccessRateEjectionConfig), successRateEjection) : null; + this.failurePercentageEjection = failurePercentageEjection + ? Object.assign(Object.assign({}, defaultFailurePercentageEjectionConfig), failurePercentageEjection) : null; + } + getLoadBalancerName() { + return TYPE_NAME; + } + toJsonObject() { + var _a, _b; + return { + outlier_detection: { + interval: (0, duration_1.msToDuration)(this.intervalMs), + base_ejection_time: (0, duration_1.msToDuration)(this.baseEjectionTimeMs), + max_ejection_time: (0, duration_1.msToDuration)(this.maxEjectionTimeMs), + max_ejection_percent: this.maxEjectionPercent, + success_rate_ejection: (_a = this.successRateEjection) !== null && _a !== void 0 ? _a : undefined, + failure_percentage_ejection: (_b = this.failurePercentageEjection) !== null && _b !== void 0 ? _b : undefined, + child_policy: [this.childPolicy.toJsonObject()], + }, + }; + } + getIntervalMs() { + return this.intervalMs; + } + getBaseEjectionTimeMs() { + return this.baseEjectionTimeMs; + } + getMaxEjectionTimeMs() { + return this.maxEjectionTimeMs; + } + getMaxEjectionPercent() { + return this.maxEjectionPercent; + } + getSuccessRateEjectionConfig() { + return this.successRateEjection; + } + getFailurePercentageEjectionConfig() { + return this.failurePercentageEjection; + } + getChildPolicy() { + return this.childPolicy; + } + static createFromJson(obj) { + var _a; + validatePositiveDuration(obj, 'interval'); + validatePositiveDuration(obj, 'base_ejection_time'); + validatePositiveDuration(obj, 'max_ejection_time'); + validatePercentage(obj, 'max_ejection_percent'); + if ('success_rate_ejection' in obj && + obj.success_rate_ejection !== undefined) { + if (typeof obj.success_rate_ejection !== 'object') { + throw new Error('outlier detection config success_rate_ejection must be an object'); + } + validateFieldType(obj.success_rate_ejection, 'stdev_factor', 'number', 'success_rate_ejection'); + validatePercentage(obj.success_rate_ejection, 'enforcement_percentage', 'success_rate_ejection'); + validateFieldType(obj.success_rate_ejection, 'minimum_hosts', 'number', 'success_rate_ejection'); + validateFieldType(obj.success_rate_ejection, 'request_volume', 'number', 'success_rate_ejection'); + } + if ('failure_percentage_ejection' in obj && + obj.failure_percentage_ejection !== undefined) { + if (typeof obj.failure_percentage_ejection !== 'object') { + throw new Error('outlier detection config failure_percentage_ejection must be an object'); + } + validatePercentage(obj.failure_percentage_ejection, 'threshold', 'failure_percentage_ejection'); + validatePercentage(obj.failure_percentage_ejection, 'enforcement_percentage', 'failure_percentage_ejection'); + validateFieldType(obj.failure_percentage_ejection, 'minimum_hosts', 'number', 'failure_percentage_ejection'); + validateFieldType(obj.failure_percentage_ejection, 'request_volume', 'number', 'failure_percentage_ejection'); + } + if (!('child_policy' in obj) || !Array.isArray(obj.child_policy)) { + throw new Error('outlier detection config child_policy must be an array'); + } + const childPolicy = (0, load_balancer_1.selectLbConfigFromList)(obj.child_policy); + if (!childPolicy) { + throw new Error('outlier detection config child_policy: no valid recognized policy found'); + } + return new OutlierDetectionLoadBalancingConfig(obj.interval ? (0, duration_1.durationToMs)(obj.interval) : null, obj.base_ejection_time ? (0, duration_1.durationToMs)(obj.base_ejection_time) : null, obj.max_ejection_time ? (0, duration_1.durationToMs)(obj.max_ejection_time) : null, (_a = obj.max_ejection_percent) !== null && _a !== void 0 ? _a : null, obj.success_rate_ejection, obj.failure_percentage_ejection, childPolicy); + } +} +exports.OutlierDetectionLoadBalancingConfig = OutlierDetectionLoadBalancingConfig; +class OutlierDetectionSubchannelWrapper extends subchannel_interface_1.BaseSubchannelWrapper { + constructor(childSubchannel, mapEntry) { + super(childSubchannel); + this.mapEntry = mapEntry; + this.refCount = 0; + } + ref() { + this.child.ref(); + this.refCount += 1; + } + unref() { + this.child.unref(); + this.refCount -= 1; + if (this.refCount <= 0) { + if (this.mapEntry) { + const index = this.mapEntry.subchannelWrappers.indexOf(this); + if (index >= 0) { + this.mapEntry.subchannelWrappers.splice(index, 1); + } + } + } + } + eject() { + this.setHealthy(false); + } + uneject() { + this.setHealthy(true); + } + getMapEntry() { + return this.mapEntry; + } + getWrappedSubchannel() { + return this.child; + } +} +function createEmptyBucket() { + return { + success: 0, + failure: 0, + }; +} +class CallCounter { + constructor() { + this.activeBucket = createEmptyBucket(); + this.inactiveBucket = createEmptyBucket(); + } + addSuccess() { + this.activeBucket.success += 1; + } + addFailure() { + this.activeBucket.failure += 1; + } + switchBuckets() { + this.inactiveBucket = this.activeBucket; + this.activeBucket = createEmptyBucket(); + } + getLastSuccesses() { + return this.inactiveBucket.success; + } + getLastFailures() { + return this.inactiveBucket.failure; + } +} +class OutlierDetectionPicker { + constructor(wrappedPicker, countCalls) { + this.wrappedPicker = wrappedPicker; + this.countCalls = countCalls; + } + pick(pickArgs) { + const wrappedPick = this.wrappedPicker.pick(pickArgs); + if (wrappedPick.pickResultType === picker_1.PickResultType.COMPLETE) { + const subchannelWrapper = wrappedPick.subchannel; + const mapEntry = subchannelWrapper.getMapEntry(); + if (mapEntry) { + let onCallEnded = wrappedPick.onCallEnded; + if (this.countCalls) { + onCallEnded = statusCode => { + var _a; + if (statusCode === constants_1.Status.OK) { + mapEntry.counter.addSuccess(); + } + else { + mapEntry.counter.addFailure(); + } + (_a = wrappedPick.onCallEnded) === null || _a === void 0 ? void 0 : _a.call(wrappedPick, statusCode); + }; + } + return Object.assign(Object.assign({}, wrappedPick), { subchannel: subchannelWrapper.getWrappedSubchannel(), onCallEnded: onCallEnded }); + } + else { + return Object.assign(Object.assign({}, wrappedPick), { subchannel: subchannelWrapper.getWrappedSubchannel() }); + } + } + else { + return wrappedPick; + } + } +} +class OutlierDetectionLoadBalancer { + constructor(channelControlHelper, options) { + this.entryMap = new subchannel_address_1.EndpointMap(); + this.latestConfig = null; + this.timerStartTime = null; + this.childBalancer = new load_balancer_child_handler_1.ChildLoadBalancerHandler((0, experimental_1.createChildChannelControlHelper)(channelControlHelper, { + createSubchannel: (subchannelAddress, subchannelArgs) => { + const originalSubchannel = channelControlHelper.createSubchannel(subchannelAddress, subchannelArgs); + const mapEntry = this.entryMap.getForSubchannelAddress(subchannelAddress); + const subchannelWrapper = new OutlierDetectionSubchannelWrapper(originalSubchannel, mapEntry); + if ((mapEntry === null || mapEntry === void 0 ? void 0 : mapEntry.currentEjectionTimestamp) !== null) { + // If the address is ejected, propagate that to the new subchannel wrapper + subchannelWrapper.eject(); + } + mapEntry === null || mapEntry === void 0 ? void 0 : mapEntry.subchannelWrappers.push(subchannelWrapper); + return subchannelWrapper; + }, + updateState: (connectivityState, picker) => { + if (connectivityState === connectivity_state_1.ConnectivityState.READY) { + channelControlHelper.updateState(connectivityState, new OutlierDetectionPicker(picker, this.isCountingEnabled())); + } + else { + channelControlHelper.updateState(connectivityState, picker); + } + }, + }), options); + this.ejectionTimer = setInterval(() => { }, 0); + clearInterval(this.ejectionTimer); + } + isCountingEnabled() { + return (this.latestConfig !== null && + (this.latestConfig.getSuccessRateEjectionConfig() !== null || + this.latestConfig.getFailurePercentageEjectionConfig() !== null)); + } + getCurrentEjectionPercent() { + let ejectionCount = 0; + for (const mapEntry of this.entryMap.values()) { + if (mapEntry.currentEjectionTimestamp !== null) { + ejectionCount += 1; + } + } + return (ejectionCount * 100) / this.entryMap.size; + } + runSuccessRateCheck(ejectionTimestamp) { + if (!this.latestConfig) { + return; + } + const successRateConfig = this.latestConfig.getSuccessRateEjectionConfig(); + if (!successRateConfig) { + return; + } + trace('Running success rate check'); + // Step 1 + const targetRequestVolume = successRateConfig.request_volume; + let addresesWithTargetVolume = 0; + const successRates = []; + for (const [endpoint, mapEntry] of this.entryMap.entries()) { + const successes = mapEntry.counter.getLastSuccesses(); + const failures = mapEntry.counter.getLastFailures(); + trace('Stats for ' + + (0, subchannel_address_1.endpointToString)(endpoint) + + ': successes=' + + successes + + ' failures=' + + failures + + ' targetRequestVolume=' + + targetRequestVolume); + if (successes + failures >= targetRequestVolume) { + addresesWithTargetVolume += 1; + successRates.push(successes / (successes + failures)); + } + } + trace('Found ' + + addresesWithTargetVolume + + ' success rate candidates; currentEjectionPercent=' + + this.getCurrentEjectionPercent() + + ' successRates=[' + + successRates + + ']'); + if (addresesWithTargetVolume < successRateConfig.minimum_hosts) { + return; + } + // Step 2 + const successRateMean = successRates.reduce((a, b) => a + b) / successRates.length; + let successRateDeviationSum = 0; + for (const rate of successRates) { + const deviation = rate - successRateMean; + successRateDeviationSum += deviation * deviation; + } + const successRateVariance = successRateDeviationSum / successRates.length; + const successRateStdev = Math.sqrt(successRateVariance); + const ejectionThreshold = successRateMean - + successRateStdev * (successRateConfig.stdev_factor / 1000); + trace('stdev=' + successRateStdev + ' ejectionThreshold=' + ejectionThreshold); + // Step 3 + for (const [address, mapEntry] of this.entryMap.entries()) { + // Step 3.i + if (this.getCurrentEjectionPercent() >= + this.latestConfig.getMaxEjectionPercent()) { + break; + } + // Step 3.ii + const successes = mapEntry.counter.getLastSuccesses(); + const failures = mapEntry.counter.getLastFailures(); + if (successes + failures < targetRequestVolume) { + continue; + } + // Step 3.iii + const successRate = successes / (successes + failures); + trace('Checking candidate ' + address + ' successRate=' + successRate); + if (successRate < ejectionThreshold) { + const randomNumber = Math.random() * 100; + trace('Candidate ' + + address + + ' randomNumber=' + + randomNumber + + ' enforcement_percentage=' + + successRateConfig.enforcement_percentage); + if (randomNumber < successRateConfig.enforcement_percentage) { + trace('Ejecting candidate ' + address); + this.eject(mapEntry, ejectionTimestamp); + } + } + } + } + runFailurePercentageCheck(ejectionTimestamp) { + if (!this.latestConfig) { + return; + } + const failurePercentageConfig = this.latestConfig.getFailurePercentageEjectionConfig(); + if (!failurePercentageConfig) { + return; + } + trace('Running failure percentage check. threshold=' + + failurePercentageConfig.threshold + + ' request volume threshold=' + + failurePercentageConfig.request_volume); + // Step 1 + let addressesWithTargetVolume = 0; + for (const mapEntry of this.entryMap.values()) { + const successes = mapEntry.counter.getLastSuccesses(); + const failures = mapEntry.counter.getLastFailures(); + if (successes + failures >= failurePercentageConfig.request_volume) { + addressesWithTargetVolume += 1; + } + } + if (addressesWithTargetVolume < failurePercentageConfig.minimum_hosts) { + return; + } + // Step 2 + for (const [address, mapEntry] of this.entryMap.entries()) { + // Step 2.i + if (this.getCurrentEjectionPercent() >= + this.latestConfig.getMaxEjectionPercent()) { + break; + } + // Step 2.ii + const successes = mapEntry.counter.getLastSuccesses(); + const failures = mapEntry.counter.getLastFailures(); + trace('Candidate successes=' + successes + ' failures=' + failures); + if (successes + failures < failurePercentageConfig.request_volume) { + continue; + } + // Step 2.iii + const failurePercentage = (failures * 100) / (failures + successes); + if (failurePercentage > failurePercentageConfig.threshold) { + const randomNumber = Math.random() * 100; + trace('Candidate ' + + address + + ' randomNumber=' + + randomNumber + + ' enforcement_percentage=' + + failurePercentageConfig.enforcement_percentage); + if (randomNumber < failurePercentageConfig.enforcement_percentage) { + trace('Ejecting candidate ' + address); + this.eject(mapEntry, ejectionTimestamp); + } + } + } + } + eject(mapEntry, ejectionTimestamp) { + mapEntry.currentEjectionTimestamp = new Date(); + mapEntry.ejectionTimeMultiplier += 1; + for (const subchannelWrapper of mapEntry.subchannelWrappers) { + subchannelWrapper.eject(); + } + } + uneject(mapEntry) { + mapEntry.currentEjectionTimestamp = null; + for (const subchannelWrapper of mapEntry.subchannelWrappers) { + subchannelWrapper.uneject(); + } + } + switchAllBuckets() { + for (const mapEntry of this.entryMap.values()) { + mapEntry.counter.switchBuckets(); + } + } + startTimer(delayMs) { + var _a, _b; + this.ejectionTimer = setTimeout(() => this.runChecks(), delayMs); + (_b = (_a = this.ejectionTimer).unref) === null || _b === void 0 ? void 0 : _b.call(_a); + } + runChecks() { + const ejectionTimestamp = new Date(); + trace('Ejection timer running'); + this.switchAllBuckets(); + if (!this.latestConfig) { + return; + } + this.timerStartTime = ejectionTimestamp; + this.startTimer(this.latestConfig.getIntervalMs()); + this.runSuccessRateCheck(ejectionTimestamp); + this.runFailurePercentageCheck(ejectionTimestamp); + for (const [address, mapEntry] of this.entryMap.entries()) { + if (mapEntry.currentEjectionTimestamp === null) { + if (mapEntry.ejectionTimeMultiplier > 0) { + mapEntry.ejectionTimeMultiplier -= 1; + } + } + else { + const baseEjectionTimeMs = this.latestConfig.getBaseEjectionTimeMs(); + const maxEjectionTimeMs = this.latestConfig.getMaxEjectionTimeMs(); + const returnTime = new Date(mapEntry.currentEjectionTimestamp.getTime()); + returnTime.setMilliseconds(returnTime.getMilliseconds() + + Math.min(baseEjectionTimeMs * mapEntry.ejectionTimeMultiplier, Math.max(baseEjectionTimeMs, maxEjectionTimeMs))); + if (returnTime < new Date()) { + trace('Unejecting ' + address); + this.uneject(mapEntry); + } + } + } + } + updateAddressList(endpointList, lbConfig, attributes) { + if (!(lbConfig instanceof OutlierDetectionLoadBalancingConfig)) { + return; + } + for (const endpoint of endpointList) { + if (!this.entryMap.has(endpoint)) { + trace('Adding map entry for ' + (0, subchannel_address_1.endpointToString)(endpoint)); + this.entryMap.set(endpoint, { + counter: new CallCounter(), + currentEjectionTimestamp: null, + ejectionTimeMultiplier: 0, + subchannelWrappers: [], + }); + } + } + this.entryMap.deleteMissing(endpointList); + const childPolicy = lbConfig.getChildPolicy(); + this.childBalancer.updateAddressList(endpointList, childPolicy, attributes); + if (lbConfig.getSuccessRateEjectionConfig() || + lbConfig.getFailurePercentageEjectionConfig()) { + if (this.timerStartTime) { + trace('Previous timer existed. Replacing timer'); + clearTimeout(this.ejectionTimer); + const remainingDelay = lbConfig.getIntervalMs() - + (new Date().getTime() - this.timerStartTime.getTime()); + this.startTimer(remainingDelay); + } + else { + trace('Starting new timer'); + this.timerStartTime = new Date(); + this.startTimer(lbConfig.getIntervalMs()); + this.switchAllBuckets(); + } + } + else { + trace('Counting disabled. Cancelling timer.'); + this.timerStartTime = null; + clearTimeout(this.ejectionTimer); + for (const mapEntry of this.entryMap.values()) { + this.uneject(mapEntry); + mapEntry.ejectionTimeMultiplier = 0; + } + } + this.latestConfig = lbConfig; + } + exitIdle() { + this.childBalancer.exitIdle(); + } + resetBackoff() { + this.childBalancer.resetBackoff(); + } + destroy() { + clearTimeout(this.ejectionTimer); + this.childBalancer.destroy(); + } + getTypeName() { + return TYPE_NAME; + } +} +exports.OutlierDetectionLoadBalancer = OutlierDetectionLoadBalancer; +function setup() { + if (OUTLIER_DETECTION_ENABLED) { + (0, experimental_1.registerLoadBalancerType)(TYPE_NAME, OutlierDetectionLoadBalancer, OutlierDetectionLoadBalancingConfig); + } +} +exports.setup = setup; +//# sourceMappingURL=load-balancer-outlier-detection.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/load-balancer-outlier-detection.js.map b/node_modules/@grpc/grpc-js/build/src/load-balancer-outlier-detection.js.map new file mode 100644 index 0000000..56eb518 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/load-balancer-outlier-detection.js.map @@ -0,0 +1 @@ +{"version":3,"file":"load-balancer-outlier-detection.js","sourceRoot":"","sources":["../../src/load-balancer-outlier-detection.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;GAeG;;;;AAGH,6DAAyD;AACzD,2CAAmD;AACnD,yCAA8E;AAC9E,iDAIwB;AACxB,mDAIyB;AACzB,+EAA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AClC,CAAC;iBAAM,CAAC;gBACN,KAAK,CAAC,oBAAoB,CAAC,CAAC;gBAC5B,IAAI,CAAC,cAAc,GAAG,IAAI,IAAI,EAAE,CAAC;gBACjC,IAAI,CAAC,UAAU,CAAC,QAAQ,CAAC,aAAa,EAAE,CAAC,CAAC;gBAC1C,IAAI,CAAC,gBAAgB,EAAE,CAAC;YAC1B,CAAC;QACH,CAAC;aAAM,CAAC;YACN,KAAK,CAAC,sCAAsC,CAAC,CAAC;YAC9C,IAAI,CAAC,cAAc,GAAG,IAAI,CAAC;YAC3B,YAAY,CAAC,IAAI,CAAC,aAAa,CAAC,CAAC;YACjC,KAAK,MAAM,QAAQ,IAAI,IAAI,CAAC,QAAQ,CAAC,MAAM,EAAE,EAAE,CAAC;gBAC9C,IAAI,CAAC,OAAO,CAAC,QAAQ,CAAC,CAAC;gBACvB,QAAQ,CAAC,sBAAsB,GAAG,CAAC,CAAC;YACtC,CAAC;QACH,CAAC;QAED,IAAI,CAAC,YAAY,GAAG,QAAQ,CAAC;IAC/B,CAAC;IACD,QAAQ;QACN,IAAI,CAAC,aAAa,CAAC,QAAQ,EAAE,CAAC;IAChC,CAAC;IACD,YAAY;QACV,IAAI,CAAC,aAAa,CAAC,YAAY,EAAE,CAAC;IACpC,CAAC;IACD,OAAO;QACL,YAAY,CAAC,IAAI,CAAC,aAAa,CAAC,CAAC;QACjC,IAAI,CAAC,aAAa,CAAC,OAAO,EAAE,CAAC;IAC/B,CAAC;IACD,WAAW;QACT,OAAO,SAAS,CAAC;IACnB,CAAC;CACF;AA1WD,oEA0WC;AAED,SAAgB,KAAK;IACnB,IAAI,yBAAyB,EAAE,CAAC;QAC9B,IAAA,uCAAwB,EACtB,SAAS,EACT,4BAA4B,EAC5B,mCAAmC,CACpC,CAAC;IACJ,CAAC;AACH,CAAC;AARD,sBAQC"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/load-balancer-pick-first.d.ts b/node_modules/@grpc/grpc-js/build/src/load-balancer-pick-first.d.ts new file mode 100644 index 0000000..69e1f75 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/load-balancer-pick-first.d.ts @@ -0,0 +1,127 @@ +import { LoadBalancer, ChannelControlHelper, TypedLoadBalancingConfig } from './load-balancer'; +import { ConnectivityState } from './connectivity-state'; +import { Picker } from './picker'; +import { Endpoint } from './subchannel-address'; +import { ChannelOptions } from './channel-options'; +export declare class PickFirstLoadBalancingConfig implements TypedLoadBalancingConfig { + private readonly shuffleAddressList; + constructor(shuffleAddressList: boolean); + getLoadBalancerName(): string; + toJsonObject(): object; + getShuffleAddressList(): boolean; + static createFromJson(obj: any): PickFirstLoadBalancingConfig; +} +/** + * Return a new array with the elements of the input array in a random order + * @param list The input array + * @returns A shuffled array of the elements of list + */ +export declare function shuffled(list: T[]): T[]; +export declare class PickFirstLoadBalancer implements LoadBalancer { + private readonly channelControlHelper; + /** + * The list of subchannels this load balancer is currently attempting to + * connect to. + */ + private children; + /** + * The current connectivity state of the load balancer. + */ + private currentState; + /** + * The index within the `subchannels` array of the subchannel with the most + * recently started connection attempt. + */ + private currentSubchannelIndex; + /** + * The currently picked subchannel used for making calls. Populated if + * and only if the load balancer's current state is READY. In that case, + * the subchannel's current state is also READY. + */ + private currentPick; + /** + * Listener callback attached to each subchannel in the `subchannels` list + * while establishing a connection. + */ + private subchannelStateListener; + private pickedSubchannelHealthListener; + /** + * Timer reference for the timer tracking when to start + */ + private connectionDelayTimeout; + private triedAllSubchannels; + /** + * The LB policy enters sticky TRANSIENT_FAILURE mode when all + * subchannels have failed to connect at least once, and it stays in that + * mode until a connection attempt is successful. While in sticky TF mode, + * the LB policy continuously attempts to connect to all of its subchannels. + */ + private stickyTransientFailureMode; + private reportHealthStatus; + /** + * Indicates whether we called channelControlHelper.requestReresolution since + * the last call to updateAddressList + */ + private requestedResolutionSinceLastUpdate; + /** + * The most recent error reported by any subchannel as it transitioned to + * TRANSIENT_FAILURE. + */ + private lastError; + private latestAddressList; + /** + * Load balancer that attempts to connect to each backend in the address list + * in order, and picks the first one that connects, using it for every + * request. + * @param channelControlHelper `ChannelControlHelper` instance provided by + * this load balancer's owner. + */ + constructor(channelControlHelper: ChannelControlHelper, options: ChannelOptions); + private allChildrenHaveReportedTF; + private calculateAndReportNewState; + private requestReresolution; + private maybeEnterStickyTransientFailureMode; + private removeCurrentPick; + private onSubchannelStateUpdate; + private startNextSubchannelConnecting; + /** + * Have a single subchannel in the `subchannels` list start connecting. + * @param subchannelIndex The index into the `subchannels` list. + */ + private startConnecting; + private pickSubchannel; + private updateState; + private resetSubchannelList; + private connectToAddressList; + updateAddressList(endpointList: Endpoint[], lbConfig: TypedLoadBalancingConfig): void; + exitIdle(): void; + resetBackoff(): void; + destroy(): void; + getTypeName(): string; +} +/** + * This class handles the leaf load balancing operations for a single endpoint. + * It is a thin wrapper around a PickFirstLoadBalancer with a different API + * that more closely reflects how it will be used as a leaf balancer. + */ +export declare class LeafLoadBalancer { + private endpoint; + private pickFirstBalancer; + private latestState; + private latestPicker; + constructor(endpoint: Endpoint, channelControlHelper: ChannelControlHelper, options: ChannelOptions); + startConnecting(): void; + /** + * Update the endpoint associated with this LeafLoadBalancer to a new + * endpoint. Does not trigger connection establishment if a connection + * attempt is not already in progress. + * @param newEndpoint + */ + updateEndpoint(newEndpoint: Endpoint): void; + getConnectivityState(): ConnectivityState; + getPicker(): Picker; + getEndpoint(): Endpoint; + exitIdle(): void; + destroy(): void; +} +export declare function setup(): void; diff --git a/node_modules/@grpc/grpc-js/build/src/load-balancer-pick-first.js b/node_modules/@grpc/grpc-js/build/src/load-balancer-pick-first.js new file mode 100644 index 0000000..a2e0728 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/load-balancer-pick-first.js @@ -0,0 +1,499 @@ +"use strict"; +/* + * Copyright 2019 gRPC authors. + * + * 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. + * + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.setup = exports.LeafLoadBalancer = exports.PickFirstLoadBalancer = exports.shuffled = exports.PickFirstLoadBalancingConfig = void 0; +const load_balancer_1 = require("./load-balancer"); +const connectivity_state_1 = require("./connectivity-state"); +const picker_1 = require("./picker"); +const logging = require("./logging"); +const constants_1 = require("./constants"); +const subchannel_address_1 = require("./subchannel-address"); +const net_1 = require("net"); +const TRACER_NAME = 'pick_first'; +function trace(text) { + logging.trace(constants_1.LogVerbosity.DEBUG, TRACER_NAME, text); +} +const TYPE_NAME = 'pick_first'; +/** + * Delay after starting a connection on a subchannel before starting a + * connection on the next subchannel in the list, for Happy Eyeballs algorithm. + */ +const CONNECTION_DELAY_INTERVAL_MS = 250; +class PickFirstLoadBalancingConfig { + constructor(shuffleAddressList) { + this.shuffleAddressList = shuffleAddressList; + } + getLoadBalancerName() { + return TYPE_NAME; + } + toJsonObject() { + return { + [TYPE_NAME]: { + shuffleAddressList: this.shuffleAddressList, + }, + }; + } + getShuffleAddressList() { + return this.shuffleAddressList; + } + // eslint-disable-next-line @typescript-eslint/no-explicit-any + static createFromJson(obj) { + if ('shuffleAddressList' in obj && + !(typeof obj.shuffleAddressList === 'boolean')) { + throw new Error('pick_first config field shuffleAddressList must be a boolean if provided'); + } + return new PickFirstLoadBalancingConfig(obj.shuffleAddressList === true); + } +} +exports.PickFirstLoadBalancingConfig = PickFirstLoadBalancingConfig; +/** + * Picker for a `PickFirstLoadBalancer` in the READY state. Always returns the + * picked subchannel. + */ +class PickFirstPicker { + constructor(subchannel) { + this.subchannel = subchannel; + } + pick(pickArgs) { + return { + pickResultType: picker_1.PickResultType.COMPLETE, + subchannel: this.subchannel, + status: null, + onCallStarted: null, + onCallEnded: null, + }; + } +} +/** + * Return a new array with the elements of the input array in a random order + * @param list The input array + * @returns A shuffled array of the elements of list + */ +function shuffled(list) { + const result = list.slice(); + for (let i = result.length - 1; i > 1; i--) { + const j = Math.floor(Math.random() * (i + 1)); + const temp = result[i]; + result[i] = result[j]; + result[j] = temp; + } + return result; +} +exports.shuffled = shuffled; +/** + * Interleave addresses in addressList by family in accordance with RFC-8304 section 4 + * @param addressList + * @returns + */ +function interleaveAddressFamilies(addressList) { + const result = []; + const ipv6Addresses = []; + const ipv4Addresses = []; + const ipv6First = (0, subchannel_address_1.isTcpSubchannelAddress)(addressList[0]) && (0, net_1.isIPv6)(addressList[0].host); + for (const address of addressList) { + if ((0, subchannel_address_1.isTcpSubchannelAddress)(address) && (0, net_1.isIPv6)(address.host)) { + ipv6Addresses.push(address); + } + else { + ipv4Addresses.push(address); + } + } + const firstList = ipv6First ? ipv6Addresses : ipv4Addresses; + const secondList = ipv6First ? ipv4Addresses : ipv6Addresses; + for (let i = 0; i < Math.max(firstList.length, secondList.length); i++) { + if (i < firstList.length) { + result.push(firstList[i]); + } + if (i < secondList.length) { + result.push(secondList[i]); + } + } + return result; +} +const REPORT_HEALTH_STATUS_OPTION_NAME = 'grpc-node.internal.pick-first.report_health_status'; +class PickFirstLoadBalancer { + /** + * Load balancer that attempts to connect to each backend in the address list + * in order, and picks the first one that connects, using it for every + * request. + * @param channelControlHelper `ChannelControlHelper` instance provided by + * this load balancer's owner. + */ + constructor(channelControlHelper, options) { + this.channelControlHelper = channelControlHelper; + /** + * The list of subchannels this load balancer is currently attempting to + * connect to. + */ + this.children = []; + /** + * The current connectivity state of the load balancer. + */ + this.currentState = connectivity_state_1.ConnectivityState.IDLE; + /** + * The index within the `subchannels` array of the subchannel with the most + * recently started connection attempt. + */ + this.currentSubchannelIndex = 0; + /** + * The currently picked subchannel used for making calls. Populated if + * and only if the load balancer's current state is READY. In that case, + * the subchannel's current state is also READY. + */ + this.currentPick = null; + /** + * Listener callback attached to each subchannel in the `subchannels` list + * while establishing a connection. + */ + this.subchannelStateListener = (subchannel, previousState, newState, keepaliveTime, errorMessage) => { + this.onSubchannelStateUpdate(subchannel, previousState, newState, errorMessage); + }; + this.pickedSubchannelHealthListener = () => this.calculateAndReportNewState(); + this.triedAllSubchannels = false; + /** + * The LB policy enters sticky TRANSIENT_FAILURE mode when all + * subchannels have failed to connect at least once, and it stays in that + * mode until a connection attempt is successful. While in sticky TF mode, + * the LB policy continuously attempts to connect to all of its subchannels. + */ + this.stickyTransientFailureMode = false; + /** + * Indicates whether we called channelControlHelper.requestReresolution since + * the last call to updateAddressList + */ + this.requestedResolutionSinceLastUpdate = false; + /** + * The most recent error reported by any subchannel as it transitioned to + * TRANSIENT_FAILURE. + */ + this.lastError = null; + this.latestAddressList = null; + this.connectionDelayTimeout = setTimeout(() => { }, 0); + clearTimeout(this.connectionDelayTimeout); + this.reportHealthStatus = options[REPORT_HEALTH_STATUS_OPTION_NAME]; + } + allChildrenHaveReportedTF() { + return this.children.every(child => child.hasReportedTransientFailure); + } + calculateAndReportNewState() { + if (this.currentPick) { + if (this.reportHealthStatus && !this.currentPick.isHealthy()) { + this.updateState(connectivity_state_1.ConnectivityState.TRANSIENT_FAILURE, new picker_1.UnavailablePicker({ + details: `Picked subchannel ${this.currentPick.getAddress()} is unhealthy`, + })); + } + else { + this.updateState(connectivity_state_1.ConnectivityState.READY, new PickFirstPicker(this.currentPick)); + } + } + else if (this.children.length === 0) { + this.updateState(connectivity_state_1.ConnectivityState.IDLE, new picker_1.QueuePicker(this)); + } + else { + if (this.stickyTransientFailureMode) { + this.updateState(connectivity_state_1.ConnectivityState.TRANSIENT_FAILURE, new picker_1.UnavailablePicker({ + details: `No connection established. Last error: ${this.lastError}`, + })); + } + else { + this.updateState(connectivity_state_1.ConnectivityState.CONNECTING, new picker_1.QueuePicker(this)); + } + } + } + requestReresolution() { + this.requestedResolutionSinceLastUpdate = true; + this.channelControlHelper.requestReresolution(); + } + maybeEnterStickyTransientFailureMode() { + if (!this.allChildrenHaveReportedTF()) { + return; + } + if (!this.requestedResolutionSinceLastUpdate) { + /* Each time we get an update we reset each subchannel's + * hasReportedTransientFailure flag, so the next time we get to this + * point after that, each subchannel has reported TRANSIENT_FAILURE + * at least once since then. That is the trigger for requesting + * reresolution, whether or not the LB policy is already in sticky TF + * mode. */ + this.requestReresolution(); + } + if (this.stickyTransientFailureMode) { + return; + } + this.stickyTransientFailureMode = true; + for (const { subchannel } of this.children) { + subchannel.startConnecting(); + } + this.calculateAndReportNewState(); + } + removeCurrentPick() { + if (this.currentPick !== null) { + /* Unref can cause a state change, which can cause a change in the value + * of this.currentPick, so we hold a local reference to make sure that + * does not impact this function. */ + const currentPick = this.currentPick; + this.currentPick = null; + currentPick.unref(); + currentPick.removeConnectivityStateListener(this.subchannelStateListener); + this.channelControlHelper.removeChannelzChild(currentPick.getChannelzRef()); + if (this.reportHealthStatus) { + currentPick.removeHealthStateWatcher(this.pickedSubchannelHealthListener); + } + } + } + onSubchannelStateUpdate(subchannel, previousState, newState, errorMessage) { + var _a; + if ((_a = this.currentPick) === null || _a === void 0 ? void 0 : _a.realSubchannelEquals(subchannel)) { + if (newState !== connectivity_state_1.ConnectivityState.READY) { + this.removeCurrentPick(); + this.calculateAndReportNewState(); + this.requestReresolution(); + } + return; + } + for (const [index, child] of this.children.entries()) { + if (subchannel.realSubchannelEquals(child.subchannel)) { + if (newState === connectivity_state_1.ConnectivityState.READY) { + this.pickSubchannel(child.subchannel); + } + if (newState === connectivity_state_1.ConnectivityState.TRANSIENT_FAILURE) { + child.hasReportedTransientFailure = true; + if (errorMessage) { + this.lastError = errorMessage; + } + this.maybeEnterStickyTransientFailureMode(); + if (index === this.currentSubchannelIndex) { + this.startNextSubchannelConnecting(index + 1); + } + } + child.subchannel.startConnecting(); + return; + } + } + } + startNextSubchannelConnecting(startIndex) { + clearTimeout(this.connectionDelayTimeout); + if (this.triedAllSubchannels) { + return; + } + for (const [index, child] of this.children.entries()) { + if (index >= startIndex) { + const subchannelState = child.subchannel.getConnectivityState(); + if (subchannelState === connectivity_state_1.ConnectivityState.IDLE || + subchannelState === connectivity_state_1.ConnectivityState.CONNECTING) { + this.startConnecting(index); + return; + } + } + } + this.triedAllSubchannels = true; + this.maybeEnterStickyTransientFailureMode(); + } + /** + * Have a single subchannel in the `subchannels` list start connecting. + * @param subchannelIndex The index into the `subchannels` list. + */ + startConnecting(subchannelIndex) { + var _a, _b; + clearTimeout(this.connectionDelayTimeout); + this.currentSubchannelIndex = subchannelIndex; + if (this.children[subchannelIndex].subchannel.getConnectivityState() === + connectivity_state_1.ConnectivityState.IDLE) { + trace('Start connecting to subchannel with address ' + + this.children[subchannelIndex].subchannel.getAddress()); + process.nextTick(() => { + var _a; + (_a = this.children[subchannelIndex]) === null || _a === void 0 ? void 0 : _a.subchannel.startConnecting(); + }); + } + this.connectionDelayTimeout = setTimeout(() => { + this.startNextSubchannelConnecting(subchannelIndex + 1); + }, CONNECTION_DELAY_INTERVAL_MS); + (_b = (_a = this.connectionDelayTimeout).unref) === null || _b === void 0 ? void 0 : _b.call(_a); + } + pickSubchannel(subchannel) { + if (this.currentPick && subchannel.realSubchannelEquals(this.currentPick)) { + return; + } + trace('Pick subchannel with address ' + subchannel.getAddress()); + this.stickyTransientFailureMode = false; + this.removeCurrentPick(); + this.currentPick = subchannel; + subchannel.ref(); + if (this.reportHealthStatus) { + subchannel.addHealthStateWatcher(this.pickedSubchannelHealthListener); + } + this.channelControlHelper.addChannelzChild(subchannel.getChannelzRef()); + this.resetSubchannelList(); + clearTimeout(this.connectionDelayTimeout); + this.calculateAndReportNewState(); + } + updateState(newState, picker) { + trace(connectivity_state_1.ConnectivityState[this.currentState] + + ' -> ' + + connectivity_state_1.ConnectivityState[newState]); + this.currentState = newState; + this.channelControlHelper.updateState(newState, picker); + } + resetSubchannelList() { + for (const child of this.children) { + if (!(this.currentPick && + child.subchannel.realSubchannelEquals(this.currentPick))) { + /* The connectivity state listener is the same whether the subchannel + * is in the list of children or it is the currentPick, so if it is in + * both, removing it here would cause problems. In particular, that + * always happens immediately after the subchannel is picked. */ + child.subchannel.removeConnectivityStateListener(this.subchannelStateListener); + } + /* Refs are counted independently for the children list and the + * currentPick, so we call unref whether or not the child is the + * currentPick. Channelz child references are also refcounted, so + * removeChannelzChild can be handled the same way. */ + child.subchannel.unref(); + this.channelControlHelper.removeChannelzChild(child.subchannel.getChannelzRef()); + } + this.currentSubchannelIndex = 0; + this.children = []; + this.triedAllSubchannels = false; + this.requestedResolutionSinceLastUpdate = false; + } + connectToAddressList(addressList) { + const newChildrenList = addressList.map(address => ({ + subchannel: this.channelControlHelper.createSubchannel(address, {}), + hasReportedTransientFailure: false, + })); + /* Ref each subchannel before resetting the list, to ensure that + * subchannels shared between the list don't drop to 0 refs during the + * transition. */ + for (const { subchannel } of newChildrenList) { + subchannel.ref(); + this.channelControlHelper.addChannelzChild(subchannel.getChannelzRef()); + } + this.resetSubchannelList(); + this.children = newChildrenList; + for (const { subchannel } of this.children) { + subchannel.addConnectivityStateListener(this.subchannelStateListener); + if (subchannel.getConnectivityState() === connectivity_state_1.ConnectivityState.READY) { + this.pickSubchannel(subchannel); + return; + } + } + for (const child of this.children) { + if (child.subchannel.getConnectivityState() === + connectivity_state_1.ConnectivityState.TRANSIENT_FAILURE) { + child.hasReportedTransientFailure = true; + } + } + this.startNextSubchannelConnecting(0); + this.calculateAndReportNewState(); + } + updateAddressList(endpointList, lbConfig) { + if (!(lbConfig instanceof PickFirstLoadBalancingConfig)) { + return; + } + /* Previously, an update would be discarded if it was identical to the + * previous update, to minimize churn. Now the DNS resolver is + * rate-limited, so that is less of a concern. */ + if (lbConfig.getShuffleAddressList()) { + endpointList = shuffled(endpointList); + } + const rawAddressList = [].concat(...endpointList.map(endpoint => endpoint.addresses)); + if (rawAddressList.length === 0) { + throw new Error('No addresses in endpoint list passed to pick_first'); + } + const addressList = interleaveAddressFamilies(rawAddressList); + this.latestAddressList = addressList; + this.connectToAddressList(addressList); + } + exitIdle() { + if (this.currentState === connectivity_state_1.ConnectivityState.IDLE && + this.latestAddressList) { + this.connectToAddressList(this.latestAddressList); + } + } + resetBackoff() { + /* The pick first load balancer does not have a connection backoff, so this + * does nothing */ + } + destroy() { + this.resetSubchannelList(); + this.removeCurrentPick(); + } + getTypeName() { + return TYPE_NAME; + } +} +exports.PickFirstLoadBalancer = PickFirstLoadBalancer; +const LEAF_CONFIG = new PickFirstLoadBalancingConfig(false); +/** + * This class handles the leaf load balancing operations for a single endpoint. + * It is a thin wrapper around a PickFirstLoadBalancer with a different API + * that more closely reflects how it will be used as a leaf balancer. + */ +class LeafLoadBalancer { + constructor(endpoint, channelControlHelper, options) { + this.endpoint = endpoint; + this.latestState = connectivity_state_1.ConnectivityState.IDLE; + const childChannelControlHelper = (0, load_balancer_1.createChildChannelControlHelper)(channelControlHelper, { + updateState: (connectivityState, picker) => { + this.latestState = connectivityState; + this.latestPicker = picker; + channelControlHelper.updateState(connectivityState, picker); + }, + }); + this.pickFirstBalancer = new PickFirstLoadBalancer(childChannelControlHelper, Object.assign(Object.assign({}, options), { [REPORT_HEALTH_STATUS_OPTION_NAME]: true })); + this.latestPicker = new picker_1.QueuePicker(this.pickFirstBalancer); + } + startConnecting() { + this.pickFirstBalancer.updateAddressList([this.endpoint], LEAF_CONFIG); + } + /** + * Update the endpoint associated with this LeafLoadBalancer to a new + * endpoint. Does not trigger connection establishment if a connection + * attempt is not already in progress. + * @param newEndpoint + */ + updateEndpoint(newEndpoint) { + this.endpoint = newEndpoint; + if (this.latestState !== connectivity_state_1.ConnectivityState.IDLE) { + this.startConnecting(); + } + } + getConnectivityState() { + return this.latestState; + } + getPicker() { + return this.latestPicker; + } + getEndpoint() { + return this.endpoint; + } + exitIdle() { + this.pickFirstBalancer.exitIdle(); + } + destroy() { + this.pickFirstBalancer.destroy(); + } +} +exports.LeafLoadBalancer = LeafLoadBalancer; +function setup() { + (0, load_balancer_1.registerLoadBalancerType)(TYPE_NAME, PickFirstLoadBalancer, PickFirstLoadBalancingConfig); + (0, load_balancer_1.registerDefaultLoadBalancerType)(TYPE_NAME); +} +exports.setup = setup; +//# sourceMappingURL=load-balancer-pick-first.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/load-balancer-pick-first.js.map b/node_modules/@grpc/grpc-js/build/src/load-balancer-pick-first.js.map new file mode 100644 index 0000000..de5d6be --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/load-balancer-pick-first.js.map @@ -0,0 +1 @@ +{"version":3,"file":"load-balancer-pick-first.js","sourceRoot":"","sources":["../../src/load-balancer-pick-first.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;GAeG;;;AAEH,mDAOyB;AACzB,6DAAyD;AACzD,qCAOkB;AAElB,qCAAqC;AACrC,2CAA2C;AAM3C,6DAA8D;AAC9D,6BAA6B;AAG7B,MAAM,WAAW,GAAG,YAAY,CAAC;AAEjC,SAAS,KAAK,CAAC,IAAY;IACzB,OAAO,CAAC,KAAK,CAAC,wBAAY,CAAC,KAAK,EAAE,WAAW,EAAE,IAAI,CAAC,CAAC;AACvD,CAAC;AAED,MAAM,SAAS,GAAG,YAAY,CAAC;AAE/B;;;GAGG;AACH,MAAM,4BAA4B,GAAG,GAAG,CAAC;AAEzC,MAAa,4BAA4B;IACvC,YAA6B,kBAA2B;QAA3B,uBAAkB,GAAlB,kBAAkB,CAAS;IAAG,CAAC;IAE5D,mBAAmB;QACjB,OAAO,SAAS,CAAC;IACnB,CAAC;IAED,YAAY;QACV,OAAO;YACL,CAAC,SAAS,CAAC,EAAE;gBACX,kBAAkB,EAAE,IAAI,CAAC,kBAAkB;aAC5C;SACF,CAAC;IACJ,CAAC;IAED,qBAAqB;QACnB,OAAO,IAAI,CAAC,kBAAkB,CAAC;IACjC,CAAC;IAED,8DAA8D;IAC9D,MAAM,CAAC,cAAc,CAAC,GAAQ;QAC5B,IACE,oBAAoB,IAAI,GAAG;YAC3B,CAAC,CAAC,OAAO,GAAG,CAAC,kBAAkB,KAAK,SAAS,CAAC,EAC9C,CAA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C;AAED,SAAgB,KAAK;IACnB,IAAA,wCAAwB,EACtB,SAAS,EACT,qBAAqB,EACrB,4BAA4B,CAC7B,CAAC;IACF,IAAA,+CAA+B,EAAC,SAAS,CAAC,CAAC;AAC7C,CAAC;AAPD,sBAOC"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/load-balancer-round-robin.d.ts b/node_modules/@grpc/grpc-js/build/src/load-balancer-round-robin.d.ts new file mode 100644 index 0000000..b3bcdcc --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/load-balancer-round-robin.d.ts @@ -0,0 +1,24 @@ +import { LoadBalancer, ChannelControlHelper, TypedLoadBalancingConfig } from './load-balancer'; +import { Endpoint } from './subchannel-address'; +import { ChannelOptions } from './channel-options'; +export declare class RoundRobinLoadBalancer implements LoadBalancer { + private readonly channelControlHelper; + private readonly options; + private children; + private currentState; + private currentReadyPicker; + private updatesPaused; + private childChannelControlHelper; + private lastError; + constructor(channelControlHelper: ChannelControlHelper, options: ChannelOptions); + private countChildrenWithState; + private calculateAndUpdateState; + private updateState; + private resetSubchannelList; + updateAddressList(endpointList: Endpoint[], lbConfig: TypedLoadBalancingConfig): void; + exitIdle(): void; + resetBackoff(): void; + destroy(): void; + getTypeName(): string; +} +export declare function setup(): void; diff --git a/node_modules/@grpc/grpc-js/build/src/load-balancer-round-robin.js b/node_modules/@grpc/grpc-js/build/src/load-balancer-round-robin.js new file mode 100644 index 0000000..d2deb3a --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/load-balancer-round-robin.js @@ -0,0 +1,174 @@ +"use strict"; +/* + * Copyright 2019 gRPC authors. + * + * 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. + * + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.setup = exports.RoundRobinLoadBalancer = void 0; +const load_balancer_1 = require("./load-balancer"); +const connectivity_state_1 = require("./connectivity-state"); +const picker_1 = require("./picker"); +const logging = require("./logging"); +const constants_1 = require("./constants"); +const subchannel_address_1 = require("./subchannel-address"); +const load_balancer_pick_first_1 = require("./load-balancer-pick-first"); +const TRACER_NAME = 'round_robin'; +function trace(text) { + logging.trace(constants_1.LogVerbosity.DEBUG, TRACER_NAME, text); +} +const TYPE_NAME = 'round_robin'; +class RoundRobinLoadBalancingConfig { + getLoadBalancerName() { + return TYPE_NAME; + } + constructor() { } + toJsonObject() { + return { + [TYPE_NAME]: {}, + }; + } + // eslint-disable-next-line @typescript-eslint/no-explicit-any + static createFromJson(obj) { + return new RoundRobinLoadBalancingConfig(); + } +} +class RoundRobinPicker { + constructor(children, nextIndex = 0) { + this.children = children; + this.nextIndex = nextIndex; + } + pick(pickArgs) { + const childPicker = this.children[this.nextIndex].picker; + this.nextIndex = (this.nextIndex + 1) % this.children.length; + return childPicker.pick(pickArgs); + } + /** + * Check what the next subchannel returned would be. Used by the load + * balancer implementation to preserve this part of the picker state if + * possible when a subchannel connects or disconnects. + */ + peekNextEndpoint() { + return this.children[this.nextIndex].endpoint; + } +} +class RoundRobinLoadBalancer { + constructor(channelControlHelper, options) { + this.channelControlHelper = channelControlHelper; + this.options = options; + this.children = []; + this.currentState = connectivity_state_1.ConnectivityState.IDLE; + this.currentReadyPicker = null; + this.updatesPaused = false; + this.lastError = null; + this.childChannelControlHelper = (0, load_balancer_1.createChildChannelControlHelper)(channelControlHelper, { + updateState: (connectivityState, picker) => { + this.calculateAndUpdateState(); + }, + }); + } + countChildrenWithState(state) { + return this.children.filter(child => child.getConnectivityState() === state) + .length; + } + calculateAndUpdateState() { + if (this.updatesPaused) { + return; + } + if (this.countChildrenWithState(connectivity_state_1.ConnectivityState.READY) > 0) { + const readyChildren = this.children.filter(child => child.getConnectivityState() === connectivity_state_1.ConnectivityState.READY); + let index = 0; + if (this.currentReadyPicker !== null) { + const nextPickedEndpoint = this.currentReadyPicker.peekNextEndpoint(); + index = readyChildren.findIndex(child => (0, subchannel_address_1.endpointEqual)(child.getEndpoint(), nextPickedEndpoint)); + if (index < 0) { + index = 0; + } + } + this.updateState(connectivity_state_1.ConnectivityState.READY, new RoundRobinPicker(readyChildren.map(child => ({ + endpoint: child.getEndpoint(), + picker: child.getPicker(), + })), index)); + } + else if (this.countChildrenWithState(connectivity_state_1.ConnectivityState.CONNECTING) > 0) { + this.updateState(connectivity_state_1.ConnectivityState.CONNECTING, new picker_1.QueuePicker(this)); + } + else if (this.countChildrenWithState(connectivity_state_1.ConnectivityState.TRANSIENT_FAILURE) > 0) { + this.updateState(connectivity_state_1.ConnectivityState.TRANSIENT_FAILURE, new picker_1.UnavailablePicker({ + details: `No connection established. Last error: ${this.lastError}`, + })); + } + else { + this.updateState(connectivity_state_1.ConnectivityState.IDLE, new picker_1.QueuePicker(this)); + } + /* round_robin should keep all children connected, this is how we do that. + * We can't do this more efficiently in the individual child's updateState + * callback because that doesn't have a reference to which child the state + * change is associated with. */ + for (const child of this.children) { + if (child.getConnectivityState() === connectivity_state_1.ConnectivityState.IDLE) { + child.exitIdle(); + } + } + } + updateState(newState, picker) { + trace(connectivity_state_1.ConnectivityState[this.currentState] + + ' -> ' + + connectivity_state_1.ConnectivityState[newState]); + if (newState === connectivity_state_1.ConnectivityState.READY) { + this.currentReadyPicker = picker; + } + else { + this.currentReadyPicker = null; + } + this.currentState = newState; + this.channelControlHelper.updateState(newState, picker); + } + resetSubchannelList() { + for (const child of this.children) { + child.destroy(); + } + } + updateAddressList(endpointList, lbConfig) { + this.resetSubchannelList(); + trace('Connect to endpoint list ' + endpointList.map(subchannel_address_1.endpointToString)); + this.updatesPaused = true; + this.children = endpointList.map(endpoint => new load_balancer_pick_first_1.LeafLoadBalancer(endpoint, this.childChannelControlHelper, this.options)); + for (const child of this.children) { + child.startConnecting(); + } + this.updatesPaused = false; + this.calculateAndUpdateState(); + } + exitIdle() { + /* The round_robin LB policy is only in the IDLE state if it has no + * addresses to try to connect to and it has no picked subchannel. + * In that case, there is no meaningful action that can be taken here. */ + } + resetBackoff() { + // This LB policy has no backoff to reset + } + destroy() { + this.resetSubchannelList(); + } + getTypeName() { + return TYPE_NAME; + } +} +exports.RoundRobinLoadBalancer = RoundRobinLoadBalancer; +function setup() { + (0, load_balancer_1.registerLoadBalancerType)(TYPE_NAME, RoundRobinLoadBalancer, RoundRobinLoadBalancingConfig); +} +exports.setup = setup; +//# sourceMappingURL=load-balancer-round-robin.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/load-balancer-round-robin.js.map b/node_modules/@grpc/grpc-js/build/src/load-balancer-round-robin.js.map new file mode 100644 index 0000000..da9435b --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/load-balancer-round-robin.js.map @@ -0,0 +1 @@ +{"version":3,"file":"load-balancer-round-robin.js","sourceRoot":"","sources":["../../src/load-balancer-round-robin.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;GAeG;;;AAEH,mDAMyB;AACzB,6DAAyD;AACzD,qCAMkB;AAClB,qCAAqC;AACrC,2CAA2C;AAC3C,6DAI8B;AAC9B,yEAA8D;AAG9D,MAAM,WAAW,GAAG,aAAa,CAAC;AAElC,SAAS,KAAK,CAAC,IAAY;IACzB,OAAO,CAAC,KAAK,CAAC,wBAAY,CAAC,KAAK,EAAE,WAAW,EAAE,IAAI,CAAC,CAAC;AACvD,CAAC;AAED,MAAM,SAAS,GAAG,aAAa,CAAC;AAEhC,MAAM,6BAA6B;IACjC,mBAAmB;QACjB,OAAO,SAAS,CAAC;IACnB,CAAC;IAED,gBAAe,CAAC;IAEhB,YAAY;QACV,OAAO;YACL,CAAC,SAAS,CAAC,EAAE,EAAE;SAChB,CAAC;IACJ,CAAC;IAED,8DAA8D;IAC9D,MAAM,CAAC,cAAc,CAAC,GAAQ;QAC5B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AAC;IAED,iBAAiB,CACf,YAAwB,EACxB,QAAkC;QAElC,IAAI,CAAC,mBAAmB,EAAE,CAAC;QAC3B,KAAK,CAAC,2BAA2B,GAAG,YAAY,CAAC,GAAG,CAAC,qCAAgB,CAAC,CAAC,CAAC;QACxE,IAAI,CAAC,aAAa,GAAG,IAAI,CAAC;QAC1B,IAAI,CAAC,QAAQ,GAAG,YAAY,CAAC,GAAG,CAC9B,QAAQ,CAAC,EAAE,CACT,IAAI,2CAAgB,CAClB,QAAQ,EACR,IAAI,CAAC,yBAAyB,EAC9B,IAAI,CAAC,OAAO,CACb,CACJ,CAAC;QACF,KAAK,MAAM,KAAK,IAAI,IAAI,CAAC,QAAQ,EAAE,CAAC;YAClC,KAAK,CAAC,eAAe,EAAE,CAAC;QAC1B,CAAC;QACD,IAAI,CAAC,aAAa,GAAG,KAAK,CAAC;QAC3B,IAAI,CAAC,uBAAuB,EAAE,CAAC;IACjC,CAAC;IAED,QAAQ;QACN;;iFAEyE;IAC3E,CAAC;IACD,YAAY;QACV,yCAAyC;IAC3C,CAAC;IACD,OAAO;QACL,IAAI,CAAC,mBAAmB,EAAE,CAAC;IAC7B,CAAC;IACD,WAAW;QACT,OAAO,SAAS,CAAC;IACnB,CAAC;CACF;AA9ID,wDA8IC;AAED,SAAgB,KAAK;IACnB,IAAA,wCAAwB,EACtB,SAAS,EACT,sBAAsB,EACtB,6BAA6B,CAC9B,CAAC;AACJ,CAAC;AAND,sBAMC"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/load-balancer.d.ts b/node_modules/@grpc/grpc-js/build/src/load-balancer.d.ts new file mode 100644 index 0000000..adafb35 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/load-balancer.d.ts @@ -0,0 +1,99 @@ +import { ChannelOptions } from './channel-options'; +import { Endpoint, SubchannelAddress } from './subchannel-address'; +import { ConnectivityState } from './connectivity-state'; +import { Picker } from './picker'; +import type { ChannelRef, SubchannelRef } from './channelz'; +import { SubchannelInterface } from './subchannel-interface'; +import { LoadBalancingConfig } from './service-config'; +/** + * A collection of functions associated with a channel that a load balancer + * can call as necessary. + */ +export interface ChannelControlHelper { + /** + * Returns a subchannel connected to the specified address. + * @param subchannelAddress The address to connect to + * @param subchannelArgs Extra channel arguments specified by the load balancer + */ + createSubchannel(subchannelAddress: SubchannelAddress, subchannelArgs: ChannelOptions): SubchannelInterface; + /** + * Passes a new subchannel picker up to the channel. This is called if either + * the connectivity state changes or if a different picker is needed for any + * other reason. + * @param connectivityState New connectivity state + * @param picker New picker + */ + updateState(connectivityState: ConnectivityState, picker: Picker): void; + /** + * Request new data from the resolver. + */ + requestReresolution(): void; + addChannelzChild(child: ChannelRef | SubchannelRef): void; + removeChannelzChild(child: ChannelRef | SubchannelRef): void; +} +/** + * Create a child ChannelControlHelper that overrides some methods of the + * parent while letting others pass through to the parent unmodified. This + * allows other code to create these children without needing to know about + * all of the methods to be passed through. + * @param parent + * @param overrides + */ +export declare function createChildChannelControlHelper(parent: ChannelControlHelper, overrides: Partial): ChannelControlHelper; +/** + * Tracks one or more connected subchannels and determines which subchannel + * each request should use. + */ +export interface LoadBalancer { + /** + * Gives the load balancer a new list of addresses to start connecting to. + * The load balancer will start establishing connections with the new list, + * but will continue using any existing connections until the new connections + * are established + * @param endpointList The new list of addresses to connect to + * @param lbConfig The load balancing config object from the service config, + * if one was provided + */ + updateAddressList(endpointList: Endpoint[], lbConfig: TypedLoadBalancingConfig, attributes: { + [key: string]: unknown; + }): void; + /** + * If the load balancer is currently in the IDLE state, start connecting. + */ + exitIdle(): void; + /** + * If the load balancer is currently in the CONNECTING or TRANSIENT_FAILURE + * state, reset the current connection backoff timeout to its base value and + * transition to CONNECTING if in TRANSIENT_FAILURE. + */ + resetBackoff(): void; + /** + * The load balancer unrefs all of its subchannels and stops calling methods + * of its channel control helper. + */ + destroy(): void; + /** + * Get the type name for this load balancer type. Must be constant across an + * entire load balancer implementation class and must match the name that the + * balancer implementation class was registered with. + */ + getTypeName(): string; +} +export interface LoadBalancerConstructor { + new (channelControlHelper: ChannelControlHelper, options: ChannelOptions): LoadBalancer; +} +export interface TypedLoadBalancingConfig { + getLoadBalancerName(): string; + toJsonObject(): object; +} +export interface TypedLoadBalancingConfigConstructor { + new (...args: any): TypedLoadBalancingConfig; + createFromJson(obj: any): TypedLoadBalancingConfig; +} +export declare function registerLoadBalancerType(typeName: string, loadBalancerType: LoadBalancerConstructor, loadBalancingConfigType: TypedLoadBalancingConfigConstructor): void; +export declare function registerDefaultLoadBalancerType(typeName: string): void; +export declare function createLoadBalancer(config: TypedLoadBalancingConfig, channelControlHelper: ChannelControlHelper, options: ChannelOptions): LoadBalancer | null; +export declare function isLoadBalancerNameRegistered(typeName: string): boolean; +export declare function parseLoadBalancingConfig(rawConfig: LoadBalancingConfig): TypedLoadBalancingConfig; +export declare function getDefaultConfig(): TypedLoadBalancingConfig; +export declare function selectLbConfigFromList(configs: LoadBalancingConfig[], fallbackTodefault?: boolean): TypedLoadBalancingConfig | null; diff --git a/node_modules/@grpc/grpc-js/build/src/load-balancer.js b/node_modules/@grpc/grpc-js/build/src/load-balancer.js new file mode 100644 index 0000000..41ab6fa --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/load-balancer.js @@ -0,0 +1,117 @@ +"use strict"; +/* + * Copyright 2019 gRPC authors. + * + * 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. + * + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.selectLbConfigFromList = exports.getDefaultConfig = exports.parseLoadBalancingConfig = exports.isLoadBalancerNameRegistered = exports.createLoadBalancer = exports.registerDefaultLoadBalancerType = exports.registerLoadBalancerType = exports.createChildChannelControlHelper = void 0; +const logging_1 = require("./logging"); +const constants_1 = require("./constants"); +/** + * Create a child ChannelControlHelper that overrides some methods of the + * parent while letting others pass through to the parent unmodified. This + * allows other code to create these children without needing to know about + * all of the methods to be passed through. + * @param parent + * @param overrides + */ +function createChildChannelControlHelper(parent, overrides) { + var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k; + return { + createSubchannel: (_b = (_a = overrides.createSubchannel) === null || _a === void 0 ? void 0 : _a.bind(overrides)) !== null && _b !== void 0 ? _b : parent.createSubchannel.bind(parent), + updateState: (_d = (_c = overrides.updateState) === null || _c === void 0 ? void 0 : _c.bind(overrides)) !== null && _d !== void 0 ? _d : parent.updateState.bind(parent), + requestReresolution: (_f = (_e = overrides.requestReresolution) === null || _e === void 0 ? void 0 : _e.bind(overrides)) !== null && _f !== void 0 ? _f : parent.requestReresolution.bind(parent), + addChannelzChild: (_h = (_g = overrides.addChannelzChild) === null || _g === void 0 ? void 0 : _g.bind(overrides)) !== null && _h !== void 0 ? _h : parent.addChannelzChild.bind(parent), + removeChannelzChild: (_k = (_j = overrides.removeChannelzChild) === null || _j === void 0 ? void 0 : _j.bind(overrides)) !== null && _k !== void 0 ? _k : parent.removeChannelzChild.bind(parent), + }; +} +exports.createChildChannelControlHelper = createChildChannelControlHelper; +const registeredLoadBalancerTypes = {}; +let defaultLoadBalancerType = null; +function registerLoadBalancerType(typeName, loadBalancerType, loadBalancingConfigType) { + registeredLoadBalancerTypes[typeName] = { + LoadBalancer: loadBalancerType, + LoadBalancingConfig: loadBalancingConfigType, + }; +} +exports.registerLoadBalancerType = registerLoadBalancerType; +function registerDefaultLoadBalancerType(typeName) { + defaultLoadBalancerType = typeName; +} +exports.registerDefaultLoadBalancerType = registerDefaultLoadBalancerType; +function createLoadBalancer(config, channelControlHelper, options) { + const typeName = config.getLoadBalancerName(); + if (typeName in registeredLoadBalancerTypes) { + return new registeredLoadBalancerTypes[typeName].LoadBalancer(channelControlHelper, options); + } + else { + return null; + } +} +exports.createLoadBalancer = createLoadBalancer; +function isLoadBalancerNameRegistered(typeName) { + return typeName in registeredLoadBalancerTypes; +} +exports.isLoadBalancerNameRegistered = isLoadBalancerNameRegistered; +function parseLoadBalancingConfig(rawConfig) { + const keys = Object.keys(rawConfig); + if (keys.length !== 1) { + throw new Error('Provided load balancing config has multiple conflicting entries'); + } + const typeName = keys[0]; + if (typeName in registeredLoadBalancerTypes) { + try { + return registeredLoadBalancerTypes[typeName].LoadBalancingConfig.createFromJson(rawConfig[typeName]); + } + catch (e) { + throw new Error(`${typeName}: ${e.message}`); + } + } + else { + throw new Error(`Unrecognized load balancing config name ${typeName}`); + } +} +exports.parseLoadBalancingConfig = parseLoadBalancingConfig; +function getDefaultConfig() { + if (!defaultLoadBalancerType) { + throw new Error('No default load balancer type registered'); + } + return new registeredLoadBalancerTypes[defaultLoadBalancerType].LoadBalancingConfig(); +} +exports.getDefaultConfig = getDefaultConfig; +function selectLbConfigFromList(configs, fallbackTodefault = false) { + for (const config of configs) { + try { + return parseLoadBalancingConfig(config); + } + catch (e) { + (0, logging_1.log)(constants_1.LogVerbosity.DEBUG, 'Config parsing failed with error', e.message); + continue; + } + } + if (fallbackTodefault) { + if (defaultLoadBalancerType) { + return new registeredLoadBalancerTypes[defaultLoadBalancerType].LoadBalancingConfig(); + } + else { + return null; + } + } + else { + return null; + } +} +exports.selectLbConfigFromList = selectLbConfigFromList; +//# sourceMappingURL=load-balancer.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/load-balancer.js.map b/node_modules/@grpc/grpc-js/build/src/load-balancer.js.map new file mode 100644 index 0000000..25e37c7 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/load-balancer.js.map @@ -0,0 +1 @@ +{"version":3,"file":"load-balancer.js","sourceRoot":"","sources":["../../src/load-balancer.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;GAeG;;;AASH,uCAAgC;AAChC,2CAA2C;AAgC3C;;;;;;;GAOG;AACH,SAAgB,+BAA+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CACpC,uBAAuB,CACvB,CAAC,mBAAmB,EAAE,CAAC;AAC3B,CAAC;AAPD,4CAOC;AAED,SAAgB,sBAAsB,CACpC,OAA8B,EAC9B,iBAAiB,GAAG,KAAK;IAEzB,KAAK,MAAM,MAAM,IAAI,OAAO,EAAE,CAAC;QAC7B,IAAI,CAAC;YACH,OAAO,wBAAwB,CAAC,MAAM,CAAC,CAAC;QAC1C,CAAC;QAAC,OAAO,CAAC,EAAE,CAAC;YACX,IAAA,aAAG,EACD,wBAAY,CAAC,KAAK,EAClB,kCAAkC,EACjC,CAAW,CAAC,OAAO,CACrB,CAAC;YACF,SAAS;QACX,CAAC;IACH,CAAC;IACD,IAAI,iBAAiB,EAAE,CAAC;QACtB,IAAI,uBAAuB,EAAE,CAAC;YAC5B,OAAO,IAAI,2BAA2B,CACpC,uBAAuB,CACvB,CAAC,mBAAmB,EAAE,CAAC;QAC3B,CAAC;aAAM,CAAC;YACN,OAAO,IAAI,CAAC;QACd,CAAC;IACH,CAAC;SAAM,CAAC;QACN,OAAO,IAAI,CAAC;IACd,CAAC;AACH,CAAC;AA3BD,wDA2BC"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/load-balancing-call.d.ts b/node_modules/@grpc/grpc-js/build/src/load-balancing-call.d.ts new file mode 100644 index 0000000..b5cfbe4 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/load-balancing-call.d.ts @@ -0,0 +1,48 @@ +/// +import { CallCredentials } from './call-credentials'; +import { Call, DeadlineInfoProvider, InterceptingListener, MessageContext, StatusObject } from './call-interface'; +import { Status } from './constants'; +import { Deadline } from './deadline'; +import { InternalChannel } from './internal-channel'; +import { Metadata } from './metadata'; +import { CallConfig } from './resolver'; +export type RpcProgress = 'NOT_STARTED' | 'DROP' | 'REFUSED' | 'PROCESSED'; +export interface StatusObjectWithProgress extends StatusObject { + progress: RpcProgress; +} +export interface LoadBalancingCallInterceptingListener extends InterceptingListener { + onReceiveStatus(status: StatusObjectWithProgress): void; +} +export declare class LoadBalancingCall implements Call, DeadlineInfoProvider { + private readonly channel; + private readonly callConfig; + private readonly methodName; + private readonly host; + private readonly credentials; + private readonly deadline; + private readonly callNumber; + private child; + private readPending; + private pendingMessage; + private pendingHalfClose; + private ended; + private serviceUrl; + private metadata; + private listener; + private onCallEnded; + private startTime; + private childStartTime; + constructor(channel: InternalChannel, callConfig: CallConfig, methodName: string, host: string, credentials: CallCredentials, deadline: Deadline, callNumber: number); + getDeadlineInfo(): string[]; + private trace; + private outputStatus; + doPick(): void; + cancelWithStatus(status: Status, details: string): void; + getPeer(): string; + start(metadata: Metadata, listener: LoadBalancingCallInterceptingListener): void; + sendMessageWithContext(context: MessageContext, message: Buffer): void; + startRead(): void; + halfClose(): void; + setCredentials(credentials: CallCredentials): void; + getCallNumber(): number; +} diff --git a/node_modules/@grpc/grpc-js/build/src/load-balancing-call.js b/node_modules/@grpc/grpc-js/build/src/load-balancing-call.js new file mode 100644 index 0000000..bf5f71c --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/load-balancing-call.js @@ -0,0 +1,294 @@ +"use strict"; +/* + * Copyright 2022 gRPC authors. + * + * 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. + * + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.LoadBalancingCall = void 0; +const connectivity_state_1 = require("./connectivity-state"); +const constants_1 = require("./constants"); +const deadline_1 = require("./deadline"); +const metadata_1 = require("./metadata"); +const picker_1 = require("./picker"); +const uri_parser_1 = require("./uri-parser"); +const logging = require("./logging"); +const control_plane_status_1 = require("./control-plane-status"); +const http2 = require("http2"); +const TRACER_NAME = 'load_balancing_call'; +class LoadBalancingCall { + constructor(channel, callConfig, methodName, host, credentials, deadline, callNumber) { + var _a, _b; + this.channel = channel; + this.callConfig = callConfig; + this.methodName = methodName; + this.host = host; + this.credentials = credentials; + this.deadline = deadline; + this.callNumber = callNumber; + this.child = null; + this.readPending = false; + this.pendingMessage = null; + this.pendingHalfClose = false; + this.ended = false; + this.metadata = null; + this.listener = null; + this.onCallEnded = null; + this.childStartTime = null; + const splitPath = this.methodName.split('/'); + let serviceName = ''; + /* The standard path format is "/{serviceName}/{methodName}", so if we split + * by '/', the first item should be empty and the second should be the + * service name */ + if (splitPath.length >= 2) { + serviceName = splitPath[1]; + } + const hostname = (_b = (_a = (0, uri_parser_1.splitHostPort)(this.host)) === null || _a === void 0 ? void 0 : _a.host) !== null && _b !== void 0 ? _b : 'localhost'; + /* Currently, call credentials are only allowed on HTTPS connections, so we + * can assume that the scheme is "https" */ + this.serviceUrl = `https://${hostname}/${serviceName}`; + this.startTime = new Date(); + } + getDeadlineInfo() { + var _a, _b; + const deadlineInfo = []; + if (this.childStartTime) { + if (this.childStartTime > this.startTime) { + if ((_a = this.metadata) === null || _a === void 0 ? void 0 : _a.getOptions().waitForReady) { + deadlineInfo.push('wait_for_ready'); + } + deadlineInfo.push(`LB pick: ${(0, deadline_1.formatDateDifference)(this.startTime, this.childStartTime)}`); + } + deadlineInfo.push(...this.child.getDeadlineInfo()); + return deadlineInfo; + } + else { + if ((_b = this.metadata) === null || _b === void 0 ? void 0 : _b.getOptions().waitForReady) { + deadlineInfo.push('wait_for_ready'); + } + deadlineInfo.push('Waiting for LB pick'); + } + return deadlineInfo; + } + trace(text) { + logging.trace(constants_1.LogVerbosity.DEBUG, TRACER_NAME, '[' + this.callNumber + '] ' + text); + } + outputStatus(status, progress) { + var _a, _b; + if (!this.ended) { + this.ended = true; + this.trace('ended with status: code=' + + status.code + + ' details="' + + status.details + + '" start time=' + + this.startTime.toISOString()); + const finalStatus = Object.assign(Object.assign({}, status), { progress }); + (_a = this.listener) === null || _a === void 0 ? void 0 : _a.onReceiveStatus(finalStatus); + (_b = this.onCallEnded) === null || _b === void 0 ? void 0 : _b.call(this, finalStatus.code); + } + } + doPick() { + var _a, _b; + if (this.ended) { + return; + } + if (!this.metadata) { + throw new Error('doPick called before start'); + } + this.trace('Pick called'); + const finalMetadata = this.metadata.clone(); + const pickResult = this.channel.doPick(finalMetadata, this.callConfig.pickInformation); + const subchannelString = pickResult.subchannel + ? '(' + + pickResult.subchannel.getChannelzRef().id + + ') ' + + pickResult.subchannel.getAddress() + : '' + pickResult.subchannel; + this.trace('Pick result: ' + + picker_1.PickResultType[pickResult.pickResultType] + + ' subchannel: ' + + subchannelString + + ' status: ' + + ((_a = pickResult.status) === null || _a === void 0 ? void 0 : _a.code) + + ' ' + + ((_b = pickResult.status) === null || _b === void 0 ? void 0 : _b.details)); + switch (pickResult.pickResultType) { + case picker_1.PickResultType.COMPLETE: + this.credentials + .generateMetadata({ service_url: this.serviceUrl }) + .then(credsMetadata => { + var _a, _b, _c; + /* If this call was cancelled (e.g. by the deadline) before + * metadata generation finished, we shouldn't do anything with + * it. */ + if (this.ended) { + this.trace('Credentials metadata generation finished after call ended'); + return; + } + finalMetadata.merge(credsMetadata); + if (finalMetadata.get('authorization').length > 1) { + this.outputStatus({ + code: constants_1.Status.INTERNAL, + details: '"authorization" metadata cannot have multiple values', + metadata: new metadata_1.Metadata(), + }, 'PROCESSED'); + } + if (pickResult.subchannel.getConnectivityState() !== + connectivity_state_1.ConnectivityState.READY) { + this.trace('Picked subchannel ' + + subchannelString + + ' has state ' + + connectivity_state_1.ConnectivityState[pickResult.subchannel.getConnectivityState()] + + ' after getting credentials metadata. Retrying pick'); + this.doPick(); + return; + } + if (this.deadline !== Infinity) { + finalMetadata.set('grpc-timeout', (0, deadline_1.getDeadlineTimeoutString)(this.deadline)); + } + try { + this.child = pickResult + .subchannel.getRealSubchannel() + .createCall(finalMetadata, this.host, this.methodName, { + onReceiveMetadata: metadata => { + this.trace('Received metadata'); + this.listener.onReceiveMetadata(metadata); + }, + onReceiveMessage: message => { + this.trace('Received message'); + this.listener.onReceiveMessage(message); + }, + onReceiveStatus: status => { + this.trace('Received status'); + if (status.rstCode === + http2.constants.NGHTTP2_REFUSED_STREAM) { + this.outputStatus(status, 'REFUSED'); + } + else { + this.outputStatus(status, 'PROCESSED'); + } + }, + }); + this.childStartTime = new Date(); + } + catch (error) { + this.trace('Failed to start call on picked subchannel ' + + subchannelString + + ' with error ' + + error.message); + this.outputStatus({ + code: constants_1.Status.INTERNAL, + details: 'Failed to start HTTP/2 stream with error ' + + error.message, + metadata: new metadata_1.Metadata(), + }, 'NOT_STARTED'); + return; + } + (_b = (_a = this.callConfig).onCommitted) === null || _b === void 0 ? void 0 : _b.call(_a); + (_c = pickResult.onCallStarted) === null || _c === void 0 ? void 0 : _c.call(pickResult); + this.onCallEnded = pickResult.onCallEnded; + this.trace('Created child call [' + this.child.getCallNumber() + ']'); + if (this.readPending) { + this.child.startRead(); + } + if (this.pendingMessage) { + this.child.sendMessageWithContext(this.pendingMessage.context, this.pendingMessage.message); + } + if (this.pendingHalfClose) { + this.child.halfClose(); + } + }, (error) => { + // We assume the error code isn't 0 (Status.OK) + const { code, details } = (0, control_plane_status_1.restrictControlPlaneStatusCode)(typeof error.code === 'number' ? error.code : constants_1.Status.UNKNOWN, `Getting metadata from plugin failed with error: ${error.message}`); + this.outputStatus({ + code: code, + details: details, + metadata: new metadata_1.Metadata(), + }, 'PROCESSED'); + }); + break; + case picker_1.PickResultType.DROP: + const { code, details } = (0, control_plane_status_1.restrictControlPlaneStatusCode)(pickResult.status.code, pickResult.status.details); + setImmediate(() => { + this.outputStatus({ code, details, metadata: pickResult.status.metadata }, 'DROP'); + }); + break; + case picker_1.PickResultType.TRANSIENT_FAILURE: + if (this.metadata.getOptions().waitForReady) { + this.channel.queueCallForPick(this); + } + else { + const { code, details } = (0, control_plane_status_1.restrictControlPlaneStatusCode)(pickResult.status.code, pickResult.status.details); + setImmediate(() => { + this.outputStatus({ code, details, metadata: pickResult.status.metadata }, 'PROCESSED'); + }); + } + break; + case picker_1.PickResultType.QUEUE: + this.channel.queueCallForPick(this); + } + } + cancelWithStatus(status, details) { + var _a; + this.trace('cancelWithStatus code: ' + status + ' details: "' + details + '"'); + (_a = this.child) === null || _a === void 0 ? void 0 : _a.cancelWithStatus(status, details); + this.outputStatus({ code: status, details: details, metadata: new metadata_1.Metadata() }, 'PROCESSED'); + } + getPeer() { + var _a, _b; + return (_b = (_a = this.child) === null || _a === void 0 ? void 0 : _a.getPeer()) !== null && _b !== void 0 ? _b : this.channel.getTarget(); + } + start(metadata, listener) { + this.trace('start called'); + this.listener = listener; + this.metadata = metadata; + this.doPick(); + } + sendMessageWithContext(context, message) { + this.trace('write() called with message of length ' + message.length); + if (this.child) { + this.child.sendMessageWithContext(context, message); + } + else { + this.pendingMessage = { context, message }; + } + } + startRead() { + this.trace('startRead called'); + if (this.child) { + this.child.startRead(); + } + else { + this.readPending = true; + } + } + halfClose() { + this.trace('halfClose called'); + if (this.child) { + this.child.halfClose(); + } + else { + this.pendingHalfClose = true; + } + } + setCredentials(credentials) { + throw new Error('Method not implemented.'); + } + getCallNumber() { + return this.callNumber; + } +} +exports.LoadBalancingCall = LoadBalancingCall; +//# sourceMappingURL=load-balancing-call.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/load-balancing-call.js.map b/node_modules/@grpc/grpc-js/build/src/load-balancing-call.js.map new file mode 100644 index 0000000..865951d --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/load-balancing-call.js.map @@ -0,0 +1 @@ +{"version":3,"file":"load-balancing-call.js","sourceRoot":"","sources":["../../src/load-balancing-call.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;GAeG;;;AAWH,6DAAyD;AACzD,2CAAmD;AACnD,yCAAsF;AAEtF,yCAAsC;AACtC,qCAA0C;AAE1C,6CAA6C;AAC7C,qCAAqC;AACrC,iEAAwE;AACxE,+BAA+B;AAE/B,MAAM,WAAW,GAAG,q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ACF;AAtUD,8CAsUC"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/logging.d.ts b/node_modules/@grpc/grpc-js/build/src/logging.d.ts new file mode 100644 index 0000000..7ac65fa --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/logging.d.ts @@ -0,0 +1,8 @@ +/// +import { LogVerbosity } from './constants'; +export declare const getLogger: () => Partial; +export declare const setLogger: (logger: Partial) => void; +export declare const setLoggerVerbosity: (verbosity: LogVerbosity) => void; +export declare const log: (severity: LogVerbosity, ...args: any[]) => void; +export declare function trace(severity: LogVerbosity, tracer: string, text: string): void; +export declare function isTracerEnabled(tracer: string): boolean; diff --git a/node_modules/@grpc/grpc-js/build/src/logging.js b/node_modules/@grpc/grpc-js/build/src/logging.js new file mode 100644 index 0000000..89bd096 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/logging.js @@ -0,0 +1,122 @@ +"use strict"; +/* + * Copyright 2019 gRPC authors. + * + * 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 _a, _b, _c, _d; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.isTracerEnabled = exports.trace = exports.log = exports.setLoggerVerbosity = exports.setLogger = exports.getLogger = void 0; +const constants_1 = require("./constants"); +const process_1 = require("process"); +const clientVersion = require('../../package.json').version; +const DEFAULT_LOGGER = { + error: (message, ...optionalParams) => { + console.error('E ' + message, ...optionalParams); + }, + info: (message, ...optionalParams) => { + console.error('I ' + message, ...optionalParams); + }, + debug: (message, ...optionalParams) => { + console.error('D ' + message, ...optionalParams); + }, +}; +let _logger = DEFAULT_LOGGER; +let _logVerbosity = constants_1.LogVerbosity.ERROR; +const verbosityString = (_b = (_a = process.env.GRPC_NODE_VERBOSITY) !== null && _a !== void 0 ? _a : process.env.GRPC_VERBOSITY) !== null && _b !== void 0 ? _b : ''; +switch (verbosityString.toUpperCase()) { + case 'DEBUG': + _logVerbosity = constants_1.LogVerbosity.DEBUG; + break; + case 'INFO': + _logVerbosity = constants_1.LogVerbosity.INFO; + break; + case 'ERROR': + _logVerbosity = constants_1.LogVerbosity.ERROR; + break; + case 'NONE': + _logVerbosity = constants_1.LogVerbosity.NONE; + break; + default: + // Ignore any other values +} +const getLogger = () => { + return _logger; +}; +exports.getLogger = getLogger; +const setLogger = (logger) => { + _logger = logger; +}; +exports.setLogger = setLogger; +const setLoggerVerbosity = (verbosity) => { + _logVerbosity = verbosity; +}; +exports.setLoggerVerbosity = setLoggerVerbosity; +// eslint-disable-next-line @typescript-eslint/no-explicit-any +const log = (severity, ...args) => { + let logFunction; + if (severity >= _logVerbosity) { + switch (severity) { + case constants_1.LogVerbosity.DEBUG: + logFunction = _logger.debug; + break; + case constants_1.LogVerbosity.INFO: + logFunction = _logger.info; + break; + case constants_1.LogVerbosity.ERROR: + logFunction = _logger.error; + break; + } + /* Fall back to _logger.error when other methods are not available for + * compatiblity with older behavior that always logged to _logger.error */ + if (!logFunction) { + logFunction = _logger.error; + } + if (logFunction) { + logFunction.bind(_logger)(...args); + } + } +}; +exports.log = log; +const tracersString = (_d = (_c = process.env.GRPC_NODE_TRACE) !== null && _c !== void 0 ? _c : process.env.GRPC_TRACE) !== null && _d !== void 0 ? _d : ''; +const enabledTracers = new Set(); +const disabledTracers = new Set(); +for (const tracerName of tracersString.split(',')) { + if (tracerName.startsWith('-')) { + disabledTracers.add(tracerName.substring(1)); + } + else { + enabledTracers.add(tracerName); + } +} +const allEnabled = enabledTracers.has('all'); +function trace(severity, tracer, text) { + if (isTracerEnabled(tracer)) { + (0, exports.log)(severity, new Date().toISOString() + + ' | v' + + clientVersion + + ' ' + + process_1.pid + + ' | ' + + tracer + + ' | ' + + text); + } +} +exports.trace = trace; +function isTracerEnabled(tracer) { + return (!disabledTracers.has(tracer) && (allEnabled || enabledTracers.has(tracer))); +} +exports.isTracerEnabled = isTracerEnabled; +//# sourceMappingURL=logging.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/logging.js.map b/node_modules/@grpc/grpc-js/build/src/logging.js.map new file mode 100644 index 0000000..ca031f5 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/logging.js.map @@ -0,0 +1 @@ +{"version":3,"file":"logging.js","sourceRoot":"","sources":["../../src/logging.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;GAeG;;;;AAEH,2CAA2C;AAC3C,qCAA8B;AAE9B,MAAM,aAAa,GAAG,OAAO,CAAC,oBAAoB,CAAC,CAAC,OAAO,CAAC;AAE5D,MAAM,cAAc,GAAqB;IACvC,KAAK,EAAE,CAAC,OAAa,EAAE,GAAG,cAAqB,EAAE,EAAE;QACjD,OAAO,CAAC,KAAK,CAAC,IAAI,GAAG,OAAO,EAAE,GAAG,cAAc,CAAC,CAAC;IACnD,CAAC;IACD,IAAI,EAAE,CAAC,OAAa,EAAE,GAAG,cAAqB,EAAE,EAAE;QAChD,OAAO,CAAC,KAAK,CAAC,IAAI,GAAG,OAAO,EAAE,GAAG,cAAc,CAAC,CAAC;IACnD,CAAC;IACD,KAAK,EAAE,CAAC,OAAa,EAAE,GAAG,cAAqB,EAAE,EAAE;QACjD,OAAO,CAAC,KAAK,CAAC,IAAI,GAAG,OAAO,EAAE,GAAG,cAAc,CAAC,CAAC;IACnD,CAAC;CACF,CAAC;AAEF,IAAI,OAAO,GAAqB,cAAc,CAAC;AAC/C,IAAI,aAAa,GAAiB,wBAAY,CAAC,KAAK,CAAC;AAErD,MAAM,eAAe,GACnB,MAAA,MAAA,OAAO,CAAC,GAAG,CAAC,mBAAmB,mCAAI,OAAO,CAAC,GAAG,CAAC,cAAc,mCAAI,EAAE,CAAC;AAEtE,QAAQ,eAAe,CAAC,WAAW,EAAE,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Ac,CAAC,GAAG,CAAC,MAAM,CAAC,CAAC,CAC3E,CAAC;AACJ,CAAC;AAJD,0CAIC"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/make-client.d.ts b/node_modules/@grpc/grpc-js/build/src/make-client.d.ts new file mode 100644 index 0000000..39b59c1 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/make-client.d.ts @@ -0,0 +1,72 @@ +/// +import { ChannelCredentials } from './channel-credentials'; +import { ChannelOptions } from './channel-options'; +import { Client } from './client'; +import { UntypedServiceImplementation } from './server'; +export interface Serialize { + (value: T): Buffer; +} +export interface Deserialize { + (bytes: Buffer): T; +} +export interface ClientMethodDefinition { + path: string; + requestStream: boolean; + responseStream: boolean; + requestSerialize: Serialize; + responseDeserialize: Deserialize; + originalName?: string; +} +export interface ServerMethodDefinition { + path: string; + requestStream: boolean; + responseStream: boolean; + responseSerialize: Serialize; + requestDeserialize: Deserialize; + originalName?: string; +} +export interface MethodDefinition extends ClientMethodDefinition, ServerMethodDefinition { +} +export type ServiceDefinition = { + readonly [index in keyof ImplementationType]: MethodDefinition; +}; +export interface ProtobufTypeDefinition { + format: string; + type: object; + fileDescriptorProtos: Buffer[]; +} +export interface PackageDefinition { + [index: string]: ServiceDefinition | ProtobufTypeDefinition; +} +export interface ServiceClient extends Client { + [methodName: string]: Function; +} +export interface ServiceClientConstructor { + new (address: string, credentials: ChannelCredentials, options?: Partial): ServiceClient; + service: ServiceDefinition; + serviceName: string; +} +/** + * Creates a constructor for a client with the given methods, as specified in + * the methods argument. The resulting class will have an instance method for + * each method in the service, which is a partial application of one of the + * [Client]{@link grpc.Client} request methods, depending on `requestSerialize` + * and `responseSerialize`, with the `method`, `serialize`, and `deserialize` + * arguments predefined. + * @param methods An object mapping method names to + * method attributes + * @param serviceName The fully qualified name of the service + * @param classOptions An options object. + * @return New client constructor, which is a subclass of + * {@link grpc.Client}, and has the same arguments as that constructor. + */ +export declare function makeClientConstructor(methods: ServiceDefinition, serviceName: string, classOptions?: {}): ServiceClientConstructor; +export interface GrpcObject { + [index: string]: GrpcObject | ServiceClientConstructor | ProtobufTypeDefinition; +} +/** + * Load a gRPC package definition as a gRPC object hierarchy. + * @param packageDef The package definition object. + * @return The resulting gRPC object. + */ +export declare function loadPackageDefinition(packageDef: PackageDefinition): GrpcObject; diff --git a/node_modules/@grpc/grpc-js/build/src/make-client.js b/node_modules/@grpc/grpc-js/build/src/make-client.js new file mode 100644 index 0000000..6f90569 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/make-client.js @@ -0,0 +1,144 @@ +"use strict"; +/* + * Copyright 2019 gRPC authors. + * + * 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. + * + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.loadPackageDefinition = exports.makeClientConstructor = void 0; +const client_1 = require("./client"); +/** + * Map with short names for each of the requester maker functions. Used in + * makeClientConstructor + * @private + */ +const requesterFuncs = { + unary: client_1.Client.prototype.makeUnaryRequest, + server_stream: client_1.Client.prototype.makeServerStreamRequest, + client_stream: client_1.Client.prototype.makeClientStreamRequest, + bidi: client_1.Client.prototype.makeBidiStreamRequest, +}; +/** + * Returns true, if given key is included in the blacklisted + * keys. + * @param key key for check, string. + */ +function isPrototypePolluted(key) { + return ['__proto__', 'prototype', 'constructor'].includes(key); +} +/** + * Creates a constructor for a client with the given methods, as specified in + * the methods argument. The resulting class will have an instance method for + * each method in the service, which is a partial application of one of the + * [Client]{@link grpc.Client} request methods, depending on `requestSerialize` + * and `responseSerialize`, with the `method`, `serialize`, and `deserialize` + * arguments predefined. + * @param methods An object mapping method names to + * method attributes + * @param serviceName The fully qualified name of the service + * @param classOptions An options object. + * @return New client constructor, which is a subclass of + * {@link grpc.Client}, and has the same arguments as that constructor. + */ +function makeClientConstructor(methods, serviceName, classOptions) { + if (!classOptions) { + classOptions = {}; + } + class ServiceClientImpl extends client_1.Client { + } + Object.keys(methods).forEach(name => { + if (isPrototypePolluted(name)) { + return; + } + const attrs = methods[name]; + let methodType; + // TODO(murgatroid99): Verify that we don't need this anymore + if (typeof name === 'string' && name.charAt(0) === '$') { + throw new Error('Method names cannot start with $'); + } + if (attrs.requestStream) { + if (attrs.responseStream) { + methodType = 'bidi'; + } + else { + methodType = 'client_stream'; + } + } + else { + if (attrs.responseStream) { + methodType = 'server_stream'; + } + else { + methodType = 'unary'; + } + } + const serialize = attrs.requestSerialize; + const deserialize = attrs.responseDeserialize; + const methodFunc = partial(requesterFuncs[methodType], attrs.path, serialize, deserialize); + ServiceClientImpl.prototype[name] = methodFunc; + // Associate all provided attributes with the method + Object.assign(ServiceClientImpl.prototype[name], attrs); + if (attrs.originalName && !isPrototypePolluted(attrs.originalName)) { + ServiceClientImpl.prototype[attrs.originalName] = + ServiceClientImpl.prototype[name]; + } + }); + ServiceClientImpl.service = methods; + ServiceClientImpl.serviceName = serviceName; + return ServiceClientImpl; +} +exports.makeClientConstructor = makeClientConstructor; +function partial(fn, path, serialize, deserialize) { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + return function (...args) { + return fn.call(this, path, serialize, deserialize, ...args); + }; +} +function isProtobufTypeDefinition(obj) { + return 'format' in obj; +} +/** + * Load a gRPC package definition as a gRPC object hierarchy. + * @param packageDef The package definition object. + * @return The resulting gRPC object. + */ +function loadPackageDefinition(packageDef) { + const result = {}; + for (const serviceFqn in packageDef) { + if (Object.prototype.hasOwnProperty.call(packageDef, serviceFqn)) { + const service = packageDef[serviceFqn]; + const nameComponents = serviceFqn.split('.'); + if (nameComponents.some((comp) => isPrototypePolluted(comp))) { + continue; + } + const serviceName = nameComponents[nameComponents.length - 1]; + let current = result; + for (const packageName of nameComponents.slice(0, -1)) { + if (!current[packageName]) { + current[packageName] = {}; + } + current = current[packageName]; + } + if (isProtobufTypeDefinition(service)) { + current[serviceName] = service; + } + else { + current[serviceName] = makeClientConstructor(service, serviceName, {}); + } + } + } + return result; +} +exports.loadPackageDefinition = loadPackageDefinition; +//# sourceMappingURL=make-client.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/make-client.js.map b/node_modules/@grpc/grpc-js/build/src/make-client.js.map new file mode 100644 index 0000000..adfab3e --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/make-client.js.map @@ -0,0 +1 @@ +{"version":3,"file":"make-client.js","sourceRoot":"","sources":["../../src/make-client.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;GAeG;;;AAIH,qCAAkC;AAmDlC;;;;GAIG;AACH,MAAM,cAAc,GAAG;IACrB,KAAK,EAAE,eAAM,CAAC,SAAS,CAAC,gBAAgB;IACxC,aAAa,EAAE,eAAM,CAAC,SAAS,CAAC,uBAAuB;IACvD,aAAa,EAAE,eAAM,CAAC,SAAS,CAAC,uBAAuB;IACvD,IAAI,EAAE,eAAM,CAAC,SAAS,CAAC,qBAAqB;CAC7C,CAAC;AAgBF;;;;GAIG;AACH,SAAS,mBAAmB,CAAC,GAAW;IACtC,OAAO,CAAC,WAAW,EAAE,WAAW,EAAE,aAAa,CAAC,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC;AACjE,CAAC;AAED;;;;;;;;;;;;;GAaG;AACH,SAAgB,qBAAqB,CACnC,OAA0B,EAC1B,WAAmB,EACnB,YAAiB;IAEjB,IAAI,CAAC,YAAY,EAAE,CAAC;QAClB,YAAY,GAAG,EAAE,CAAC;IACpB,CAAC;IAED,MAAM,iBAAkB,SAAQ,eAAM;KAIrC;IAED,MAAM,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC,OAAO,CAAC,IAAI,CAAC,EAAE;QAClC,IAAI,mBAAmB,CAAC,IAAI,CAAC,EAAE,CAAC;YAC9B,OAAO;QACT,C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AAW,CAAC,EAAE,CAAC;oBAC1B,OAAO,CAAC,WAAW,CAAC,GAAG,EAAE,CAAC;gBAC5B,CAAC;gBACD,OAAO,GAAG,OAAO,CAAC,WAAW,CAAe,CAAC;YAC/C,CAAC;YACD,IAAI,wBAAwB,CAAC,OAAO,CAAC,EAAE,CAAC;gBACtC,OAAO,CAAC,WAAW,CAAC,GAAG,OAAO,CAAC;YACjC,CAAC;iBAAM,CAAC;gBACN,OAAO,CAAC,WAAW,CAAC,GAAG,qBAAqB,CAAC,OAAO,EAAE,WAAW,EAAE,EAAE,CAAC,CAAC;YACzE,CAAC;QACH,CAAC;IACH,CAAC;IACD,OAAO,MAAM,CAAC;AAChB,CAAC;AA3BD,sDA2BC"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/max-message-size-filter.d.ts b/node_modules/@grpc/grpc-js/build/src/max-message-size-filter.d.ts new file mode 100644 index 0000000..a497f2c --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/max-message-size-filter.d.ts @@ -0,0 +1,16 @@ +/// +import { BaseFilter, Filter, FilterFactory } from './filter'; +import { WriteObject } from './call-interface'; +import { ChannelOptions } from './channel-options'; +export declare class MaxMessageSizeFilter extends BaseFilter implements Filter { + private maxSendMessageSize; + private maxReceiveMessageSize; + constructor(options: ChannelOptions); + sendMessage(message: Promise): Promise; + receiveMessage(message: Promise): Promise; +} +export declare class MaxMessageSizeFilterFactory implements FilterFactory { + private readonly options; + constructor(options: ChannelOptions); + createFilter(): MaxMessageSizeFilter; +} diff --git a/node_modules/@grpc/grpc-js/build/src/max-message-size-filter.js b/node_modules/@grpc/grpc-js/build/src/max-message-size-filter.js new file mode 100644 index 0000000..f1cdcd9 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/max-message-size-filter.js @@ -0,0 +1,86 @@ +"use strict"; +/* + * Copyright 2020 gRPC authors. + * + * 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. + * + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.MaxMessageSizeFilterFactory = exports.MaxMessageSizeFilter = void 0; +const filter_1 = require("./filter"); +const constants_1 = require("./constants"); +const metadata_1 = require("./metadata"); +class MaxMessageSizeFilter extends filter_1.BaseFilter { + constructor(options) { + super(); + this.maxSendMessageSize = constants_1.DEFAULT_MAX_SEND_MESSAGE_LENGTH; + this.maxReceiveMessageSize = constants_1.DEFAULT_MAX_RECEIVE_MESSAGE_LENGTH; + if ('grpc.max_send_message_length' in options) { + this.maxSendMessageSize = options['grpc.max_send_message_length']; + } + if ('grpc.max_receive_message_length' in options) { + this.maxReceiveMessageSize = options['grpc.max_receive_message_length']; + } + } + async sendMessage(message) { + /* A configured size of -1 means that there is no limit, so skip the check + * entirely */ + if (this.maxSendMessageSize === -1) { + return message; + } + else { + const concreteMessage = await message; + if (concreteMessage.message.length > this.maxSendMessageSize) { + throw { + code: constants_1.Status.RESOURCE_EXHAUSTED, + details: `Sent message larger than max (${concreteMessage.message.length} vs. ${this.maxSendMessageSize})`, + metadata: new metadata_1.Metadata(), + }; + } + else { + return concreteMessage; + } + } + } + async receiveMessage(message) { + /* A configured size of -1 means that there is no limit, so skip the check + * entirely */ + if (this.maxReceiveMessageSize === -1) { + return message; + } + else { + const concreteMessage = await message; + if (concreteMessage.length > this.maxReceiveMessageSize) { + throw { + code: constants_1.Status.RESOURCE_EXHAUSTED, + details: `Received message larger than max (${concreteMessage.length} vs. ${this.maxReceiveMessageSize})`, + metadata: new metadata_1.Metadata(), + }; + } + else { + return concreteMessage; + } + } + } +} +exports.MaxMessageSizeFilter = MaxMessageSizeFilter; +class MaxMessageSizeFilterFactory { + constructor(options) { + this.options = options; + } + createFilter() { + return new MaxMessageSizeFilter(this.options); + } +} +exports.MaxMessageSizeFilterFactory = MaxMessageSizeFilterFactory; +//# sourceMappingURL=max-message-size-filter.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/max-message-size-filter.js.map b/node_modules/@grpc/grpc-js/build/src/max-message-size-filter.js.map new file mode 100644 index 0000000..9f0464e --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/max-message-size-filter.js.map @@ -0,0 +1 @@ +{"version":3,"file":"max-message-size-filter.js","sourceRoot":"","sources":["../../src/max-message-size-filter.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;GAeG;;;AAEH,qCAA6D;AAE7D,2CAIqB;AAErB,yCAAsC;AAEtC,MAAa,oBAAqB,SAAQ,mBAAU;IAGlD,YAAY,OAAuB;QACjC,KAAK,EAAE,CAAC;QAHF,uBAAkB,GAAW,2CAA+B,CAAC;QAC7D,0BAAqB,GAAW,8CAAkC,CAAC;QAGzE,IAAI,8BAA8B,IAAI,OAAO,EAAE,CAAC;YAC9C,IAAI,CAAC,kBAAkB,GAAG,OAAO,CAAC,8BAA8B,CAAE,CAAC;QACrE,CAAC;QACD,IAAI,iCAAiC,IAAI,OAAO,EAAE,CAAC;YACjD,IAAI,CAAC,qBAAqB,GAAG,OAAO,CAAC,iCAAiC,CAAE,CAAC;QAC3E,CAAC;IACH,CAAC;IAED,KAAK,CAAC,WAAW,CAAC,OAA6B;QAC7C;sBACc;QACd,IAAI,IAAI,CAAC,kBAAkB,KAAK,CAAC,CAAC,EAAE,CAAC;YACnC,OAAO,OAAO,CAAC;QACjB,CAAC;aAAM,CAAC;YACN,MAAM,eAAe,GAAG,MAAM,OAAO,CAAC;YACtC,IAAI,eAAe,CAAC,OAAO,CAAC,MAAM,GAAG,IAAI,CAAC,kBAAkB,EAAE,CAAC;gBAC7D,MAAM;oBACJ,IAAI,EAAE,kBAAM,CAAC,kBAAkB;oBAC/B,OAAO,EAAE,iCAAiC,eAAe,CAAC,OAAO,CAAC,MAAM,QAAQ,IAAI,CAAC,kBAAkB,GAAG;oBAC1G,QAAQ,EAAE,IAAI,mBAAQ,EAAE;iBACzB,CAAC;YACJ,CAAC;iBAAM,CAAC;gBACN,OAAO,eAAe,CAAC;YACzB,CAAC;QACH,CAAC;IACH,CAAC;IAED,KAAK,CAAC,cAAc,CAAC,OAAwB;QAC3C;sBACc;QACd,IAAI,IAAI,CAAC,qBAAqB,KAAK,CAAC,CAAC,EAAE,CAAC;YACtC,OAAO,OAAO,CAAC;QACjB,CAAC;aAAM,CAAC;YACN,MAAM,eAAe,GAAG,MAAM,OAAO,CAAC;YACtC,IAAI,eAAe,CAAC,MAAM,GAAG,IAAI,CAAC,qBAAqB,EAAE,CAAC;gBACxD,MAAM;oBACJ,IAAI,EAAE,kBAAM,CAAC,kBAAkB;oBAC/B,OAAO,EAAE,qCAAqC,eAAe,CAAC,MAAM,QAAQ,IAAI,CAAC,qBAAqB,GAAG;oBACzG,QAAQ,EAAE,IAAI,mBAAQ,EAAE;iBACzB,CAAC;YACJ,CAAC;iBAAM,CAAC;gBACN,OAAO,eAAe,CAAC;YACzB,CAAC;QACH,CAAC;IACH,CAAC;CACF;AAlDD,oDAkDC;AAED,MAAa,2BAA2B;IAGtC,YAA6B,OAAuB;QAAvB,YAAO,GAAP,OAAO,CAAgB;IAAG,CAAC;IAExD,YAAY;QACV,OAAO,IAAI,oBAAoB,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;IAChD,CAAC;CACF;AARD,kEAQC"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/metadata.d.ts b/node_modules/@grpc/grpc-js/build/src/metadata.d.ts new file mode 100644 index 0000000..1943b75 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/metadata.d.ts @@ -0,0 +1,87 @@ +/// +/// +/// +import * as http2 from 'http2'; +export type MetadataValue = string | Buffer; +export type MetadataObject = Map; +export interface MetadataOptions { + idempotentRequest?: boolean; + waitForReady?: boolean; + cacheableRequest?: boolean; + corked?: boolean; +} +/** + * A class for storing metadata. Keys are normalized to lowercase ASCII. + */ +export declare class Metadata { + protected internalRepr: MetadataObject; + private options; + constructor(options?: MetadataOptions); + /** + * Sets the given value for the given key by replacing any other values + * associated with that key. Normalizes the key. + * @param key The key to whose value should be set. + * @param value The value to set. Must be a buffer if and only + * if the normalized key ends with '-bin'. + */ + set(key: string, value: MetadataValue): void; + /** + * Adds the given value for the given key by appending to a list of previous + * values associated with that key. Normalizes the key. + * @param key The key for which a new value should be appended. + * @param value The value to add. Must be a buffer if and only + * if the normalized key ends with '-bin'. + */ + add(key: string, value: MetadataValue): void; + /** + * Removes the given key and any associated values. Normalizes the key. + * @param key The key whose values should be removed. + */ + remove(key: string): void; + /** + * Gets a list of all values associated with the key. Normalizes the key. + * @param key The key whose value should be retrieved. + * @return A list of values associated with the given key. + */ + get(key: string): MetadataValue[]; + /** + * Gets a plain object mapping each key to the first value associated with it. + * This reflects the most common way that people will want to see metadata. + * @return A key/value mapping of the metadata. + */ + getMap(): { + [key: string]: MetadataValue; + }; + /** + * Clones the metadata object. + * @return The newly cloned object. + */ + clone(): Metadata; + /** + * Merges all key-value pairs from a given Metadata object into this one. + * If both this object and the given object have values in the same key, + * values from the other Metadata object will be appended to this object's + * values. + * @param other A Metadata object. + */ + merge(other: Metadata): void; + setOptions(options: MetadataOptions): void; + getOptions(): MetadataOptions; + /** + * Creates an OutgoingHttpHeaders object that can be used with the http2 API. + */ + toHttp2Headers(): http2.OutgoingHttpHeaders; + /** + * This modifies the behavior of JSON.stringify to show an object + * representation of the metadata map. + */ + toJSON(): { + [key: string]: MetadataValue[]; + }; + /** + * Returns a new Metadata object based fields in a given IncomingHttpHeaders + * object. + * @param headers An IncomingHttpHeaders object. + */ + static fromHttp2Headers(headers: http2.IncomingHttpHeaders): Metadata; +} diff --git a/node_modules/@grpc/grpc-js/build/src/metadata.js b/node_modules/@grpc/grpc-js/build/src/metadata.js new file mode 100644 index 0000000..c0ea411 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/metadata.js @@ -0,0 +1,249 @@ +"use strict"; +/* + * Copyright 2019 gRPC authors. + * + * 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. + * + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Metadata = void 0; +const logging_1 = require("./logging"); +const constants_1 = require("./constants"); +const error_1 = require("./error"); +const LEGAL_KEY_REGEX = /^[0-9a-z_.-]+$/; +const LEGAL_NON_BINARY_VALUE_REGEX = /^[ -~]*$/; +function isLegalKey(key) { + return LEGAL_KEY_REGEX.test(key); +} +function isLegalNonBinaryValue(value) { + return LEGAL_NON_BINARY_VALUE_REGEX.test(value); +} +function isBinaryKey(key) { + return key.endsWith('-bin'); +} +function isCustomMetadata(key) { + return !key.startsWith('grpc-'); +} +function normalizeKey(key) { + return key.toLowerCase(); +} +function validate(key, value) { + if (!isLegalKey(key)) { + throw new Error('Metadata key "' + key + '" contains illegal characters'); + } + if (value !== null && value !== undefined) { + if (isBinaryKey(key)) { + if (!Buffer.isBuffer(value)) { + throw new Error("keys that end with '-bin' must have Buffer values"); + } + } + else { + if (Buffer.isBuffer(value)) { + throw new Error("keys that don't end with '-bin' must have String values"); + } + if (!isLegalNonBinaryValue(value)) { + throw new Error('Metadata string value "' + value + '" contains illegal characters'); + } + } + } +} +/** + * A class for storing metadata. Keys are normalized to lowercase ASCII. + */ +class Metadata { + constructor(options = {}) { + this.internalRepr = new Map(); + this.options = options; + } + /** + * Sets the given value for the given key by replacing any other values + * associated with that key. Normalizes the key. + * @param key The key to whose value should be set. + * @param value The value to set. Must be a buffer if and only + * if the normalized key ends with '-bin'. + */ + set(key, value) { + key = normalizeKey(key); + validate(key, value); + this.internalRepr.set(key, [value]); + } + /** + * Adds the given value for the given key by appending to a list of previous + * values associated with that key. Normalizes the key. + * @param key The key for which a new value should be appended. + * @param value The value to add. Must be a buffer if and only + * if the normalized key ends with '-bin'. + */ + add(key, value) { + key = normalizeKey(key); + validate(key, value); + const existingValue = this.internalRepr.get(key); + if (existingValue === undefined) { + this.internalRepr.set(key, [value]); + } + else { + existingValue.push(value); + } + } + /** + * Removes the given key and any associated values. Normalizes the key. + * @param key The key whose values should be removed. + */ + remove(key) { + key = normalizeKey(key); + // validate(key); + this.internalRepr.delete(key); + } + /** + * Gets a list of all values associated with the key. Normalizes the key. + * @param key The key whose value should be retrieved. + * @return A list of values associated with the given key. + */ + get(key) { + key = normalizeKey(key); + // validate(key); + return this.internalRepr.get(key) || []; + } + /** + * Gets a plain object mapping each key to the first value associated with it. + * This reflects the most common way that people will want to see metadata. + * @return A key/value mapping of the metadata. + */ + getMap() { + const result = {}; + for (const [key, values] of this.internalRepr) { + if (values.length > 0) { + const v = values[0]; + result[key] = Buffer.isBuffer(v) ? Buffer.from(v) : v; + } + } + return result; + } + /** + * Clones the metadata object. + * @return The newly cloned object. + */ + clone() { + const newMetadata = new Metadata(this.options); + const newInternalRepr = newMetadata.internalRepr; + for (const [key, value] of this.internalRepr) { + const clonedValue = value.map(v => { + if (Buffer.isBuffer(v)) { + return Buffer.from(v); + } + else { + return v; + } + }); + newInternalRepr.set(key, clonedValue); + } + return newMetadata; + } + /** + * Merges all key-value pairs from a given Metadata object into this one. + * If both this object and the given object have values in the same key, + * values from the other Metadata object will be appended to this object's + * values. + * @param other A Metadata object. + */ + merge(other) { + for (const [key, values] of other.internalRepr) { + const mergedValue = (this.internalRepr.get(key) || []).concat(values); + this.internalRepr.set(key, mergedValue); + } + } + setOptions(options) { + this.options = options; + } + getOptions() { + return this.options; + } + /** + * Creates an OutgoingHttpHeaders object that can be used with the http2 API. + */ + toHttp2Headers() { + // NOTE: Node <8.9 formats http2 headers incorrectly. + const result = {}; + for (const [key, values] of this.internalRepr) { + // We assume that the user's interaction with this object is limited to + // through its public API (i.e. keys and values are already validated). + result[key] = values.map(bufToString); + } + return result; + } + /** + * This modifies the behavior of JSON.stringify to show an object + * representation of the metadata map. + */ + toJSON() { + const result = {}; + for (const [key, values] of this.internalRepr) { + result[key] = values; + } + return result; + } + /** + * Returns a new Metadata object based fields in a given IncomingHttpHeaders + * object. + * @param headers An IncomingHttpHeaders object. + */ + static fromHttp2Headers(headers) { + const result = new Metadata(); + for (const key of Object.keys(headers)) { + // Reserved headers (beginning with `:`) are not valid keys. + if (key.charAt(0) === ':') { + continue; + } + const values = headers[key]; + try { + if (isBinaryKey(key)) { + if (Array.isArray(values)) { + values.forEach(value => { + result.add(key, Buffer.from(value, 'base64')); + }); + } + else if (values !== undefined) { + if (isCustomMetadata(key)) { + values.split(',').forEach(v => { + result.add(key, Buffer.from(v.trim(), 'base64')); + }); + } + else { + result.add(key, Buffer.from(values, 'base64')); + } + } + } + else { + if (Array.isArray(values)) { + values.forEach(value => { + result.add(key, value); + }); + } + else if (values !== undefined) { + result.add(key, values); + } + } + } + catch (error) { + const message = `Failed to add metadata entry ${key}: ${values}. ${(0, error_1.getErrorMessage)(error)}. For more information see https://github.com/grpc/grpc-node/issues/1173`; + (0, logging_1.log)(constants_1.LogVerbosity.ERROR, message); + } + } + return result; + } +} +exports.Metadata = Metadata; +const bufToString = (val) => { + return Buffer.isBuffer(val) ? val.toString('base64') : val; +}; +//# sourceMappingURL=metadata.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/metadata.js.map b/node_modules/@grpc/grpc-js/build/src/metadata.js.map new file mode 100644 index 0000000..e3d809c --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/metadata.js.map @@ -0,0 +1 @@ +{"version":3,"file":"metadata.js","sourceRoot":"","sources":["../../src/metadata.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;GAeG;;;AAGH,uCAAgC;AAChC,2CAA2C;AAC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AM,CAAC,CAAC;oBAC1B,CAAC;gBACH,CAAC;YACH,CAAC;YAAC,OAAO,KAAK,EAAE,CAAC;gBACf,MAAM,OAAO,GAAG,gCAAgC,GAAG,KAAK,MAAM,KAAK,IAAA,uBAAe,EAChF,KAAK,CACN,0EAA0E,CAAC;gBAC5E,IAAA,aAAG,EAAC,wBAAY,CAAC,KAAK,EAAE,OAAO,CAAC,CAAC;YACnC,CAAC;QACH,CAAC;QAED,OAAO,MAAM,CAAC;IAChB,CAAC;CACF;AA7MD,4BA6MC;AAED,MAAM,WAAW,GAAG,CAAC,GAAoB,EAAU,EAAE;IACnD,OAAO,MAAM,CAAC,QAAQ,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC,QAAQ,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAC,GAAG,CAAC;AAC7D,CAAC,CAAC"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/object-stream.d.ts b/node_modules/@grpc/grpc-js/build/src/object-stream.d.ts new file mode 100644 index 0000000..b424cc7 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/object-stream.d.ts @@ -0,0 +1,28 @@ +/// +import { Readable, Writable } from 'stream'; +import { EmitterAugmentation1 } from './events'; +export type WriteCallback = (error: Error | null | undefined) => void; +export interface IntermediateObjectReadable extends Readable { + read(size?: number): any & T; +} +export type ObjectReadable = { + read(size?: number): T; +} & EmitterAugmentation1<'data', T> & IntermediateObjectReadable; +export interface IntermediateObjectWritable extends Writable { + _write(chunk: any & T, encoding: string, callback: Function): void; + write(chunk: any & T, cb?: WriteCallback): boolean; + write(chunk: any & T, encoding?: any, cb?: WriteCallback): boolean; + setDefaultEncoding(encoding: string): this; + end(): ReturnType extends Writable ? this : void; + end(chunk: any & T, cb?: Function): ReturnType extends Writable ? this : void; + end(chunk: any & T, encoding?: any, cb?: Function): ReturnType extends Writable ? this : void; +} +export interface ObjectWritable extends IntermediateObjectWritable { + _write(chunk: T, encoding: string, callback: Function): void; + write(chunk: T, cb?: Function): boolean; + write(chunk: T, encoding?: any, cb?: Function): boolean; + setDefaultEncoding(encoding: string): this; + end(): ReturnType extends Writable ? this : void; + end(chunk: T, cb?: Function): ReturnType extends Writable ? this : void; + end(chunk: T, encoding?: any, cb?: Function): ReturnType extends Writable ? this : void; +} diff --git a/node_modules/@grpc/grpc-js/build/src/object-stream.js b/node_modules/@grpc/grpc-js/build/src/object-stream.js new file mode 100644 index 0000000..b947656 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/object-stream.js @@ -0,0 +1,19 @@ +"use strict"; +/* + * Copyright 2019 gRPC authors. + * + * 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. + * + */ +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=object-stream.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/object-stream.js.map b/node_modules/@grpc/grpc-js/build/src/object-stream.js.map new file mode 100644 index 0000000..fe8b624 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/object-stream.js.map @@ -0,0 +1 @@ +{"version":3,"file":"object-stream.js","sourceRoot":"","sources":["../../src/object-stream.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;GAeG"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/picker.d.ts b/node_modules/@grpc/grpc-js/build/src/picker.d.ts new file mode 100644 index 0000000..11a0110 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/picker.d.ts @@ -0,0 +1,94 @@ +import { StatusObject } from './call-interface'; +import { Metadata } from './metadata'; +import { Status } from './constants'; +import { LoadBalancer } from './load-balancer'; +import { SubchannelInterface } from './subchannel-interface'; +export declare enum PickResultType { + COMPLETE = 0, + QUEUE = 1, + TRANSIENT_FAILURE = 2, + DROP = 3 +} +export interface PickResult { + pickResultType: PickResultType; + /** + * The subchannel to use as the transport for the call. Only meaningful if + * `pickResultType` is COMPLETE. If null, indicates that the call should be + * dropped. + */ + subchannel: SubchannelInterface | null; + /** + * The status object to end the call with. Populated if and only if + * `pickResultType` is TRANSIENT_FAILURE. + */ + status: StatusObject | null; + onCallStarted: (() => void) | null; + onCallEnded: ((statusCode: Status) => void) | null; +} +export interface CompletePickResult extends PickResult { + pickResultType: PickResultType.COMPLETE; + subchannel: SubchannelInterface | null; + status: null; + onCallStarted: (() => void) | null; + onCallEnded: ((statusCode: Status) => void) | null; +} +export interface QueuePickResult extends PickResult { + pickResultType: PickResultType.QUEUE; + subchannel: null; + status: null; + onCallStarted: null; + onCallEnded: null; +} +export interface TransientFailurePickResult extends PickResult { + pickResultType: PickResultType.TRANSIENT_FAILURE; + subchannel: null; + status: StatusObject; + onCallStarted: null; + onCallEnded: null; +} +export interface DropCallPickResult extends PickResult { + pickResultType: PickResultType.DROP; + subchannel: null; + status: StatusObject; + onCallStarted: null; + onCallEnded: null; +} +export interface PickArgs { + metadata: Metadata; + extraPickInfo: { + [key: string]: string; + }; +} +/** + * A proxy object representing the momentary state of a load balancer. Picks + * subchannels or returns other information based on that state. Should be + * replaced every time the load balancer changes state. + */ +export interface Picker { + pick(pickArgs: PickArgs): PickResult; +} +/** + * A standard picker representing a load balancer in the TRANSIENT_FAILURE + * state. Always responds to every pick request with an UNAVAILABLE status. + */ +export declare class UnavailablePicker implements Picker { + private status; + constructor(status?: Partial); + pick(pickArgs: PickArgs): TransientFailurePickResult; +} +/** + * A standard picker representing a load balancer in the IDLE or CONNECTING + * state. Always responds to every pick request with a QUEUE pick result + * indicating that the pick should be tried again with the next `Picker`. Also + * reports back to the load balancer that a connection should be established + * once any pick is attempted. + * If the childPicker is provided, delegate to it instead of returning the + * hardcoded QUEUE pick result, but still calls exitIdle. + */ +export declare class QueuePicker { + private loadBalancer; + private childPicker?; + private calledExitIdle; + constructor(loadBalancer: LoadBalancer, childPicker?: Picker | undefined); + pick(pickArgs: PickArgs): PickResult; +} diff --git a/node_modules/@grpc/grpc-js/build/src/picker.js b/node_modules/@grpc/grpc-js/build/src/picker.js new file mode 100644 index 0000000..e796f09 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/picker.js @@ -0,0 +1,86 @@ +"use strict"; +/* + * Copyright 2019 gRPC authors. + * + * 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. + * + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.QueuePicker = exports.UnavailablePicker = exports.PickResultType = void 0; +const metadata_1 = require("./metadata"); +const constants_1 = require("./constants"); +var PickResultType; +(function (PickResultType) { + PickResultType[PickResultType["COMPLETE"] = 0] = "COMPLETE"; + PickResultType[PickResultType["QUEUE"] = 1] = "QUEUE"; + PickResultType[PickResultType["TRANSIENT_FAILURE"] = 2] = "TRANSIENT_FAILURE"; + PickResultType[PickResultType["DROP"] = 3] = "DROP"; +})(PickResultType || (exports.PickResultType = PickResultType = {})); +/** + * A standard picker representing a load balancer in the TRANSIENT_FAILURE + * state. Always responds to every pick request with an UNAVAILABLE status. + */ +class UnavailablePicker { + constructor(status) { + this.status = Object.assign({ code: constants_1.Status.UNAVAILABLE, details: 'No connection established', metadata: new metadata_1.Metadata() }, status); + } + pick(pickArgs) { + return { + pickResultType: PickResultType.TRANSIENT_FAILURE, + subchannel: null, + status: this.status, + onCallStarted: null, + onCallEnded: null, + }; + } +} +exports.UnavailablePicker = UnavailablePicker; +/** + * A standard picker representing a load balancer in the IDLE or CONNECTING + * state. Always responds to every pick request with a QUEUE pick result + * indicating that the pick should be tried again with the next `Picker`. Also + * reports back to the load balancer that a connection should be established + * once any pick is attempted. + * If the childPicker is provided, delegate to it instead of returning the + * hardcoded QUEUE pick result, but still calls exitIdle. + */ +class QueuePicker { + // Constructed with a load balancer. Calls exitIdle on it the first time pick is called + constructor(loadBalancer, childPicker) { + this.loadBalancer = loadBalancer; + this.childPicker = childPicker; + this.calledExitIdle = false; + } + pick(pickArgs) { + if (!this.calledExitIdle) { + process.nextTick(() => { + this.loadBalancer.exitIdle(); + }); + this.calledExitIdle = true; + } + if (this.childPicker) { + return this.childPicker.pick(pickArgs); + } + else { + return { + pickResultType: PickResultType.QUEUE, + subchannel: null, + status: null, + onCallStarted: null, + onCallEnded: null, + }; + } + } +} +exports.QueuePicker = QueuePicker; +//# sourceMappingURL=picker.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/picker.js.map b/node_modules/@grpc/grpc-js/build/src/picker.js.map new file mode 100644 index 0000000..3dab5b3 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/picker.js.map @@ -0,0 +1 @@ +{"version":3,"file":"picker.js","sourceRoot":"","sources":["../../src/picker.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;GAeG;;;AAGH,yCAAsC;AACtC,2CAAqC;AAIrC,IAAY,cAKX;AALD,WAAY,cAAc;IACxB,2DAAQ,CAAA;IACR,qDAAK,CAAA;IACL,6EAAiB,CAAA;IACjB,mDAAI,CAAA;AACN,CAAC,EALW,cAAc,8BAAd,cAAc,QAKzB;AAiED;;;GAGG;AACH,MAAa,iBAAiB;IAE5B,YAAY,MAA8B;QACxC,IAAI,CAAC,MAAM,mBACT,IAAI,EAAE,kBAAM,CAAC,WAAW,EACxB,OAAO,EAAE,2BAA2B,EACpC,QAAQ,EAAE,IAAI,mBAAQ,EAAE,IACrB,MAAM,CACV,CAAC;IACJ,CAAC;IACD,IAAI,CAAC,QAAkB;QACrB,OAAO;YACL,cAAc,EAAE,cAAc,CAAC,iBAAiB;YAChD,UAAU,EAAE,IAAI;YAChB,MAAM,EAAE,IAAI,CAAC,MAAM;YACnB,aAAa,EAAE,IAAI;YACnB,WAAW,EAAE,IAAI;SAClB,CAAC;IACJ,CAAC;CACF;AAnBD,8CAmBC;AAED;;;;;;;;GAQG;AACH,MAAa,WAAW;IAEtB,uFAAuF;IACvF,YACU,YAA0B,EAC1B,WAAoB;QADpB,iBAAY,GAAZ,YAAY,CAAc;QAC1B,gBAAW,GAAX,WAAW,CAAS;QAJtB,mBAAc,GAAG,KAAK,CAAC;IAK5B,CAAC;IAEJ,IAAI,CAAC,QAAkB;QACrB,IAAI,CAAC,IAAI,CAAC,cAAc,EAAE,CAAC;YACzB,OAAO,CAAC,QAAQ,CAAC,GAAG,EAAE;gBACpB,IAAI,CAAC,YAAY,CAAC,QAAQ,EAAE,CAAC;YAC/B,CAAC,CAAC,CAAC;YACH,IAAI,CAAC,cAAc,GAAG,IAAI,CAAC;QAC7B,CAAC;QACD,IAAI,IAAI,CAAC,WAAW,EAAE,CAAC;YACrB,OAAO,IAAI,CAAC,WAAW,CAAC,IAAI,CAAC,QAAQ,CAAC,CAAC;QACzC,CAAC;aAAM,CAAC;YACN,OAAO;gBACL,cAAc,EAAE,cAAc,CAAC,KAAK;gBACpC,UAAU,EAAE,IAAI;gBAChB,MAAM,EAAE,IAAI;gBACZ,aAAa,EAAE,IAAI;gBACnB,WAAW,EAAE,IAAI;aAClB,CAAC;QACJ,CAAC;IACH,CAAC;CACF;AA3BD,kCA2BC"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/resolver-dns.d.ts b/node_modules/@grpc/grpc-js/build/src/resolver-dns.d.ts new file mode 100644 index 0000000..138f7f1 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/resolver-dns.d.ts @@ -0,0 +1,13 @@ +/** + * The default TCP port to connect to if not explicitly specified in the target. + */ +export declare const DEFAULT_PORT = 443; +/** + * Set up the DNS resolver class by registering it as the handler for the + * "dns:" prefix and as the default resolver. + */ +export declare function setup(): void; +export interface DnsUrl { + host: string; + port?: string; +} diff --git a/node_modules/@grpc/grpc-js/build/src/resolver-dns.js b/node_modules/@grpc/grpc-js/build/src/resolver-dns.js new file mode 100644 index 0000000..fcbd786 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/resolver-dns.js @@ -0,0 +1,319 @@ +"use strict"; +/* + * Copyright 2019 gRPC authors. + * + * 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. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.setup = exports.DEFAULT_PORT = void 0; +const resolver_1 = require("./resolver"); +const dns = require("dns"); +const util = require("util"); +const service_config_1 = require("./service-config"); +const constants_1 = require("./constants"); +const metadata_1 = require("./metadata"); +const logging = require("./logging"); +const constants_2 = require("./constants"); +const uri_parser_1 = require("./uri-parser"); +const net_1 = require("net"); +const backoff_timeout_1 = require("./backoff-timeout"); +const TRACER_NAME = 'dns_resolver'; +function trace(text) { + logging.trace(constants_2.LogVerbosity.DEBUG, TRACER_NAME, text); +} +/** + * The default TCP port to connect to if not explicitly specified in the target. + */ +exports.DEFAULT_PORT = 443; +const DEFAULT_MIN_TIME_BETWEEN_RESOLUTIONS_MS = 30000; +const resolveTxtPromise = util.promisify(dns.resolveTxt); +const dnsLookupPromise = util.promisify(dns.lookup); +/** + * Resolver implementation that handles DNS names and IP addresses. + */ +class DnsResolver { + constructor(target, listener, channelOptions) { + var _a, _b, _c; + this.target = target; + this.listener = listener; + this.pendingLookupPromise = null; + this.pendingTxtPromise = null; + this.latestLookupResult = null; + this.latestServiceConfig = null; + this.latestServiceConfigError = null; + this.continueResolving = false; + this.isNextResolutionTimerRunning = false; + this.isServiceConfigEnabled = true; + this.returnedIpResult = false; + trace('Resolver constructed for target ' + (0, uri_parser_1.uriToString)(target)); + const hostPort = (0, uri_parser_1.splitHostPort)(target.path); + if (hostPort === null) { + this.ipResult = null; + this.dnsHostname = null; + this.port = null; + } + else { + if ((0, net_1.isIPv4)(hostPort.host) || (0, net_1.isIPv6)(hostPort.host)) { + this.ipResult = [ + { + addresses: [ + { + host: hostPort.host, + port: (_a = hostPort.port) !== null && _a !== void 0 ? _a : exports.DEFAULT_PORT, + }, + ], + }, + ]; + this.dnsHostname = null; + this.port = null; + } + else { + this.ipResult = null; + this.dnsHostname = hostPort.host; + this.port = (_b = hostPort.port) !== null && _b !== void 0 ? _b : exports.DEFAULT_PORT; + } + } + this.percentage = Math.random() * 100; + if (channelOptions['grpc.service_config_disable_resolution'] === 1) { + this.isServiceConfigEnabled = false; + } + this.defaultResolutionError = { + code: constants_1.Status.UNAVAILABLE, + details: `Name resolution failed for target ${(0, uri_parser_1.uriToString)(this.target)}`, + metadata: new metadata_1.Metadata(), + }; + const backoffOptions = { + initialDelay: channelOptions['grpc.initial_reconnect_backoff_ms'], + maxDelay: channelOptions['grpc.max_reconnect_backoff_ms'], + }; + this.backoff = new backoff_timeout_1.BackoffTimeout(() => { + if (this.continueResolving) { + this.startResolutionWithBackoff(); + } + }, backoffOptions); + this.backoff.unref(); + this.minTimeBetweenResolutionsMs = + (_c = channelOptions['grpc.dns_min_time_between_resolutions_ms']) !== null && _c !== void 0 ? _c : DEFAULT_MIN_TIME_BETWEEN_RESOLUTIONS_MS; + this.nextResolutionTimer = setTimeout(() => { }, 0); + clearTimeout(this.nextResolutionTimer); + } + /** + * If the target is an IP address, just provide that address as a result. + * Otherwise, initiate A, AAAA, and TXT lookups + */ + startResolution() { + if (this.ipResult !== null) { + if (!this.returnedIpResult) { + trace('Returning IP address for target ' + (0, uri_parser_1.uriToString)(this.target)); + setImmediate(() => { + this.listener.onSuccessfulResolution(this.ipResult, null, null, null, {}); + }); + this.returnedIpResult = true; + } + this.backoff.stop(); + this.backoff.reset(); + this.stopNextResolutionTimer(); + return; + } + if (this.dnsHostname === null) { + trace('Failed to parse DNS address ' + (0, uri_parser_1.uriToString)(this.target)); + setImmediate(() => { + this.listener.onError({ + code: constants_1.Status.UNAVAILABLE, + details: `Failed to parse DNS address ${(0, uri_parser_1.uriToString)(this.target)}`, + metadata: new metadata_1.Metadata(), + }); + }); + this.stopNextResolutionTimer(); + } + else { + if (this.pendingLookupPromise !== null) { + return; + } + trace('Looking up DNS hostname ' + this.dnsHostname); + /* We clear out latestLookupResult here to ensure that it contains the + * latest result since the last time we started resolving. That way, the + * TXT resolution handler can use it, but only if it finishes second. We + * don't clear out any previous service config results because it's + * better to use a service config that's slightly out of date than to + * revert to an effectively blank one. */ + this.latestLookupResult = null; + const hostname = this.dnsHostname; + /* We lookup both address families here and then split them up later + * because when looking up a single family, dns.lookup outputs an error + * if the name exists but there are no records for that family, and that + * error is indistinguishable from other kinds of errors */ + this.pendingLookupPromise = dnsLookupPromise(hostname, { all: true }); + this.pendingLookupPromise.then(addressList => { + if (this.pendingLookupPromise === null) { + return; + } + this.pendingLookupPromise = null; + this.backoff.reset(); + this.backoff.stop(); + const subchannelAddresses = addressList.map(addr => ({ host: addr.address, port: +this.port })); + this.latestLookupResult = subchannelAddresses.map(address => ({ + addresses: [address], + })); + const allAddressesString = '[' + + subchannelAddresses + .map(addr => addr.host + ':' + addr.port) + .join(',') + + ']'; + trace('Resolved addresses for target ' + + (0, uri_parser_1.uriToString)(this.target) + + ': ' + + allAddressesString); + if (this.latestLookupResult.length === 0) { + this.listener.onError(this.defaultResolutionError); + return; + } + /* If the TXT lookup has not yet finished, both of the last two + * arguments will be null, which is the equivalent of getting an + * empty TXT response. When the TXT lookup does finish, its handler + * can update the service config by using the same address list */ + this.listener.onSuccessfulResolution(this.latestLookupResult, this.latestServiceConfig, this.latestServiceConfigError, null, {}); + }, err => { + if (this.pendingLookupPromise === null) { + return; + } + trace('Resolution error for target ' + + (0, uri_parser_1.uriToString)(this.target) + + ': ' + + err.message); + this.pendingLookupPromise = null; + this.stopNextResolutionTimer(); + this.listener.onError(this.defaultResolutionError); + }); + /* If there already is a still-pending TXT resolution, we can just use + * that result when it comes in */ + if (this.isServiceConfigEnabled && this.pendingTxtPromise === null) { + /* We handle the TXT query promise differently than the others because + * the name resolution attempt as a whole is a success even if the TXT + * lookup fails */ + this.pendingTxtPromise = resolveTxtPromise(hostname); + this.pendingTxtPromise.then(txtRecord => { + if (this.pendingTxtPromise === null) { + return; + } + this.pendingTxtPromise = null; + try { + this.latestServiceConfig = (0, service_config_1.extractAndSelectServiceConfig)(txtRecord, this.percentage); + } + catch (err) { + this.latestServiceConfigError = { + code: constants_1.Status.UNAVAILABLE, + details: `Parsing service config failed with error ${err.message}`, + metadata: new metadata_1.Metadata(), + }; + } + if (this.latestLookupResult !== null) { + /* We rely here on the assumption that calling this function with + * identical parameters will be essentialy idempotent, and calling + * it with the same address list and a different service config + * should result in a fast and seamless switchover. */ + this.listener.onSuccessfulResolution(this.latestLookupResult, this.latestServiceConfig, this.latestServiceConfigError, null, {}); + } + }, err => { + /* If TXT lookup fails we should do nothing, which means that we + * continue to use the result of the most recent successful lookup, + * or the default null config object if there has never been a + * successful lookup. We do not set the latestServiceConfigError + * here because that is specifically used for response validation + * errors. We still need to handle this error so that it does not + * bubble up as an unhandled promise rejection. */ + }); + } + } + } + startNextResolutionTimer() { + var _a, _b; + clearTimeout(this.nextResolutionTimer); + this.nextResolutionTimer = setTimeout(() => { + this.stopNextResolutionTimer(); + if (this.continueResolving) { + this.startResolutionWithBackoff(); + } + }, this.minTimeBetweenResolutionsMs); + (_b = (_a = this.nextResolutionTimer).unref) === null || _b === void 0 ? void 0 : _b.call(_a); + this.isNextResolutionTimerRunning = true; + } + stopNextResolutionTimer() { + clearTimeout(this.nextResolutionTimer); + this.isNextResolutionTimerRunning = false; + } + startResolutionWithBackoff() { + if (this.pendingLookupPromise === null) { + this.continueResolving = false; + this.backoff.runOnce(); + this.startNextResolutionTimer(); + this.startResolution(); + } + } + updateResolution() { + /* If there is a pending lookup, just let it finish. Otherwise, if the + * nextResolutionTimer or backoff timer is running, set the + * continueResolving flag to resolve when whichever of those timers + * fires. Otherwise, start resolving immediately. */ + if (this.pendingLookupPromise === null) { + if (this.isNextResolutionTimerRunning || this.backoff.isRunning()) { + if (this.isNextResolutionTimerRunning) { + trace('resolution update delayed by "min time between resolutions" rate limit'); + } + else { + trace('resolution update delayed by backoff timer until ' + + this.backoff.getEndTime().toISOString()); + } + this.continueResolving = true; + } + else { + this.startResolutionWithBackoff(); + } + } + } + /** + * Reset the resolver to the same state it had when it was created. In-flight + * DNS requests cannot be cancelled, but they are discarded and their results + * will be ignored. + */ + destroy() { + this.continueResolving = false; + this.backoff.reset(); + this.backoff.stop(); + this.stopNextResolutionTimer(); + this.pendingLookupPromise = null; + this.pendingTxtPromise = null; + this.latestLookupResult = null; + this.latestServiceConfig = null; + this.latestServiceConfigError = null; + this.returnedIpResult = false; + } + /** + * Get the default authority for the given target. For IP targets, that is + * the IP address. For DNS targets, it is the hostname. + * @param target + */ + static getDefaultAuthority(target) { + return target.path; + } +} +/** + * Set up the DNS resolver class by registering it as the handler for the + * "dns:" prefix and as the default resolver. + */ +function setup() { + (0, resolver_1.registerResolver)('dns', DnsResolver); + (0, resolver_1.registerDefaultScheme)('dns'); +} +exports.setup = setup; +//# sourceMappingURL=resolver-dns.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/resolver-dns.js.map b/node_modules/@grpc/grpc-js/build/src/resolver-dns.js.map new file mode 100644 index 0000000..3f9a28a --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/resolver-dns.js.map @@ -0,0 +1 @@ +{"version":3,"file":"resolver-dns.js","sourceRoot":"","sources":["../../src/resolver-dns.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG;;;AAEH,yCAKoB;AACpB,2BAA2B;A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iBAAiB,GAAG,KAAK,CAAC;QAC/B,IAAI,CAAC,OAAO,CAAC,KAAK,EAAE,CAAC;QACrB,IAAI,CAAC,OAAO,CAAC,IAAI,EAAE,CAAC;QACpB,IAAI,CAAC,uBAAuB,EAAE,CAAC;QAC/B,IAAI,CAAC,oBAAoB,GAAG,IAAI,CAAC;QACjC,IAAI,CAAC,iBAAiB,GAAG,IAAI,CAAC;QAC9B,IAAI,CAAC,kBAAkB,GAAG,IAAI,CAAC;QAC/B,IAAI,CAAC,mBAAmB,GAAG,IAAI,CAAC;QAChC,IAAI,CAAC,wBAAwB,GAAG,IAAI,CAAC;QACrC,IAAI,CAAC,gBAAgB,GAAG,KAAK,CAAC;IAChC,CAAC;IAED;;;;OAIG;IACH,MAAM,CAAC,mBAAmB,CAAC,MAAe;QACxC,OAAO,MAAM,CAAC,IAAI,CAAC;IACrB,CAAC;CACF;AAED;;;GAGG;AACH,SAAgB,KAAK;IACnB,IAAA,2BAAgB,EAAC,KAAK,EAAE,WAAW,CAAC,CAAC;IACrC,IAAA,gCAAqB,EAAC,KAAK,CAAC,CAAC;AAC/B,CAAC;AAHD,sBAGC"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/resolver-ip.d.ts b/node_modules/@grpc/grpc-js/build/src/resolver-ip.d.ts new file mode 100644 index 0000000..2bec678 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/resolver-ip.d.ts @@ -0,0 +1 @@ +export declare function setup(): void; diff --git a/node_modules/@grpc/grpc-js/build/src/resolver-ip.js b/node_modules/@grpc/grpc-js/build/src/resolver-ip.js new file mode 100644 index 0000000..826b863 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/resolver-ip.js @@ -0,0 +1,105 @@ +"use strict"; +/* + * Copyright 2021 gRPC authors. + * + * 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. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.setup = void 0; +const net_1 = require("net"); +const constants_1 = require("./constants"); +const metadata_1 = require("./metadata"); +const resolver_1 = require("./resolver"); +const uri_parser_1 = require("./uri-parser"); +const logging = require("./logging"); +const TRACER_NAME = 'ip_resolver'; +function trace(text) { + logging.trace(constants_1.LogVerbosity.DEBUG, TRACER_NAME, text); +} +const IPV4_SCHEME = 'ipv4'; +const IPV6_SCHEME = 'ipv6'; +/** + * The default TCP port to connect to if not explicitly specified in the target. + */ +const DEFAULT_PORT = 443; +class IpResolver { + constructor(target, listener, channelOptions) { + var _a; + this.listener = listener; + this.endpoints = []; + this.error = null; + this.hasReturnedResult = false; + trace('Resolver constructed for target ' + (0, uri_parser_1.uriToString)(target)); + const addresses = []; + if (!(target.scheme === IPV4_SCHEME || target.scheme === IPV6_SCHEME)) { + this.error = { + code: constants_1.Status.UNAVAILABLE, + details: `Unrecognized scheme ${target.scheme} in IP resolver`, + metadata: new metadata_1.Metadata(), + }; + return; + } + const pathList = target.path.split(','); + for (const path of pathList) { + const hostPort = (0, uri_parser_1.splitHostPort)(path); + if (hostPort === null) { + this.error = { + code: constants_1.Status.UNAVAILABLE, + details: `Failed to parse ${target.scheme} address ${path}`, + metadata: new metadata_1.Metadata(), + }; + return; + } + if ((target.scheme === IPV4_SCHEME && !(0, net_1.isIPv4)(hostPort.host)) || + (target.scheme === IPV6_SCHEME && !(0, net_1.isIPv6)(hostPort.host))) { + this.error = { + code: constants_1.Status.UNAVAILABLE, + details: `Failed to parse ${target.scheme} address ${path}`, + metadata: new metadata_1.Metadata(), + }; + return; + } + addresses.push({ + host: hostPort.host, + port: (_a = hostPort.port) !== null && _a !== void 0 ? _a : DEFAULT_PORT, + }); + } + this.endpoints = addresses.map(address => ({ addresses: [address] })); + trace('Parsed ' + target.scheme + ' address list ' + addresses); + } + updateResolution() { + if (!this.hasReturnedResult) { + this.hasReturnedResult = true; + process.nextTick(() => { + if (this.error) { + this.listener.onError(this.error); + } + else { + this.listener.onSuccessfulResolution(this.endpoints, null, null, null, {}); + } + }); + } + } + destroy() { + this.hasReturnedResult = false; + } + static getDefaultAuthority(target) { + return target.path.split(',')[0]; + } +} +function setup() { + (0, resolver_1.registerResolver)(IPV4_SCHEME, IpResolver); + (0, resolver_1.registerResolver)(IPV6_SCHEME, IpResolver); +} +exports.setup = setup; +//# sourceMappingURL=resolver-ip.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/resolver-ip.js.map b/node_modules/@grpc/grpc-js/build/src/resolver-ip.js.map new file mode 100644 index 0000000..0b33282 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/resolver-ip.js.map @@ -0,0 +1 @@ +{"version":3,"file":"resolver-ip.js","sourceRoot":"","sources":["../../src/resolver-ip.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG;;;AAEH,6BAAqC;AAGrC,2CAAmD;AACnD,yCAAsC;AACtC,yCAA0E;AAE1E,6CAAmE;AACnE,qCAAqC;AAErC,MAAM,WAAW,GAAG,aAAa,CAAC;AAElC,SAAS,KAAK,CAAC,IAAY;IACzB,OAAO,CAAC,KAAK,CAAC,wBAAY,CAAC,KAAK,EAAE,WAAW,EAAE,IAAI,CAAC,CAAC;AACvD,CAAC;AAED,MAAM,WAAW,GAAG,MAAM,CAAC;AAC3B,MAAM,WAAW,GAAG,MAAM,CAAC;AAE3B;;GAEG;AACH,MAAM,YAAY,GAAG,GAAG,CAAC;AAEzB,MAAM,UAAU;IAId,YACE,MAAe,EACP,QAA0B,EAClC,cAA8B;;QADtB,aAAQ,GAAR,QAAQ,CAAkB;QAL5B,cAAS,GAAe,EAAE,CAAC;QAC3B,UAAK,GAAwB,IAAI,CAAC;QAClC,sBAAiB,GAAG,KAAK,CAAC;QAMhC,KAAK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WAAW,EAAE,UAAU,CAAC,CAAC;AAC5C,CAAC;AAHD,sBAGC"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/resolver-uds.d.ts b/node_modules/@grpc/grpc-js/build/src/resolver-uds.d.ts new file mode 100644 index 0000000..2bec678 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/resolver-uds.d.ts @@ -0,0 +1 @@ +export declare function setup(): void; diff --git a/node_modules/@grpc/grpc-js/build/src/resolver-uds.js b/node_modules/@grpc/grpc-js/build/src/resolver-uds.js new file mode 100644 index 0000000..349d9b6 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/resolver-uds.js @@ -0,0 +1,51 @@ +"use strict"; +/* + * Copyright 2019 gRPC authors. + * + * 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. + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.setup = void 0; +const resolver_1 = require("./resolver"); +class UdsResolver { + constructor(target, listener, channelOptions) { + this.listener = listener; + this.hasReturnedResult = false; + this.endpoints = []; + let path; + if (target.authority === '') { + path = '/' + target.path; + } + else { + path = target.path; + } + this.endpoints = [{ addresses: [{ path }] }]; + } + updateResolution() { + if (!this.hasReturnedResult) { + this.hasReturnedResult = true; + process.nextTick(this.listener.onSuccessfulResolution, this.endpoints, null, null, null, {}); + } + } + destroy() { + this.hasReturnedResult = false; + } + static getDefaultAuthority(target) { + return 'localhost'; + } +} +function setup() { + (0, resolver_1.registerResolver)('unix', UdsResolver); +} +exports.setup = setup; +//# sourceMappingURL=resolver-uds.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/resolver-uds.js.map b/node_modules/@grpc/grpc-js/build/src/resolver-uds.js.map new file mode 100644 index 0000000..437ce9d --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/resolver-uds.js.map @@ -0,0 +1 @@ +{"version":3,"file":"resolver-uds.js","sourceRoot":"","sources":["../../src/resolver-uds.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;GAcG;;;AAEH,yCAA0E;AAK1E,MAAM,WAAW;IAGf,YACE,MAAe,EACP,QAA0B,EAClC,cAA8B;QADtB,aAAQ,GAAR,QAAQ,CAAkB;QAJ5B,sBAAiB,GAAG,KAAK,CAAC;QAC1B,cAAS,GAAe,EAAE,CAAC;QAMjC,IAAI,IAAY,CAAC;QACjB,IAAI,MAAM,CAAC,SAAS,KAAK,EAAE,EAAE,CAAC;YAC5B,IAAI,GAAG,GAAG,GAAG,MAAM,CAAC,IAAI,CAAC;QAC3B,CAAC;aAAM,CAAC;YACN,IAAI,GAAG,MAAM,CAAC,IAAI,CAAC;QACrB,CAAC;QACD,IAAI,CAAC,SAAS,GAAG,CAAC,EAAE,SAAS,EAAE,CAAC,EAAE,IAAI,EAAE,CAAC,EAAE,CAAC,CAAC;IAC/C,CAAC;IACD,gBAAgB;QACd,IAAI,CAAC,IAAI,CAAC,iBAAiB,EAAE,CAAC;YAC5B,IAAI,CAAC,iBAAiB,GAAG,IAAI,CAAC;YAC9B,OAAO,CAAC,QAAQ,CACd,IAAI,CAAC,QAAQ,CAAC,sBAAsB,EACpC,IAAI,CAAC,SAAS,EACd,IAAI,EACJ,IAAI,EACJ,IAAI,EACJ,EAAE,CACH,CAAC;QACJ,CAAC;IACH,CAAC;IAED,OAAO;QACL,IAAI,CAAC,iBAAiB,GAAG,KAAK,CAAC;IACjC,CAAC;IAED,MAAM,CAAC,mBAAmB,CAAC,MAAe;QACxC,OAAO,WAAW,CAAC;IACrB,CAAC;CACF;AAED,SAAgB,KAAK;IACnB,IAAA,2BAAgB,EAAC,MAAM,EAAE,WAAW,CAAC,CAAC;AACxC,CAAC;AAFD,sBAEC"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/resolver.d.ts b/node_modules/@grpc/grpc-js/build/src/resolver.d.ts new file mode 100644 index 0000000..6453ee1 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/resolver.d.ts @@ -0,0 +1,105 @@ +import { MethodConfig, ServiceConfig } from './service-config'; +import { StatusObject } from './call-interface'; +import { Endpoint } from './subchannel-address'; +import { GrpcUri } from './uri-parser'; +import { ChannelOptions } from './channel-options'; +import { Metadata } from './metadata'; +import { Status } from './constants'; +import { Filter, FilterFactory } from './filter'; +export interface CallConfig { + methodConfig: MethodConfig; + onCommitted?: () => void; + pickInformation: { + [key: string]: string; + }; + status: Status; + dynamicFilterFactories: FilterFactory[]; +} +/** + * Selects a configuration for a method given the name and metadata. Defined in + * https://github.com/grpc/proposal/blob/master/A31-xds-timeout-support-and-config-selector.md#new-functionality-in-grpc + */ +export interface ConfigSelector { + (methodName: string, metadata: Metadata, channelId: number): CallConfig; +} +/** + * A listener object passed to the resolver's constructor that provides name + * resolution updates back to the resolver's owner. + */ +export interface ResolverListener { + /** + * Called whenever the resolver has new name resolution results to report + * @param addressList The new list of backend addresses + * @param serviceConfig The new service configuration corresponding to the + * `addressList`. Will be `null` if no service configuration was + * retrieved or if the service configuration was invalid + * @param serviceConfigError If non-`null`, indicates that the retrieved + * service configuration was invalid + */ + onSuccessfulResolution(addressList: Endpoint[], serviceConfig: ServiceConfig | null, serviceConfigError: StatusObject | null, configSelector: ConfigSelector | null, attributes: { + [key: string]: unknown; + }): void; + /** + * Called whenever a name resolution attempt fails. + * @param error Describes how resolution failed + */ + onError(error: StatusObject): void; +} +/** + * A resolver class that handles one or more of the name syntax schemes defined + * in the [gRPC Name Resolution document](https://github.com/grpc/grpc/blob/master/doc/naming.md) + */ +export interface Resolver { + /** + * Indicates that the caller wants new name resolution data. Calling this + * function may eventually result in calling one of the `ResolverListener` + * functions, but that is not guaranteed. Those functions will never be + * called synchronously with the constructor or updateResolution. + */ + updateResolution(): void; + /** + * Discard all resources owned by the resolver. A later call to + * `updateResolution` should reinitialize those resources. No + * `ResolverListener` callbacks should be called after `destroy` is called + * until `updateResolution` is called again. + */ + destroy(): void; +} +export interface ResolverConstructor { + new (target: GrpcUri, listener: ResolverListener, channelOptions: ChannelOptions): Resolver; + /** + * Get the default authority for a target. This loosely corresponds to that + * target's hostname. Throws an error if this resolver class cannot parse the + * `target`. + * @param target + */ + getDefaultAuthority(target: GrpcUri): string; +} +/** + * Register a resolver class to handle target names prefixed with the `prefix` + * string. This prefix should correspond to a URI scheme name listed in the + * [gRPC Name Resolution document](https://github.com/grpc/grpc/blob/master/doc/naming.md) + * @param prefix + * @param resolverClass + */ +export declare function registerResolver(scheme: string, resolverClass: ResolverConstructor): void; +/** + * Register a default resolver to handle target names that do not start with + * any registered prefix. + * @param resolverClass + */ +export declare function registerDefaultScheme(scheme: string): void; +/** + * Create a name resolver for the specified target, if possible. Throws an + * error if no such name resolver can be created. + * @param target + * @param listener + */ +export declare function createResolver(target: GrpcUri, listener: ResolverListener, options: ChannelOptions): Resolver; +/** + * Get the default authority for the specified target, if possible. Throws an + * error if no registered name resolver can parse that target string. + * @param target + */ +export declare function getDefaultAuthority(target: GrpcUri): string; +export declare function mapUriDefaultScheme(target: GrpcUri): GrpcUri | null; diff --git a/node_modules/@grpc/grpc-js/build/src/resolver.js b/node_modules/@grpc/grpc-js/build/src/resolver.js new file mode 100644 index 0000000..530cb83 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/resolver.js @@ -0,0 +1,88 @@ +"use strict"; +/* + * Copyright 2019 gRPC authors. + * + * 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. + * + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.mapUriDefaultScheme = exports.getDefaultAuthority = exports.createResolver = exports.registerDefaultScheme = exports.registerResolver = void 0; +const uri_parser_1 = require("./uri-parser"); +const registeredResolvers = {}; +let defaultScheme = null; +/** + * Register a resolver class to handle target names prefixed with the `prefix` + * string. This prefix should correspond to a URI scheme name listed in the + * [gRPC Name Resolution document](https://github.com/grpc/grpc/blob/master/doc/naming.md) + * @param prefix + * @param resolverClass + */ +function registerResolver(scheme, resolverClass) { + registeredResolvers[scheme] = resolverClass; +} +exports.registerResolver = registerResolver; +/** + * Register a default resolver to handle target names that do not start with + * any registered prefix. + * @param resolverClass + */ +function registerDefaultScheme(scheme) { + defaultScheme = scheme; +} +exports.registerDefaultScheme = registerDefaultScheme; +/** + * Create a name resolver for the specified target, if possible. Throws an + * error if no such name resolver can be created. + * @param target + * @param listener + */ +function createResolver(target, listener, options) { + if (target.scheme !== undefined && target.scheme in registeredResolvers) { + return new registeredResolvers[target.scheme](target, listener, options); + } + else { + throw new Error(`No resolver could be created for target ${(0, uri_parser_1.uriToString)(target)}`); + } +} +exports.createResolver = createResolver; +/** + * Get the default authority for the specified target, if possible. Throws an + * error if no registered name resolver can parse that target string. + * @param target + */ +function getDefaultAuthority(target) { + if (target.scheme !== undefined && target.scheme in registeredResolvers) { + return registeredResolvers[target.scheme].getDefaultAuthority(target); + } + else { + throw new Error(`Invalid target ${(0, uri_parser_1.uriToString)(target)}`); + } +} +exports.getDefaultAuthority = getDefaultAuthority; +function mapUriDefaultScheme(target) { + if (target.scheme === undefined || !(target.scheme in registeredResolvers)) { + if (defaultScheme !== null) { + return { + scheme: defaultScheme, + authority: undefined, + path: (0, uri_parser_1.uriToString)(target), + }; + } + else { + return null; + } + } + return target; +} +exports.mapUriDefaultScheme = mapUriDefaultScheme; +//# sourceMappingURL=resolver.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/resolver.js.map b/node_modules/@grpc/grpc-js/build/src/resolver.js.map new file mode 100644 index 0000000..93bb3bb --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/resolver.js.map @@ -0,0 +1 @@ +{"version":3,"file":"resolver.js","sourceRoot":"","sources":["../../src/resolver.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;GAeG;;;AAKH,6CAAoD;AAuFpD,MAAM,mBAAmB,GAA8C,EAAE,CAAC;AAC1E,IAAI,aAAa,GAAkB,IAAI,CAAC;AAExC;;;;;;GAMG;AACH,SAAgB,gBAAgB,CAC9B,MAAc,EACd,aAAkC;IAElC,mBAAmB,CAAC,MAAM,CAAC,GAAG,aAAa,CAAC;AAC9C,CAAC;AALD,4CAKC;AAED;;;;GAIG;AACH,SAAgB,qBAAqB,CAAC,MAAc;IAClD,aAAa,GAAG,MAAM,CAAC;AACzB,CAAC;AAFD,sDAEC;AAED;;;;;GAKG;AACH,SAAgB,cAAc,CAC5B,MAAe,EACf,QAA0B,EAC1B,OAAuB;IAEvB,IAAI,MAAM,CAAC,MAAM,KAAK,SAAS,IAAI,MAAM,CAAC,MAAM,IAAI,mBAAmB,EAAE,CAAC;QACxE,OAAO,IAAI,mBAAmB,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC,MAAM,EAAE,QAAQ,EAAE,OAAO,CAAC,CAAC;IAC3E,CAAC;SAAM,CAAC;QACN,MAAM,IAAI,KAAK,CACb,2CAA2C,IAAA,wBAAW,EAAC,MAAM,CAAC,EAAE,CACjE,CAAC;IACJ,CAAC;AACH,CAAC;AAZD,wCAYC;AAED;;;;GAIG;AACH,SAAgB,mBAAmB,CAAC,MAAe;IACjD,IAAI,MAAM,CAAC,MAAM,KAAK,SAAS,IAAI,MAAM,CAAC,MAAM,IAAI,mBAAmB,EAAE,CAAC;QACxE,OAAO,mBAAmB,CAAC,MAAM,CAAC,MAAM,CAAC,CAAC,mBAAmB,CAAC,MAAM,CAAC,CAAC;IACxE,CAAC;SAAM,CAAC;QACN,MAAM,IAAI,KAAK,CAAC,kBAAkB,IAAA,wBAAW,EAAC,MAAM,CAAC,EAAE,CAAC,CAAC;IAC3D,CAAC;AACH,CAAC;AAND,kDAMC;AAED,SAAgB,mBAAmB,CAAC,MAAe;IACjD,IAAI,MAAM,CAAC,MAAM,KAAK,SAAS,IAAI,CAAC,CAAC,MAAM,CAAC,MAAM,IAAI,mBAAmB,CAAC,EAAE,CAAC;QAC3E,IAAI,aAAa,KAAK,IAAI,EAAE,CAAC;YAC3B,OAAO;gBACL,MAAM,EAAE,aAAa;gBACrB,SAAS,EAAE,SAAS;gBACpB,IAAI,EAAE,IAAA,wBAAW,EAAC,MAAM,CAAC;aAC1B,CAAC;QACJ,CAAC;aAAM,CAAC;YACN,OAAO,IAAI,CAAC;QACd,CAAC;IACH,CAAC;IACD,OAAO,MAAM,CAAC;AAChB,CAAC;AAbD,kDAaC"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/resolving-call.d.ts b/node_modules/@grpc/grpc-js/build/src/resolving-call.d.ts new file mode 100644 index 0000000..5b4a143 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/resolving-call.d.ts @@ -0,0 +1,48 @@ +/// +import { CallCredentials } from './call-credentials'; +import { Call, CallStreamOptions, InterceptingListener, MessageContext, StatusObject } from './call-interface'; +import { Status } from './constants'; +import { FilterStackFactory } from './filter-stack'; +import { InternalChannel } from './internal-channel'; +import { Metadata } from './metadata'; +export declare class ResolvingCall implements Call { + private readonly channel; + private readonly method; + private readonly filterStackFactory; + private credentials; + private callNumber; + private child; + private readPending; + private pendingMessage; + private pendingHalfClose; + private ended; + private readFilterPending; + private writeFilterPending; + private pendingChildStatus; + private metadata; + private listener; + private deadline; + private host; + private statusWatchers; + private deadlineTimer; + private filterStack; + private deadlineStartTime; + private configReceivedTime; + private childStartTime; + constructor(channel: InternalChannel, method: string, options: CallStreamOptions, filterStackFactory: FilterStackFactory, credentials: CallCredentials, callNumber: number); + private trace; + private runDeadlineTimer; + private outputStatus; + private sendMessageOnChild; + getConfig(): void; + reportResolverError(status: StatusObject): void; + cancelWithStatus(status: Status, details: string): void; + getPeer(): string; + start(metadata: Metadata, listener: InterceptingListener): void; + sendMessageWithContext(context: MessageContext, message: Buffer): void; + startRead(): void; + halfClose(): void; + setCredentials(credentials: CallCredentials): void; + addStatusWatcher(watcher: (status: StatusObject) => void): void; + getCallNumber(): number; +} diff --git a/node_modules/@grpc/grpc-js/build/src/resolving-call.js b/node_modules/@grpc/grpc-js/build/src/resolving-call.js new file mode 100644 index 0000000..254536d --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/resolving-call.js @@ -0,0 +1,305 @@ +"use strict"; +/* + * Copyright 2022 gRPC authors. + * + * 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. + * + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ResolvingCall = void 0; +const constants_1 = require("./constants"); +const deadline_1 = require("./deadline"); +const metadata_1 = require("./metadata"); +const logging = require("./logging"); +const control_plane_status_1 = require("./control-plane-status"); +const TRACER_NAME = 'resolving_call'; +class ResolvingCall { + constructor(channel, method, options, filterStackFactory, credentials, callNumber) { + this.channel = channel; + this.method = method; + this.filterStackFactory = filterStackFactory; + this.credentials = credentials; + this.callNumber = callNumber; + this.child = null; + this.readPending = false; + this.pendingMessage = null; + this.pendingHalfClose = false; + this.ended = false; + this.readFilterPending = false; + this.writeFilterPending = false; + this.pendingChildStatus = null; + this.metadata = null; + this.listener = null; + this.statusWatchers = []; + this.deadlineTimer = setTimeout(() => { }, 0); + this.filterStack = null; + this.deadlineStartTime = null; + this.configReceivedTime = null; + this.childStartTime = null; + this.deadline = options.deadline; + this.host = options.host; + if (options.parentCall) { + if (options.flags & constants_1.Propagate.CANCELLATION) { + options.parentCall.on('cancelled', () => { + this.cancelWithStatus(constants_1.Status.CANCELLED, 'Cancelled by parent call'); + }); + } + if (options.flags & constants_1.Propagate.DEADLINE) { + this.trace('Propagating deadline from parent: ' + + options.parentCall.getDeadline()); + this.deadline = (0, deadline_1.minDeadline)(this.deadline, options.parentCall.getDeadline()); + } + } + this.trace('Created'); + this.runDeadlineTimer(); + } + trace(text) { + logging.trace(constants_1.LogVerbosity.DEBUG, TRACER_NAME, '[' + this.callNumber + '] ' + text); + } + runDeadlineTimer() { + clearTimeout(this.deadlineTimer); + this.deadlineStartTime = new Date(); + this.trace('Deadline: ' + (0, deadline_1.deadlineToString)(this.deadline)); + const timeout = (0, deadline_1.getRelativeTimeout)(this.deadline); + if (timeout !== Infinity) { + this.trace('Deadline will be reached in ' + timeout + 'ms'); + const handleDeadline = () => { + if (!this.deadlineStartTime) { + this.cancelWithStatus(constants_1.Status.DEADLINE_EXCEEDED, 'Deadline exceeded'); + return; + } + const deadlineInfo = []; + const deadlineEndTime = new Date(); + deadlineInfo.push(`Deadline exceeded after ${(0, deadline_1.formatDateDifference)(this.deadlineStartTime, deadlineEndTime)}`); + if (this.configReceivedTime) { + if (this.configReceivedTime > this.deadlineStartTime) { + deadlineInfo.push(`name resolution: ${(0, deadline_1.formatDateDifference)(this.deadlineStartTime, this.configReceivedTime)}`); + } + if (this.childStartTime) { + if (this.childStartTime > this.configReceivedTime) { + deadlineInfo.push(`metadata filters: ${(0, deadline_1.formatDateDifference)(this.configReceivedTime, this.childStartTime)}`); + } + } + else { + deadlineInfo.push('waiting for metadata filters'); + } + } + else { + deadlineInfo.push('waiting for name resolution'); + } + if (this.child) { + deadlineInfo.push(...this.child.getDeadlineInfo()); + } + this.cancelWithStatus(constants_1.Status.DEADLINE_EXCEEDED, deadlineInfo.join(',')); + }; + if (timeout <= 0) { + process.nextTick(handleDeadline); + } + else { + this.deadlineTimer = setTimeout(handleDeadline, timeout); + } + } + } + outputStatus(status) { + if (!this.ended) { + this.ended = true; + if (!this.filterStack) { + this.filterStack = this.filterStackFactory.createFilter(); + } + clearTimeout(this.deadlineTimer); + const filteredStatus = this.filterStack.receiveTrailers(status); + this.trace('ended with status: code=' + + filteredStatus.code + + ' details="' + + filteredStatus.details + + '"'); + this.statusWatchers.forEach(watcher => watcher(filteredStatus)); + process.nextTick(() => { + var _a; + (_a = this.listener) === null || _a === void 0 ? void 0 : _a.onReceiveStatus(filteredStatus); + }); + } + } + sendMessageOnChild(context, message) { + if (!this.child) { + throw new Error('sendMessageonChild called with child not populated'); + } + const child = this.child; + this.writeFilterPending = true; + this.filterStack.sendMessage(Promise.resolve({ message: message, flags: context.flags })).then(filteredMessage => { + this.writeFilterPending = false; + child.sendMessageWithContext(context, filteredMessage.message); + if (this.pendingHalfClose) { + child.halfClose(); + } + }, (status) => { + this.cancelWithStatus(status.code, status.details); + }); + } + getConfig() { + if (this.ended) { + return; + } + if (!this.metadata || !this.listener) { + throw new Error('getConfig called before start'); + } + const configResult = this.channel.getConfig(this.method, this.metadata); + if (configResult.type === 'NONE') { + this.channel.queueCallForConfig(this); + return; + } + else if (configResult.type === 'ERROR') { + if (this.metadata.getOptions().waitForReady) { + this.channel.queueCallForConfig(this); + } + else { + this.outputStatus(configResult.error); + } + return; + } + // configResult.type === 'SUCCESS' + this.configReceivedTime = new Date(); + const config = configResult.config; + if (config.status !== constants_1.Status.OK) { + const { code, details } = (0, control_plane_status_1.restrictControlPlaneStatusCode)(config.status, 'Failed to route call to method ' + this.method); + this.outputStatus({ + code: code, + details: details, + metadata: new metadata_1.Metadata(), + }); + return; + } + if (config.methodConfig.timeout) { + const configDeadline = new Date(); + configDeadline.setSeconds(configDeadline.getSeconds() + config.methodConfig.timeout.seconds); + configDeadline.setMilliseconds(configDeadline.getMilliseconds() + + config.methodConfig.timeout.nanos / 1000000); + this.deadline = (0, deadline_1.minDeadline)(this.deadline, configDeadline); + this.runDeadlineTimer(); + } + this.filterStackFactory.push(config.dynamicFilterFactories); + this.filterStack = this.filterStackFactory.createFilter(); + this.filterStack.sendMetadata(Promise.resolve(this.metadata)).then(filteredMetadata => { + this.child = this.channel.createInnerCall(config, this.method, this.host, this.credentials, this.deadline); + this.trace('Created child [' + this.child.getCallNumber() + ']'); + this.childStartTime = new Date(); + this.child.start(filteredMetadata, { + onReceiveMetadata: metadata => { + this.trace('Received metadata'); + this.listener.onReceiveMetadata(this.filterStack.receiveMetadata(metadata)); + }, + onReceiveMessage: message => { + this.trace('Received message'); + this.readFilterPending = true; + this.filterStack.receiveMessage(message).then(filteredMesssage => { + this.trace('Finished filtering received message'); + this.readFilterPending = false; + this.listener.onReceiveMessage(filteredMesssage); + if (this.pendingChildStatus) { + this.outputStatus(this.pendingChildStatus); + } + }, (status) => { + this.cancelWithStatus(status.code, status.details); + }); + }, + onReceiveStatus: status => { + this.trace('Received status'); + if (this.readFilterPending) { + this.pendingChildStatus = status; + } + else { + this.outputStatus(status); + } + }, + }); + if (this.readPending) { + this.child.startRead(); + } + if (this.pendingMessage) { + this.sendMessageOnChild(this.pendingMessage.context, this.pendingMessage.message); + } + else if (this.pendingHalfClose) { + this.child.halfClose(); + } + }, (status) => { + this.outputStatus(status); + }); + } + reportResolverError(status) { + var _a; + if ((_a = this.metadata) === null || _a === void 0 ? void 0 : _a.getOptions().waitForReady) { + this.channel.queueCallForConfig(this); + } + else { + this.outputStatus(status); + } + } + cancelWithStatus(status, details) { + var _a; + this.trace('cancelWithStatus code: ' + status + ' details: "' + details + '"'); + (_a = this.child) === null || _a === void 0 ? void 0 : _a.cancelWithStatus(status, details); + this.outputStatus({ + code: status, + details: details, + metadata: new metadata_1.Metadata(), + }); + } + getPeer() { + var _a, _b; + return (_b = (_a = this.child) === null || _a === void 0 ? void 0 : _a.getPeer()) !== null && _b !== void 0 ? _b : this.channel.getTarget(); + } + start(metadata, listener) { + this.trace('start called'); + this.metadata = metadata.clone(); + this.listener = listener; + this.getConfig(); + } + sendMessageWithContext(context, message) { + this.trace('write() called with message of length ' + message.length); + if (this.child) { + this.sendMessageOnChild(context, message); + } + else { + this.pendingMessage = { context, message }; + } + } + startRead() { + this.trace('startRead called'); + if (this.child) { + this.child.startRead(); + } + else { + this.readPending = true; + } + } + halfClose() { + this.trace('halfClose called'); + if (this.child && !this.writeFilterPending) { + this.child.halfClose(); + } + else { + this.pendingHalfClose = true; + } + } + setCredentials(credentials) { + this.credentials = this.credentials.compose(credentials); + } + addStatusWatcher(watcher) { + this.statusWatchers.push(watcher); + } + getCallNumber() { + return this.callNumber; + } +} +exports.ResolvingCall = ResolvingCall; +//# sourceMappingURL=resolving-call.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/resolving-call.js.map b/node_modules/@grpc/grpc-js/build/src/resolving-call.js.map new file mode 100644 index 0000000..6ff518e --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/resolving-call.js.map @@ -0,0 +1 @@ +{"version":3,"file":"resolving-call.js","sourceRoot":"","sources":["../../src/resolving-call.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;GAeG;;;AAWH,2CAA8D;AAC9D,yCAMoB;AAGpB,yCAAsC;AACtC,qCAAqC;AACrC,iEAAwE;AAExE,MAAM,WAAW,GAAG,gBAAgB,CAAC;AAErC,MAAa,aAAa;IAsBxB,YACmB,OAAwB,EACxB,MAAc,EAC/B,OAA0B,EACT,kBAAsC,EAC/C,WAA4B,EAC5B,UAAkB;QALT,YAAO,GAAP,OAAO,CAAiB;QACxB,WAAM,GAAN,MAAM,CAAQ;QAEd,uBAAkB,GAAlB,kBAAkB,CAAoB;QAC/C,gBAAW,GAAX,WAAW,CAAiB;QAC5B,eAAU,GAAV,UAAU,CAAQ;QA3BpB,UAAK,GAAyC,IAAI,CAAC;QACnD,gBAAW,GAAG,KAAK,CAAC;QACpB,mBAAc,GACpB,IAAI,CAAC;QACC,qBAAgB,GAAG,KAAK,CAAC;QACzB,UAAK,GAAG,KAAK,CAAC;QACd,sBAAiB,GAAG,KAA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AI,CAAC,cAAc,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;IACpC,CAAC;IAED,aAAa;QACX,OAAO,IAAI,CAAC,UAAU,CAAC;IACzB,CAAC;CACF;AAjUD,sCAiUC"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/resolving-load-balancer.d.ts b/node_modules/@grpc/grpc-js/build/src/resolving-load-balancer.d.ts new file mode 100644 index 0000000..b93174e --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/resolving-load-balancer.d.ts @@ -0,0 +1,67 @@ +import { ChannelControlHelper, LoadBalancer, TypedLoadBalancingConfig } from './load-balancer'; +import { ServiceConfig } from './service-config'; +import { ConfigSelector } from './resolver'; +import { StatusObject } from './call-interface'; +import { Endpoint } from './subchannel-address'; +import { GrpcUri } from './uri-parser'; +import { ChannelOptions } from './channel-options'; +export interface ResolutionCallback { + (serviceConfig: ServiceConfig, configSelector: ConfigSelector): void; +} +export interface ResolutionFailureCallback { + (status: StatusObject): void; +} +export declare class ResolvingLoadBalancer implements LoadBalancer { + private readonly target; + private readonly channelControlHelper; + private readonly onSuccessfulResolution; + private readonly onFailedResolution; + /** + * The resolver class constructed for the target address. + */ + private readonly innerResolver; + private readonly childLoadBalancer; + private latestChildState; + private latestChildPicker; + /** + * This resolving load balancer's current connectivity state. + */ + private currentState; + private readonly defaultServiceConfig; + /** + * The service config object from the last successful resolution, if + * available. A value of null indicates that we have not yet received a valid + * service config from the resolver. + */ + private previousServiceConfig; + /** + * The backoff timer for handling name resolution failures. + */ + private readonly backoffTimeout; + /** + * Indicates whether we should attempt to resolve again after the backoff + * timer runs out. + */ + private continueResolving; + /** + * Wrapper class that behaves like a `LoadBalancer` and also handles name + * resolution internally. + * @param target The address of the backend to connect to. + * @param channelControlHelper `ChannelControlHelper` instance provided by + * this load balancer's owner. + * @param defaultServiceConfig The default service configuration to be used + * if none is provided by the name resolver. A `null` value indicates + * that the default behavior should be the default unconfigured behavior. + * In practice, that means using the "pick first" load balancer + * implmentation + */ + constructor(target: GrpcUri, channelControlHelper: ChannelControlHelper, channelOptions: ChannelOptions, onSuccessfulResolution: ResolutionCallback, onFailedResolution: ResolutionFailureCallback); + private updateResolution; + private updateState; + private handleResolutionFailure; + exitIdle(): void; + updateAddressList(endpointList: Endpoint[], lbConfig: TypedLoadBalancingConfig | null): never; + resetBackoff(): void; + destroy(): void; + getTypeName(): string; +} diff --git a/node_modules/@grpc/grpc-js/build/src/resolving-load-balancer.js b/node_modules/@grpc/grpc-js/build/src/resolving-load-balancer.js new file mode 100644 index 0000000..274b303 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/resolving-load-balancer.js @@ -0,0 +1,309 @@ +"use strict"; +/* + * Copyright 2019 gRPC authors. + * + * 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. + * + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ResolvingLoadBalancer = void 0; +const load_balancer_1 = require("./load-balancer"); +const service_config_1 = require("./service-config"); +const connectivity_state_1 = require("./connectivity-state"); +const resolver_1 = require("./resolver"); +const picker_1 = require("./picker"); +const backoff_timeout_1 = require("./backoff-timeout"); +const constants_1 = require("./constants"); +const metadata_1 = require("./metadata"); +const logging = require("./logging"); +const constants_2 = require("./constants"); +const uri_parser_1 = require("./uri-parser"); +const load_balancer_child_handler_1 = require("./load-balancer-child-handler"); +const TRACER_NAME = 'resolving_load_balancer'; +function trace(text) { + logging.trace(constants_2.LogVerbosity.DEBUG, TRACER_NAME, text); +} +/** + * Name match levels in order from most to least specific. This is the order in + * which searches will be performed. + */ +const NAME_MATCH_LEVEL_ORDER = [ + 'SERVICE_AND_METHOD', + 'SERVICE', + 'EMPTY', +]; +function hasMatchingName(service, method, methodConfig, matchLevel) { + for (const name of methodConfig.name) { + switch (matchLevel) { + case 'EMPTY': + if (!name.service && !name.method) { + return true; + } + break; + case 'SERVICE': + if (name.service === service && !name.method) { + return true; + } + break; + case 'SERVICE_AND_METHOD': + if (name.service === service && name.method === method) { + return true; + } + } + } + return false; +} +function findMatchingConfig(service, method, methodConfigs, matchLevel) { + for (const config of methodConfigs) { + if (hasMatchingName(service, method, config, matchLevel)) { + return config; + } + } + return null; +} +function getDefaultConfigSelector(serviceConfig) { + return function defaultConfigSelector(methodName, metadata) { + var _a, _b; + const splitName = methodName.split('/').filter(x => x.length > 0); + const service = (_a = splitName[0]) !== null && _a !== void 0 ? _a : ''; + const method = (_b = splitName[1]) !== null && _b !== void 0 ? _b : ''; + if (serviceConfig && serviceConfig.methodConfig) { + /* Check for the following in order, and return the first method + * config that matches: + * 1. A name that exactly matches the service and method + * 2. A name with no method set that matches the service + * 3. An empty name + */ + for (const matchLevel of NAME_MATCH_LEVEL_ORDER) { + const matchingConfig = findMatchingConfig(service, method, serviceConfig.methodConfig, matchLevel); + if (matchingConfig) { + return { + methodConfig: matchingConfig, + pickInformation: {}, + status: constants_1.Status.OK, + dynamicFilterFactories: [], + }; + } + } + } + return { + methodConfig: { name: [] }, + pickInformation: {}, + status: constants_1.Status.OK, + dynamicFilterFactories: [], + }; + }; +} +class ResolvingLoadBalancer { + /** + * Wrapper class that behaves like a `LoadBalancer` and also handles name + * resolution internally. + * @param target The address of the backend to connect to. + * @param channelControlHelper `ChannelControlHelper` instance provided by + * this load balancer's owner. + * @param defaultServiceConfig The default service configuration to be used + * if none is provided by the name resolver. A `null` value indicates + * that the default behavior should be the default unconfigured behavior. + * In practice, that means using the "pick first" load balancer + * implmentation + */ + constructor(target, channelControlHelper, channelOptions, onSuccessfulResolution, onFailedResolution) { + this.target = target; + this.channelControlHelper = channelControlHelper; + this.onSuccessfulResolution = onSuccessfulResolution; + this.onFailedResolution = onFailedResolution; + this.latestChildState = connectivity_state_1.ConnectivityState.IDLE; + this.latestChildPicker = new picker_1.QueuePicker(this); + /** + * This resolving load balancer's current connectivity state. + */ + this.currentState = connectivity_state_1.ConnectivityState.IDLE; + /** + * The service config object from the last successful resolution, if + * available. A value of null indicates that we have not yet received a valid + * service config from the resolver. + */ + this.previousServiceConfig = null; + /** + * Indicates whether we should attempt to resolve again after the backoff + * timer runs out. + */ + this.continueResolving = false; + if (channelOptions['grpc.service_config']) { + this.defaultServiceConfig = (0, service_config_1.validateServiceConfig)(JSON.parse(channelOptions['grpc.service_config'])); + } + else { + this.defaultServiceConfig = { + loadBalancingConfig: [], + methodConfig: [], + }; + } + this.updateState(connectivity_state_1.ConnectivityState.IDLE, new picker_1.QueuePicker(this)); + this.childLoadBalancer = new load_balancer_child_handler_1.ChildLoadBalancerHandler({ + createSubchannel: channelControlHelper.createSubchannel.bind(channelControlHelper), + requestReresolution: () => { + /* If the backoffTimeout is running, we're still backing off from + * making resolve requests, so we shouldn't make another one here. + * In that case, the backoff timer callback will call + * updateResolution */ + if (this.backoffTimeout.isRunning()) { + trace('requestReresolution delayed by backoff timer until ' + + this.backoffTimeout.getEndTime().toISOString()); + this.continueResolving = true; + } + else { + this.updateResolution(); + } + }, + updateState: (newState, picker) => { + this.latestChildState = newState; + this.latestChildPicker = picker; + this.updateState(newState, picker); + }, + addChannelzChild: channelControlHelper.addChannelzChild.bind(channelControlHelper), + removeChannelzChild: channelControlHelper.removeChannelzChild.bind(channelControlHelper), + }, channelOptions); + this.innerResolver = (0, resolver_1.createResolver)(target, { + onSuccessfulResolution: (endpointList, serviceConfig, serviceConfigError, configSelector, attributes) => { + var _a; + this.backoffTimeout.stop(); + this.backoffTimeout.reset(); + let workingServiceConfig = null; + /* This first group of conditionals implements the algorithm described + * in https://github.com/grpc/proposal/blob/master/A21-service-config-error-handling.md + * in the section called "Behavior on receiving a new gRPC Config". + */ + if (serviceConfig === null) { + // Step 4 and 5 + if (serviceConfigError === null) { + // Step 5 + this.previousServiceConfig = null; + workingServiceConfig = this.defaultServiceConfig; + } + else { + // Step 4 + if (this.previousServiceConfig === null) { + // Step 4.ii + this.handleResolutionFailure(serviceConfigError); + } + else { + // Step 4.i + workingServiceConfig = this.previousServiceConfig; + } + } + } + else { + // Step 3 + workingServiceConfig = serviceConfig; + this.previousServiceConfig = serviceConfig; + } + const workingConfigList = (_a = workingServiceConfig === null || workingServiceConfig === void 0 ? void 0 : workingServiceConfig.loadBalancingConfig) !== null && _a !== void 0 ? _a : []; + const loadBalancingConfig = (0, load_balancer_1.selectLbConfigFromList)(workingConfigList, true); + if (loadBalancingConfig === null) { + // There were load balancing configs but none are supported. This counts as a resolution failure + this.handleResolutionFailure({ + code: constants_1.Status.UNAVAILABLE, + details: 'All load balancer options in service config are not compatible', + metadata: new metadata_1.Metadata(), + }); + return; + } + this.childLoadBalancer.updateAddressList(endpointList, loadBalancingConfig, attributes); + const finalServiceConfig = workingServiceConfig !== null && workingServiceConfig !== void 0 ? workingServiceConfig : this.defaultServiceConfig; + this.onSuccessfulResolution(finalServiceConfig, configSelector !== null && configSelector !== void 0 ? configSelector : getDefaultConfigSelector(finalServiceConfig)); + }, + onError: (error) => { + this.handleResolutionFailure(error); + }, + }, channelOptions); + const backoffOptions = { + initialDelay: channelOptions['grpc.initial_reconnect_backoff_ms'], + maxDelay: channelOptions['grpc.max_reconnect_backoff_ms'], + }; + this.backoffTimeout = new backoff_timeout_1.BackoffTimeout(() => { + if (this.continueResolving) { + this.updateResolution(); + this.continueResolving = false; + } + else { + this.updateState(this.latestChildState, this.latestChildPicker); + } + }, backoffOptions); + this.backoffTimeout.unref(); + } + updateResolution() { + this.innerResolver.updateResolution(); + if (this.currentState === connectivity_state_1.ConnectivityState.IDLE) { + /* this.latestChildPicker is initialized as new QueuePicker(this), which + * is an appropriate value here if the child LB policy is unset. + * Otherwise, we want to delegate to the child here, in case that + * triggers something. */ + this.updateState(connectivity_state_1.ConnectivityState.CONNECTING, this.latestChildPicker); + } + this.backoffTimeout.runOnce(); + } + updateState(connectivityState, picker) { + trace((0, uri_parser_1.uriToString)(this.target) + + ' ' + + connectivity_state_1.ConnectivityState[this.currentState] + + ' -> ' + + connectivity_state_1.ConnectivityState[connectivityState]); + // Ensure that this.exitIdle() is called by the picker + if (connectivityState === connectivity_state_1.ConnectivityState.IDLE) { + picker = new picker_1.QueuePicker(this, picker); + } + this.currentState = connectivityState; + this.channelControlHelper.updateState(connectivityState, picker); + } + handleResolutionFailure(error) { + if (this.latestChildState === connectivity_state_1.ConnectivityState.IDLE) { + this.updateState(connectivity_state_1.ConnectivityState.TRANSIENT_FAILURE, new picker_1.UnavailablePicker(error)); + this.onFailedResolution(error); + } + } + exitIdle() { + if (this.currentState === connectivity_state_1.ConnectivityState.IDLE || + this.currentState === connectivity_state_1.ConnectivityState.TRANSIENT_FAILURE) { + if (this.backoffTimeout.isRunning()) { + this.continueResolving = true; + } + else { + this.updateResolution(); + } + } + this.childLoadBalancer.exitIdle(); + } + updateAddressList(endpointList, lbConfig) { + throw new Error('updateAddressList not supported on ResolvingLoadBalancer'); + } + resetBackoff() { + this.backoffTimeout.reset(); + this.childLoadBalancer.resetBackoff(); + } + destroy() { + this.childLoadBalancer.destroy(); + this.innerResolver.destroy(); + this.backoffTimeout.reset(); + this.backoffTimeout.stop(); + this.latestChildState = connectivity_state_1.ConnectivityState.IDLE; + this.latestChildPicker = new picker_1.QueuePicker(this); + this.currentState = connectivity_state_1.ConnectivityState.IDLE; + this.previousServiceConfig = null; + this.continueResolving = false; + } + getTypeName() { + return 'resolving_load_balancer'; + } +} +exports.ResolvingLoadBalancer = ResolvingLoadBalancer; +//# sourceMappingURL=resolving-load-balancer.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/resolving-load-balancer.js.map b/node_modules/@grpc/grpc-js/build/src/resolving-load-balancer.js.map new file mode 100644 index 0000000..c22181d --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/resolving-load-balancer.js.map @@ -0,0 +1 @@ +{"version":3,"file":"resolving-load-balancer.js","sourceRoot":"","sources":["../../src/resolving-load-balancer.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;GAeG;;;AAEH,mDAKyB;AACzB,qDAI0B;AAC1B,6DAAyD;AACzD,yCAAsE;AAEtE,qCAAkE;AAClE,uDAAmE;AACnE,2CAAqC;AAErC,yCAAsC;AACtC,qCAAqC;AACrC,2CAA2C;AAE3C,6CAAoD;AACpD,+EAAyE;AAGzE,MAAM,WAAW,GAAG,yBAAyB,CAAC;AAE9C,SAAS,KAAK,CAAC,IAAY;IACzB,OAAO,CAAC,KAAK,CAAC,wBAAY,CAAC,KAAK,EAAE,WAAW,EAAE,IAAI,CAAC,CAAC;AACvD,CAAC;AAID;;;GAGG;AACH,MAAM,sBAAsB,GAAqB;IAC/C,oBAAoB;IACpB,SAAS;IACT,OAAO;CACR,CAAC;AAEF,SAAS,eAAe,CACtB,OAAe,EACf,MAAc,EACd,YAA0B,EAC1B,UAA0B;IAE1B,KAAK,MAAM,IAAI,IAAI,YAAY,CAAC,IAAI,EAAE,CAAC;QACrC,QAAQ,UAAU,EAAE,CAAC;YACnB,KAAK,OAAO;gBACV,IAAI,CAAC,IAAI,CAAC,OAAO,IAAI,CAAC,IAAI,CAAC,MAAM,EAAE,CAAC;oBAClC,OAAO,IAAI,CAAC;gBACd,CAAC;gBACD,MAAM;YACR,KAAK,SAAS;gBACZ,IAAI,IAAI,CAAC,OAAO,KAAK,OAAO,IAAI,CAAC,IAAI,CAAC,MAAM,EAAE,CAAC;oBAC7C,OAAO,IAAI,CAAC;gBACd,CAAC;gBACD,MAAM;YACR,KAAK,oBAAoB;gBACvB,IAAI,IAAI,CAAC,OAAO,KAAK,OAAO,IAAI,IAAI,CAAC,MAAM,KAAK,MAAM,EAAE,CAAC;oBACvD,OAAO,IAAI,CAAC;gBACd,CAAC;QACL,CAAC;IACH,CAAC;IACD,OAAO,KAAK,CAAC;AACf,CAAC;AAED,SAAS,kBAAkB,CACzB,OAA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AAI,CAAC,iBAAiB,GAAG,IAAI,oBAAW,CAAC,IAAI,CAAC,CAAC;QAC/C,IAAI,CAAC,YAAY,GAAG,sCAAiB,CAAC,IAAI,CAAC;QAC3C,IAAI,CAAC,qBAAqB,GAAG,IAAI,CAAC;QAClC,IAAI,CAAC,iBAAiB,GAAG,KAAK,CAAC;IACjC,CAAC;IAED,WAAW;QACT,OAAO,yBAAyB,CAAC;IACnC,CAAC;CACF;AApQD,sDAoQC"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/retrying-call.d.ts b/node_modules/@grpc/grpc-js/build/src/retrying-call.d.ts new file mode 100644 index 0000000..9f99f47 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/retrying-call.d.ts @@ -0,0 +1,97 @@ +/// +import { CallCredentials } from './call-credentials'; +import { Status } from './constants'; +import { Deadline } from './deadline'; +import { Metadata } from './metadata'; +import { CallConfig } from './resolver'; +import { Call, DeadlineInfoProvider, InterceptingListener, MessageContext } from './call-interface'; +import { InternalChannel } from './internal-channel'; +export declare class RetryThrottler { + private readonly maxTokens; + private readonly tokenRatio; + private tokens; + constructor(maxTokens: number, tokenRatio: number, previousRetryThrottler?: RetryThrottler); + addCallSucceeded(): void; + addCallFailed(): void; + canRetryCall(): boolean; +} +export declare class MessageBufferTracker { + private totalLimit; + private limitPerCall; + private totalAllocated; + private allocatedPerCall; + constructor(totalLimit: number, limitPerCall: number); + allocate(size: number, callId: number): boolean; + free(size: number, callId: number): void; + freeAll(callId: number): void; +} +export declare class RetryingCall implements Call, DeadlineInfoProvider { + private readonly channel; + private readonly callConfig; + private readonly methodName; + private readonly host; + private readonly credentials; + private readonly deadline; + private readonly callNumber; + private readonly bufferTracker; + private readonly retryThrottler?; + private state; + private listener; + private initialMetadata; + private underlyingCalls; + private writeBuffer; + /** + * The offset of message indices in the writeBuffer. For example, if + * writeBufferOffset is 10, message 10 is in writeBuffer[0] and message 15 + * is in writeBuffer[5]. + */ + private writeBufferOffset; + /** + * Tracks whether a read has been started, so that we know whether to start + * reads on new child calls. This only matters for the first read, because + * once a message comes in the child call becomes committed and there will + * be no new child calls. + */ + private readStarted; + private transparentRetryUsed; + /** + * Number of attempts so far + */ + private attempts; + private hedgingTimer; + private committedCallIndex; + private initialRetryBackoffSec; + private nextRetryBackoffSec; + private startTime; + constructor(channel: InternalChannel, callConfig: CallConfig, methodName: string, host: string, credentials: CallCredentials, deadline: Deadline, callNumber: number, bufferTracker: MessageBufferTracker, retryThrottler?: RetryThrottler | undefined); + getDeadlineInfo(): string[]; + getCallNumber(): number; + private trace; + private reportStatus; + cancelWithStatus(status: Status, details: string): void; + getPeer(): string; + private getBufferEntry; + private getNextBufferIndex; + private clearSentMessages; + private commitCall; + private commitCallWithMostMessages; + private isStatusCodeInList; + private getNextRetryBackoffMs; + private maybeRetryCall; + private countActiveCalls; + private handleProcessedStatus; + private getPushback; + private handleChildStatus; + private maybeStartHedgingAttempt; + private maybeStartHedgingTimer; + private startNewAttempt; + start(metadata: Metadata, listener: InterceptingListener): void; + private handleChildWriteCompleted; + private sendNextChildMessage; + sendMessageWithContext(context: MessageContext, message: Buffer): void; + startRead(): void; + halfClose(): void; + setCredentials(newCredentials: CallCredentials): void; + getMethod(): string; + getHost(): string; +} diff --git a/node_modules/@grpc/grpc-js/build/src/retrying-call.js b/node_modules/@grpc/grpc-js/build/src/retrying-call.js new file mode 100644 index 0000000..a4bdfe4 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/retrying-call.js @@ -0,0 +1,658 @@ +"use strict"; +/* + * Copyright 2022 gRPC authors. + * + * 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. + * + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.RetryingCall = exports.MessageBufferTracker = exports.RetryThrottler = void 0; +const constants_1 = require("./constants"); +const deadline_1 = require("./deadline"); +const metadata_1 = require("./metadata"); +const logging = require("./logging"); +const TRACER_NAME = 'retrying_call'; +class RetryThrottler { + constructor(maxTokens, tokenRatio, previousRetryThrottler) { + this.maxTokens = maxTokens; + this.tokenRatio = tokenRatio; + if (previousRetryThrottler) { + /* When carrying over tokens from a previous config, rescale them to the + * new max value */ + this.tokens = + previousRetryThrottler.tokens * + (maxTokens / previousRetryThrottler.maxTokens); + } + else { + this.tokens = maxTokens; + } + } + addCallSucceeded() { + this.tokens = Math.max(this.tokens + this.tokenRatio, this.maxTokens); + } + addCallFailed() { + this.tokens = Math.min(this.tokens - 1, 0); + } + canRetryCall() { + return this.tokens > this.maxTokens / 2; + } +} +exports.RetryThrottler = RetryThrottler; +class MessageBufferTracker { + constructor(totalLimit, limitPerCall) { + this.totalLimit = totalLimit; + this.limitPerCall = limitPerCall; + this.totalAllocated = 0; + this.allocatedPerCall = new Map(); + } + allocate(size, callId) { + var _a; + const currentPerCall = (_a = this.allocatedPerCall.get(callId)) !== null && _a !== void 0 ? _a : 0; + if (this.limitPerCall - currentPerCall < size || + this.totalLimit - this.totalAllocated < size) { + return false; + } + this.allocatedPerCall.set(callId, currentPerCall + size); + this.totalAllocated += size; + return true; + } + free(size, callId) { + var _a; + if (this.totalAllocated < size) { + throw new Error(`Invalid buffer allocation state: call ${callId} freed ${size} > total allocated ${this.totalAllocated}`); + } + this.totalAllocated -= size; + const currentPerCall = (_a = this.allocatedPerCall.get(callId)) !== null && _a !== void 0 ? _a : 0; + if (currentPerCall < size) { + throw new Error(`Invalid buffer allocation state: call ${callId} freed ${size} > allocated for call ${currentPerCall}`); + } + this.allocatedPerCall.set(callId, currentPerCall - size); + } + freeAll(callId) { + var _a; + const currentPerCall = (_a = this.allocatedPerCall.get(callId)) !== null && _a !== void 0 ? _a : 0; + if (this.totalAllocated < currentPerCall) { + throw new Error(`Invalid buffer allocation state: call ${callId} allocated ${currentPerCall} > total allocated ${this.totalAllocated}`); + } + this.totalAllocated -= currentPerCall; + this.allocatedPerCall.delete(callId); + } +} +exports.MessageBufferTracker = MessageBufferTracker; +const PREVIONS_RPC_ATTEMPTS_METADATA_KEY = 'grpc-previous-rpc-attempts'; +class RetryingCall { + constructor(channel, callConfig, methodName, host, credentials, deadline, callNumber, bufferTracker, retryThrottler) { + this.channel = channel; + this.callConfig = callConfig; + this.methodName = methodName; + this.host = host; + this.credentials = credentials; + this.deadline = deadline; + this.callNumber = callNumber; + this.bufferTracker = bufferTracker; + this.retryThrottler = retryThrottler; + this.listener = null; + this.initialMetadata = null; + this.underlyingCalls = []; + this.writeBuffer = []; + /** + * The offset of message indices in the writeBuffer. For example, if + * writeBufferOffset is 10, message 10 is in writeBuffer[0] and message 15 + * is in writeBuffer[5]. + */ + this.writeBufferOffset = 0; + /** + * Tracks whether a read has been started, so that we know whether to start + * reads on new child calls. This only matters for the first read, because + * once a message comes in the child call becomes committed and there will + * be no new child calls. + */ + this.readStarted = false; + this.transparentRetryUsed = false; + /** + * Number of attempts so far + */ + this.attempts = 0; + this.hedgingTimer = null; + this.committedCallIndex = null; + this.initialRetryBackoffSec = 0; + this.nextRetryBackoffSec = 0; + if (callConfig.methodConfig.retryPolicy) { + this.state = 'RETRY'; + const retryPolicy = callConfig.methodConfig.retryPolicy; + this.nextRetryBackoffSec = this.initialRetryBackoffSec = Number(retryPolicy.initialBackoff.substring(0, retryPolicy.initialBackoff.length - 1)); + } + else if (callConfig.methodConfig.hedgingPolicy) { + this.state = 'HEDGING'; + } + else { + this.state = 'TRANSPARENT_ONLY'; + } + this.startTime = new Date(); + } + getDeadlineInfo() { + if (this.underlyingCalls.length === 0) { + return []; + } + const deadlineInfo = []; + const latestCall = this.underlyingCalls[this.underlyingCalls.length - 1]; + if (this.underlyingCalls.length > 1) { + deadlineInfo.push(`previous attempts: ${this.underlyingCalls.length - 1}`); + } + if (latestCall.startTime > this.startTime) { + deadlineInfo.push(`time to current attempt start: ${(0, deadline_1.formatDateDifference)(this.startTime, latestCall.startTime)}`); + } + deadlineInfo.push(...latestCall.call.getDeadlineInfo()); + return deadlineInfo; + } + getCallNumber() { + return this.callNumber; + } + trace(text) { + logging.trace(constants_1.LogVerbosity.DEBUG, TRACER_NAME, '[' + this.callNumber + '] ' + text); + } + reportStatus(statusObject) { + this.trace('ended with status: code=' + + statusObject.code + + ' details="' + + statusObject.details + + '" start time=' + + this.startTime.toISOString()); + this.bufferTracker.freeAll(this.callNumber); + this.writeBufferOffset = this.writeBufferOffset + this.writeBuffer.length; + this.writeBuffer = []; + process.nextTick(() => { + var _a; + // Explicitly construct status object to remove progress field + (_a = this.listener) === null || _a === void 0 ? void 0 : _a.onReceiveStatus({ + code: statusObject.code, + details: statusObject.details, + metadata: statusObject.metadata, + }); + }); + } + cancelWithStatus(status, details) { + this.trace('cancelWithStatus code: ' + status + ' details: "' + details + '"'); + this.reportStatus({ code: status, details, metadata: new metadata_1.Metadata() }); + for (const { call } of this.underlyingCalls) { + call.cancelWithStatus(status, details); + } + } + getPeer() { + if (this.committedCallIndex !== null) { + return this.underlyingCalls[this.committedCallIndex].call.getPeer(); + } + else { + return 'unknown'; + } + } + getBufferEntry(messageIndex) { + var _a; + return ((_a = this.writeBuffer[messageIndex - this.writeBufferOffset]) !== null && _a !== void 0 ? _a : { + entryType: 'FREED', + allocated: false, + }); + } + getNextBufferIndex() { + return this.writeBufferOffset + this.writeBuffer.length; + } + clearSentMessages() { + if (this.state !== 'COMMITTED') { + return; + } + const earliestNeededMessageIndex = this.underlyingCalls[this.committedCallIndex].nextMessageToSend; + for (let messageIndex = this.writeBufferOffset; messageIndex < earliestNeededMessageIndex; messageIndex++) { + const bufferEntry = this.getBufferEntry(messageIndex); + if (bufferEntry.allocated) { + this.bufferTracker.free(bufferEntry.message.message.length, this.callNumber); + } + } + this.writeBuffer = this.writeBuffer.slice(earliestNeededMessageIndex - this.writeBufferOffset); + this.writeBufferOffset = earliestNeededMessageIndex; + } + commitCall(index) { + if (this.state === 'COMMITTED') { + return; + } + if (this.underlyingCalls[index].state === 'COMPLETED') { + return; + } + this.trace('Committing call [' + + this.underlyingCalls[index].call.getCallNumber() + + '] at index ' + + index); + this.state = 'COMMITTED'; + this.committedCallIndex = index; + for (let i = 0; i < this.underlyingCalls.length; i++) { + if (i === index) { + continue; + } + if (this.underlyingCalls[i].state === 'COMPLETED') { + continue; + } + this.underlyingCalls[i].state = 'COMPLETED'; + this.underlyingCalls[i].call.cancelWithStatus(constants_1.Status.CANCELLED, 'Discarded in favor of other hedged attempt'); + } + this.clearSentMessages(); + } + commitCallWithMostMessages() { + if (this.state === 'COMMITTED') { + return; + } + let mostMessages = -1; + let callWithMostMessages = -1; + for (const [index, childCall] of this.underlyingCalls.entries()) { + if (childCall.state === 'ACTIVE' && + childCall.nextMessageToSend > mostMessages) { + mostMessages = childCall.nextMessageToSend; + callWithMostMessages = index; + } + } + if (callWithMostMessages === -1) { + /* There are no active calls, disable retries to force the next call that + * is started to be committed. */ + this.state = 'TRANSPARENT_ONLY'; + } + else { + this.commitCall(callWithMostMessages); + } + } + isStatusCodeInList(list, code) { + return list.some(value => value === code || + value.toString().toLowerCase() === constants_1.Status[code].toLowerCase()); + } + getNextRetryBackoffMs() { + var _a; + const retryPolicy = (_a = this.callConfig) === null || _a === void 0 ? void 0 : _a.methodConfig.retryPolicy; + if (!retryPolicy) { + return 0; + } + const nextBackoffMs = Math.random() * this.nextRetryBackoffSec * 1000; + const maxBackoffSec = Number(retryPolicy.maxBackoff.substring(0, retryPolicy.maxBackoff.length - 1)); + this.nextRetryBackoffSec = Math.min(this.nextRetryBackoffSec * retryPolicy.backoffMultiplier, maxBackoffSec); + return nextBackoffMs; + } + maybeRetryCall(pushback, callback) { + if (this.state !== 'RETRY') { + callback(false); + return; + } + const retryPolicy = this.callConfig.methodConfig.retryPolicy; + if (this.attempts >= Math.min(retryPolicy.maxAttempts, 5)) { + callback(false); + return; + } + let retryDelayMs; + if (pushback === null) { + retryDelayMs = this.getNextRetryBackoffMs(); + } + else if (pushback < 0) { + this.state = 'TRANSPARENT_ONLY'; + callback(false); + return; + } + else { + retryDelayMs = pushback; + this.nextRetryBackoffSec = this.initialRetryBackoffSec; + } + setTimeout(() => { + var _a, _b; + if (this.state !== 'RETRY') { + callback(false); + return; + } + if ((_b = (_a = this.retryThrottler) === null || _a === void 0 ? void 0 : _a.canRetryCall()) !== null && _b !== void 0 ? _b : true) { + callback(true); + this.attempts += 1; + this.startNewAttempt(); + } + }, retryDelayMs); + } + countActiveCalls() { + let count = 0; + for (const call of this.underlyingCalls) { + if ((call === null || call === void 0 ? void 0 : call.state) === 'ACTIVE') { + count += 1; + } + } + return count; + } + handleProcessedStatus(status, callIndex, pushback) { + var _a, _b, _c; + switch (this.state) { + case 'COMMITTED': + case 'TRANSPARENT_ONLY': + this.commitCall(callIndex); + this.reportStatus(status); + break; + case 'HEDGING': + if (this.isStatusCodeInList((_a = this.callConfig.methodConfig.hedgingPolicy.nonFatalStatusCodes) !== null && _a !== void 0 ? _a : [], status.code)) { + (_b = this.retryThrottler) === null || _b === void 0 ? void 0 : _b.addCallFailed(); + let delayMs; + if (pushback === null) { + delayMs = 0; + } + else if (pushback < 0) { + this.state = 'TRANSPARENT_ONLY'; + this.commitCall(callIndex); + this.reportStatus(status); + return; + } + else { + delayMs = pushback; + } + setTimeout(() => { + this.maybeStartHedgingAttempt(); + // If after trying to start a call there are no active calls, this was the last one + if (this.countActiveCalls() === 0) { + this.commitCall(callIndex); + this.reportStatus(status); + } + }, delayMs); + } + else { + this.commitCall(callIndex); + this.reportStatus(status); + } + break; + case 'RETRY': + if (this.isStatusCodeInList(this.callConfig.methodConfig.retryPolicy.retryableStatusCodes, status.code)) { + (_c = this.retryThrottler) === null || _c === void 0 ? void 0 : _c.addCallFailed(); + this.maybeRetryCall(pushback, retried => { + if (!retried) { + this.commitCall(callIndex); + this.reportStatus(status); + } + }); + } + else { + this.commitCall(callIndex); + this.reportStatus(status); + } + break; + } + } + getPushback(metadata) { + const mdValue = metadata.get('grpc-retry-pushback-ms'); + if (mdValue.length === 0) { + return null; + } + try { + return parseInt(mdValue[0]); + } + catch (e) { + return -1; + } + } + handleChildStatus(status, callIndex) { + var _a; + if (this.underlyingCalls[callIndex].state === 'COMPLETED') { + return; + } + this.trace('state=' + + this.state + + ' handling status with progress ' + + status.progress + + ' from child [' + + this.underlyingCalls[callIndex].call.getCallNumber() + + '] in state ' + + this.underlyingCalls[callIndex].state); + this.underlyingCalls[callIndex].state = 'COMPLETED'; + if (status.code === constants_1.Status.OK) { + (_a = this.retryThrottler) === null || _a === void 0 ? void 0 : _a.addCallSucceeded(); + this.commitCall(callIndex); + this.reportStatus(status); + return; + } + if (this.state === 'COMMITTED') { + this.reportStatus(status); + return; + } + const pushback = this.getPushback(status.metadata); + switch (status.progress) { + case 'NOT_STARTED': + // RPC never leaves the client, always safe to retry + this.startNewAttempt(); + break; + case 'REFUSED': + // RPC reaches the server library, but not the server application logic + if (this.transparentRetryUsed) { + this.handleProcessedStatus(status, callIndex, pushback); + } + else { + this.transparentRetryUsed = true; + this.startNewAttempt(); + } + break; + case 'DROP': + this.commitCall(callIndex); + this.reportStatus(status); + break; + case 'PROCESSED': + this.handleProcessedStatus(status, callIndex, pushback); + break; + } + } + maybeStartHedgingAttempt() { + if (this.state !== 'HEDGING') { + return; + } + if (!this.callConfig.methodConfig.hedgingPolicy) { + return; + } + const hedgingPolicy = this.callConfig.methodConfig.hedgingPolicy; + if (this.attempts >= Math.min(hedgingPolicy.maxAttempts, 5)) { + return; + } + this.attempts += 1; + this.startNewAttempt(); + this.maybeStartHedgingTimer(); + } + maybeStartHedgingTimer() { + var _a, _b, _c; + if (this.hedgingTimer) { + clearTimeout(this.hedgingTimer); + } + if (this.state !== 'HEDGING') { + return; + } + if (!this.callConfig.methodConfig.hedgingPolicy) { + return; + } + const hedgingPolicy = this.callConfig.methodConfig.hedgingPolicy; + if (this.attempts >= Math.min(hedgingPolicy.maxAttempts, 5)) { + return; + } + const hedgingDelayString = (_a = hedgingPolicy.hedgingDelay) !== null && _a !== void 0 ? _a : '0s'; + const hedgingDelaySec = Number(hedgingDelayString.substring(0, hedgingDelayString.length - 1)); + this.hedgingTimer = setTimeout(() => { + this.maybeStartHedgingAttempt(); + }, hedgingDelaySec * 1000); + (_c = (_b = this.hedgingTimer).unref) === null || _c === void 0 ? void 0 : _c.call(_b); + } + startNewAttempt() { + const child = this.channel.createLoadBalancingCall(this.callConfig, this.methodName, this.host, this.credentials, this.deadline); + this.trace('Created child call [' + + child.getCallNumber() + + '] for attempt ' + + this.attempts); + const index = this.underlyingCalls.length; + this.underlyingCalls.push({ + state: 'ACTIVE', + call: child, + nextMessageToSend: 0, + startTime: new Date() + }); + const previousAttempts = this.attempts - 1; + const initialMetadata = this.initialMetadata.clone(); + if (previousAttempts > 0) { + initialMetadata.set(PREVIONS_RPC_ATTEMPTS_METADATA_KEY, `${previousAttempts}`); + } + let receivedMetadata = false; + child.start(initialMetadata, { + onReceiveMetadata: metadata => { + this.trace('Received metadata from child [' + child.getCallNumber() + ']'); + this.commitCall(index); + receivedMetadata = true; + if (previousAttempts > 0) { + metadata.set(PREVIONS_RPC_ATTEMPTS_METADATA_KEY, `${previousAttempts}`); + } + if (this.underlyingCalls[index].state === 'ACTIVE') { + this.listener.onReceiveMetadata(metadata); + } + }, + onReceiveMessage: message => { + this.trace('Received message from child [' + child.getCallNumber() + ']'); + this.commitCall(index); + if (this.underlyingCalls[index].state === 'ACTIVE') { + this.listener.onReceiveMessage(message); + } + }, + onReceiveStatus: status => { + this.trace('Received status from child [' + child.getCallNumber() + ']'); + if (!receivedMetadata && previousAttempts > 0) { + status.metadata.set(PREVIONS_RPC_ATTEMPTS_METADATA_KEY, `${previousAttempts}`); + } + this.handleChildStatus(status, index); + }, + }); + this.sendNextChildMessage(index); + if (this.readStarted) { + child.startRead(); + } + } + start(metadata, listener) { + this.trace('start called'); + this.listener = listener; + this.initialMetadata = metadata; + this.attempts += 1; + this.startNewAttempt(); + this.maybeStartHedgingTimer(); + } + handleChildWriteCompleted(childIndex) { + var _a, _b; + const childCall = this.underlyingCalls[childIndex]; + const messageIndex = childCall.nextMessageToSend; + (_b = (_a = this.getBufferEntry(messageIndex)).callback) === null || _b === void 0 ? void 0 : _b.call(_a); + this.clearSentMessages(); + childCall.nextMessageToSend += 1; + this.sendNextChildMessage(childIndex); + } + sendNextChildMessage(childIndex) { + const childCall = this.underlyingCalls[childIndex]; + if (childCall.state === 'COMPLETED') { + return; + } + if (this.getBufferEntry(childCall.nextMessageToSend)) { + const bufferEntry = this.getBufferEntry(childCall.nextMessageToSend); + switch (bufferEntry.entryType) { + case 'MESSAGE': + childCall.call.sendMessageWithContext({ + callback: error => { + // Ignore error + this.handleChildWriteCompleted(childIndex); + }, + }, bufferEntry.message.message); + break; + case 'HALF_CLOSE': + childCall.nextMessageToSend += 1; + childCall.call.halfClose(); + break; + case 'FREED': + // Should not be possible + break; + } + } + } + sendMessageWithContext(context, message) { + var _a; + this.trace('write() called with message of length ' + message.length); + const writeObj = { + message, + flags: context.flags, + }; + const messageIndex = this.getNextBufferIndex(); + const bufferEntry = { + entryType: 'MESSAGE', + message: writeObj, + allocated: this.bufferTracker.allocate(message.length, this.callNumber), + }; + this.writeBuffer.push(bufferEntry); + if (bufferEntry.allocated) { + (_a = context.callback) === null || _a === void 0 ? void 0 : _a.call(context); + for (const [callIndex, call] of this.underlyingCalls.entries()) { + if (call.state === 'ACTIVE' && + call.nextMessageToSend === messageIndex) { + call.call.sendMessageWithContext({ + callback: error => { + // Ignore error + this.handleChildWriteCompleted(callIndex); + }, + }, message); + } + } + } + else { + this.commitCallWithMostMessages(); + // commitCallWithMostMessages can fail if we are between ping attempts + if (this.committedCallIndex === null) { + return; + } + const call = this.underlyingCalls[this.committedCallIndex]; + bufferEntry.callback = context.callback; + if (call.state === 'ACTIVE' && call.nextMessageToSend === messageIndex) { + call.call.sendMessageWithContext({ + callback: error => { + // Ignore error + this.handleChildWriteCompleted(this.committedCallIndex); + }, + }, message); + } + } + } + startRead() { + this.trace('startRead called'); + this.readStarted = true; + for (const underlyingCall of this.underlyingCalls) { + if ((underlyingCall === null || underlyingCall === void 0 ? void 0 : underlyingCall.state) === 'ACTIVE') { + underlyingCall.call.startRead(); + } + } + } + halfClose() { + this.trace('halfClose called'); + const halfCloseIndex = this.getNextBufferIndex(); + this.writeBuffer.push({ + entryType: 'HALF_CLOSE', + allocated: false, + }); + for (const call of this.underlyingCalls) { + if ((call === null || call === void 0 ? void 0 : call.state) === 'ACTIVE' && + call.nextMessageToSend === halfCloseIndex) { + call.nextMessageToSend += 1; + call.call.halfClose(); + } + } + } + setCredentials(newCredentials) { + throw new Error('Method not implemented.'); + } + getMethod() { + return this.methodName; + } + getHost() { + return this.host; + } +} +exports.RetryingCall = RetryingCall; +//# sourceMappingURL=retrying-call.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/retrying-call.js.map b/node_modules/@grpc/grpc-js/build/src/retrying-call.js.map new file mode 100644 index 0000000..b30e3da --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/retrying-call.js.map @@ -0,0 +1 @@ +{"version":3,"file":"retrying-call.js","sourceRoot":"","sources":["../../src/retrying-call.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;GAeG;;;AAGH,2CAAmD;AACnD,yCAA4D;AAC5D,yCAAsC;AAEtC,qCAAqC;AAgBrC,MAAM,WAAW,GAAG,eAAe,CAAC;AAEpC,MAAa,cAAc;IAEzB,YACmB,SAAiB,EACjB,UAAkB,EACnC,sBAAuC;QAFtB,cAAS,GAAT,SAAS,CAAQ;QACjB,eAAU,GAAV,UAAU,CAAQ;QAGnC,IAAI,sBAAsB,EAAE,CAAC;YAC3B;+BACmB;YACnB,IAAI,CAAC,MAAM;gBACT,sBAAsB,CAAC,MAAM;oBAC7B,CAAC,SAAS,GAAG,sBAAsB,CAAC,SAAS,CAAC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AAI,CAAC,kBAAkB,EAAE,CAAC;QACjD,IAAI,CAAC,WAAW,CAAC,IAAI,CAAC;YACpB,SAAS,EAAE,YAAY;YACvB,SAAS,EAAE,KAAK;SACjB,CAAC,CAAC;QACH,KAAK,MAAM,IAAI,IAAI,IAAI,CAAC,eAAe,EAAE,CAAC;YACxC,IACE,CAAA,IAAI,aAAJ,IAAI,uBAAJ,IAAI,CAAE,KAAK,MAAK,QAAQ;gBACxB,IAAI,CAAC,iBAAiB,KAAK,cAAc,EACzC,CAAC;gBACD,IAAI,CAAC,iBAAiB,IAAI,CAAC,CAAC;gBAC5B,IAAI,CAAC,IAAI,CAAC,SAAS,EAAE,CAAC;YACxB,CAAC;QACH,CAAC;IACH,CAAC;IACD,cAAc,CAAC,cAA+B;QAC5C,MAAM,IAAI,KAAK,CAAC,yBAAyB,CAAC,CAAC;IAC7C,CAAC;IACD,SAAS;QACP,OAAO,IAAI,CAAC,UAAU,CAAC;IACzB,CAAC;IACD,OAAO;QACL,OAAO,IAAI,CAAC,IAAI,CAAC;IACnB,CAAC;CACF;AA3pBD,oCA2pBC"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/server-call.d.ts b/node_modules/@grpc/grpc-js/build/src/server-call.d.ts new file mode 100644 index 0000000..a96a52a --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/server-call.d.ts @@ -0,0 +1,126 @@ +/// +/// +import { EventEmitter } from 'events'; +import { Duplex, Readable, Writable } from 'stream'; +import type { Deserialize, Serialize } from './make-client'; +import { Metadata } from './metadata'; +import type { ObjectReadable, ObjectWritable } from './object-stream'; +import type { StatusObject, PartialStatusObject } from './call-interface'; +import type { Deadline } from './deadline'; +import type { ServerInterceptingCallInterface } from './server-interceptors'; +export type ServerStatusResponse = Partial; +export type ServerErrorResponse = ServerStatusResponse & Error; +export type ServerSurfaceCall = { + cancelled: boolean; + readonly metadata: Metadata; + getPeer(): string; + sendMetadata(responseMetadata: Metadata): void; + getDeadline(): Deadline; + getPath(): string; +} & EventEmitter; +export type ServerUnaryCall = ServerSurfaceCall & { + request: RequestType; +}; +export type ServerReadableStream = ServerSurfaceCall & ObjectReadable; +export type ServerWritableStream = ServerSurfaceCall & ObjectWritable & { + request: RequestType; + end: (metadata?: Metadata) => void; +}; +export type ServerDuplexStream = ServerSurfaceCall & ObjectReadable & ObjectWritable & { + end: (metadata?: Metadata) => void; +}; +export declare function serverErrorToStatus(error: ServerErrorResponse | ServerStatusResponse, overrideTrailers?: Metadata | undefined): PartialStatusObject; +export declare class ServerUnaryCallImpl extends EventEmitter implements ServerUnaryCall { + private path; + private call; + metadata: Metadata; + request: RequestType; + cancelled: boolean; + constructor(path: string, call: ServerInterceptingCallInterface, metadata: Metadata, request: RequestType); + getPeer(): string; + sendMetadata(responseMetadata: Metadata): void; + getDeadline(): Deadline; + getPath(): string; +} +export declare class ServerReadableStreamImpl extends Readable implements ServerReadableStream { + private path; + private call; + metadata: Metadata; + cancelled: boolean; + constructor(path: string, call: ServerInterceptingCallInterface, metadata: Metadata); + _read(size: number): void; + getPeer(): string; + sendMetadata(responseMetadata: Metadata): void; + getDeadline(): Deadline; + getPath(): string; +} +export declare class ServerWritableStreamImpl extends Writable implements ServerWritableStream { + private path; + private call; + metadata: Metadata; + request: RequestType; + cancelled: boolean; + private trailingMetadata; + private pendingStatus; + constructor(path: string, call: ServerInterceptingCallInterface, metadata: Metadata, request: RequestType); + getPeer(): string; + sendMetadata(responseMetadata: Metadata): void; + getDeadline(): Deadline; + getPath(): string; + _write(chunk: ResponseType, encoding: string, callback: (...args: any[]) => void): void; + _final(callback: Function): void; + end(metadata?: any): this; +} +export declare class ServerDuplexStreamImpl extends Duplex implements ServerDuplexStream { + private path; + private call; + metadata: Metadata; + cancelled: boolean; + private trailingMetadata; + private pendingStatus; + constructor(path: string, call: ServerInterceptingCallInterface, metadata: Metadata); + getPeer(): string; + sendMetadata(responseMetadata: Metadata): void; + getDeadline(): Deadline; + getPath(): string; + _read(size: number): void; + _write(chunk: ResponseType, encoding: string, callback: (...args: any[]) => void): void; + _final(callback: Function): void; + end(metadata?: any): this; +} +export type sendUnaryData = (error: ServerErrorResponse | ServerStatusResponse | null, value?: ResponseType | null, trailer?: Metadata, flags?: number) => void; +export type handleUnaryCall = (call: ServerUnaryCall, callback: sendUnaryData) => void; +export type handleClientStreamingCall = (call: ServerReadableStream, callback: sendUnaryData) => void; +export type handleServerStreamingCall = (call: ServerWritableStream) => void; +export type handleBidiStreamingCall = (call: ServerDuplexStream) => void; +export type HandleCall = handleUnaryCall | handleClientStreamingCall | handleServerStreamingCall | handleBidiStreamingCall; +export interface UnaryHandler { + func: handleUnaryCall; + serialize: Serialize; + deserialize: Deserialize; + type: 'unary'; + path: string; +} +export interface ClientStreamingHandler { + func: handleClientStreamingCall; + serialize: Serialize; + deserialize: Deserialize; + type: 'clientStream'; + path: string; +} +export interface ServerStreamingHandler { + func: handleServerStreamingCall; + serialize: Serialize; + deserialize: Deserialize; + type: 'serverStream'; + path: string; +} +export interface BidiStreamingHandler { + func: handleBidiStreamingCall; + serialize: Serialize; + deserialize: Deserialize; + type: 'bidi'; + path: string; +} +export type Handler = UnaryHandler | ClientStreamingHandler | ServerStreamingHandler | BidiStreamingHandler; +export type HandlerType = 'bidi' | 'clientStream' | 'serverStream' | 'unary'; diff --git a/node_modules/@grpc/grpc-js/build/src/server-call.js b/node_modules/@grpc/grpc-js/build/src/server-call.js new file mode 100644 index 0000000..5b42d24 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/server-call.js @@ -0,0 +1,190 @@ +"use strict"; +/* + * Copyright 2019 gRPC authors. + * + * 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. + * + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ServerDuplexStreamImpl = exports.ServerWritableStreamImpl = exports.ServerReadableStreamImpl = exports.ServerUnaryCallImpl = exports.serverErrorToStatus = void 0; +const events_1 = require("events"); +const stream_1 = require("stream"); +const constants_1 = require("./constants"); +const metadata_1 = require("./metadata"); +function serverErrorToStatus(error, overrideTrailers) { + var _a; + const status = { + code: constants_1.Status.UNKNOWN, + details: 'message' in error ? error.message : 'Unknown Error', + metadata: (_a = overrideTrailers !== null && overrideTrailers !== void 0 ? overrideTrailers : error.metadata) !== null && _a !== void 0 ? _a : null, + }; + if ('code' in error && + typeof error.code === 'number' && + Number.isInteger(error.code)) { + status.code = error.code; + if ('details' in error && typeof error.details === 'string') { + status.details = error.details; + } + } + return status; +} +exports.serverErrorToStatus = serverErrorToStatus; +class ServerUnaryCallImpl extends events_1.EventEmitter { + constructor(path, call, metadata, request) { + super(); + this.path = path; + this.call = call; + this.metadata = metadata; + this.request = request; + this.cancelled = false; + } + getPeer() { + return this.call.getPeer(); + } + sendMetadata(responseMetadata) { + this.call.sendMetadata(responseMetadata); + } + getDeadline() { + return this.call.getDeadline(); + } + getPath() { + return this.path; + } +} +exports.ServerUnaryCallImpl = ServerUnaryCallImpl; +class ServerReadableStreamImpl extends stream_1.Readable { + constructor(path, call, metadata) { + super({ objectMode: true }); + this.path = path; + this.call = call; + this.metadata = metadata; + this.cancelled = false; + } + _read(size) { + this.call.startRead(); + } + getPeer() { + return this.call.getPeer(); + } + sendMetadata(responseMetadata) { + this.call.sendMetadata(responseMetadata); + } + getDeadline() { + return this.call.getDeadline(); + } + getPath() { + return this.path; + } +} +exports.ServerReadableStreamImpl = ServerReadableStreamImpl; +class ServerWritableStreamImpl extends stream_1.Writable { + constructor(path, call, metadata, request) { + super({ objectMode: true }); + this.path = path; + this.call = call; + this.metadata = metadata; + this.request = request; + this.pendingStatus = { + code: constants_1.Status.OK, + details: 'OK', + }; + this.cancelled = false; + this.trailingMetadata = new metadata_1.Metadata(); + this.on('error', err => { + this.pendingStatus = serverErrorToStatus(err); + this.end(); + }); + } + getPeer() { + return this.call.getPeer(); + } + sendMetadata(responseMetadata) { + this.call.sendMetadata(responseMetadata); + } + getDeadline() { + return this.call.getDeadline(); + } + getPath() { + return this.path; + } + _write(chunk, encoding, + // eslint-disable-next-line @typescript-eslint/no-explicit-any + callback) { + this.call.sendMessage(chunk, callback); + } + _final(callback) { + var _a; + callback(null); + this.call.sendStatus(Object.assign(Object.assign({}, this.pendingStatus), { metadata: (_a = this.pendingStatus.metadata) !== null && _a !== void 0 ? _a : this.trailingMetadata })); + } + // eslint-disable-next-line @typescript-eslint/no-explicit-any + end(metadata) { + if (metadata) { + this.trailingMetadata = metadata; + } + return super.end(); + } +} +exports.ServerWritableStreamImpl = ServerWritableStreamImpl; +class ServerDuplexStreamImpl extends stream_1.Duplex { + constructor(path, call, metadata) { + super({ objectMode: true }); + this.path = path; + this.call = call; + this.metadata = metadata; + this.pendingStatus = { + code: constants_1.Status.OK, + details: 'OK', + }; + this.cancelled = false; + this.trailingMetadata = new metadata_1.Metadata(); + this.on('error', err => { + this.pendingStatus = serverErrorToStatus(err); + this.end(); + }); + } + getPeer() { + return this.call.getPeer(); + } + sendMetadata(responseMetadata) { + this.call.sendMetadata(responseMetadata); + } + getDeadline() { + return this.call.getDeadline(); + } + getPath() { + return this.path; + } + _read(size) { + this.call.startRead(); + } + _write(chunk, encoding, + // eslint-disable-next-line @typescript-eslint/no-explicit-any + callback) { + this.call.sendMessage(chunk, callback); + } + _final(callback) { + var _a; + callback(null); + this.call.sendStatus(Object.assign(Object.assign({}, this.pendingStatus), { metadata: (_a = this.pendingStatus.metadata) !== null && _a !== void 0 ? _a : this.trailingMetadata })); + } + // eslint-disable-next-line @typescript-eslint/no-explicit-any + end(metadata) { + if (metadata) { + this.trailingMetadata = metadata; + } + return super.end(); + } +} +exports.ServerDuplexStreamImpl = ServerDuplexStreamImpl; +//# sourceMappingURL=server-call.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/server-call.js.map b/node_modules/@grpc/grpc-js/build/src/server-call.js.map new file mode 100644 index 0000000..9e0c636 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/server-call.js.map @@ -0,0 +1 @@ +{"version":3,"file":"server-call.js","sourceRoot":"","sources":["../../src/server-call.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;GAeG;;;AAEH,mCAAsC;AACtC,mCAAoD;AAEpD,2CAAqC;AAErC,yCAAsC;AAkCtC,SAAgB,mBAAmB,CACjC,KAAiD,EACjD,gBAAuC;;IAEvC,MAAM,MAAM,GAAwB;QAClC,IAAI,EAAE,kBAAM,CAAC,OAAO;QACpB,OAAO,EAAE,SAAS,IAAI,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,OAAO,CAAC,CAAC,CAAC,eAAe;QAC7D,QAAQ,EAAE,MAAA,gBAAgB,aAAhB,gBAAgB,cAAhB,gBAAgB,GAAI,KAAK,CAAC,QAAQ,mCAAI,IAAI;KACrD,CAAC;IAEF,IACE,MAAM,IAAI,KAAK;QACf,OAAO,KAAK,CAAC,IAAI,KAAK,QAAQ;QAC9B,MAAM,CAAC,SAAS,CAAC,KAAK,CAAC,IAAI,CAAC,EAC5B,CAAC;QACD,MAAM,CAAC,IAAI,GAAG,KAAK,CAAC,IAAI,CAAC;QAEzB,IAAI,SAAS,IAAI,KAAK,IAAI,OAAO,KAAK,CAAC,OAAO,KAAK,QAAQ,EAAE,CAAC;YAC5D,MAAM,CAAC,OAAO,GAAG,KAAK,CAAC,OAAQ,CAAC;QAClC,CAAC;IACH,CAAC;IACD,OAAO,MAAM,CAAC;AAChB,CAAC;AAtBD,kDAsBC;AAED,MAAa,mBACX,SAAQ,qBAAY;IAKpB,YACU,IAAY,EACZ,IAAqC,EACtC,QAAkB,EAClB,OAAoB;QAE3B,KAAK,EAAE,CAAC;QALA,SAAI,GAAJ,IAAI,CAAQ;QACZ,SAAI,GAAJ,IAAI,CA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AI,CAAC,SAAS,EAAE,CAAC;IACxB,CAAC;IAED,MAAM,CACJ,KAAmB,EACnB,QAAgB;IAChB,8DAA8D;IAC9D,QAAkC;QAElC,IAAI,CAAC,IAAI,CAAC,WAAW,CAAC,KAAK,EAAE,QAAQ,CAAC,CAAC;IACzC,CAAC;IAED,MAAM,CAAC,QAAkB;;QACvB,QAAQ,CAAC,IAAI,CAAC,CAAC;QACf,IAAI,CAAC,IAAI,CAAC,UAAU,iCACf,IAAI,CAAC,aAAa,KACrB,QAAQ,EAAE,MAAA,IAAI,CAAC,aAAa,CAAC,QAAQ,mCAAI,IAAI,CAAC,gBAAgB,IAC9D,CAAC;IACL,CAAC;IAED,8DAA8D;IAC9D,GAAG,CAAC,QAAc;QAChB,IAAI,QAAQ,EAAE,CAAC;YACb,IAAI,CAAC,gBAAgB,GAAG,QAAQ,CAAC;QACnC,CAAC;QAED,OAAO,KAAK,CAAC,GAAG,EAAE,CAAC;IACrB,CAAC;CACF;AAvED,wDAuEC"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/server-credentials.d.ts b/node_modules/@grpc/grpc-js/build/src/server-credentials.d.ts new file mode 100644 index 0000000..6c64eda --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/server-credentials.d.ts @@ -0,0 +1,14 @@ +/// +/// +import { SecureServerOptions } from 'http2'; +export interface KeyCertPair { + private_key: Buffer; + cert_chain: Buffer; +} +export declare abstract class ServerCredentials { + abstract _isSecure(): boolean; + abstract _getSettings(): SecureServerOptions | null; + abstract _equals(other: ServerCredentials): boolean; + static createInsecure(): ServerCredentials; + static createSsl(rootCerts: Buffer | null, keyCertPairs: KeyCertPair[], checkClientCertificate?: boolean): ServerCredentials; +} diff --git a/node_modules/@grpc/grpc-js/build/src/server-credentials.js b/node_modules/@grpc/grpc-js/build/src/server-credentials.js new file mode 100644 index 0000000..3bcf1be --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/server-credentials.js @@ -0,0 +1,167 @@ +"use strict"; +/* + * Copyright 2019 gRPC authors. + * + * 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. + * + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.ServerCredentials = void 0; +const tls_helpers_1 = require("./tls-helpers"); +class ServerCredentials { + static createInsecure() { + return new InsecureServerCredentials(); + } + static createSsl(rootCerts, keyCertPairs, checkClientCertificate = false) { + var _a; + if (rootCerts !== null && !Buffer.isBuffer(rootCerts)) { + throw new TypeError('rootCerts must be null or a Buffer'); + } + if (!Array.isArray(keyCertPairs)) { + throw new TypeError('keyCertPairs must be an array'); + } + if (typeof checkClientCertificate !== 'boolean') { + throw new TypeError('checkClientCertificate must be a boolean'); + } + const cert = []; + const key = []; + for (let i = 0; i < keyCertPairs.length; i++) { + const pair = keyCertPairs[i]; + if (pair === null || typeof pair !== 'object') { + throw new TypeError(`keyCertPair[${i}] must be an object`); + } + if (!Buffer.isBuffer(pair.private_key)) { + throw new TypeError(`keyCertPair[${i}].private_key must be a Buffer`); + } + if (!Buffer.isBuffer(pair.cert_chain)) { + throw new TypeError(`keyCertPair[${i}].cert_chain must be a Buffer`); + } + cert.push(pair.cert_chain); + key.push(pair.private_key); + } + return new SecureServerCredentials({ + ca: (_a = rootCerts !== null && rootCerts !== void 0 ? rootCerts : (0, tls_helpers_1.getDefaultRootsData)()) !== null && _a !== void 0 ? _a : undefined, + cert, + key, + requestCert: checkClientCertificate, + ciphers: tls_helpers_1.CIPHER_SUITES, + }); + } +} +exports.ServerCredentials = ServerCredentials; +class InsecureServerCredentials extends ServerCredentials { + _isSecure() { + return false; + } + _getSettings() { + return null; + } + _equals(other) { + return other instanceof InsecureServerCredentials; + } +} +class SecureServerCredentials extends ServerCredentials { + constructor(options) { + super(); + this.options = options; + } + _isSecure() { + return true; + } + _getSettings() { + return this.options; + } + /** + * Checks equality by checking the options that are actually set by + * createSsl. + * @param other + * @returns + */ + _equals(other) { + if (this === other) { + return true; + } + if (!(other instanceof SecureServerCredentials)) { + return false; + } + // options.ca equality check + if (Buffer.isBuffer(this.options.ca) && Buffer.isBuffer(other.options.ca)) { + if (!this.options.ca.equals(other.options.ca)) { + return false; + } + } + else { + if (this.options.ca !== other.options.ca) { + return false; + } + } + // options.cert equality check + if (Array.isArray(this.options.cert) && Array.isArray(other.options.cert)) { + if (this.options.cert.length !== other.options.cert.length) { + return false; + } + for (let i = 0; i < this.options.cert.length; i++) { + const thisCert = this.options.cert[i]; + const otherCert = other.options.cert[i]; + if (Buffer.isBuffer(thisCert) && Buffer.isBuffer(otherCert)) { + if (!thisCert.equals(otherCert)) { + return false; + } + } + else { + if (thisCert !== otherCert) { + return false; + } + } + } + } + else { + if (this.options.cert !== other.options.cert) { + return false; + } + } + // options.key equality check + if (Array.isArray(this.options.key) && Array.isArray(other.options.key)) { + if (this.options.key.length !== other.options.key.length) { + return false; + } + for (let i = 0; i < this.options.key.length; i++) { + const thisKey = this.options.key[i]; + const otherKey = other.options.key[i]; + if (Buffer.isBuffer(thisKey) && Buffer.isBuffer(otherKey)) { + if (!thisKey.equals(otherKey)) { + return false; + } + } + else { + if (thisKey !== otherKey) { + return false; + } + } + } + } + else { + if (this.options.key !== other.options.key) { + return false; + } + } + // options.requestCert equality check + if (this.options.requestCert !== other.options.requestCert) { + return false; + } + /* ciphers is derived from a value that is constant for the process, so no + * equality check is needed. */ + return true; + } +} +//# sourceMappingURL=server-credentials.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/server-credentials.js.map b/node_modules/@grpc/grpc-js/build/src/server-credentials.js.map new file mode 100644 index 0000000..81a40a4 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/server-credentials.js.map @@ -0,0 +1 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ACH,CAAC;YACH,CAAC;QACH,CAAC;aAAM,CAAC;YACN,IAAI,IAAI,CAAC,OAAO,CAAC,GAAG,KAAK,KAAK,CAAC,OAAO,CAAC,GAAG,EAAE,CAAC;gBAC3C,OAAO,KAAK,CAAC;YACf,CAAC;QACH,CAAC;QACD,qCAAqC;QACrC,IAAI,IAAI,CAAC,OAAO,CAAC,WAAW,KAAK,KAAK,CAAC,OAAO,CAAC,WAAW,EAAE,CAAC;YAC3D,OAAO,KAAK,CAAC;QACf,CAAC;QACD;uCAC+B;QAC/B,OAAO,IAAI,CAAC;IACd,CAAC;CACF"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/server-interceptors.d.ts b/node_modules/@grpc/grpc-js/build/src/server-interceptors.d.ts new file mode 100644 index 0000000..e8bbd0d --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/server-interceptors.d.ts @@ -0,0 +1,178 @@ +/// +import { PartialStatusObject } from './call-interface'; +import { ServerMethodDefinition } from './make-client'; +import { Metadata } from './metadata'; +import { ChannelOptions } from './channel-options'; +import { Handler } from './server-call'; +import { Deadline } from './deadline'; +import * as http2 from 'http2'; +import { CallEventTracker } from './transport'; +export interface ServerMetadataListener { + (metadata: Metadata, next: (metadata: Metadata) => void): void; +} +export interface ServerMessageListener { + (message: any, next: (message: any) => void): void; +} +export interface ServerHalfCloseListener { + (next: () => void): void; +} +export interface ServerCancelListener { + (): void; +} +export interface FullServerListener { + onReceiveMetadata: ServerMetadataListener; + onReceiveMessage: ServerMessageListener; + onReceiveHalfClose: ServerHalfCloseListener; + onCancel: ServerCancelListener; +} +export type ServerListener = Partial; +export declare class ServerListenerBuilder { + private metadata; + private message; + private halfClose; + private cancel; + withOnReceiveMetadata(onReceiveMetadata: ServerMetadataListener): this; + withOnReceiveMessage(onReceiveMessage: ServerMessageListener): this; + withOnReceiveHalfClose(onReceiveHalfClose: ServerHalfCloseListener): this; + withOnCancel(onCancel: ServerCancelListener): this; + build(): ServerListener; +} +export interface InterceptingServerListener { + onReceiveMetadata(metadata: Metadata): void; + onReceiveMessage(message: any): void; + onReceiveHalfClose(): void; + onCancel(): void; +} +export declare function isInterceptingServerListener(listener: ServerListener | InterceptingServerListener): listener is InterceptingServerListener; +export interface StartResponder { + (next: (listener?: ServerListener) => void): void; +} +export interface MetadataResponder { + (metadata: Metadata, next: (metadata: Metadata) => void): void; +} +export interface MessageResponder { + (message: any, next: (message: any) => void): void; +} +export interface StatusResponder { + (status: PartialStatusObject, next: (status: PartialStatusObject) => void): void; +} +export interface FullResponder { + start: StartResponder; + sendMetadata: MetadataResponder; + sendMessage: MessageResponder; + sendStatus: StatusResponder; +} +export type Responder = Partial; +export declare class ResponderBuilder { + private start; + private metadata; + private message; + private status; + withStart(start: StartResponder): this; + withSendMetadata(sendMetadata: MetadataResponder): this; + withSendMessage(sendMessage: MessageResponder): this; + withSendStatus(sendStatus: StatusResponder): this; + build(): Responder; +} +export interface ServerInterceptingCallInterface { + /** + * Register the listener to handle inbound events. + */ + start(listener: InterceptingServerListener): void; + /** + * Send response metadata. + */ + sendMetadata(metadata: Metadata): void; + /** + * Send a response message. + */ + sendMessage(message: any, callback: () => void): void; + /** + * End the call by sending this status. + */ + sendStatus(status: PartialStatusObject): void; + /** + * Start a single read, eventually triggering either listener.onReceiveMessage or listener.onReceiveHalfClose. + */ + startRead(): void; + /** + * Return the peer address of the client making the request, if known, or "unknown" otherwise + */ + getPeer(): string; + /** + * Return the call deadline set by the client. The value is Infinity if there is no deadline. + */ + getDeadline(): Deadline; +} +export declare class ServerInterceptingCall implements ServerInterceptingCallInterface { + private nextCall; + private responder; + private processingMetadata; + private processingMessage; + private pendingMessage; + private pendingMessageCallback; + private pendingStatus; + constructor(nextCall: ServerInterceptingCallInterface, responder?: Responder); + private processPendingMessage; + private processPendingStatus; + start(listener: InterceptingServerListener): void; + sendMetadata(metadata: Metadata): void; + sendMessage(message: any, callback: () => void): void; + sendStatus(status: PartialStatusObject): void; + startRead(): void; + getPeer(): string; + getDeadline(): Deadline; +} +export interface ServerInterceptor { + (methodDescriptor: ServerMethodDefinition, call: ServerInterceptingCallInterface): ServerInterceptingCall; +} +export declare class BaseServerInterceptingCall implements ServerInterceptingCallInterface { + private readonly stream; + private readonly callEventTracker; + private readonly handler; + private listener; + private metadata; + private deadlineTimer; + private deadline; + private maxSendMessageSize; + private maxReceiveMessageSize; + private cancelled; + private metadataSent; + private wantTrailers; + private cancelNotified; + private incomingEncoding; + private decoder; + private readQueue; + private isReadPending; + private receivedHalfClose; + private streamEnded; + constructor(stream: http2.ServerHttp2Stream, headers: http2.IncomingHttpHeaders, callEventTracker: CallEventTracker | null, handler: Handler, options: ChannelOptions); + private handleTimeoutHeader; + private checkCancelled; + private notifyOnCancel; + /** + * A server handler can start sending messages without explicitly sending + * metadata. In that case, we need to send headers before sending any + * messages. This function does that if necessary. + */ + private maybeSendMetadata; + /** + * Serialize a message to a length-delimited byte string. + * @param value + * @returns + */ + private serializeMessage; + private decompressMessage; + private decompressAndMaybePush; + private maybePushNextMessage; + private handleDataFrame; + private handleEndEvent; + start(listener: InterceptingServerListener): void; + sendMetadata(metadata: Metadata): void; + sendMessage(message: any, callback: () => void): void; + sendStatus(status: PartialStatusObject): void; + startRead(): void; + getPeer(): string; + getDeadline(): Deadline; +} +export declare function getServerInterceptingCall(interceptors: ServerInterceptor[], stream: http2.ServerHttp2Stream, headers: http2.IncomingHttpHeaders, callEventTracker: CallEventTracker | null, handler: Handler, options: ChannelOptions): ServerInterceptingCallInterface; diff --git a/node_modules/@grpc/grpc-js/build/src/server-interceptors.js b/node_modules/@grpc/grpc-js/build/src/server-interceptors.js new file mode 100644 index 0000000..a14d1aa --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/server-interceptors.js @@ -0,0 +1,734 @@ +"use strict"; +/* + * Copyright 2024 gRPC authors. + * + * 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. + * + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.getServerInterceptingCall = exports.BaseServerInterceptingCall = exports.ServerInterceptingCall = exports.ResponderBuilder = exports.isInterceptingServerListener = exports.ServerListenerBuilder = void 0; +const metadata_1 = require("./metadata"); +const constants_1 = require("./constants"); +const http2 = require("http2"); +const error_1 = require("./error"); +const zlib = require("zlib"); +const util_1 = require("util"); +const stream_decoder_1 = require("./stream-decoder"); +const logging = require("./logging"); +const unzip = (0, util_1.promisify)(zlib.unzip); +const inflate = (0, util_1.promisify)(zlib.inflate); +const TRACER_NAME = 'server_call'; +function trace(text) { + logging.trace(constants_1.LogVerbosity.DEBUG, TRACER_NAME, text); +} +class ServerListenerBuilder { + constructor() { + this.metadata = undefined; + this.message = undefined; + this.halfClose = undefined; + this.cancel = undefined; + } + withOnReceiveMetadata(onReceiveMetadata) { + this.metadata = onReceiveMetadata; + return this; + } + withOnReceiveMessage(onReceiveMessage) { + this.message = onReceiveMessage; + return this; + } + withOnReceiveHalfClose(onReceiveHalfClose) { + this.halfClose = onReceiveHalfClose; + return this; + } + withOnCancel(onCancel) { + this.cancel = onCancel; + return this; + } + build() { + return { + onReceiveMetadata: this.metadata, + onReceiveMessage: this.message, + onReceiveHalfClose: this.halfClose, + onCancel: this.cancel, + }; + } +} +exports.ServerListenerBuilder = ServerListenerBuilder; +function isInterceptingServerListener(listener) { + return (listener.onReceiveMetadata !== undefined && + listener.onReceiveMetadata.length === 1); +} +exports.isInterceptingServerListener = isInterceptingServerListener; +class InterceptingServerListenerImpl { + constructor(listener, nextListener) { + this.listener = listener; + this.nextListener = nextListener; + /** + * Once the call is cancelled, ignore all other events. + */ + this.cancelled = false; + this.processingMetadata = false; + this.hasPendingMessage = false; + this.pendingMessage = null; + this.processingMessage = false; + this.hasPendingHalfClose = false; + } + processPendingMessage() { + if (this.hasPendingMessage) { + this.nextListener.onReceiveMessage(this.pendingMessage); + this.pendingMessage = null; + this.hasPendingMessage = false; + } + } + processPendingHalfClose() { + if (this.hasPendingHalfClose) { + this.nextListener.onReceiveHalfClose(); + this.hasPendingHalfClose = false; + } + } + onReceiveMetadata(metadata) { + if (this.cancelled) { + return; + } + this.processingMetadata = true; + this.listener.onReceiveMetadata(metadata, interceptedMetadata => { + this.processingMetadata = false; + if (this.cancelled) { + return; + } + this.nextListener.onReceiveMetadata(interceptedMetadata); + this.processPendingMessage(); + this.processPendingHalfClose(); + }); + } + onReceiveMessage(message) { + if (this.cancelled) { + return; + } + this.processingMessage = true; + this.listener.onReceiveMessage(message, msg => { + this.processingMessage = false; + if (this.cancelled) { + return; + } + if (this.processingMetadata) { + this.pendingMessage = msg; + this.hasPendingMessage = true; + } + else { + this.nextListener.onReceiveMessage(msg); + this.processPendingHalfClose(); + } + }); + } + onReceiveHalfClose() { + if (this.cancelled) { + return; + } + this.listener.onReceiveHalfClose(() => { + if (this.cancelled) { + return; + } + if (this.processingMetadata || this.processingMessage) { + this.hasPendingHalfClose = true; + } + else { + this.nextListener.onReceiveHalfClose(); + } + }); + } + onCancel() { + this.cancelled = true; + this.listener.onCancel(); + this.nextListener.onCancel(); + } +} +class ResponderBuilder { + constructor() { + this.start = undefined; + this.metadata = undefined; + this.message = undefined; + this.status = undefined; + } + withStart(start) { + this.start = start; + return this; + } + withSendMetadata(sendMetadata) { + this.metadata = sendMetadata; + return this; + } + withSendMessage(sendMessage) { + this.message = sendMessage; + return this; + } + withSendStatus(sendStatus) { + this.status = sendStatus; + return this; + } + build() { + return { + start: this.start, + sendMetadata: this.metadata, + sendMessage: this.message, + sendStatus: this.status, + }; + } +} +exports.ResponderBuilder = ResponderBuilder; +const defaultServerListener = { + onReceiveMetadata: (metadata, next) => { + next(metadata); + }, + onReceiveMessage: (message, next) => { + next(message); + }, + onReceiveHalfClose: next => { + next(); + }, + onCancel: () => { }, +}; +const defaultResponder = { + start: next => { + next(); + }, + sendMetadata: (metadata, next) => { + next(metadata); + }, + sendMessage: (message, next) => { + next(message); + }, + sendStatus: (status, next) => { + next(status); + }, +}; +class ServerInterceptingCall { + constructor(nextCall, responder) { + var _a, _b, _c, _d; + this.nextCall = nextCall; + this.processingMetadata = false; + this.processingMessage = false; + this.pendingMessage = null; + this.pendingMessageCallback = null; + this.pendingStatus = null; + this.responder = { + start: (_a = responder === null || responder === void 0 ? void 0 : responder.start) !== null && _a !== void 0 ? _a : defaultResponder.start, + sendMetadata: (_b = responder === null || responder === void 0 ? void 0 : responder.sendMetadata) !== null && _b !== void 0 ? _b : defaultResponder.sendMetadata, + sendMessage: (_c = responder === null || responder === void 0 ? void 0 : responder.sendMessage) !== null && _c !== void 0 ? _c : defaultResponder.sendMessage, + sendStatus: (_d = responder === null || responder === void 0 ? void 0 : responder.sendStatus) !== null && _d !== void 0 ? _d : defaultResponder.sendStatus, + }; + } + processPendingMessage() { + if (this.pendingMessageCallback) { + this.nextCall.sendMessage(this.pendingMessage, this.pendingMessageCallback); + this.pendingMessage = null; + this.pendingMessageCallback = null; + } + } + processPendingStatus() { + if (this.pendingStatus) { + this.nextCall.sendStatus(this.pendingStatus); + this.pendingStatus = null; + } + } + start(listener) { + this.responder.start(interceptedListener => { + var _a, _b, _c, _d; + const fullInterceptedListener = { + onReceiveMetadata: (_a = interceptedListener === null || interceptedListener === void 0 ? void 0 : interceptedListener.onReceiveMetadata) !== null && _a !== void 0 ? _a : defaultServerListener.onReceiveMetadata, + onReceiveMessage: (_b = interceptedListener === null || interceptedListener === void 0 ? void 0 : interceptedListener.onReceiveMessage) !== null && _b !== void 0 ? _b : defaultServerListener.onReceiveMessage, + onReceiveHalfClose: (_c = interceptedListener === null || interceptedListener === void 0 ? void 0 : interceptedListener.onReceiveHalfClose) !== null && _c !== void 0 ? _c : defaultServerListener.onReceiveHalfClose, + onCancel: (_d = interceptedListener === null || interceptedListener === void 0 ? void 0 : interceptedListener.onCancel) !== null && _d !== void 0 ? _d : defaultServerListener.onCancel, + }; + const finalInterceptingListener = new InterceptingServerListenerImpl(fullInterceptedListener, listener); + this.nextCall.start(finalInterceptingListener); + }); + } + sendMetadata(metadata) { + this.processingMetadata = true; + this.responder.sendMetadata(metadata, interceptedMetadata => { + this.processingMetadata = false; + this.nextCall.sendMetadata(interceptedMetadata); + this.processPendingMessage(); + this.processPendingStatus(); + }); + } + sendMessage(message, callback) { + this.processingMessage = true; + this.responder.sendMessage(message, interceptedMessage => { + this.processingMessage = false; + if (this.processingMetadata) { + this.pendingMessage = interceptedMessage; + this.pendingMessageCallback = callback; + } + else { + this.nextCall.sendMessage(interceptedMessage, callback); + } + }); + } + sendStatus(status) { + this.responder.sendStatus(status, interceptedStatus => { + if (this.processingMetadata || this.processingMessage) { + this.pendingStatus = interceptedStatus; + } + else { + this.nextCall.sendStatus(interceptedStatus); + } + }); + } + startRead() { + this.nextCall.startRead(); + } + getPeer() { + return this.nextCall.getPeer(); + } + getDeadline() { + return this.nextCall.getDeadline(); + } +} +exports.ServerInterceptingCall = ServerInterceptingCall; +const GRPC_ACCEPT_ENCODING_HEADER = 'grpc-accept-encoding'; +const GRPC_ENCODING_HEADER = 'grpc-encoding'; +const GRPC_MESSAGE_HEADER = 'grpc-message'; +const GRPC_STATUS_HEADER = 'grpc-status'; +const GRPC_TIMEOUT_HEADER = 'grpc-timeout'; +const DEADLINE_REGEX = /(\d{1,8})\s*([HMSmun])/; +const deadlineUnitsToMs = { + H: 3600000, + M: 60000, + S: 1000, + m: 1, + u: 0.001, + n: 0.000001, +}; +const defaultCompressionHeaders = { + // TODO(cjihrig): Remove these encoding headers from the default response + // once compression is integrated. + [GRPC_ACCEPT_ENCODING_HEADER]: 'identity,deflate,gzip', + [GRPC_ENCODING_HEADER]: 'identity', +}; +const defaultResponseHeaders = { + [http2.constants.HTTP2_HEADER_STATUS]: http2.constants.HTTP_STATUS_OK, + [http2.constants.HTTP2_HEADER_CONTENT_TYPE]: 'application/grpc+proto', +}; +const defaultResponseOptions = { + waitForTrailers: true, +}; +class BaseServerInterceptingCall { + constructor(stream, headers, callEventTracker, handler, options) { + this.stream = stream; + this.callEventTracker = callEventTracker; + this.handler = handler; + this.listener = null; + this.deadlineTimer = null; + this.deadline = Infinity; + this.maxSendMessageSize = constants_1.DEFAULT_MAX_SEND_MESSAGE_LENGTH; + this.maxReceiveMessageSize = constants_1.DEFAULT_MAX_RECEIVE_MESSAGE_LENGTH; + this.cancelled = false; + this.metadataSent = false; + this.wantTrailers = false; + this.cancelNotified = false; + this.incomingEncoding = 'identity'; + this.decoder = new stream_decoder_1.StreamDecoder(); + this.readQueue = []; + this.isReadPending = false; + this.receivedHalfClose = false; + this.streamEnded = false; + this.stream.once('error', (err) => { + /* We need an error handler to avoid uncaught error event exceptions, but + * there is nothing we can reasonably do here. Any error event should + * have a corresponding close event, which handles emitting the cancelled + * event. And the stream is now in a bad state, so we can't reasonably + * expect to be able to send an error over it. */ + }); + this.stream.once('close', () => { + var _a; + trace('Request to method ' + + ((_a = this.handler) === null || _a === void 0 ? void 0 : _a.path) + + ' stream closed with rstCode ' + + this.stream.rstCode); + if (this.callEventTracker && !this.streamEnded) { + this.streamEnded = true; + this.callEventTracker.onStreamEnd(false); + this.callEventTracker.onCallEnd({ + code: constants_1.Status.CANCELLED, + details: 'Stream closed before sending status', + metadata: null, + }); + } + this.notifyOnCancel(); + }); + this.stream.on('data', (data) => { + this.handleDataFrame(data); + }); + this.stream.pause(); + this.stream.on('end', () => { + this.handleEndEvent(); + }); + if ('grpc.max_send_message_length' in options) { + this.maxSendMessageSize = options['grpc.max_send_message_length']; + } + if ('grpc.max_receive_message_length' in options) { + this.maxReceiveMessageSize = options['grpc.max_receive_message_length']; + } + const metadata = metadata_1.Metadata.fromHttp2Headers(headers); + if (logging.isTracerEnabled(TRACER_NAME)) { + trace('Request to ' + + this.handler.path + + ' received headers ' + + JSON.stringify(metadata.toJSON())); + } + const timeoutHeader = metadata.get(GRPC_TIMEOUT_HEADER); + if (timeoutHeader.length > 0) { + this.handleTimeoutHeader(timeoutHeader[0]); + } + const encodingHeader = metadata.get(GRPC_ENCODING_HEADER); + if (encodingHeader.length > 0) { + this.incomingEncoding = encodingHeader[0]; + } + // Remove several headers that should not be propagated to the application + metadata.remove(GRPC_TIMEOUT_HEADER); + metadata.remove(GRPC_ENCODING_HEADER); + metadata.remove(GRPC_ACCEPT_ENCODING_HEADER); + metadata.remove(http2.constants.HTTP2_HEADER_ACCEPT_ENCODING); + metadata.remove(http2.constants.HTTP2_HEADER_TE); + metadata.remove(http2.constants.HTTP2_HEADER_CONTENT_TYPE); + this.metadata = metadata; + } + handleTimeoutHeader(timeoutHeader) { + const match = timeoutHeader.toString().match(DEADLINE_REGEX); + if (match === null) { + const status = { + code: constants_1.Status.INTERNAL, + details: `Invalid ${GRPC_TIMEOUT_HEADER} value "${timeoutHeader}"`, + metadata: null, + }; + // Wait for the constructor to complete before sending the error. + process.nextTick(() => { + this.sendStatus(status); + }); + return; + } + const timeout = (+match[1] * deadlineUnitsToMs[match[2]]) | 0; + const now = new Date(); + this.deadline = now.setMilliseconds(now.getMilliseconds() + timeout); + this.deadlineTimer = setTimeout(() => { + const status = { + code: constants_1.Status.DEADLINE_EXCEEDED, + details: 'Deadline exceeded', + metadata: null, + }; + this.sendStatus(status); + }, timeout); + } + checkCancelled() { + /* In some cases the stream can become destroyed before the close event + * fires. That creates a race condition that this check works around */ + if (!this.cancelled && (this.stream.destroyed || this.stream.closed)) { + this.notifyOnCancel(); + this.cancelled = true; + } + return this.cancelled; + } + notifyOnCancel() { + if (this.cancelNotified) { + return; + } + this.cancelNotified = true; + this.cancelled = true; + process.nextTick(() => { + var _a; + (_a = this.listener) === null || _a === void 0 ? void 0 : _a.onCancel(); + }); + if (this.deadlineTimer) { + clearTimeout(this.deadlineTimer); + } + // Flush incoming data frames + this.stream.resume(); + } + /** + * A server handler can start sending messages without explicitly sending + * metadata. In that case, we need to send headers before sending any + * messages. This function does that if necessary. + */ + maybeSendMetadata() { + if (!this.metadataSent) { + this.sendMetadata(new metadata_1.Metadata()); + } + } + /** + * Serialize a message to a length-delimited byte string. + * @param value + * @returns + */ + serializeMessage(value) { + const messageBuffer = this.handler.serialize(value); + const byteLength = messageBuffer.byteLength; + const output = Buffer.allocUnsafe(byteLength + 5); + /* Note: response compression is currently not supported, so this + * compressed bit is always 0. */ + output.writeUInt8(0, 0); + output.writeUInt32BE(byteLength, 1); + messageBuffer.copy(output, 5); + return output; + } + decompressMessage(message, encoding) { + switch (encoding) { + case 'deflate': + return inflate(message.subarray(5)); + case 'gzip': + return unzip(message.subarray(5)); + case 'identity': + return message.subarray(5); + default: + return Promise.reject({ + code: constants_1.Status.UNIMPLEMENTED, + details: `Received message compressed with unsupported encoding "${encoding}"`, + }); + } + } + async decompressAndMaybePush(queueEntry) { + if (queueEntry.type !== 'COMPRESSED') { + throw new Error(`Invalid queue entry type: ${queueEntry.type}`); + } + const compressed = queueEntry.compressedMessage.readUInt8(0) === 1; + const compressedMessageEncoding = compressed + ? this.incomingEncoding + : 'identity'; + const decompressedMessage = await this.decompressMessage(queueEntry.compressedMessage, compressedMessageEncoding); + try { + queueEntry.parsedMessage = this.handler.deserialize(decompressedMessage); + } + catch (err) { + this.sendStatus({ + code: constants_1.Status.INTERNAL, + details: `Error deserializing request: ${err.message}`, + }); + return; + } + queueEntry.type = 'READABLE'; + this.maybePushNextMessage(); + } + maybePushNextMessage() { + if (this.listener && + this.isReadPending && + this.readQueue.length > 0 && + this.readQueue[0].type !== 'COMPRESSED') { + this.isReadPending = false; + const nextQueueEntry = this.readQueue.shift(); + if (nextQueueEntry.type === 'READABLE') { + this.listener.onReceiveMessage(nextQueueEntry.parsedMessage); + } + else { + // nextQueueEntry.type === 'HALF_CLOSE' + this.listener.onReceiveHalfClose(); + } + } + } + handleDataFrame(data) { + var _a; + if (this.checkCancelled()) { + return; + } + trace('Request to ' + + this.handler.path + + ' received data frame of size ' + + data.length); + const rawMessages = this.decoder.write(data); + for (const messageBytes of rawMessages) { + this.stream.pause(); + if (this.maxReceiveMessageSize !== -1 && + messageBytes.length - 5 > this.maxReceiveMessageSize) { + this.sendStatus({ + code: constants_1.Status.RESOURCE_EXHAUSTED, + details: `Received message larger than max (${messageBytes.length - 5} vs. ${this.maxReceiveMessageSize})`, + metadata: null, + }); + return; + } + const queueEntry = { + type: 'COMPRESSED', + compressedMessage: messageBytes, + parsedMessage: null, + }; + this.readQueue.push(queueEntry); + this.decompressAndMaybePush(queueEntry); + (_a = this.callEventTracker) === null || _a === void 0 ? void 0 : _a.addMessageReceived(); + } + } + handleEndEvent() { + this.readQueue.push({ + type: 'HALF_CLOSE', + compressedMessage: null, + parsedMessage: null, + }); + this.receivedHalfClose = true; + this.maybePushNextMessage(); + } + start(listener) { + trace('Request to ' + this.handler.path + ' start called'); + if (this.checkCancelled()) { + return; + } + this.listener = listener; + listener.onReceiveMetadata(this.metadata); + } + sendMetadata(metadata) { + if (this.checkCancelled()) { + return; + } + if (this.metadataSent) { + return; + } + this.metadataSent = true; + const custom = metadata ? metadata.toHttp2Headers() : null; + const headers = Object.assign(Object.assign(Object.assign({}, defaultResponseHeaders), defaultCompressionHeaders), custom); + this.stream.respond(headers, defaultResponseOptions); + } + sendMessage(message, callback) { + if (this.checkCancelled()) { + return; + } + let response; + try { + response = this.serializeMessage(message); + } + catch (e) { + this.sendStatus({ + code: constants_1.Status.INTERNAL, + details: `Error serializing response: ${(0, error_1.getErrorMessage)(e)}`, + metadata: null, + }); + return; + } + if (this.maxSendMessageSize !== -1 && + response.length - 5 > this.maxSendMessageSize) { + this.sendStatus({ + code: constants_1.Status.RESOURCE_EXHAUSTED, + details: `Sent message larger than max (${response.length} vs. ${this.maxSendMessageSize})`, + metadata: null, + }); + return; + } + this.maybeSendMetadata(); + trace('Request to ' + + this.handler.path + + ' sent data frame of size ' + + response.length); + this.stream.write(response, error => { + var _a; + if (error) { + this.sendStatus({ + code: constants_1.Status.INTERNAL, + details: `Error writing message: ${(0, error_1.getErrorMessage)(error)}`, + metadata: null, + }); + return; + } + (_a = this.callEventTracker) === null || _a === void 0 ? void 0 : _a.addMessageSent(); + callback(); + }); + } + sendStatus(status) { + var _a, _b; + if (this.checkCancelled()) { + return; + } + trace('Request to method ' + + ((_a = this.handler) === null || _a === void 0 ? void 0 : _a.path) + + ' ended with status code: ' + + constants_1.Status[status.code] + + ' details: ' + + status.details); + if (this.metadataSent) { + if (!this.wantTrailers) { + this.wantTrailers = true; + this.stream.once('wantTrailers', () => { + var _a; + if (this.callEventTracker && !this.streamEnded) { + this.streamEnded = true; + this.callEventTracker.onStreamEnd(true); + this.callEventTracker.onCallEnd(status); + } + const trailersToSend = Object.assign({ [GRPC_STATUS_HEADER]: status.code, [GRPC_MESSAGE_HEADER]: encodeURI(status.details) }, (_a = status.metadata) === null || _a === void 0 ? void 0 : _a.toHttp2Headers()); + this.stream.sendTrailers(trailersToSend); + this.notifyOnCancel(); + }); + this.stream.end(); + } + else { + this.notifyOnCancel(); + } + } + else { + if (this.callEventTracker && !this.streamEnded) { + this.streamEnded = true; + this.callEventTracker.onStreamEnd(true); + this.callEventTracker.onCallEnd(status); + } + // Trailers-only response + const trailersToSend = Object.assign(Object.assign({ [GRPC_STATUS_HEADER]: status.code, [GRPC_MESSAGE_HEADER]: encodeURI(status.details) }, defaultResponseHeaders), (_b = status.metadata) === null || _b === void 0 ? void 0 : _b.toHttp2Headers()); + this.stream.respond(trailersToSend, { endStream: true }); + this.notifyOnCancel(); + } + } + startRead() { + trace('Request to ' + this.handler.path + ' startRead called'); + if (this.checkCancelled()) { + return; + } + this.isReadPending = true; + if (this.readQueue.length === 0) { + if (!this.receivedHalfClose) { + this.stream.resume(); + } + } + else { + this.maybePushNextMessage(); + } + } + getPeer() { + var _a; + const socket = (_a = this.stream.session) === null || _a === void 0 ? void 0 : _a.socket; + if (socket === null || socket === void 0 ? void 0 : socket.remoteAddress) { + if (socket.remotePort) { + return `${socket.remoteAddress}:${socket.remotePort}`; + } + else { + return socket.remoteAddress; + } + } + else { + return 'unknown'; + } + } + getDeadline() { + return this.deadline; + } +} +exports.BaseServerInterceptingCall = BaseServerInterceptingCall; +function getServerInterceptingCall(interceptors, stream, headers, callEventTracker, handler, options) { + const methodDefinition = { + path: handler.path, + requestStream: handler.type === 'clientStream' || handler.type === 'bidi', + responseStream: handler.type === 'serverStream' || handler.type === 'bidi', + requestDeserialize: handler.deserialize, + responseSerialize: handler.serialize, + }; + const baseCall = new BaseServerInterceptingCall(stream, headers, callEventTracker, handler, options); + return interceptors.reduce((call, interceptor) => { + return interceptor(methodDefinition, call); + }, baseCall); +} +exports.getServerInterceptingCall = getServerInterceptingCall; +//# sourceMappingURL=server-interceptors.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/server-interceptors.js.map b/node_modules/@grpc/grpc-js/build/src/server-interceptors.js.map new file mode 100644 index 0000000..272b7ff --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/server-interceptors.js.map @@ -0,0 +1 @@ +{"version":3,"file":"server-interceptors.js","sourceRoot":"","sources":["../../src/server-interceptors.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;GAeG;;;AAIH,yCAAsC;AAItC,2CAKqB;AACrB,+BAA+B;AAC/B,mCAA0C;AAC1C,6BAA6B;AAC7B,+BAAiC;AACjC,qDAAiD;AAEjD,qCAAqC;AAErC,MAAM,KAAK,GAAG,IAAA,gBAAS,EAAC,IAAI,CAAC,KAAK,CAAC,CAAC;AACpC,MAAM,OAAO,GAAG,IAAA,gBAAS,EAAC,IAAI,CAAC,OAAO,CAAC,CAAC;AAExC,MAAM,WAAW,GAAG,aAAa,CAAC;AAElC,SAAS,KAAK,CAAC,IAAY;IACzB,OAAO,CAAC,KAAK,CAAC,wBAAY,CAAC,KAAK,EAAE,WAAW,EAAE,IAAI,CAAC,CAAC;AACvD,CAAC;AA4BD,MAAa,qBAAqB;IAAlC;QACU,aAAQ,GAAuC,S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AAO,CAAC,SAAS;KACrC,CAAC;IACF,MAAM,QAAQ,GAAG,IAAI,0BAA0B,CAC7C,MAAM,EACN,OAAO,EACP,gBAAgB,EAChB,OAAO,EACP,OAAO,CACR,CAAC;IACF,OAAO,YAAY,CAAC,MAAM,CACxB,CAAC,IAAqC,EAAE,WAA8B,EAAE,EAAE;QACxE,OAAO,WAAW,CAAC,gBAAgB,EAAE,IAAI,CAAC,CAAC;IAC7C,CAAC,EACD,QAAQ,CACT,CAAC;AACJ,CAAC;AA5BD,8DA4BC"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/server.d.ts b/node_modules/@grpc/grpc-js/build/src/server.d.ts new file mode 100644 index 0000000..9a76b64 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/server.d.ts @@ -0,0 +1,113 @@ +import { Deserialize, Serialize, ServiceDefinition } from './make-client'; +import { HandleCall } from './server-call'; +import { ServerCredentials } from './server-credentials'; +import { ChannelOptions } from './channel-options'; +import { ServerRef } from './channelz'; +import { ServerInterceptor } from './server-interceptors'; +export type UntypedHandleCall = HandleCall; +export interface UntypedServiceImplementation { + [name: string]: UntypedHandleCall; +} +export interface ServerOptions extends ChannelOptions { + interceptors?: ServerInterceptor[]; +} +export declare class Server { + private boundPorts; + private http2Servers; + private sessionIdleTimeouts; + private handlers; + private sessions; + /** + * This field only exists to ensure that the start method throws an error if + * it is called twice, as it did previously. + */ + private started; + private shutdown; + private options; + private serverAddressString; + private readonly channelzEnabled; + private channelzRef; + private channelzTrace; + private callTracker; + private listenerChildrenTracker; + private sessionChildrenTracker; + private readonly maxConnectionAgeMs; + private readonly maxConnectionAgeGraceMs; + private readonly keepaliveTimeMs; + private readonly keepaliveTimeoutMs; + private readonly sessionIdleTimeout; + private readonly interceptors; + /** + * Options that will be used to construct all Http2Server instances for this + * Server. + */ + private commonServerOptions; + constructor(options?: ServerOptions); + private getChannelzInfo; + private getChannelzSessionInfo; + private trace; + addProtoService(): never; + addService(service: ServiceDefinition, implementation: UntypedServiceImplementation): void; + removeService(service: ServiceDefinition): void; + bind(port: string, creds: ServerCredentials): never; + private registerListenerToChannelz; + private createHttp2Server; + private bindOneAddress; + private bindManyPorts; + private bindAddressList; + private resolvePort; + private bindPort; + private normalizePort; + bindAsync(port: string, creds: ServerCredentials, callback: (error: Error | null, port: number) => void): void; + private closeServer; + private closeSession; + private completeUnbind; + /** + * Unbind a previously bound port, or cancel an in-progress bindAsync + * operation. If port 0 was bound, only the actual bound port can be + * unbound. For example, if bindAsync was called with "localhost:0" and the + * bound port result was 54321, it can be unbound as "localhost:54321". + * @param port + */ + unbind(port: string): void; + /** + * Gracefully close all connections associated with a previously bound port. + * After the grace time, forcefully close all remaining open connections. + * + * If port 0 was bound, only the actual bound port can be + * drained. For example, if bindAsync was called with "localhost:0" and the + * bound port result was 54321, it can be drained as "localhost:54321". + * @param port + * @param graceTimeMs + * @returns + */ + drain(port: string, graceTimeMs: number): void; + forceShutdown(): void; + register(name: string, handler: HandleCall, serialize: Serialize, deserialize: Deserialize, type: string): boolean; + unregister(name: string): boolean; + /** + * @deprecated No longer needed as of version 1.10.x + */ + start(): void; + tryShutdown(callback: (error?: Error) => void): void; + addHttp2Port(): never; + /** + * Get the channelz reference object for this server. The returned value is + * garbage if channelz is disabled for this server. + * @returns + */ + getChannelzRef(): ServerRef; + private _verifyContentType; + private _retrieveHandler; + private _respondWithError; + private _channelzHandler; + private _streamHandler; + private _runHandlerForCall; + private _setupHandlers; + private _sessionHandler; + private _channelzSessionHandler; + private enableIdleTimeout; + private onIdleTimeout; + private onStreamOpened; + private onStreamClose; +} diff --git a/node_modules/@grpc/grpc-js/build/src/server.js b/node_modules/@grpc/grpc-js/build/src/server.js new file mode 100644 index 0000000..29f8016 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/server.js @@ -0,0 +1,1417 @@ +"use strict"; +/* + * Copyright 2019 gRPC authors. + * + * 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 __runInitializers = (this && this.__runInitializers) || function (thisArg, initializers, value) { + var useValue = arguments.length > 2; + for (var i = 0; i < initializers.length; i++) { + value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg); + } + return useValue ? value : void 0; +}; +var __esDecorate = (this && this.__esDecorate) || function (ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) { + function accept(f) { if (f !== void 0 && typeof f !== "function") throw new TypeError("Function expected"); return f; } + var kind = contextIn.kind, key = kind === "getter" ? "get" : kind === "setter" ? "set" : "value"; + var target = !descriptorIn && ctor ? contextIn["static"] ? ctor : ctor.prototype : null; + var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {}); + var _, done = false; + for (var i = decorators.length - 1; i >= 0; i--) { + var context = {}; + for (var p in contextIn) context[p] = p === "access" ? {} : contextIn[p]; + for (var p in contextIn.access) context.access[p] = contextIn.access[p]; + context.addInitializer = function (f) { if (done) throw new TypeError("Cannot add initializers after decoration has completed"); extraInitializers.push(accept(f || null)); }; + var result = (0, decorators[i])(kind === "accessor" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context); + if (kind === "accessor") { + if (result === void 0) continue; + if (result === null || typeof result !== "object") throw new TypeError("Object expected"); + if (_ = accept(result.get)) descriptor.get = _; + if (_ = accept(result.set)) descriptor.set = _; + if (_ = accept(result.init)) initializers.unshift(_); + } + else if (_ = accept(result)) { + if (kind === "field") initializers.unshift(_); + else descriptor[key] = _; + } + } + if (target) Object.defineProperty(target, contextIn.name, descriptor); + done = true; +}; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Server = void 0; +const http2 = require("http2"); +const util = require("util"); +const constants_1 = require("./constants"); +const server_call_1 = require("./server-call"); +const server_credentials_1 = require("./server-credentials"); +const resolver_1 = require("./resolver"); +const logging = require("./logging"); +const subchannel_address_1 = require("./subchannel-address"); +const uri_parser_1 = require("./uri-parser"); +const channelz_1 = require("./channelz"); +const server_interceptors_1 = require("./server-interceptors"); +const UNLIMITED_CONNECTION_AGE_MS = ~(1 << 31); +const KEEPALIVE_MAX_TIME_MS = ~(1 << 31); +const KEEPALIVE_TIMEOUT_MS = 20000; +const MAX_CONNECTION_IDLE_MS = ~(1 << 31); +const { HTTP2_HEADER_PATH } = http2.constants; +const TRACER_NAME = 'server'; +const kMaxAge = Buffer.from('max_age'); +function noop() { } +/** + * Decorator to wrap a class method with util.deprecate + * @param message The message to output if the deprecated method is called + * @returns + */ +function deprecate(message) { + return function (target, context) { + return util.deprecate(target, message); + }; +} +function getUnimplementedStatusResponse(methodName) { + return { + code: constants_1.Status.UNIMPLEMENTED, + details: `The server does not implement the method ${methodName}`, + }; +} +function getDefaultHandler(handlerType, methodName) { + const unimplementedStatusResponse = getUnimplementedStatusResponse(methodName); + switch (handlerType) { + case 'unary': + return (call, callback) => { + callback(unimplementedStatusResponse, null); + }; + case 'clientStream': + return (call, callback) => { + callback(unimplementedStatusResponse, null); + }; + case 'serverStream': + return (call) => { + call.emit('error', unimplementedStatusResponse); + }; + case 'bidi': + return (call) => { + call.emit('error', unimplementedStatusResponse); + }; + default: + throw new Error(`Invalid handlerType ${handlerType}`); + } +} +let Server = (() => { + var _a; + let _instanceExtraInitializers = []; + let _start_decorators; + return _a = class Server { + constructor(options) { + var _b, _c, _d, _e, _f, _g; + this.boundPorts = (__runInitializers(this, _instanceExtraInitializers), new Map()); + this.http2Servers = new Map(); + this.sessionIdleTimeouts = new Map(); + this.handlers = new Map(); + this.sessions = new Map(); + /** + * This field only exists to ensure that the start method throws an error if + * it is called twice, as it did previously. + */ + this.started = false; + this.shutdown = false; + this.serverAddressString = 'null'; + // Channelz Info + this.channelzEnabled = true; + this.options = options !== null && options !== void 0 ? options : {}; + if (this.options['grpc.enable_channelz'] === 0) { + this.channelzEnabled = false; + this.channelzTrace = new channelz_1.ChannelzTraceStub(); + this.callTracker = new channelz_1.ChannelzCallTrackerStub(); + this.listenerChildrenTracker = new channelz_1.ChannelzChildrenTrackerStub(); + this.sessionChildrenTracker = new channelz_1.ChannelzChildrenTrackerStub(); + } + else { + this.channelzTrace = new channelz_1.ChannelzTrace(); + this.callTracker = new channelz_1.ChannelzCallTracker(); + this.listenerChildrenTracker = new channelz_1.ChannelzChildrenTracker(); + this.sessionChildrenTracker = new channelz_1.ChannelzChildrenTracker(); + } + this.channelzRef = (0, channelz_1.registerChannelzServer)('server', () => this.getChannelzInfo(), this.channelzEnabled); + this.channelzTrace.addTrace('CT_INFO', 'Server created'); + this.maxConnectionAgeMs = + (_b = this.options['grpc.max_connection_age_ms']) !== null && _b !== void 0 ? _b : UNLIMITED_CONNECTION_AGE_MS; + this.maxConnectionAgeGraceMs = + (_c = this.options['grpc.max_connection_age_grace_ms']) !== null && _c !== void 0 ? _c : UNLIMITED_CONNECTION_AGE_MS; + this.keepaliveTimeMs = + (_d = this.options['grpc.keepalive_time_ms']) !== null && _d !== void 0 ? _d : KEEPALIVE_MAX_TIME_MS; + this.keepaliveTimeoutMs = + (_e = this.options['grpc.keepalive_timeout_ms']) !== null && _e !== void 0 ? _e : KEEPALIVE_TIMEOUT_MS; + this.sessionIdleTimeout = + (_f = this.options['grpc.max_connection_idle_ms']) !== null && _f !== void 0 ? _f : MAX_CONNECTION_IDLE_MS; + this.commonServerOptions = { + maxSendHeaderBlockLength: Number.MAX_SAFE_INTEGER, + }; + if ('grpc-node.max_session_memory' in this.options) { + this.commonServerOptions.maxSessionMemory = + this.options['grpc-node.max_session_memory']; + } + else { + /* By default, set a very large max session memory limit, to effectively + * disable enforcement of the limit. Some testing indicates that Node's + * behavior degrades badly when this limit is reached, so we solve that + * by disabling the check entirely. */ + this.commonServerOptions.maxSessionMemory = Number.MAX_SAFE_INTEGER; + } + if ('grpc.max_concurrent_streams' in this.options) { + this.commonServerOptions.settings = { + maxConcurrentStreams: this.options['grpc.max_concurrent_streams'], + }; + } + this.interceptors = (_g = this.options.interceptors) !== null && _g !== void 0 ? _g : []; + this.trace('Server constructed'); + } + getChannelzInfo() { + return { + trace: this.channelzTrace, + callTracker: this.callTracker, + listenerChildren: this.listenerChildrenTracker.getChildLists(), + sessionChildren: this.sessionChildrenTracker.getChildLists(), + }; + } + getChannelzSessionInfo(session) { + var _b, _c, _d; + const sessionInfo = this.sessions.get(session); + const sessionSocket = session.socket; + const remoteAddress = sessionSocket.remoteAddress + ? (0, subchannel_address_1.stringToSubchannelAddress)(sessionSocket.remoteAddress, sessionSocket.remotePort) + : null; + const localAddress = sessionSocket.localAddress + ? (0, subchannel_address_1.stringToSubchannelAddress)(sessionSocket.localAddress, sessionSocket.localPort) + : null; + let tlsInfo; + if (session.encrypted) { + const tlsSocket = sessionSocket; + const cipherInfo = tlsSocket.getCipher(); + const certificate = tlsSocket.getCertificate(); + const peerCertificate = tlsSocket.getPeerCertificate(); + tlsInfo = { + cipherSuiteStandardName: (_b = cipherInfo.standardName) !== null && _b !== void 0 ? _b : null, + cipherSuiteOtherName: cipherInfo.standardName ? null : cipherInfo.name, + localCertificate: certificate && 'raw' in certificate ? certificate.raw : null, + remoteCertificate: peerCertificate && 'raw' in peerCertificate + ? peerCertificate.raw + : null, + }; + } + else { + tlsInfo = null; + } + const socketInfo = { + remoteAddress: remoteAddress, + localAddress: localAddress, + security: tlsInfo, + remoteName: null, + streamsStarted: sessionInfo.streamTracker.callsStarted, + streamsSucceeded: sessionInfo.streamTracker.callsSucceeded, + streamsFailed: sessionInfo.streamTracker.callsFailed, + messagesSent: sessionInfo.messagesSent, + messagesReceived: sessionInfo.messagesReceived, + keepAlivesSent: sessionInfo.keepAlivesSent, + lastLocalStreamCreatedTimestamp: null, + lastRemoteStreamCreatedTimestamp: sessionInfo.streamTracker.lastCallStartedTimestamp, + lastMessageSentTimestamp: sessionInfo.lastMessageSentTimestamp, + lastMessageReceivedTimestamp: sessionInfo.lastMessageReceivedTimestamp, + localFlowControlWindow: (_c = session.state.localWindowSize) !== null && _c !== void 0 ? _c : null, + remoteFlowControlWindow: (_d = session.state.remoteWindowSize) !== null && _d !== void 0 ? _d : null, + }; + return socketInfo; + } + trace(text) { + logging.trace(constants_1.LogVerbosity.DEBUG, TRACER_NAME, '(' + this.channelzRef.id + ') ' + text); + } + addProtoService() { + throw new Error('Not implemented. Use addService() instead'); + } + addService(service, implementation) { + if (service === null || + typeof service !== 'object' || + implementation === null || + typeof implementation !== 'object') { + throw new Error('addService() requires two objects as arguments'); + } + const serviceKeys = Object.keys(service); + if (serviceKeys.length === 0) { + throw new Error('Cannot add an empty service to a server'); + } + serviceKeys.forEach(name => { + const attrs = service[name]; + let methodType; + if (attrs.requestStream) { + if (attrs.responseStream) { + methodType = 'bidi'; + } + else { + methodType = 'clientStream'; + } + } + else { + if (attrs.responseStream) { + methodType = 'serverStream'; + } + else { + methodType = 'unary'; + } + } + let implFn = implementation[name]; + let impl; + if (implFn === undefined && typeof attrs.originalName === 'string') { + implFn = implementation[attrs.originalName]; + } + if (implFn !== undefined) { + impl = implFn.bind(implementation); + } + else { + impl = getDefaultHandler(methodType, name); + } + const success = this.register(attrs.path, impl, attrs.responseSerialize, attrs.requestDeserialize, methodType); + if (success === false) { + throw new Error(`Method handler for ${attrs.path} already provided.`); + } + }); + } + removeService(service) { + if (service === null || typeof service !== 'object') { + throw new Error('removeService() requires object as argument'); + } + const serviceKeys = Object.keys(service); + serviceKeys.forEach(name => { + const attrs = service[name]; + this.unregister(attrs.path); + }); + } + bind(port, creds) { + throw new Error('Not implemented. Use bindAsync() instead'); + } + registerListenerToChannelz(boundAddress) { + return (0, channelz_1.registerChannelzSocket)((0, subchannel_address_1.subchannelAddressToString)(boundAddress), () => { + return { + localAddress: boundAddress, + remoteAddress: null, + security: null, + remoteName: null, + streamsStarted: 0, + streamsSucceeded: 0, + streamsFailed: 0, + messagesSent: 0, + messagesReceived: 0, + keepAlivesSent: 0, + lastLocalStreamCreatedTimestamp: null, + lastRemoteStreamCreatedTimestamp: null, + lastMessageSentTimestamp: null, + lastMessageReceivedTimestamp: null, + localFlowControlWindow: null, + remoteFlowControlWindow: null, + }; + }, this.channelzEnabled); + } + createHttp2Server(credentials) { + let http2Server; + if (credentials._isSecure()) { + const secureServerOptions = Object.assign(this.commonServerOptions, credentials._getSettings()); + secureServerOptions.enableTrace = + this.options['grpc-node.tls_enable_trace'] === 1; + http2Server = http2.createSecureServer(secureServerOptions); + http2Server.on('secureConnection', (socket) => { + /* These errors need to be handled by the user of Http2SecureServer, + * according to https://github.com/nodejs/node/issues/35824 */ + socket.on('error', (e) => { + this.trace('An incoming TLS connection closed with error: ' + e.message); + }); + }); + } + else { + http2Server = http2.createServer(this.commonServerOptions); + } + http2Server.setTimeout(0, noop); + this._setupHandlers(http2Server); + return http2Server; + } + bindOneAddress(address, boundPortObject) { + this.trace('Attempting to bind ' + (0, subchannel_address_1.subchannelAddressToString)(address)); + const http2Server = this.createHttp2Server(boundPortObject.credentials); + return new Promise((resolve, reject) => { + const onError = (err) => { + this.trace('Failed to bind ' + + (0, subchannel_address_1.subchannelAddressToString)(address) + + ' with error ' + + err.message); + resolve({ + port: 'port' in address ? address.port : 1, + error: err.message, + }); + }; + http2Server.once('error', onError); + http2Server.listen(address, () => { + const boundAddress = http2Server.address(); + let boundSubchannelAddress; + if (typeof boundAddress === 'string') { + boundSubchannelAddress = { + path: boundAddress, + }; + } + else { + boundSubchannelAddress = { + host: boundAddress.address, + port: boundAddress.port, + }; + } + const channelzRef = this.registerListenerToChannelz(boundSubchannelAddress); + this.listenerChildrenTracker.refChild(channelzRef); + this.http2Servers.set(http2Server, { + channelzRef: channelzRef, + sessions: new Set(), + }); + boundPortObject.listeningServers.add(http2Server); + this.trace('Successfully bound ' + + (0, subchannel_address_1.subchannelAddressToString)(boundSubchannelAddress)); + resolve({ + port: 'port' in boundSubchannelAddress ? boundSubchannelAddress.port : 1, + }); + http2Server.removeListener('error', onError); + }); + }); + } + async bindManyPorts(addressList, boundPortObject) { + if (addressList.length === 0) { + return { + count: 0, + port: 0, + errors: [], + }; + } + if ((0, subchannel_address_1.isTcpSubchannelAddress)(addressList[0]) && addressList[0].port === 0) { + /* If binding to port 0, first try to bind the first address, then bind + * the rest of the address list to the specific port that it binds. */ + const firstAddressResult = await this.bindOneAddress(addressList[0], boundPortObject); + if (firstAddressResult.error) { + /* If the first address fails to bind, try the same operation starting + * from the second item in the list. */ + const restAddressResult = await this.bindManyPorts(addressList.slice(1), boundPortObject); + return Object.assign(Object.assign({}, restAddressResult), { errors: [firstAddressResult.error, ...restAddressResult.errors] }); + } + else { + const restAddresses = addressList + .slice(1) + .map(address => (0, subchannel_address_1.isTcpSubchannelAddress)(address) + ? { host: address.host, port: firstAddressResult.port } + : address); + const restAddressResult = await Promise.all(restAddresses.map(address => this.bindOneAddress(address, boundPortObject))); + const allResults = [firstAddressResult, ...restAddressResult]; + return { + count: allResults.filter(result => result.error === undefined).length, + port: firstAddressResult.port, + errors: allResults + .filter(result => result.error) + .map(result => result.error), + }; + } + } + else { + const allResults = await Promise.all(addressList.map(address => this.bindOneAddress(address, boundPortObject))); + return { + count: allResults.filter(result => result.error === undefined).length, + port: allResults[0].port, + errors: allResults + .filter(result => result.error) + .map(result => result.error), + }; + } + } + async bindAddressList(addressList, boundPortObject) { + const bindResult = await this.bindManyPorts(addressList, boundPortObject); + if (bindResult.count > 0) { + if (bindResult.count < addressList.length) { + logging.log(constants_1.LogVerbosity.INFO, `WARNING Only ${bindResult.count} addresses added out of total ${addressList.length} resolved`); + } + return bindResult.port; + } + else { + const errorString = `No address added out of total ${addressList.length} resolved`; + logging.log(constants_1.LogVerbosity.ERROR, errorString); + throw new Error(`${errorString} errors: [${bindResult.errors.join(',')}]`); + } + } + resolvePort(port) { + return new Promise((resolve, reject) => { + const resolverListener = { + onSuccessfulResolution: (endpointList, serviceConfig, serviceConfigError) => { + // We only want one resolution result. Discard all future results + resolverListener.onSuccessfulResolution = () => { }; + const addressList = [].concat(...endpointList.map(endpoint => endpoint.addresses)); + if (addressList.length === 0) { + reject(new Error(`No addresses resolved for port ${port}`)); + return; + } + resolve(addressList); + }, + onError: error => { + reject(new Error(error.details)); + }, + }; + const resolver = (0, resolver_1.createResolver)(port, resolverListener, this.options); + resolver.updateResolution(); + }); + } + async bindPort(port, boundPortObject) { + const addressList = await this.resolvePort(port); + if (boundPortObject.cancelled) { + this.completeUnbind(boundPortObject); + throw new Error('bindAsync operation cancelled by unbind call'); + } + const portNumber = await this.bindAddressList(addressList, boundPortObject); + if (boundPortObject.cancelled) { + this.completeUnbind(boundPortObject); + throw new Error('bindAsync operation cancelled by unbind call'); + } + return portNumber; + } + normalizePort(port) { + const initialPortUri = (0, uri_parser_1.parseUri)(port); + if (initialPortUri === null) { + throw new Error(`Could not parse port "${port}"`); + } + const portUri = (0, resolver_1.mapUriDefaultScheme)(initialPortUri); + if (portUri === null) { + throw new Error(`Could not get a default scheme for port "${port}"`); + } + return portUri; + } + bindAsync(port, creds, callback) { + if (this.shutdown) { + throw new Error('bindAsync called after shutdown'); + } + if (typeof port !== 'string') { + throw new TypeError('port must be a string'); + } + if (creds === null || !(creds instanceof server_credentials_1.ServerCredentials)) { + throw new TypeError('creds must be a ServerCredentials object'); + } + if (typeof callback !== 'function') { + throw new TypeError('callback must be a function'); + } + this.trace('bindAsync port=' + port); + const portUri = this.normalizePort(port); + const deferredCallback = (error, port) => { + process.nextTick(() => callback(error, port)); + }; + /* First, if this port is already bound or that bind operation is in + * progress, use that result. */ + let boundPortObject = this.boundPorts.get((0, uri_parser_1.uriToString)(portUri)); + if (boundPortObject) { + if (!creds._equals(boundPortObject.credentials)) { + deferredCallback(new Error(`${port} already bound with incompatible credentials`), 0); + return; + } + /* If that operation has previously been cancelled by an unbind call, + * uncancel it. */ + boundPortObject.cancelled = false; + if (boundPortObject.completionPromise) { + boundPortObject.completionPromise.then(portNum => callback(null, portNum), error => callback(error, 0)); + } + else { + deferredCallback(null, boundPortObject.portNumber); + } + return; + } + boundPortObject = { + mapKey: (0, uri_parser_1.uriToString)(portUri), + originalUri: portUri, + completionPromise: null, + cancelled: false, + portNumber: 0, + credentials: creds, + listeningServers: new Set(), + }; + const splitPort = (0, uri_parser_1.splitHostPort)(portUri.path); + const completionPromise = this.bindPort(portUri, boundPortObject); + boundPortObject.completionPromise = completionPromise; + /* If the port number is 0, defer populating the map entry until after the + * bind operation completes and we have a specific port number. Otherwise, + * populate it immediately. */ + if ((splitPort === null || splitPort === void 0 ? void 0 : splitPort.port) === 0) { + completionPromise.then(portNum => { + const finalUri = { + scheme: portUri.scheme, + authority: portUri.authority, + path: (0, uri_parser_1.combineHostPort)({ host: splitPort.host, port: portNum }), + }; + boundPortObject.mapKey = (0, uri_parser_1.uriToString)(finalUri); + boundPortObject.completionPromise = null; + boundPortObject.portNumber = portNum; + this.boundPorts.set(boundPortObject.mapKey, boundPortObject); + callback(null, portNum); + }, error => { + callback(error, 0); + }); + } + else { + this.boundPorts.set(boundPortObject.mapKey, boundPortObject); + completionPromise.then(portNum => { + boundPortObject.completionPromise = null; + boundPortObject.portNumber = portNum; + callback(null, portNum); + }, error => { + callback(error, 0); + }); + } + } + closeServer(server, callback) { + this.trace('Closing server with address ' + JSON.stringify(server.address())); + const serverInfo = this.http2Servers.get(server); + server.close(() => { + if (serverInfo) { + this.listenerChildrenTracker.unrefChild(serverInfo.channelzRef); + (0, channelz_1.unregisterChannelzRef)(serverInfo.channelzRef); + } + this.http2Servers.delete(server); + callback === null || callback === void 0 ? void 0 : callback(); + }); + } + closeSession(session, callback) { + var _b; + this.trace('Closing session initiated by ' + ((_b = session.socket) === null || _b === void 0 ? void 0 : _b.remoteAddress)); + const sessionInfo = this.sessions.get(session); + const closeCallback = () => { + if (sessionInfo) { + this.sessionChildrenTracker.unrefChild(sessionInfo.ref); + (0, channelz_1.unregisterChannelzRef)(sessionInfo.ref); + } + callback === null || callback === void 0 ? void 0 : callback(); + }; + if (session.closed) { + queueMicrotask(closeCallback); + } + else { + session.close(closeCallback); + } + } + completeUnbind(boundPortObject) { + for (const server of boundPortObject.listeningServers) { + const serverInfo = this.http2Servers.get(server); + this.closeServer(server, () => { + boundPortObject.listeningServers.delete(server); + }); + if (serverInfo) { + for (const session of serverInfo.sessions) { + this.closeSession(session); + } + } + } + this.boundPorts.delete(boundPortObject.mapKey); + } + /** + * Unbind a previously bound port, or cancel an in-progress bindAsync + * operation. If port 0 was bound, only the actual bound port can be + * unbound. For example, if bindAsync was called with "localhost:0" and the + * bound port result was 54321, it can be unbound as "localhost:54321". + * @param port + */ + unbind(port) { + this.trace('unbind port=' + port); + const portUri = this.normalizePort(port); + const splitPort = (0, uri_parser_1.splitHostPort)(portUri.path); + if ((splitPort === null || splitPort === void 0 ? void 0 : splitPort.port) === 0) { + throw new Error('Cannot unbind port 0'); + } + const boundPortObject = this.boundPorts.get((0, uri_parser_1.uriToString)(portUri)); + if (boundPortObject) { + this.trace('unbinding ' + + boundPortObject.mapKey + + ' originally bound as ' + + (0, uri_parser_1.uriToString)(boundPortObject.originalUri)); + /* If the bind operation is pending, the cancelled flag will trigger + * the unbind operation later. */ + if (boundPortObject.completionPromise) { + boundPortObject.cancelled = true; + } + else { + this.completeUnbind(boundPortObject); + } + } + } + /** + * Gracefully close all connections associated with a previously bound port. + * After the grace time, forcefully close all remaining open connections. + * + * If port 0 was bound, only the actual bound port can be + * drained. For example, if bindAsync was called with "localhost:0" and the + * bound port result was 54321, it can be drained as "localhost:54321". + * @param port + * @param graceTimeMs + * @returns + */ + drain(port, graceTimeMs) { + var _b, _c; + this.trace('drain port=' + port + ' graceTimeMs=' + graceTimeMs); + const portUri = this.normalizePort(port); + const splitPort = (0, uri_parser_1.splitHostPort)(portUri.path); + if ((splitPort === null || splitPort === void 0 ? void 0 : splitPort.port) === 0) { + throw new Error('Cannot drain port 0'); + } + const boundPortObject = this.boundPorts.get((0, uri_parser_1.uriToString)(portUri)); + if (!boundPortObject) { + return; + } + const allSessions = new Set(); + for (const http2Server of boundPortObject.listeningServers) { + const serverEntry = this.http2Servers.get(http2Server); + if (serverEntry) { + for (const session of serverEntry.sessions) { + allSessions.add(session); + this.closeSession(session, () => { + allSessions.delete(session); + }); + } + } + } + /* After the grace time ends, send another goaway to all remaining sessions + * with the CANCEL code. */ + (_c = (_b = setTimeout(() => { + for (const session of allSessions) { + session.destroy(http2.constants.NGHTTP2_CANCEL); + } + }, graceTimeMs)).unref) === null || _c === void 0 ? void 0 : _c.call(_b); + } + forceShutdown() { + for (const boundPortObject of this.boundPorts.values()) { + boundPortObject.cancelled = true; + } + this.boundPorts.clear(); + // Close the server if it is still running. + for (const server of this.http2Servers.keys()) { + this.closeServer(server); + } + // Always destroy any available sessions. It's possible that one or more + // tryShutdown() calls are in progress. Don't wait on them to finish. + this.sessions.forEach((channelzInfo, session) => { + this.closeSession(session); + // Cast NGHTTP2_CANCEL to any because TypeScript doesn't seem to + // recognize destroy(code) as a valid signature. + // eslint-disable-next-line @typescript-eslint/no-explicit-any + session.destroy(http2.constants.NGHTTP2_CANCEL); + }); + this.sessions.clear(); + (0, channelz_1.unregisterChannelzRef)(this.channelzRef); + this.shutdown = true; + } + register(name, handler, serialize, deserialize, type) { + if (this.handlers.has(name)) { + return false; + } + this.handlers.set(name, { + func: handler, + serialize, + deserialize, + type, + path: name, + }); + return true; + } + unregister(name) { + return this.handlers.delete(name); + } + /** + * @deprecated No longer needed as of version 1.10.x + */ + start() { + if (this.http2Servers.size === 0 || + [...this.http2Servers.keys()].every(server => !server.listening)) { + throw new Error('server must be bound in order to start'); + } + if (this.started === true) { + throw new Error('server is already started'); + } + this.started = true; + } + tryShutdown(callback) { + var _b; + const wrappedCallback = (error) => { + (0, channelz_1.unregisterChannelzRef)(this.channelzRef); + callback(error); + }; + let pendingChecks = 0; + function maybeCallback() { + pendingChecks--; + if (pendingChecks === 0) { + wrappedCallback(); + } + } + this.shutdown = true; + for (const [serverKey, server] of this.http2Servers.entries()) { + pendingChecks++; + const serverString = server.channelzRef.name; + this.trace('Waiting for server ' + serverString + ' to close'); + this.closeServer(serverKey, () => { + this.trace('Server ' + serverString + ' finished closing'); + maybeCallback(); + }); + for (const session of server.sessions.keys()) { + pendingChecks++; + const sessionString = (_b = session.socket) === null || _b === void 0 ? void 0 : _b.remoteAddress; + this.trace('Waiting for session ' + sessionString + ' to close'); + this.closeSession(session, () => { + this.trace('Session ' + sessionString + ' finished closing'); + maybeCallback(); + }); + } + } + if (pendingChecks === 0) { + wrappedCallback(); + } + } + addHttp2Port() { + throw new Error('Not yet implemented'); + } + /** + * Get the channelz reference object for this server. The returned value is + * garbage if channelz is disabled for this server. + * @returns + */ + getChannelzRef() { + return this.channelzRef; + } + _verifyContentType(stream, headers) { + const contentType = headers[http2.constants.HTTP2_HEADER_CONTENT_TYPE]; + if (typeof contentType !== 'string' || + !contentType.startsWith('application/grpc')) { + stream.respond({ + [http2.constants.HTTP2_HEADER_STATUS]: http2.constants.HTTP_STATUS_UNSUPPORTED_MEDIA_TYPE, + }, { endStream: true }); + return false; + } + return true; + } + _retrieveHandler(path) { + this.trace('Received call to method ' + + path + + ' at address ' + + this.serverAddressString); + const handler = this.handlers.get(path); + if (handler === undefined) { + this.trace('No handler registered for method ' + + path + + '. Sending UNIMPLEMENTED status.'); + return null; + } + return handler; + } + _respondWithError(err, stream, channelzSessionInfo = null) { + var _b, _c; + const trailersToSend = Object.assign({ 'grpc-status': (_b = err.code) !== null && _b !== void 0 ? _b : constants_1.Status.INTERNAL, 'grpc-message': err.details, [http2.constants.HTTP2_HEADER_STATUS]: http2.constants.HTTP_STATUS_OK, [http2.constants.HTTP2_HEADER_CONTENT_TYPE]: 'application/grpc+proto' }, (_c = err.metadata) === null || _c === void 0 ? void 0 : _c.toHttp2Headers()); + stream.respond(trailersToSend, { endStream: true }); + this.callTracker.addCallFailed(); + channelzSessionInfo === null || channelzSessionInfo === void 0 ? void 0 : channelzSessionInfo.streamTracker.addCallFailed(); + } + _channelzHandler(stream, headers) { + // for handling idle timeout + this.onStreamOpened(stream); + const channelzSessionInfo = this.sessions.get(stream.session); + this.callTracker.addCallStarted(); + channelzSessionInfo === null || channelzSessionInfo === void 0 ? void 0 : channelzSessionInfo.streamTracker.addCallStarted(); + if (!this._verifyContentType(stream, headers)) { + this.callTracker.addCallFailed(); + channelzSessionInfo === null || channelzSessionInfo === void 0 ? void 0 : channelzSessionInfo.streamTracker.addCallFailed(); + return; + } + const path = headers[HTTP2_HEADER_PATH]; + const handler = this._retrieveHandler(path); + if (!handler) { + this._respondWithError(getUnimplementedStatusResponse(path), stream, channelzSessionInfo); + return; + } + const callEventTracker = { + addMessageSent: () => { + if (channelzSessionInfo) { + channelzSessionInfo.messagesSent += 1; + channelzSessionInfo.lastMessageSentTimestamp = new Date(); + } + }, + addMessageReceived: () => { + if (channelzSessionInfo) { + channelzSessionInfo.messagesReceived += 1; + channelzSessionInfo.lastMessageReceivedTimestamp = new Date(); + } + }, + onCallEnd: status => { + if (status.code === constants_1.Status.OK) { + this.callTracker.addCallSucceeded(); + } + else { + this.callTracker.addCallFailed(); + } + }, + onStreamEnd: success => { + if (channelzSessionInfo) { + if (success) { + channelzSessionInfo.streamTracker.addCallSucceeded(); + } + else { + channelzSessionInfo.streamTracker.addCallFailed(); + } + } + }, + }; + const call = (0, server_interceptors_1.getServerInterceptingCall)(this.interceptors, stream, headers, callEventTracker, handler, this.options); + if (!this._runHandlerForCall(call, handler)) { + this.callTracker.addCallFailed(); + channelzSessionInfo === null || channelzSessionInfo === void 0 ? void 0 : channelzSessionInfo.streamTracker.addCallFailed(); + call.sendStatus({ + code: constants_1.Status.INTERNAL, + details: `Unknown handler type: ${handler.type}`, + }); + } + } + _streamHandler(stream, headers) { + // for handling idle timeout + this.onStreamOpened(stream); + if (this._verifyContentType(stream, headers) !== true) { + return; + } + const path = headers[HTTP2_HEADER_PATH]; + const handler = this._retrieveHandler(path); + if (!handler) { + this._respondWithError(getUnimplementedStatusResponse(path), stream, null); + return; + } + const call = (0, server_interceptors_1.getServerInterceptingCall)(this.interceptors, stream, headers, null, handler, this.options); + if (!this._runHandlerForCall(call, handler)) { + call.sendStatus({ + code: constants_1.Status.INTERNAL, + details: `Unknown handler type: ${handler.type}`, + }); + } + } + _runHandlerForCall(call, handler) { + const { type } = handler; + if (type === 'unary') { + handleUnary(call, handler); + } + else if (type === 'clientStream') { + handleClientStreaming(call, handler); + } + else if (type === 'serverStream') { + handleServerStreaming(call, handler); + } + else if (type === 'bidi') { + handleBidiStreaming(call, handler); + } + else { + return false; + } + return true; + } + _setupHandlers(http2Server) { + if (http2Server === null) { + return; + } + const serverAddress = http2Server.address(); + let serverAddressString = 'null'; + if (serverAddress) { + if (typeof serverAddress === 'string') { + serverAddressString = serverAddress; + } + else { + serverAddressString = serverAddress.address + ':' + serverAddress.port; + } + } + this.serverAddressString = serverAddressString; + const handler = this.channelzEnabled + ? this._channelzHandler + : this._streamHandler; + const sessionHandler = this.channelzEnabled + ? this._channelzSessionHandler(http2Server) + : this._sessionHandler(http2Server); + http2Server.on('stream', handler.bind(this)); + http2Server.on('session', sessionHandler); + } + _sessionHandler(http2Server) { + return (session) => { + var _b, _c, _d; + (_b = this.http2Servers.get(http2Server)) === null || _b === void 0 ? void 0 : _b.sessions.add(session); + let connectionAgeTimer = null; + let connectionAgeGraceTimer = null; + let keeapliveTimeTimer = null; + let keepaliveTimeoutTimer = null; + let sessionClosedByServer = false; + const idleTimeoutObj = this.enableIdleTimeout(session); + if (this.maxConnectionAgeMs !== UNLIMITED_CONNECTION_AGE_MS) { + // Apply a random jitter within a +/-10% range + const jitterMagnitude = this.maxConnectionAgeMs / 10; + const jitter = Math.random() * jitterMagnitude * 2 - jitterMagnitude; + connectionAgeTimer = setTimeout(() => { + var _b, _c; + sessionClosedByServer = true; + this.trace('Connection dropped by max connection age: ' + + ((_b = session.socket) === null || _b === void 0 ? void 0 : _b.remoteAddress)); + try { + session.goaway(http2.constants.NGHTTP2_NO_ERROR, ~(1 << 31), kMaxAge); + } + catch (e) { + // The goaway can't be sent because the session is already closed + session.destroy(); + return; + } + session.close(); + /* Allow a grace period after sending the GOAWAY before forcibly + * closing the connection. */ + if (this.maxConnectionAgeGraceMs !== UNLIMITED_CONNECTION_AGE_MS) { + connectionAgeGraceTimer = setTimeout(() => { + session.destroy(); + }, this.maxConnectionAgeGraceMs); + (_c = connectionAgeGraceTimer.unref) === null || _c === void 0 ? void 0 : _c.call(connectionAgeGraceTimer); + } + }, this.maxConnectionAgeMs + jitter); + (_c = connectionAgeTimer.unref) === null || _c === void 0 ? void 0 : _c.call(connectionAgeTimer); + } + if (this.keepaliveTimeMs < KEEPALIVE_MAX_TIME_MS) { + keeapliveTimeTimer = setInterval(() => { + var _b; + keepaliveTimeoutTimer = setTimeout(() => { + sessionClosedByServer = true; + session.close(); + }, this.keepaliveTimeoutMs); + (_b = keepaliveTimeoutTimer.unref) === null || _b === void 0 ? void 0 : _b.call(keepaliveTimeoutTimer); + try { + session.ping((err, duration, payload) => { + if (keepaliveTimeoutTimer) { + clearTimeout(keepaliveTimeoutTimer); + } + if (err) { + sessionClosedByServer = true; + this.trace('Connection dropped due to error of a ping frame ' + + err.message + + ' return in ' + + duration); + session.close(); + } + }); + } + catch (e) { + clearTimeout(keepaliveTimeoutTimer); + // The ping can't be sent because the session is already closed + session.destroy(); + } + }, this.keepaliveTimeMs); + (_d = keeapliveTimeTimer.unref) === null || _d === void 0 ? void 0 : _d.call(keeapliveTimeTimer); + } + session.on('close', () => { + var _b, _c; + if (!sessionClosedByServer) { + this.trace(`Connection dropped by client ${(_b = session.socket) === null || _b === void 0 ? void 0 : _b.remoteAddress}`); + } + if (connectionAgeTimer) { + clearTimeout(connectionAgeTimer); + } + if (connectionAgeGraceTimer) { + clearTimeout(connectionAgeGraceTimer); + } + if (keeapliveTimeTimer) { + clearInterval(keeapliveTimeTimer); + if (keepaliveTimeoutTimer) { + clearTimeout(keepaliveTimeoutTimer); + } + } + if (idleTimeoutObj !== null) { + clearTimeout(idleTimeoutObj.timeout); + this.sessionIdleTimeouts.delete(session); + } + (_c = this.http2Servers.get(http2Server)) === null || _c === void 0 ? void 0 : _c.sessions.delete(session); + }); + }; + } + _channelzSessionHandler(http2Server) { + return (session) => { + var _b, _c, _d, _e, _f; + const channelzRef = (0, channelz_1.registerChannelzSocket)((_c = (_b = session.socket) === null || _b === void 0 ? void 0 : _b.remoteAddress) !== null && _c !== void 0 ? _c : 'unknown', this.getChannelzSessionInfo.bind(this, session), this.channelzEnabled); + const channelzSessionInfo = { + ref: channelzRef, + streamTracker: new channelz_1.ChannelzCallTracker(), + messagesSent: 0, + messagesReceived: 0, + keepAlivesSent: 0, + lastMessageSentTimestamp: null, + lastMessageReceivedTimestamp: null, + }; + (_d = this.http2Servers.get(http2Server)) === null || _d === void 0 ? void 0 : _d.sessions.add(session); + this.sessions.set(session, channelzSessionInfo); + const clientAddress = `${session.socket.remoteAddress}:${session.socket.remotePort}`; + this.channelzTrace.addTrace('CT_INFO', 'Connection established by client ' + clientAddress); + this.trace('Connection established by client ' + clientAddress); + this.sessionChildrenTracker.refChild(channelzRef); + let connectionAgeTimer = null; + let connectionAgeGraceTimer = null; + let keeapliveTimeTimer = null; + let keepaliveTimeoutTimer = null; + let sessionClosedByServer = false; + const idleTimeoutObj = this.enableIdleTimeout(session); + if (this.maxConnectionAgeMs !== UNLIMITED_CONNECTION_AGE_MS) { + // Apply a random jitter within a +/-10% range + const jitterMagnitude = this.maxConnectionAgeMs / 10; + const jitter = Math.random() * jitterMagnitude * 2 - jitterMagnitude; + connectionAgeTimer = setTimeout(() => { + var _b; + sessionClosedByServer = true; + this.channelzTrace.addTrace('CT_INFO', 'Connection dropped by max connection age from ' + clientAddress); + try { + session.goaway(http2.constants.NGHTTP2_NO_ERROR, ~(1 << 31), kMaxAge); + } + catch (e) { + // The goaway can't be sent because the session is already closed + session.destroy(); + return; + } + session.close(); + /* Allow a grace period after sending the GOAWAY before forcibly + * closing the connection. */ + if (this.maxConnectionAgeGraceMs !== UNLIMITED_CONNECTION_AGE_MS) { + connectionAgeGraceTimer = setTimeout(() => { + session.destroy(); + }, this.maxConnectionAgeGraceMs); + (_b = connectionAgeGraceTimer.unref) === null || _b === void 0 ? void 0 : _b.call(connectionAgeGraceTimer); + } + }, this.maxConnectionAgeMs + jitter); + (_e = connectionAgeTimer.unref) === null || _e === void 0 ? void 0 : _e.call(connectionAgeTimer); + } + if (this.keepaliveTimeMs < KEEPALIVE_MAX_TIME_MS) { + keeapliveTimeTimer = setInterval(() => { + var _b; + keepaliveTimeoutTimer = setTimeout(() => { + sessionClosedByServer = true; + this.channelzTrace.addTrace('CT_INFO', 'Connection dropped by keepalive timeout from ' + clientAddress); + session.close(); + }, this.keepaliveTimeoutMs); + (_b = keepaliveTimeoutTimer.unref) === null || _b === void 0 ? void 0 : _b.call(keepaliveTimeoutTimer); + try { + session.ping((err, duration, payload) => { + if (keepaliveTimeoutTimer) { + clearTimeout(keepaliveTimeoutTimer); + } + if (err) { + sessionClosedByServer = true; + this.channelzTrace.addTrace('CT_INFO', 'Connection dropped due to error of a ping frame ' + + err.message + + ' return in ' + + duration); + session.close(); + } + }); + channelzSessionInfo.keepAlivesSent += 1; + } + catch (e) { + clearTimeout(keepaliveTimeoutTimer); + // The ping can't be sent because the session is already closed + session.destroy(); + } + }, this.keepaliveTimeMs); + (_f = keeapliveTimeTimer.unref) === null || _f === void 0 ? void 0 : _f.call(keeapliveTimeTimer); + } + session.on('close', () => { + var _b; + if (!sessionClosedByServer) { + this.channelzTrace.addTrace('CT_INFO', 'Connection dropped by client ' + clientAddress); + } + this.sessionChildrenTracker.unrefChild(channelzRef); + (0, channelz_1.unregisterChannelzRef)(channelzRef); + if (connectionAgeTimer) { + clearTimeout(connectionAgeTimer); + } + if (connectionAgeGraceTimer) { + clearTimeout(connectionAgeGraceTimer); + } + if (keeapliveTimeTimer) { + clearInterval(keeapliveTimeTimer); + if (keepaliveTimeoutTimer) { + clearTimeout(keepaliveTimeoutTimer); + } + } + if (idleTimeoutObj !== null) { + clearTimeout(idleTimeoutObj.timeout); + this.sessionIdleTimeouts.delete(session); + } + (_b = this.http2Servers.get(http2Server)) === null || _b === void 0 ? void 0 : _b.sessions.delete(session); + this.sessions.delete(session); + }); + }; + } + enableIdleTimeout(session) { + var _b, _c; + if (this.sessionIdleTimeout >= MAX_CONNECTION_IDLE_MS) { + return null; + } + const idleTimeoutObj = { + activeStreams: 0, + lastIdle: Date.now(), + onClose: this.onStreamClose.bind(this, session), + timeout: setTimeout(this.onIdleTimeout, this.sessionIdleTimeout, this, session), + }; + (_c = (_b = idleTimeoutObj.timeout).unref) === null || _c === void 0 ? void 0 : _c.call(_b); + this.sessionIdleTimeouts.set(session, idleTimeoutObj); + const { socket } = session; + this.trace('Enable idle timeout for ' + + socket.remoteAddress + + ':' + + socket.remotePort); + return idleTimeoutObj; + } + onIdleTimeout(ctx, session) { + const { socket } = session; + const sessionInfo = ctx.sessionIdleTimeouts.get(session); + // if it is called while we have activeStreams - timer will not be rescheduled + // until last active stream is closed, then it will call .refresh() on the timer + // important part is to not clearTimeout(timer) or it becomes unusable + // for future refreshes + if (sessionInfo !== undefined && + sessionInfo.activeStreams === 0 && + Date.now() - sessionInfo.lastIdle >= ctx.sessionIdleTimeout) { + ctx.trace('Session idle timeout triggered for ' + + (socket === null || socket === void 0 ? void 0 : socket.remoteAddress) + + ':' + + (socket === null || socket === void 0 ? void 0 : socket.remotePort) + + ' last idle at ' + + sessionInfo.lastIdle); + ctx.closeSession(session); + } + } + onStreamOpened(stream) { + const session = stream.session; + const idleTimeoutObj = this.sessionIdleTimeouts.get(session); + if (idleTimeoutObj) { + idleTimeoutObj.activeStreams += 1; + stream.once('close', idleTimeoutObj.onClose); + } + } + onStreamClose(session) { + var _b, _c; + const idleTimeoutObj = this.sessionIdleTimeouts.get(session); + if (idleTimeoutObj) { + idleTimeoutObj.activeStreams -= 1; + if (idleTimeoutObj.activeStreams === 0) { + idleTimeoutObj.lastIdle = Date.now(); + idleTimeoutObj.timeout.refresh(); + this.trace('Session onStreamClose' + + ((_b = session.socket) === null || _b === void 0 ? void 0 : _b.remoteAddress) + + ':' + + ((_c = session.socket) === null || _c === void 0 ? void 0 : _c.remotePort) + + ' at ' + + idleTimeoutObj.lastIdle); + } + } + } + }, + (() => { + const _metadata = typeof Symbol === "function" && Symbol.metadata ? Object.create(null) : void 0; + _start_decorators = [deprecate('Calling start() is no longer necessary. It can be safely omitted.')]; + __esDecorate(_a, null, _start_decorators, { kind: "method", name: "start", static: false, private: false, access: { has: obj => "start" in obj, get: obj => obj.start }, metadata: _metadata }, null, _instanceExtraInitializers); + if (_metadata) Object.defineProperty(_a, Symbol.metadata, { enumerable: true, configurable: true, writable: true, value: _metadata }); + })(), + _a; +})(); +exports.Server = Server; +async function handleUnary(call, handler) { + let stream; + function respond(err, value, trailer, flags) { + if (err) { + call.sendStatus((0, server_call_1.serverErrorToStatus)(err, trailer)); + return; + } + call.sendMessage(value, () => { + call.sendStatus({ + code: constants_1.Status.OK, + details: 'OK', + metadata: trailer !== null && trailer !== void 0 ? trailer : null, + }); + }); + } + let requestMetadata; + let requestMessage = null; + call.start({ + onReceiveMetadata(metadata) { + requestMetadata = metadata; + call.startRead(); + }, + onReceiveMessage(message) { + if (requestMessage) { + call.sendStatus({ + code: constants_1.Status.UNIMPLEMENTED, + details: `Received a second request message for server streaming method ${handler.path}`, + metadata: null, + }); + return; + } + requestMessage = message; + call.startRead(); + }, + onReceiveHalfClose() { + if (!requestMessage) { + call.sendStatus({ + code: constants_1.Status.UNIMPLEMENTED, + details: `Received no request message for server streaming method ${handler.path}`, + metadata: null, + }); + return; + } + stream = new server_call_1.ServerWritableStreamImpl(handler.path, call, requestMetadata, requestMessage); + try { + handler.func(stream, respond); + } + catch (err) { + call.sendStatus({ + code: constants_1.Status.UNKNOWN, + details: `Server method handler threw error ${err.message}`, + metadata: null, + }); + } + }, + onCancel() { + if (stream) { + stream.cancelled = true; + stream.emit('cancelled', 'cancelled'); + } + }, + }); +} +function handleClientStreaming(call, handler) { + let stream; + function respond(err, value, trailer, flags) { + if (err) { + call.sendStatus((0, server_call_1.serverErrorToStatus)(err, trailer)); + return; + } + call.sendMessage(value, () => { + call.sendStatus({ + code: constants_1.Status.OK, + details: 'OK', + metadata: trailer !== null && trailer !== void 0 ? trailer : null, + }); + }); + } + call.start({ + onReceiveMetadata(metadata) { + stream = new server_call_1.ServerDuplexStreamImpl(handler.path, call, metadata); + try { + handler.func(stream, respond); + } + catch (err) { + call.sendStatus({ + code: constants_1.Status.UNKNOWN, + details: `Server method handler threw error ${err.message}`, + metadata: null, + }); + } + }, + onReceiveMessage(message) { + stream.push(message); + }, + onReceiveHalfClose() { + stream.push(null); + }, + onCancel() { + if (stream) { + stream.cancelled = true; + stream.emit('cancelled', 'cancelled'); + stream.destroy(); + } + }, + }); +} +function handleServerStreaming(call, handler) { + let stream; + let requestMetadata; + let requestMessage = null; + call.start({ + onReceiveMetadata(metadata) { + requestMetadata = metadata; + call.startRead(); + }, + onReceiveMessage(message) { + if (requestMessage) { + call.sendStatus({ + code: constants_1.Status.UNIMPLEMENTED, + details: `Received a second request message for server streaming method ${handler.path}`, + metadata: null, + }); + return; + } + requestMessage = message; + call.startRead(); + }, + onReceiveHalfClose() { + if (!requestMessage) { + call.sendStatus({ + code: constants_1.Status.UNIMPLEMENTED, + details: `Received no request message for server streaming method ${handler.path}`, + metadata: null, + }); + return; + } + stream = new server_call_1.ServerWritableStreamImpl(handler.path, call, requestMetadata, requestMessage); + try { + handler.func(stream); + } + catch (err) { + call.sendStatus({ + code: constants_1.Status.UNKNOWN, + details: `Server method handler threw error ${err.message}`, + metadata: null, + }); + } + }, + onCancel() { + if (stream) { + stream.cancelled = true; + stream.emit('cancelled', 'cancelled'); + stream.destroy(); + } + }, + }); +} +function handleBidiStreaming(call, handler) { + let stream; + call.start({ + onReceiveMetadata(metadata) { + stream = new server_call_1.ServerDuplexStreamImpl(handler.path, call, metadata); + try { + handler.func(stream); + } + catch (err) { + call.sendStatus({ + code: constants_1.Status.UNKNOWN, + details: `Server method handler threw error ${err.message}`, + metadata: null, + }); + } + }, + onReceiveMessage(message) { + stream.push(message); + }, + onReceiveHalfClose() { + stream.push(null); + }, + onCancel() { + if (stream) { + stream.cancelled = true; + stream.emit('cancelled', 'cancelled'); + stream.destroy(); + } + }, + }); +} +//# sourceMappingURL=server.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/server.js.map b/node_modules/@grpc/grpc-js/build/src/server.js.map new file mode 100644 index 0000000..04ffdda --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/server.js.map @@ -0,0 +1 @@ +{"version":3,"file":"server.js","sourceRoot":"","sources":["../../src/server.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;GAeG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAEH,+BAA+B;AAC/B,6BAA6B;AAG7B,2CAAmD;AAGnD,+CAkBuB;AACvB,6DAAyD;AAEzD,yCAIoB;AACpB,qCAAqC;AACrC,6DAK8B;AAC9B,6CAMsB;AACtB,yCAeoB;AAEpB,+DAI+B;AAI/B,MAAM,2BAA2B,GAAG,CAAC,CAAC,CAAC,IAAI,EAAE,CAAC,CAAC;AAC/C,MAAM,qBAAqB,GAAG,CAAC,CAAC,CAAC,IAAI,EAAE,CAAC,CAAC;AACzC,MAAM,oBAAoB,GAAG,KAAK,CAAC;AACnC,MAAM,sBAAsB,GAAG,CAAC,CAAC,CAAC,IAAI,EAAE,CAAC,CAAC;AAE1C,MAAM,EAAE,iBAAiB,EAAE,GAAG,KAAK,CAAC,SAAS,CAAC;AAE9C,MAAM,WAAW,GAAG,QAAQ,CAAC;AAC7B,MAAM,OAAO,GAAG,MAAM,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC;AAevC,SAAS,IAAI,KAAU,CAAC;AAExB;;;;GAIG;AACH,SAAS,SAAS,CAAC,OAAe;IAChC,OAAO,UACL,MAA6C,EAC7C,OAGC;Q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AC;YAClE,IAAI,CAAC;gBACH,OAAO,CAAC,IAAI,CAAC,MAAM,CAAC,CAAC;YACvB,CAAC;YAAC,OAAO,GAAG,EAAE,CAAC;gBACb,IAAI,CAAC,UAAU,CAAC;oBACd,IAAI,EAAE,kBAAM,CAAC,OAAO;oBACpB,OAAO,EAAE,qCACN,GAAa,CAAC,OACjB,EAAE;oBACF,QAAQ,EAAE,IAAI;iBACf,CAAC,CAAC;YACL,CAAC;QACH,CAAC;QACD,gBAAgB,CAAC,OAAO;YACtB,MAAM,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;QACvB,CAAC;QACD,kBAAkB;YAChB,MAAM,CAAC,IAAI,CAAC,IAAI,CAAC,CAAC;QACpB,CAAC;QACD,QAAQ;YACN,IAAI,MAAM,EAAE,CAAC;gBACX,MAAM,CAAC,SAAS,GAAG,IAAI,CAAC;gBACxB,MAAM,CAAC,IAAI,CAAC,WAAW,EAAE,WAAW,CAAC,CAAC;gBACtC,MAAM,CAAC,OAAO,EAAE,CAAC;YACnB,CAAC;QACH,CAAC;KACF,CAAC,CAAC;AACL,CAAC"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/service-config.d.ts b/node_modules/@grpc/grpc-js/build/src/service-config.d.ts new file mode 100644 index 0000000..c638f4f --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/service-config.d.ts @@ -0,0 +1,58 @@ +import { Status } from './constants'; +import { Duration } from './duration'; +export interface MethodConfigName { + service?: string; + method?: string; +} +export interface RetryPolicy { + maxAttempts: number; + initialBackoff: string; + maxBackoff: string; + backoffMultiplier: number; + retryableStatusCodes: (Status | string)[]; +} +export interface HedgingPolicy { + maxAttempts: number; + hedgingDelay?: string; + nonFatalStatusCodes?: (Status | string)[]; +} +export interface MethodConfig { + name: MethodConfigName[]; + waitForReady?: boolean; + timeout?: Duration; + maxRequestBytes?: number; + maxResponseBytes?: number; + retryPolicy?: RetryPolicy; + hedgingPolicy?: HedgingPolicy; +} +export interface RetryThrottling { + maxTokens: number; + tokenRatio: number; +} +export interface LoadBalancingConfig { + [key: string]: object; +} +export interface ServiceConfig { + loadBalancingPolicy?: string; + loadBalancingConfig: LoadBalancingConfig[]; + methodConfig: MethodConfig[]; + retryThrottling?: RetryThrottling; +} +export interface ServiceConfigCanaryConfig { + clientLanguage?: string[]; + percentage?: number; + clientHostname?: string[]; + serviceConfig: ServiceConfig; +} +export declare function validateRetryThrottling(obj: any): RetryThrottling; +export declare function validateServiceConfig(obj: any): ServiceConfig; +/** + * Find the "grpc_config" record among the TXT records, parse its value as JSON, validate its contents, + * and select a service config with selection fields that all match this client. Most of these steps + * can fail with an error; the caller must handle any errors thrown this way. + * @param txtRecord The TXT record array that is output from a successful call to dns.resolveTxt + * @param percentage A number chosen from the range [0, 100) that is used to select which config to use + * @return The service configuration to use, given the percentage value, or null if the service config + * data has a valid format but none of the options match the current client. + */ +export declare function extractAndSelectServiceConfig(txtRecord: string[][], percentage: number): ServiceConfig | null; diff --git a/node_modules/@grpc/grpc-js/build/src/service-config.js b/node_modules/@grpc/grpc-js/build/src/service-config.js new file mode 100644 index 0000000..daaf32f --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/service-config.js @@ -0,0 +1,431 @@ +"use strict"; +/* + * Copyright 2019 gRPC authors. + * + * 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. + * + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.extractAndSelectServiceConfig = exports.validateServiceConfig = exports.validateRetryThrottling = void 0; +/* This file implements gRFC A2 and the service config spec: + * https://github.com/grpc/proposal/blob/master/A2-service-configs-in-dns.md + * https://github.com/grpc/grpc/blob/master/doc/service_config.md. Each + * function here takes an object with unknown structure and returns its + * specific object type if the input has the right structure, and throws an + * error otherwise. */ +/* The any type is purposely used here. All functions validate their input at + * runtime */ +/* eslint-disable @typescript-eslint/no-explicit-any */ +const os = require("os"); +const constants_1 = require("./constants"); +/** + * Recognizes a number with up to 9 digits after the decimal point, followed by + * an "s", representing a number of seconds. + */ +const DURATION_REGEX = /^\d+(\.\d{1,9})?s$/; +/** + * Client language name used for determining whether this client matches a + * `ServiceConfigCanaryConfig`'s `clientLanguage` list. + */ +const CLIENT_LANGUAGE_STRING = 'node'; +function validateName(obj) { + // In this context, and unset field and '' are considered the same + if ('service' in obj && obj.service !== '') { + if (typeof obj.service !== 'string') { + throw new Error(`Invalid method config name: invalid service: expected type string, got ${typeof obj.service}`); + } + if ('method' in obj && obj.method !== '') { + if (typeof obj.method !== 'string') { + throw new Error(`Invalid method config name: invalid method: expected type string, got ${typeof obj.service}`); + } + return { + service: obj.service, + method: obj.method, + }; + } + else { + return { + service: obj.service, + }; + } + } + else { + if ('method' in obj && obj.method !== undefined) { + throw new Error(`Invalid method config name: method set with empty or unset service`); + } + return {}; + } +} +function validateRetryPolicy(obj) { + if (!('maxAttempts' in obj) || + !Number.isInteger(obj.maxAttempts) || + obj.maxAttempts < 2) { + throw new Error('Invalid method config retry policy: maxAttempts must be an integer at least 2'); + } + if (!('initialBackoff' in obj) || + typeof obj.initialBackoff !== 'string' || + !DURATION_REGEX.test(obj.initialBackoff)) { + throw new Error('Invalid method config retry policy: initialBackoff must be a string consisting of a positive integer followed by s'); + } + if (!('maxBackoff' in obj) || + typeof obj.maxBackoff !== 'string' || + !DURATION_REGEX.test(obj.maxBackoff)) { + throw new Error('Invalid method config retry policy: maxBackoff must be a string consisting of a positive integer followed by s'); + } + if (!('backoffMultiplier' in obj) || + typeof obj.backoffMultiplier !== 'number' || + obj.backoffMultiplier <= 0) { + throw new Error('Invalid method config retry policy: backoffMultiplier must be a number greater than 0'); + } + if (!('retryableStatusCodes' in obj && Array.isArray(obj.retryableStatusCodes))) { + throw new Error('Invalid method config retry policy: retryableStatusCodes is required'); + } + if (obj.retryableStatusCodes.length === 0) { + throw new Error('Invalid method config retry policy: retryableStatusCodes must be non-empty'); + } + for (const value of obj.retryableStatusCodes) { + if (typeof value === 'number') { + if (!Object.values(constants_1.Status).includes(value)) { + throw new Error('Invalid method config retry policy: retryableStatusCodes value not in status code range'); + } + } + else if (typeof value === 'string') { + if (!Object.values(constants_1.Status).includes(value.toUpperCase())) { + throw new Error('Invalid method config retry policy: retryableStatusCodes value not a status code name'); + } + } + else { + throw new Error('Invalid method config retry policy: retryableStatusCodes value must be a string or number'); + } + } + return { + maxAttempts: obj.maxAttempts, + initialBackoff: obj.initialBackoff, + maxBackoff: obj.maxBackoff, + backoffMultiplier: obj.backoffMultiplier, + retryableStatusCodes: obj.retryableStatusCodes, + }; +} +function validateHedgingPolicy(obj) { + if (!('maxAttempts' in obj) || + !Number.isInteger(obj.maxAttempts) || + obj.maxAttempts < 2) { + throw new Error('Invalid method config hedging policy: maxAttempts must be an integer at least 2'); + } + if ('hedgingDelay' in obj && + (typeof obj.hedgingDelay !== 'string' || + !DURATION_REGEX.test(obj.hedgingDelay))) { + throw new Error('Invalid method config hedging policy: hedgingDelay must be a string consisting of a positive integer followed by s'); + } + if ('nonFatalStatusCodes' in obj && Array.isArray(obj.nonFatalStatusCodes)) { + for (const value of obj.nonFatalStatusCodes) { + if (typeof value === 'number') { + if (!Object.values(constants_1.Status).includes(value)) { + throw new Error('Invlid method config hedging policy: nonFatalStatusCodes value not in status code range'); + } + } + else if (typeof value === 'string') { + if (!Object.values(constants_1.Status).includes(value.toUpperCase())) { + throw new Error('Invlid method config hedging policy: nonFatalStatusCodes value not a status code name'); + } + } + else { + throw new Error('Invlid method config hedging policy: nonFatalStatusCodes value must be a string or number'); + } + } + } + const result = { + maxAttempts: obj.maxAttempts, + }; + if (obj.hedgingDelay) { + result.hedgingDelay = obj.hedgingDelay; + } + if (obj.nonFatalStatusCodes) { + result.nonFatalStatusCodes = obj.nonFatalStatusCodes; + } + return result; +} +function validateMethodConfig(obj) { + var _a; + const result = { + name: [], + }; + if (!('name' in obj) || !Array.isArray(obj.name)) { + throw new Error('Invalid method config: invalid name array'); + } + for (const name of obj.name) { + result.name.push(validateName(name)); + } + if ('waitForReady' in obj) { + if (typeof obj.waitForReady !== 'boolean') { + throw new Error('Invalid method config: invalid waitForReady'); + } + result.waitForReady = obj.waitForReady; + } + if ('timeout' in obj) { + if (typeof obj.timeout === 'object') { + if (!('seconds' in obj.timeout) || + !(typeof obj.timeout.seconds === 'number')) { + throw new Error('Invalid method config: invalid timeout.seconds'); + } + if (!('nanos' in obj.timeout) || + !(typeof obj.timeout.nanos === 'number')) { + throw new Error('Invalid method config: invalid timeout.nanos'); + } + result.timeout = obj.timeout; + } + else if (typeof obj.timeout === 'string' && + DURATION_REGEX.test(obj.timeout)) { + const timeoutParts = obj.timeout + .substring(0, obj.timeout.length - 1) + .split('.'); + result.timeout = { + seconds: timeoutParts[0] | 0, + nanos: ((_a = timeoutParts[1]) !== null && _a !== void 0 ? _a : 0) | 0, + }; + } + else { + throw new Error('Invalid method config: invalid timeout'); + } + } + if ('maxRequestBytes' in obj) { + if (typeof obj.maxRequestBytes !== 'number') { + throw new Error('Invalid method config: invalid maxRequestBytes'); + } + result.maxRequestBytes = obj.maxRequestBytes; + } + if ('maxResponseBytes' in obj) { + if (typeof obj.maxResponseBytes !== 'number') { + throw new Error('Invalid method config: invalid maxRequestBytes'); + } + result.maxResponseBytes = obj.maxResponseBytes; + } + if ('retryPolicy' in obj) { + if ('hedgingPolicy' in obj) { + throw new Error('Invalid method config: retryPolicy and hedgingPolicy cannot both be specified'); + } + else { + result.retryPolicy = validateRetryPolicy(obj.retryPolicy); + } + } + else if ('hedgingPolicy' in obj) { + result.hedgingPolicy = validateHedgingPolicy(obj.hedgingPolicy); + } + return result; +} +function validateRetryThrottling(obj) { + if (!('maxTokens' in obj) || + typeof obj.maxTokens !== 'number' || + obj.maxTokens <= 0 || + obj.maxTokens > 1000) { + throw new Error('Invalid retryThrottling: maxTokens must be a number in (0, 1000]'); + } + if (!('tokenRatio' in obj) || + typeof obj.tokenRatio !== 'number' || + obj.tokenRatio <= 0) { + throw new Error('Invalid retryThrottling: tokenRatio must be a number greater than 0'); + } + return { + maxTokens: +obj.maxTokens.toFixed(3), + tokenRatio: +obj.tokenRatio.toFixed(3), + }; +} +exports.validateRetryThrottling = validateRetryThrottling; +function validateLoadBalancingConfig(obj) { + if (!(typeof obj === 'object' && obj !== null)) { + throw new Error(`Invalid loadBalancingConfig: unexpected type ${typeof obj}`); + } + const keys = Object.keys(obj); + if (keys.length > 1) { + throw new Error(`Invalid loadBalancingConfig: unexpected multiple keys ${keys}`); + } + if (keys.length === 0) { + throw new Error('Invalid loadBalancingConfig: load balancing policy name required'); + } + return { + [keys[0]]: obj[keys[0]], + }; +} +function validateServiceConfig(obj) { + const result = { + loadBalancingConfig: [], + methodConfig: [], + }; + if ('loadBalancingPolicy' in obj) { + if (typeof obj.loadBalancingPolicy === 'string') { + result.loadBalancingPolicy = obj.loadBalancingPolicy; + } + else { + throw new Error('Invalid service config: invalid loadBalancingPolicy'); + } + } + if ('loadBalancingConfig' in obj) { + if (Array.isArray(obj.loadBalancingConfig)) { + for (const config of obj.loadBalancingConfig) { + result.loadBalancingConfig.push(validateLoadBalancingConfig(config)); + } + } + else { + throw new Error('Invalid service config: invalid loadBalancingConfig'); + } + } + if ('methodConfig' in obj) { + if (Array.isArray(obj.methodConfig)) { + for (const methodConfig of obj.methodConfig) { + result.methodConfig.push(validateMethodConfig(methodConfig)); + } + } + } + if ('retryThrottling' in obj) { + result.retryThrottling = validateRetryThrottling(obj.retryThrottling); + } + // Validate method name uniqueness + const seenMethodNames = []; + for (const methodConfig of result.methodConfig) { + for (const name of methodConfig.name) { + for (const seenName of seenMethodNames) { + if (name.service === seenName.service && + name.method === seenName.method) { + throw new Error(`Invalid service config: duplicate name ${name.service}/${name.method}`); + } + } + seenMethodNames.push(name); + } + } + return result; +} +exports.validateServiceConfig = validateServiceConfig; +function validateCanaryConfig(obj) { + if (!('serviceConfig' in obj)) { + throw new Error('Invalid service config choice: missing service config'); + } + const result = { + serviceConfig: validateServiceConfig(obj.serviceConfig), + }; + if ('clientLanguage' in obj) { + if (Array.isArray(obj.clientLanguage)) { + result.clientLanguage = []; + for (const lang of obj.clientLanguage) { + if (typeof lang === 'string') { + result.clientLanguage.push(lang); + } + else { + throw new Error('Invalid service config choice: invalid clientLanguage'); + } + } + } + else { + throw new Error('Invalid service config choice: invalid clientLanguage'); + } + } + if ('clientHostname' in obj) { + if (Array.isArray(obj.clientHostname)) { + result.clientHostname = []; + for (const lang of obj.clientHostname) { + if (typeof lang === 'string') { + result.clientHostname.push(lang); + } + else { + throw new Error('Invalid service config choice: invalid clientHostname'); + } + } + } + else { + throw new Error('Invalid service config choice: invalid clientHostname'); + } + } + if ('percentage' in obj) { + if (typeof obj.percentage === 'number' && + 0 <= obj.percentage && + obj.percentage <= 100) { + result.percentage = obj.percentage; + } + else { + throw new Error('Invalid service config choice: invalid percentage'); + } + } + // Validate that no unexpected fields are present + const allowedFields = [ + 'clientLanguage', + 'percentage', + 'clientHostname', + 'serviceConfig', + ]; + for (const field in obj) { + if (!allowedFields.includes(field)) { + throw new Error(`Invalid service config choice: unexpected field ${field}`); + } + } + return result; +} +function validateAndSelectCanaryConfig(obj, percentage) { + if (!Array.isArray(obj)) { + throw new Error('Invalid service config list'); + } + for (const config of obj) { + const validatedConfig = validateCanaryConfig(config); + /* For each field, we check if it is present, then only discard the + * config if the field value does not match the current client */ + if (typeof validatedConfig.percentage === 'number' && + percentage > validatedConfig.percentage) { + continue; + } + if (Array.isArray(validatedConfig.clientHostname)) { + let hostnameMatched = false; + for (const hostname of validatedConfig.clientHostname) { + if (hostname === os.hostname()) { + hostnameMatched = true; + } + } + if (!hostnameMatched) { + continue; + } + } + if (Array.isArray(validatedConfig.clientLanguage)) { + let languageMatched = false; + for (const language of validatedConfig.clientLanguage) { + if (language === CLIENT_LANGUAGE_STRING) { + languageMatched = true; + } + } + if (!languageMatched) { + continue; + } + } + return validatedConfig.serviceConfig; + } + throw new Error('No matching service config found'); +} +/** + * Find the "grpc_config" record among the TXT records, parse its value as JSON, validate its contents, + * and select a service config with selection fields that all match this client. Most of these steps + * can fail with an error; the caller must handle any errors thrown this way. + * @param txtRecord The TXT record array that is output from a successful call to dns.resolveTxt + * @param percentage A number chosen from the range [0, 100) that is used to select which config to use + * @return The service configuration to use, given the percentage value, or null if the service config + * data has a valid format but none of the options match the current client. + */ +function extractAndSelectServiceConfig(txtRecord, percentage) { + for (const record of txtRecord) { + if (record.length > 0 && record[0].startsWith('grpc_config=')) { + /* Treat the list of strings in this record as a single string and remove + * "grpc_config=" from the beginning. The rest should be a JSON string */ + const recordString = record.join('').substring('grpc_config='.length); + const recordJson = JSON.parse(recordString); + return validateAndSelectCanaryConfig(recordJson, percentage); + } + } + return null; +} +exports.extractAndSelectServiceConfig = extractAndSelectServiceConfig; +//# sourceMappingURL=service-config.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/service-config.js.map b/node_modules/@grpc/grpc-js/build/src/service-config.js.map new file mode 100644 index 0000000..419d18a --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/service-config.js.map @@ -0,0 +1 @@ +{"version":3,"file":"service-config.js","sourceRoot":"","sources":["../../src/service-config.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;GAeG;;;AAEH;;;;;sBAKsB;AAEtB;aACa;AACb,uDAAuD;AAEvD,yBAAyB;AACzB,2CAAqC;AAuDrC;;;GAGG;AACH,MAAM,cAAc,GAAG,oBAAoB,CAAC;AAE5C;;;GAGG;AACH,MAAM,sBAAsB,GAAG,MAAM,CAAC;AAEtC,SAAS,YAAY,CAAC,GAAQ;IAC5B,kEAAkE;IAClE,IAAI,SAAS,IAAI,GAAG,IAAI,GAAG,CAAC,OAAO,KAAK,EAAE,EAAE,CAAC;QAC3C,IAAI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YACzE,MAAM,YAAY,GAAG,MAAM,CAAC,IAAI,CAAC,EAAE,CAAC,CAAC,SAAS,CAAC,cAAc,CAAC,MAAM,CAAC,CAAC;YACtE,MAAM,UAAU,GAAQ,IAAI,CAAC,KAAK,CAAC,YAAY,CAAC,CAAC;YACjD,OAAO,6BAA6B,CAAC,UAAU,EAAE,UAAU,CAAC,CAAC;QAC/D,CAAC;IACH,CAAC;IACD,OAAO,IAAI,CAAC;AACd,CAAC;AAdD,sEAcC"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/status-builder.d.ts b/node_modules/@grpc/grpc-js/build/src/status-builder.d.ts new file mode 100644 index 0000000..5628226 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/status-builder.d.ts @@ -0,0 +1,28 @@ +import { StatusObject } from './call-interface'; +import { Status } from './constants'; +import { Metadata } from './metadata'; +/** + * A builder for gRPC status objects. + */ +export declare class StatusBuilder { + private code; + private details; + private metadata; + constructor(); + /** + * Adds a status code to the builder. + */ + withCode(code: Status): this; + /** + * Adds details to the builder. + */ + withDetails(details: string): this; + /** + * Adds metadata to the builder. + */ + withMetadata(metadata: Metadata): this; + /** + * Builds the status object. + */ + build(): Partial; +} diff --git a/node_modules/@grpc/grpc-js/build/src/status-builder.js b/node_modules/@grpc/grpc-js/build/src/status-builder.js new file mode 100644 index 0000000..7426e54 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/status-builder.js @@ -0,0 +1,68 @@ +"use strict"; +/* + * Copyright 2019 gRPC authors. + * + * 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. + * + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.StatusBuilder = void 0; +/** + * A builder for gRPC status objects. + */ +class StatusBuilder { + constructor() { + this.code = null; + this.details = null; + this.metadata = null; + } + /** + * Adds a status code to the builder. + */ + withCode(code) { + this.code = code; + return this; + } + /** + * Adds details to the builder. + */ + withDetails(details) { + this.details = details; + return this; + } + /** + * Adds metadata to the builder. + */ + withMetadata(metadata) { + this.metadata = metadata; + return this; + } + /** + * Builds the status object. + */ + build() { + const status = {}; + if (this.code !== null) { + status.code = this.code; + } + if (this.details !== null) { + status.details = this.details; + } + if (this.metadata !== null) { + status.metadata = this.metadata; + } + return status; + } +} +exports.StatusBuilder = StatusBuilder; +//# sourceMappingURL=status-builder.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/status-builder.js.map b/node_modules/@grpc/grpc-js/build/src/status-builder.js.map new file mode 100644 index 0000000..33277b2 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/status-builder.js.map @@ -0,0 +1 @@ +{"version":3,"file":"status-builder.js","sourceRoot":"","sources":["../../src/status-builder.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;GAeG;;;AAMH;;GAEG;AACH,MAAa,aAAa;IAKxB;QACE,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;QACjB,IAAI,CAAC,OAAO,GAAG,IAAI,CAAC;QACpB,IAAI,CAAC,QAAQ,GAAG,IAAI,CAAC;IACvB,CAAC;IAED;;OAEG;IACH,QAAQ,CAAC,IAAY;QACnB,IAAI,CAAC,IAAI,GAAG,IAAI,CAAC;QACjB,OAAO,IAAI,CAAC;IACd,CAAC;IAED;;OAEG;IACH,WAAW,CAAC,OAAe;QACzB,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;QACvB,OAAO,IAAI,CAAC;IACd,CAAC;IAED;;OAEG;IACH,YAAY,CAAC,QAAkB;QAC7B,IAAI,CAAC,QAAQ,GAAG,QAAQ,CAAC;QACzB,OAAO,IAAI,CAAC;IACd,CAAC;IAED;;OAEG;IACH,KAAK;QACH,MAAM,MAAM,GAA0B,EAAE,CAAC;QAEzC,IAAI,IAAI,CAAC,IAAI,KAAK,IAAI,EAAE,CAAC;YACvB,MAAM,CAAC,IAAI,GAAG,IAAI,CAAC,IAAI,CAAC;QAC1B,CAAC;QAED,IAAI,IAAI,CAAC,OAAO,KAAK,IAAI,EAAE,CAAC;YAC1B,MAAM,CAAC,OAAO,GAAG,IAAI,CAAC,OAAO,CAAC;QAChC,CAAC;QAED,IAAI,IAAI,CAAC,QAAQ,KAAK,IAAI,EAAE,CAAC;YAC3B,MAAM,CAAC,QAAQ,GAAG,IAAI,CAAC,QAAQ,CAAC;QAClC,CAAC;QAED,OAAO,MAAM,CAAC;IAChB,CAAC;CACF;AAvDD,sCAuDC"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/stream-decoder.d.ts b/node_modules/@grpc/grpc-js/build/src/stream-decoder.d.ts new file mode 100644 index 0000000..512962f --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/stream-decoder.d.ts @@ -0,0 +1,11 @@ +/// +export declare class StreamDecoder { + private readState; + private readCompressFlag; + private readPartialSize; + private readSizeRemaining; + private readMessageSize; + private readPartialMessage; + private readMessageRemaining; + write(data: Buffer): Buffer[]; +} diff --git a/node_modules/@grpc/grpc-js/build/src/stream-decoder.js b/node_modules/@grpc/grpc-js/build/src/stream-decoder.js new file mode 100644 index 0000000..5c64d42 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/stream-decoder.js @@ -0,0 +1,96 @@ +"use strict"; +/* + * Copyright 2019 gRPC authors. + * + * 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. + * + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.StreamDecoder = void 0; +var ReadState; +(function (ReadState) { + ReadState[ReadState["NO_DATA"] = 0] = "NO_DATA"; + ReadState[ReadState["READING_SIZE"] = 1] = "READING_SIZE"; + ReadState[ReadState["READING_MESSAGE"] = 2] = "READING_MESSAGE"; +})(ReadState || (ReadState = {})); +class StreamDecoder { + constructor() { + this.readState = ReadState.NO_DATA; + this.readCompressFlag = Buffer.alloc(1); + this.readPartialSize = Buffer.alloc(4); + this.readSizeRemaining = 4; + this.readMessageSize = 0; + this.readPartialMessage = []; + this.readMessageRemaining = 0; + } + write(data) { + let readHead = 0; + let toRead; + const result = []; + while (readHead < data.length) { + switch (this.readState) { + case ReadState.NO_DATA: + this.readCompressFlag = data.slice(readHead, readHead + 1); + readHead += 1; + this.readState = ReadState.READING_SIZE; + this.readPartialSize.fill(0); + this.readSizeRemaining = 4; + this.readMessageSize = 0; + this.readMessageRemaining = 0; + this.readPartialMessage = []; + break; + case ReadState.READING_SIZE: + toRead = Math.min(data.length - readHead, this.readSizeRemaining); + data.copy(this.readPartialSize, 4 - this.readSizeRemaining, readHead, readHead + toRead); + this.readSizeRemaining -= toRead; + readHead += toRead; + // readSizeRemaining >=0 here + if (this.readSizeRemaining === 0) { + this.readMessageSize = this.readPartialSize.readUInt32BE(0); + this.readMessageRemaining = this.readMessageSize; + if (this.readMessageRemaining > 0) { + this.readState = ReadState.READING_MESSAGE; + } + else { + const message = Buffer.concat([this.readCompressFlag, this.readPartialSize], 5); + this.readState = ReadState.NO_DATA; + result.push(message); + } + } + break; + case ReadState.READING_MESSAGE: + toRead = Math.min(data.length - readHead, this.readMessageRemaining); + this.readPartialMessage.push(data.slice(readHead, readHead + toRead)); + this.readMessageRemaining -= toRead; + readHead += toRead; + // readMessageRemaining >=0 here + if (this.readMessageRemaining === 0) { + // At this point, we have read a full message + const framedMessageBuffers = [ + this.readCompressFlag, + this.readPartialSize, + ].concat(this.readPartialMessage); + const framedMessage = Buffer.concat(framedMessageBuffers, this.readMessageSize + 5); + this.readState = ReadState.NO_DATA; + result.push(framedMessage); + } + break; + default: + throw new Error('Unexpected read state'); + } + } + return result; + } +} +exports.StreamDecoder = StreamDecoder; +//# sourceMappingURL=stream-decoder.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/stream-decoder.js.map b/node_modules/@grpc/grpc-js/build/src/stream-decoder.js.map new file mode 100644 index 0000000..524e97a --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/stream-decoder.js.map @@ -0,0 +1 @@ +{"version":3,"file":"stream-decoder.js","sourceRoot":"","sources":["../../src/stream-decoder.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;GAeG;;;AAEH,IAAK,SAIJ;AAJD,WAAK,SAAS;IACZ,+CAAO,CAAA;IACP,yDAAY,CAAA;IACZ,+DAAe,CAAA;AACjB,CAAC,EAJI,SAAS,KAAT,SAAS,QAIb;AAED,MAAa,aAAa;IAA1B;QACU,cAAS,GAAc,SAAS,CAAC,OAAO,CAAC;QACzC,qBAAgB,GAAW,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;QAC3C,oBAAe,GAAW,MAAM,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;QAC1C,sBAAiB,GAAG,CAAC,CAAC;QACtB,oBAAe,GAAG,CAAC,CAAC;QACpB,uBAAkB,GAAa,EAAE,CAAC;QAClC,yBAAoB,GAAG,CAAC,CAAC;IA0EnC,CAAC;IAxEC,KAAK,CAAC,IAAY;QAChB,IAAI,QAAQ,GAAG,CAAC,CAAC;QACjB,IAAI,MAAc,CAAC;QACnB,MAAM,MAAM,GAAa,EAAE,CAAC;QAE5B,OAAO,QAAQ,GAAG,IAAI,CAAC,MAAM,EAAE,CAAC;YAC9B,QAAQ,IAAI,CAAC,SAAS,EAAE,CAAC;gBACvB,KAAK,SAAS,CAAC,OAAO;oBACpB,IAAI,CAAC,gBAAgB,GAAG,IAAI,CAAC,KAAK,CAAC,QAAQ,EAAE,QAAQ,GAAG,CAAC,CAAC,C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AAS,CAAC,OAAO,CAAC;4BACnC,MAAM,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC;wBACvB,CAAC;oBACH,CAAC;oBACD,MAAM;gBACR,KAAK,SAAS,CAAC,eAAe;oBAC5B,MAAM,GAAG,IAAI,CAAC,GAAG,CAAC,IAAI,CAAC,MAAM,GAAG,QAAQ,EAAE,IAAI,CAAC,oBAAoB,CAAC,CAAC;oBACrE,IAAI,CAAC,kBAAkB,CAAC,IAAI,CAAC,IAAI,CAAC,KAAK,CAAC,QAAQ,EAAE,QAAQ,GAAG,MAAM,CAAC,CAAC,CAAC;oBACtE,IAAI,CAAC,oBAAoB,IAAI,MAAM,CAAC;oBACpC,QAAQ,IAAI,MAAM,CAAC;oBACnB,gCAAgC;oBAChC,IAAI,IAAI,CAAC,oBAAoB,KAAK,CAAC,EAAE,CAAC;wBACpC,6CAA6C;wBAC7C,MAAM,oBAAoB,GAAG;4BAC3B,IAAI,CAAC,gBAAgB;4BACrB,IAAI,CAAC,eAAe;yBACrB,CAAC,MAAM,CAAC,IAAI,CAAC,kBAAkB,CAAC,CAAC;wBAClC,MAAM,aAAa,GAAG,MAAM,CAAC,MAAM,CACjC,oBAAoB,EACpB,IAAI,CAAC,eAAe,GAAG,CAAC,CACzB,CAAC;wBAEF,IAAI,CAAC,SAAS,GAAG,SAAS,CAAC,OAAO,CAAC;wBACnC,MAAM,CAAC,IAAI,CAAC,aAAa,CAAC,CAAC;oBAC7B,CAAC;oBACD,MAAM;gBACR;oBACE,MAAM,IAAI,KAAK,CAAC,uBAAuB,CAAC,CAAC;YAC7C,CAAC;QACH,CAAC;QAED,OAAO,MAAM,CAAC;IAChB,CAAC;CACF;AAjFD,sCAiFC"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/subchannel-address.d.ts b/node_modules/@grpc/grpc-js/build/src/subchannel-address.d.ts new file mode 100644 index 0000000..f403563 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/subchannel-address.d.ts @@ -0,0 +1,42 @@ +export interface TcpSubchannelAddress { + port: number; + host: string; +} +export interface IpcSubchannelAddress { + path: string; +} +/** + * This represents a single backend address to connect to. This interface is a + * subset of net.SocketConnectOpts, i.e. the options described at + * https://nodejs.org/api/net.html#net_socket_connect_options_connectlistener. + * Those are in turn a subset of the options that can be passed to http2.connect. + */ +export type SubchannelAddress = TcpSubchannelAddress | IpcSubchannelAddress; +export declare function isTcpSubchannelAddress(address: SubchannelAddress): address is TcpSubchannelAddress; +export declare function subchannelAddressEqual(address1?: SubchannelAddress, address2?: SubchannelAddress): boolean; +export declare function subchannelAddressToString(address: SubchannelAddress): string; +export declare function stringToSubchannelAddress(addressString: string, port?: number): SubchannelAddress; +export interface Endpoint { + addresses: SubchannelAddress[]; +} +export declare function endpointEqual(endpoint1: Endpoint, endpoint2: Endpoint): boolean; +export declare function endpointToString(endpoint: Endpoint): string; +export declare function endpointHasAddress(endpoint: Endpoint, expectedAddress: SubchannelAddress): boolean; +export declare class EndpointMap { + private map; + get size(): number; + getForSubchannelAddress(address: SubchannelAddress): ValueType | undefined; + /** + * Delete any entries in this map with keys that are not in endpoints + * @param endpoints + */ + deleteMissing(endpoints: Endpoint[]): ValueType[]; + get(endpoint: Endpoint): ValueType | undefined; + set(endpoint: Endpoint, mapEntry: ValueType): void; + delete(endpoint: Endpoint): void; + has(endpoint: Endpoint): boolean; + clear(): void; + keys(): IterableIterator; + values(): IterableIterator; + entries(): IterableIterator<[Endpoint, ValueType]>; +} diff --git a/node_modules/@grpc/grpc-js/build/src/subchannel-address.js b/node_modules/@grpc/grpc-js/build/src/subchannel-address.js new file mode 100644 index 0000000..feb3589 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/subchannel-address.js @@ -0,0 +1,202 @@ +"use strict"; +/* + * Copyright 2021 gRPC authors. + * + * 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. + * + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.EndpointMap = exports.endpointHasAddress = exports.endpointToString = exports.endpointEqual = exports.stringToSubchannelAddress = exports.subchannelAddressToString = exports.subchannelAddressEqual = exports.isTcpSubchannelAddress = void 0; +const net_1 = require("net"); +function isTcpSubchannelAddress(address) { + return 'port' in address; +} +exports.isTcpSubchannelAddress = isTcpSubchannelAddress; +function subchannelAddressEqual(address1, address2) { + if (!address1 && !address2) { + return true; + } + if (!address1 || !address2) { + return false; + } + if (isTcpSubchannelAddress(address1)) { + return (isTcpSubchannelAddress(address2) && + address1.host === address2.host && + address1.port === address2.port); + } + else { + return !isTcpSubchannelAddress(address2) && address1.path === address2.path; + } +} +exports.subchannelAddressEqual = subchannelAddressEqual; +function subchannelAddressToString(address) { + if (isTcpSubchannelAddress(address)) { + if ((0, net_1.isIPv6)(address.host)) { + return '[' + address.host + ']:' + address.port; + } + else { + return address.host + ':' + address.port; + } + } + else { + return address.path; + } +} +exports.subchannelAddressToString = subchannelAddressToString; +const DEFAULT_PORT = 443; +function stringToSubchannelAddress(addressString, port) { + if ((0, net_1.isIP)(addressString)) { + return { + host: addressString, + port: port !== null && port !== void 0 ? port : DEFAULT_PORT, + }; + } + else { + return { + path: addressString, + }; + } +} +exports.stringToSubchannelAddress = stringToSubchannelAddress; +function endpointEqual(endpoint1, endpoint2) { + if (endpoint1.addresses.length !== endpoint2.addresses.length) { + return false; + } + for (let i = 0; i < endpoint1.addresses.length; i++) { + if (!subchannelAddressEqual(endpoint1.addresses[i], endpoint2.addresses[i])) { + return false; + } + } + return true; +} +exports.endpointEqual = endpointEqual; +function endpointToString(endpoint) { + return ('[' + endpoint.addresses.map(subchannelAddressToString).join(', ') + ']'); +} +exports.endpointToString = endpointToString; +function endpointHasAddress(endpoint, expectedAddress) { + for (const address of endpoint.addresses) { + if (subchannelAddressEqual(address, expectedAddress)) { + return true; + } + } + return false; +} +exports.endpointHasAddress = endpointHasAddress; +function endpointEqualUnordered(endpoint1, endpoint2) { + if (endpoint1.addresses.length !== endpoint2.addresses.length) { + return false; + } + for (const address1 of endpoint1.addresses) { + let matchFound = false; + for (const address2 of endpoint2.addresses) { + if (subchannelAddressEqual(address1, address2)) { + matchFound = true; + break; + } + } + if (!matchFound) { + return false; + } + } + return true; +} +class EndpointMap { + constructor() { + this.map = new Set(); + } + get size() { + return this.map.size; + } + getForSubchannelAddress(address) { + for (const entry of this.map) { + if (endpointHasAddress(entry.key, address)) { + return entry.value; + } + } + return undefined; + } + /** + * Delete any entries in this map with keys that are not in endpoints + * @param endpoints + */ + deleteMissing(endpoints) { + const removedValues = []; + for (const entry of this.map) { + let foundEntry = false; + for (const endpoint of endpoints) { + if (endpointEqualUnordered(endpoint, entry.key)) { + foundEntry = true; + } + } + if (!foundEntry) { + removedValues.push(entry.value); + this.map.delete(entry); + } + } + return removedValues; + } + get(endpoint) { + for (const entry of this.map) { + if (endpointEqualUnordered(endpoint, entry.key)) { + return entry.value; + } + } + return undefined; + } + set(endpoint, mapEntry) { + for (const entry of this.map) { + if (endpointEqualUnordered(endpoint, entry.key)) { + entry.value = mapEntry; + return; + } + } + this.map.add({ key: endpoint, value: mapEntry }); + } + delete(endpoint) { + for (const entry of this.map) { + if (endpointEqualUnordered(endpoint, entry.key)) { + this.map.delete(entry); + return; + } + } + } + has(endpoint) { + for (const entry of this.map) { + if (endpointEqualUnordered(endpoint, entry.key)) { + return true; + } + } + return false; + } + clear() { + this.map.clear(); + } + *keys() { + for (const entry of this.map) { + yield entry.key; + } + } + *values() { + for (const entry of this.map) { + yield entry.value; + } + } + *entries() { + for (const entry of this.map) { + yield [entry.key, entry.value]; + } + } +} +exports.EndpointMap = EndpointMap; +//# sourceMappingURL=subchannel-address.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/subchannel-address.js.map b/node_modules/@grpc/grpc-js/build/src/subchannel-address.js.map new file mode 100644 index 0000000..6f48413 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/subchannel-address.js.map @@ -0,0 +1 @@ +{"version":3,"file":"subchannel-address.js","sourceRoot":"","sources":["../../src/subchannel-address.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;GAeG;;;AAEH,6BAAmC;AAmBnC,SAAgB,sBAAsB,CACpC,OAA0B;IAE1B,OAAO,MAAM,IAAI,OAAO,CAAC;AAC3B,CAAC;AAJD,wDAIC;AAED,SAAgB,sBAAsB,CACpC,QAA4B,EAC5B,QAA4B;IAE5B,IAAI,CAAC,QAAQ,IAAI,CAAC,QAAQ,EAAE,CAAC;QAC3B,OAAO,IAAI,CAAC;IACd,CAAC;IACD,IAAI,CAAC,QAAQ,IAAI,CAAC,QAAQ,EAAE,CAAC;QAC3B,OAAO,KAAK,CAAC;IACf,CAAC;IACD,IAAI,sBAAsB,CAAC,QAAQ,CAAC,EAAE,CAAC;QACrC,OAAO,CACL,sBAAsB,CAAC,QAAQ,CAAC;YAChC,QAAQ,CAAC,IAAI,KAAK,QAAQ,CAAC,IAAI;YAC/B,QAAQ,CAAC,IAAI,KAAK,QAAQ,CAAC,IAAI,CAChC,CAAC;IACJ,CAAC;SAAM,CAAC;QACN,OAAO,CAAC,sBAAsB,CAAC,QAAQ,CAAC,IAAI,QAAQ,CAAC,IAAI,KAAK,QAAQ,CAAC,IAAI,CAAC;IAC9E,CAAC;AACH,CAAC;AAnBD,wDAmBC;AAED,SAAgB,yBAAyB,CAAC,OAA0B;IAClE,IAAI,sBAAsB,CAAC,OAAO,CAAC,EAAE,CAAC;QACpC,IAAI,IAAA,YAAM,EAAC,OAAO,CAAC,IAAI,CAAC,EAAE,CAAC;YACzB,OAAO,GAAG,GAAG,OAAO,CAAC,IAAI,GAAG,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC;QAClD,CAAC;aAAM,CAAC;YACN,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AM,CAAC,QAAkB;QACvB,KAAK,MAAM,KAAK,IAAI,IAAI,CAAC,GAAG,EAAE,CAAC;YAC7B,IAAI,sBAAsB,CAAC,QAAQ,EAAE,KAAK,CAAC,GAAG,CAAC,EAAE,CAAC;gBAChD,IAAI,CAAC,GAAG,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC;gBACvB,OAAO;YACT,CAAC;QACH,CAAC;IACH,CAAC;IAED,GAAG,CAAC,QAAkB;QACpB,KAAK,MAAM,KAAK,IAAI,IAAI,CAAC,GAAG,EAAE,CAAC;YAC7B,IAAI,sBAAsB,CAAC,QAAQ,EAAE,KAAK,CAAC,GAAG,CAAC,EAAE,CAAC;gBAChD,OAAO,IAAI,CAAC;YACd,CAAC;QACH,CAAC;QACD,OAAO,KAAK,CAAC;IACf,CAAC;IAED,KAAK;QACH,IAAI,CAAC,GAAG,CAAC,KAAK,EAAE,CAAC;IACnB,CAAC;IAED,CAAC,IAAI;QACH,KAAK,MAAM,KAAK,IAAI,IAAI,CAAC,GAAG,EAAE,CAAC;YAC7B,MAAM,KAAK,CAAC,GAAG,CAAC;QAClB,CAAC;IACH,CAAC;IAED,CAAC,MAAM;QACL,KAAK,MAAM,KAAK,IAAI,IAAI,CAAC,GAAG,EAAE,CAAC;YAC7B,MAAM,KAAK,CAAC,KAAK,CAAC;QACpB,CAAC;IACH,CAAC;IAED,CAAC,OAAO;QACN,KAAK,MAAM,KAAK,IAAI,IAAI,CAAC,GAAG,EAAE,CAAC;YAC7B,MAAM,CAAC,KAAK,CAAC,GAAG,EAAE,KAAK,CAAC,KAAK,CAAC,CAAC;QACjC,CAAC;IACH,CAAC;CACF;AA/FD,kCA+FC"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/subchannel-call.d.ts b/node_modules/@grpc/grpc-js/build/src/subchannel-call.d.ts new file mode 100644 index 0000000..acb3151 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/subchannel-call.d.ts @@ -0,0 +1,66 @@ +/// +/// +import * as http2 from 'http2'; +import { Status } from './constants'; +import { InterceptingListener, MessageContext, StatusObject } from './call-interface'; +import { CallEventTracker, Transport } from './transport'; +export interface SubchannelCall { + cancelWithStatus(status: Status, details: string): void; + getPeer(): string; + sendMessageWithContext(context: MessageContext, message: Buffer): void; + startRead(): void; + halfClose(): void; + getCallNumber(): number; + getDeadlineInfo(): string[]; +} +export interface StatusObjectWithRstCode extends StatusObject { + rstCode?: number; +} +export interface SubchannelCallInterceptingListener extends InterceptingListener { + onReceiveStatus(status: StatusObjectWithRstCode): void; +} +export declare class Http2SubchannelCall implements SubchannelCall { + private readonly http2Stream; + private readonly callEventTracker; + private readonly listener; + private readonly transport; + private readonly callId; + private decoder; + private isReadFilterPending; + private isPushPending; + private canPush; + /** + * Indicates that an 'end' event has come from the http2 stream, so there + * will be no more data events. + */ + private readsClosed; + private statusOutput; + private unpushedReadMessages; + private httpStatusCode; + private finalStatus; + private internalError; + private serverEndedCall; + constructor(http2Stream: http2.ClientHttp2Stream, callEventTracker: CallEventTracker, listener: SubchannelCallInterceptingListener, transport: Transport, callId: number); + getDeadlineInfo(): string[]; + onDisconnect(): void; + private outputStatus; + private trace; + /** + * On first call, emits a 'status' event with the given StatusObject. + * Subsequent calls are no-ops. + * @param status The status of the call. + */ + private endCall; + private maybeOutputStatus; + private push; + private tryPush; + private handleTrailers; + private destroyHttp2Stream; + cancelWithStatus(status: Status, details: string): void; + getStatus(): StatusObject | null; + getPeer(): string; + getCallNumber(): number; + startRead(): void; + sendMessageWithContext(context: MessageContext, message: Buffer): void; + halfClose(): void; +} diff --git a/node_modules/@grpc/grpc-js/build/src/subchannel-call.js b/node_modules/@grpc/grpc-js/build/src/subchannel-call.js new file mode 100644 index 0000000..7bb815d --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/subchannel-call.js @@ -0,0 +1,502 @@ +"use strict"; +/* + * Copyright 2019 gRPC authors. + * + * 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. + * + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Http2SubchannelCall = void 0; +const http2 = require("http2"); +const os = require("os"); +const constants_1 = require("./constants"); +const metadata_1 = require("./metadata"); +const stream_decoder_1 = require("./stream-decoder"); +const logging = require("./logging"); +const constants_2 = require("./constants"); +const TRACER_NAME = 'subchannel_call'; +/** + * Should do approximately the same thing as util.getSystemErrorName but the + * TypeScript types don't have that function for some reason so I just made my + * own. + * @param errno + */ +function getSystemErrorName(errno) { + for (const [name, num] of Object.entries(os.constants.errno)) { + if (num === errno) { + return name; + } + } + return 'Unknown system error ' + errno; +} +function mapHttpStatusCode(code) { + const details = `Received HTTP status code ${code}`; + let mappedStatusCode; + switch (code) { + // TODO(murgatroid99): handle 100 and 101 + case 400: + mappedStatusCode = constants_1.Status.INTERNAL; + break; + case 401: + mappedStatusCode = constants_1.Status.UNAUTHENTICATED; + break; + case 403: + mappedStatusCode = constants_1.Status.PERMISSION_DENIED; + break; + case 404: + mappedStatusCode = constants_1.Status.UNIMPLEMENTED; + break; + case 429: + case 502: + case 503: + case 504: + mappedStatusCode = constants_1.Status.UNAVAILABLE; + break; + default: + mappedStatusCode = constants_1.Status.UNKNOWN; + } + return { + code: mappedStatusCode, + details: details, + metadata: new metadata_1.Metadata() + }; +} +class Http2SubchannelCall { + constructor(http2Stream, callEventTracker, listener, transport, callId) { + this.http2Stream = http2Stream; + this.callEventTracker = callEventTracker; + this.listener = listener; + this.transport = transport; + this.callId = callId; + this.decoder = new stream_decoder_1.StreamDecoder(); + this.isReadFilterPending = false; + this.isPushPending = false; + this.canPush = false; + /** + * Indicates that an 'end' event has come from the http2 stream, so there + * will be no more data events. + */ + this.readsClosed = false; + this.statusOutput = false; + this.unpushedReadMessages = []; + // This is populated (non-null) if and only if the call has ended + this.finalStatus = null; + this.internalError = null; + this.serverEndedCall = false; + http2Stream.on('response', (headers, flags) => { + let headersString = ''; + for (const header of Object.keys(headers)) { + headersString += '\t\t' + header + ': ' + headers[header] + '\n'; + } + this.trace('Received server headers:\n' + headersString); + this.httpStatusCode = headers[':status']; + if (flags & http2.constants.NGHTTP2_FLAG_END_STREAM) { + this.handleTrailers(headers); + } + else { + let metadata; + try { + metadata = metadata_1.Metadata.fromHttp2Headers(headers); + } + catch (error) { + this.endCall({ + code: constants_1.Status.UNKNOWN, + details: error.message, + metadata: new metadata_1.Metadata(), + }); + return; + } + this.listener.onReceiveMetadata(metadata); + } + }); + http2Stream.on('trailers', (headers) => { + this.handleTrailers(headers); + }); + http2Stream.on('data', (data) => { + /* If the status has already been output, allow the http2 stream to + * drain without processing the data. */ + if (this.statusOutput) { + return; + } + this.trace('receive HTTP/2 data frame of length ' + data.length); + const messages = this.decoder.write(data); + for (const message of messages) { + this.trace('parsed message of length ' + message.length); + this.callEventTracker.addMessageReceived(); + this.tryPush(message); + } + }); + http2Stream.on('end', () => { + this.readsClosed = true; + this.maybeOutputStatus(); + }); + http2Stream.on('close', () => { + this.serverEndedCall = true; + /* Use process.next tick to ensure that this code happens after any + * "error" event that may be emitted at about the same time, so that + * we can bubble up the error message from that event. */ + process.nextTick(() => { + var _a; + this.trace('HTTP/2 stream closed with code ' + http2Stream.rstCode); + /* If we have a final status with an OK status code, that means that + * we have received all of the messages and we have processed the + * trailers and the call completed successfully, so it doesn't matter + * how the stream ends after that */ + if (((_a = this.finalStatus) === null || _a === void 0 ? void 0 : _a.code) === constants_1.Status.OK) { + return; + } + let code; + let details = ''; + switch (http2Stream.rstCode) { + case http2.constants.NGHTTP2_NO_ERROR: + /* If we get a NO_ERROR code and we already have a status, the + * stream completed properly and we just haven't fully processed + * it yet */ + if (this.finalStatus !== null) { + return; + } + if (this.httpStatusCode && this.httpStatusCode !== 200) { + const mappedStatus = mapHttpStatusCode(this.httpStatusCode); + code = mappedStatus.code; + details = mappedStatus.details; + } + else { + code = constants_1.Status.INTERNAL; + details = `Received RST_STREAM with code ${http2Stream.rstCode} (Call ended without gRPC status)`; + } + break; + case http2.constants.NGHTTP2_REFUSED_STREAM: + code = constants_1.Status.UNAVAILABLE; + details = 'Stream refused by server'; + break; + case http2.constants.NGHTTP2_CANCEL: + code = constants_1.Status.CANCELLED; + details = 'Call cancelled'; + break; + case http2.constants.NGHTTP2_ENHANCE_YOUR_CALM: + code = constants_1.Status.RESOURCE_EXHAUSTED; + details = 'Bandwidth exhausted or memory limit exceeded'; + break; + case http2.constants.NGHTTP2_INADEQUATE_SECURITY: + code = constants_1.Status.PERMISSION_DENIED; + details = 'Protocol not secure enough'; + break; + case http2.constants.NGHTTP2_INTERNAL_ERROR: + code = constants_1.Status.INTERNAL; + if (this.internalError === null) { + /* This error code was previously handled in the default case, and + * there are several instances of it online, so I wanted to + * preserve the original error message so that people find existing + * information in searches, but also include the more recognizable + * "Internal server error" message. */ + details = `Received RST_STREAM with code ${http2Stream.rstCode} (Internal server error)`; + } + else { + if (this.internalError.code === 'ECONNRESET' || + this.internalError.code === 'ETIMEDOUT') { + code = constants_1.Status.UNAVAILABLE; + details = this.internalError.message; + } + else { + /* The "Received RST_STREAM with code ..." error is preserved + * here for continuity with errors reported online, but the + * error message at the end will probably be more relevant in + * most cases. */ + details = `Received RST_STREAM with code ${http2Stream.rstCode} triggered by internal client error: ${this.internalError.message}`; + } + } + break; + default: + code = constants_1.Status.INTERNAL; + details = `Received RST_STREAM with code ${http2Stream.rstCode}`; + } + // This is a no-op if trailers were received at all. + // This is OK, because status codes emitted here correspond to more + // catastrophic issues that prevent us from receiving trailers in the + // first place. + this.endCall({ + code, + details, + metadata: new metadata_1.Metadata(), + rstCode: http2Stream.rstCode, + }); + }); + }); + http2Stream.on('error', (err) => { + /* We need an error handler here to stop "Uncaught Error" exceptions + * from bubbling up. However, errors here should all correspond to + * "close" events, where we will handle the error more granularly */ + /* Specifically looking for stream errors that were *not* constructed + * from a RST_STREAM response here: + * https://github.com/nodejs/node/blob/8b8620d580314050175983402dfddf2674e8e22a/lib/internal/http2/core.js#L2267 + */ + if (err.code !== 'ERR_HTTP2_STREAM_ERROR') { + this.trace('Node error event: message=' + + err.message + + ' code=' + + err.code + + ' errno=' + + getSystemErrorName(err.errno) + + ' syscall=' + + err.syscall); + this.internalError = err; + } + this.callEventTracker.onStreamEnd(false); + }); + } + getDeadlineInfo() { + return [`remote_addr=${this.getPeer()}`]; + } + onDisconnect() { + this.endCall({ + code: constants_1.Status.UNAVAILABLE, + details: 'Connection dropped', + metadata: new metadata_1.Metadata(), + }); + } + outputStatus() { + /* Precondition: this.finalStatus !== null */ + if (!this.statusOutput) { + this.statusOutput = true; + this.trace('ended with status: code=' + + this.finalStatus.code + + ' details="' + + this.finalStatus.details + + '"'); + this.callEventTracker.onCallEnd(this.finalStatus); + /* We delay the actual action of bubbling up the status to insulate the + * cleanup code in this class from any errors that may be thrown in the + * upper layers as a result of bubbling up the status. In particular, + * if the status is not OK, the "error" event may be emitted + * synchronously at the top level, which will result in a thrown error if + * the user does not handle that event. */ + process.nextTick(() => { + this.listener.onReceiveStatus(this.finalStatus); + }); + /* Leave the http2 stream in flowing state to drain incoming messages, to + * ensure that the stream closure completes. The call stream already does + * not push more messages after the status is output, so the messages go + * nowhere either way. */ + this.http2Stream.resume(); + } + } + trace(text) { + logging.trace(constants_2.LogVerbosity.DEBUG, TRACER_NAME, '[' + this.callId + '] ' + text); + } + /** + * On first call, emits a 'status' event with the given StatusObject. + * Subsequent calls are no-ops. + * @param status The status of the call. + */ + endCall(status) { + /* If the status is OK and a new status comes in (e.g. from a + * deserialization failure), that new status takes priority */ + if (this.finalStatus === null || this.finalStatus.code === constants_1.Status.OK) { + this.finalStatus = status; + this.maybeOutputStatus(); + } + this.destroyHttp2Stream(); + } + maybeOutputStatus() { + if (this.finalStatus !== null) { + /* The combination check of readsClosed and that the two message buffer + * arrays are empty checks that there all incoming data has been fully + * processed */ + if (this.finalStatus.code !== constants_1.Status.OK || + (this.readsClosed && + this.unpushedReadMessages.length === 0 && + !this.isReadFilterPending && + !this.isPushPending)) { + this.outputStatus(); + } + } + } + push(message) { + this.trace('pushing to reader message of length ' + + (message instanceof Buffer ? message.length : null)); + this.canPush = false; + this.isPushPending = true; + process.nextTick(() => { + this.isPushPending = false; + /* If we have already output the status any later messages should be + * ignored, and can cause out-of-order operation errors higher up in the + * stack. Checking as late as possible here to avoid any race conditions. + */ + if (this.statusOutput) { + return; + } + this.listener.onReceiveMessage(message); + this.maybeOutputStatus(); + }); + } + tryPush(messageBytes) { + if (this.canPush) { + this.http2Stream.pause(); + this.push(messageBytes); + } + else { + this.trace('unpushedReadMessages.push message of length ' + messageBytes.length); + this.unpushedReadMessages.push(messageBytes); + } + } + handleTrailers(headers) { + this.serverEndedCall = true; + this.callEventTracker.onStreamEnd(true); + let headersString = ''; + for (const header of Object.keys(headers)) { + headersString += '\t\t' + header + ': ' + headers[header] + '\n'; + } + this.trace('Received server trailers:\n' + headersString); + let metadata; + try { + metadata = metadata_1.Metadata.fromHttp2Headers(headers); + } + catch (e) { + metadata = new metadata_1.Metadata(); + } + const metadataMap = metadata.getMap(); + let status; + if (typeof metadataMap['grpc-status'] === 'string') { + const receivedStatus = Number(metadataMap['grpc-status']); + this.trace('received status code ' + receivedStatus + ' from server'); + metadata.remove('grpc-status'); + let details = ''; + if (typeof metadataMap['grpc-message'] === 'string') { + try { + details = decodeURI(metadataMap['grpc-message']); + } + catch (e) { + details = metadataMap['grpc-message']; + } + metadata.remove('grpc-message'); + this.trace('received status details string "' + details + '" from server'); + } + status = { + code: receivedStatus, + details: details, + metadata: metadata + }; + } + else if (this.httpStatusCode) { + status = mapHttpStatusCode(this.httpStatusCode); + status.metadata = metadata; + } + else { + status = { + code: constants_1.Status.UNKNOWN, + details: 'No status information received', + metadata: metadata + }; + } + // This is a no-op if the call was already ended when handling headers. + this.endCall(status); + } + destroyHttp2Stream() { + var _a; + // The http2 stream could already have been destroyed if cancelWithStatus + // is called in response to an internal http2 error. + if (this.http2Stream.destroyed) { + return; + } + /* If the server ended the call, sending an RST_STREAM is redundant, so we + * just half close on the client side instead to finish closing the stream. + */ + if (this.serverEndedCall) { + this.http2Stream.end(); + } + else { + /* If the call has ended with an OK status, communicate that when closing + * the stream, partly to avoid a situation in which we detect an error + * RST_STREAM as a result after we have the status */ + let code; + if (((_a = this.finalStatus) === null || _a === void 0 ? void 0 : _a.code) === constants_1.Status.OK) { + code = http2.constants.NGHTTP2_NO_ERROR; + } + else { + code = http2.constants.NGHTTP2_CANCEL; + } + this.trace('close http2 stream with code ' + code); + this.http2Stream.close(code); + } + } + cancelWithStatus(status, details) { + this.trace('cancelWithStatus code: ' + status + ' details: "' + details + '"'); + this.endCall({ code: status, details, metadata: new metadata_1.Metadata() }); + } + getStatus() { + return this.finalStatus; + } + getPeer() { + return this.transport.getPeerName(); + } + getCallNumber() { + return this.callId; + } + startRead() { + /* If the stream has ended with an error, we should not emit any more + * messages and we should communicate that the stream has ended */ + if (this.finalStatus !== null && this.finalStatus.code !== constants_1.Status.OK) { + this.readsClosed = true; + this.maybeOutputStatus(); + return; + } + this.canPush = true; + if (this.unpushedReadMessages.length > 0) { + const nextMessage = this.unpushedReadMessages.shift(); + this.push(nextMessage); + return; + } + /* Only resume reading from the http2Stream if we don't have any pending + * messages to emit */ + this.http2Stream.resume(); + } + sendMessageWithContext(context, message) { + this.trace('write() called with message of length ' + message.length); + const cb = (error) => { + /* nextTick here ensures that no stream action can be taken in the call + * stack of the write callback, in order to hopefully work around + * https://github.com/nodejs/node/issues/49147 */ + process.nextTick(() => { + var _a; + let code = constants_1.Status.UNAVAILABLE; + if ((error === null || error === void 0 ? void 0 : error.code) === + 'ERR_STREAM_WRITE_AFTER_END') { + code = constants_1.Status.INTERNAL; + } + if (error) { + this.cancelWithStatus(code, `Write error: ${error.message}`); + } + (_a = context.callback) === null || _a === void 0 ? void 0 : _a.call(context); + }); + }; + this.trace('sending data chunk of length ' + message.length); + this.callEventTracker.addMessageSent(); + try { + this.http2Stream.write(message, cb); + } + catch (error) { + this.endCall({ + code: constants_1.Status.UNAVAILABLE, + details: `Write failed with error ${error.message}`, + metadata: new metadata_1.Metadata(), + }); + } + } + halfClose() { + this.trace('end() called'); + this.trace('calling end() on HTTP/2 stream'); + this.http2Stream.end(); + } +} +exports.Http2SubchannelCall = Http2SubchannelCall; +//# sourceMappingURL=subchannel-call.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/subchannel-call.js.map b/node_modules/@grpc/grpc-js/build/src/subchannel-call.js.map new file mode 100644 index 0000000..f45efa0 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/subchannel-call.js.map @@ -0,0 +1 @@ +{"version":3,"file":"subchannel-call.js","sourceRoot":"","sources":["../../src/subchannel-call.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;GAeG;;;AAEH,+BAA+B;AAC/B,yBAAyB;AAEzB,2CAAqC;AACrC,yCAAsC;AACtC,qDAAiD;AACjD,qCAAqC;AACrC,2CAA2C;AAS3C,MAAM,WAAW,GAAG,iBAAiB,CAAC;AAiBtC;;;;;GAKG;AACH,SAAS,kBAAkB,CAAC,KAAa;IACvC,KAAK,MAAM,CAAC,IAAI,EAAE,GAAG,CAAC,IAAI,MAAM,CAAC,OAAO,CAAC,EAAE,CAAC,SAAS,CAAC,KAAK,CAAC,EAAE,CAAC;QAC7D,IAAI,GAAG,KAAK,KAAK,EAAE,CAAC;YAClB,OAAO,IAAI,CAAC;QACd,CAAC;IACH,CAAC;IACD,OAAO,uBAAuB,GAAG,KAAK,CAAC;AACzC,CAAC;AAqBD,SAAS,iBAAiB,CAAC,IAAY;IACrC,MAAM,OAAO,GAAG,6BAA6B,IAAI,EAAE,CAAC;IACpD,IAAI,gBAAwB,CAAC;IAC7B,QAAQ,IAAI,EAAE,CAAC;QACb,yCAAyC;QACzC,K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;IACH,CAAC;IAED,SAAS;QACP,IAAI,CAAC,KAAK,CAAC,cAAc,CAAC,CAAC;QAC3B,IAAI,CAAC,KAAK,CAAC,gCAAgC,CAAC,CAAC;QAC7C,IAAI,CAAC,WAAW,CAAC,GAAG,EAAE,CAAC;IACzB,CAAC;CACF;AA5cD,kDA4cC"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/subchannel-interface.d.ts b/node_modules/@grpc/grpc-js/build/src/subchannel-interface.d.ts new file mode 100644 index 0000000..eb2a18d --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/subchannel-interface.d.ts @@ -0,0 +1,60 @@ +import type { SubchannelRef } from './channelz'; +import { ConnectivityState } from './connectivity-state'; +import { Subchannel } from './subchannel'; +export type ConnectivityStateListener = (subchannel: SubchannelInterface, previousState: ConnectivityState, newState: ConnectivityState, keepaliveTime: number, errorMessage?: string) => void; +export type HealthListener = (healthy: boolean) => void; +/** + * This is an interface for load balancing policies to use to interact with + * subchannels. This allows load balancing policies to wrap and unwrap + * subchannels. + * + * Any load balancing policy that wraps subchannels must unwrap the subchannel + * in the picker, so that other load balancing policies consistently have + * access to their own wrapper objects. + */ +export interface SubchannelInterface { + getConnectivityState(): ConnectivityState; + addConnectivityStateListener(listener: ConnectivityStateListener): void; + removeConnectivityStateListener(listener: ConnectivityStateListener): void; + startConnecting(): void; + getAddress(): string; + throttleKeepalive(newKeepaliveTime: number): void; + ref(): void; + unref(): void; + getChannelzRef(): SubchannelRef; + isHealthy(): boolean; + addHealthStateWatcher(listener: HealthListener): void; + removeHealthStateWatcher(listener: HealthListener): void; + /** + * If this is a wrapper, return the wrapped subchannel, otherwise return this + */ + getRealSubchannel(): Subchannel; + /** + * Returns true if this and other both proxy the same underlying subchannel. + * Can be used instead of directly accessing getRealSubchannel to allow mocks + * to avoid implementing getRealSubchannel + */ + realSubchannelEquals(other: SubchannelInterface): boolean; +} +export declare abstract class BaseSubchannelWrapper implements SubchannelInterface { + protected child: SubchannelInterface; + private healthy; + private healthListeners; + constructor(child: SubchannelInterface); + private updateHealthListeners; + getConnectivityState(): ConnectivityState; + addConnectivityStateListener(listener: ConnectivityStateListener): void; + removeConnectivityStateListener(listener: ConnectivityStateListener): void; + startConnecting(): void; + getAddress(): string; + throttleKeepalive(newKeepaliveTime: number): void; + ref(): void; + unref(): void; + getChannelzRef(): SubchannelRef; + isHealthy(): boolean; + addHealthStateWatcher(listener: HealthListener): void; + removeHealthStateWatcher(listener: HealthListener): void; + protected setHealthy(healthy: boolean): void; + getRealSubchannel(): Subchannel; + realSubchannelEquals(other: SubchannelInterface): boolean; +} diff --git a/node_modules/@grpc/grpc-js/build/src/subchannel-interface.js b/node_modules/@grpc/grpc-js/build/src/subchannel-interface.js new file mode 100644 index 0000000..f4afae8 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/subchannel-interface.js @@ -0,0 +1,92 @@ +"use strict"; +/* + * Copyright 2022 gRPC authors. + * + * 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. + * + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.BaseSubchannelWrapper = void 0; +class BaseSubchannelWrapper { + constructor(child) { + this.child = child; + this.healthy = true; + this.healthListeners = new Set(); + child.addHealthStateWatcher(childHealthy => { + /* A change to the child health state only affects this wrapper's overall + * health state if this wrapper is reporting healthy. */ + if (this.healthy) { + this.updateHealthListeners(); + } + }); + } + updateHealthListeners() { + for (const listener of this.healthListeners) { + listener(this.isHealthy()); + } + } + getConnectivityState() { + return this.child.getConnectivityState(); + } + addConnectivityStateListener(listener) { + this.child.addConnectivityStateListener(listener); + } + removeConnectivityStateListener(listener) { + this.child.removeConnectivityStateListener(listener); + } + startConnecting() { + this.child.startConnecting(); + } + getAddress() { + return this.child.getAddress(); + } + throttleKeepalive(newKeepaliveTime) { + this.child.throttleKeepalive(newKeepaliveTime); + } + ref() { + this.child.ref(); + } + unref() { + this.child.unref(); + } + getChannelzRef() { + return this.child.getChannelzRef(); + } + isHealthy() { + return this.healthy && this.child.isHealthy(); + } + addHealthStateWatcher(listener) { + this.healthListeners.add(listener); + } + removeHealthStateWatcher(listener) { + this.healthListeners.delete(listener); + } + setHealthy(healthy) { + if (healthy !== this.healthy) { + this.healthy = healthy; + /* A change to this wrapper's health state only affects the overall + * reported health state if the child is healthy. */ + if (this.child.isHealthy()) { + this.updateHealthListeners(); + } + } + } + getRealSubchannel() { + return this.child.getRealSubchannel(); + } + realSubchannelEquals(other) { + return this.getRealSubchannel() === other.getRealSubchannel(); + } +} +exports.BaseSubchannelWrapper = BaseSubchannelWrapper; +//# sourceMappingURL=subchannel-interface.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/subchannel-interface.js.map b/node_modules/@grpc/grpc-js/build/src/subchannel-interface.js.map new file mode 100644 index 0000000..362f987 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/subchannel-interface.js.map @@ -0,0 +1 @@ +{"version":3,"file":"subchannel-interface.js","sourceRoot":"","sources":["../../src/subchannel-interface.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;GAeG;;;AAkDH,MAAsB,qBAAqB;IAGzC,YAAsB,KAA0B;QAA1B,UAAK,GAAL,KAAK,CAAqB;QAFxC,YAAO,GAAG,IAAI,CAAC;QACf,oBAAe,GAAwB,IAAI,GAAG,EAAE,CAAC;QAEvD,KAAK,CAAC,qBAAqB,CAAC,YAAY,CAAC,EAAE;YACzC;oEACwD;YACxD,IAAI,IAAI,CAAC,OAAO,EAAE,CAAC;gBACjB,IAAI,CAAC,qBAAqB,EAAE,CAAC;YAC/B,CAAC;QACH,CAAC,CAAC,CAAC;IACL,CAAC;IAEO,qBAAqB;QAC3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,OAAO,KAAK,IAAI,CAAC,OAAO,EAAE,CAAC;YAC7B,IAAI,CAAC,OAAO,GAAG,OAAO,CAAC;YACvB;gEACoD;YACpD,IAAI,IAAI,CAAC,KAAK,CAAC,SAAS,EAAE,EAAE,CAAC;gBAC3B,IAAI,CAAC,qBAAqB,EAAE,CAAC;YAC/B,CAAC;QACH,CAAC;IACH,CAAC;IACD,iBAAiB;QACf,OAAO,IAAI,CAAC,KAAK,CAAC,iBAAiB,EAAE,CAAC;IACxC,CAAC;IACD,oBAAoB,CAAC,KAA0B;QAC7C,OAAO,IAAI,CAAC,iBAAiB,EAAE,KAAK,KAAK,CAAC,iBAAiB,EAAE,CAAC;IAChE,CAAC;CACF;AAvED,sDAuEC"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/subchannel-pool.d.ts b/node_modules/@grpc/grpc-js/build/src/subchannel-pool.d.ts new file mode 100644 index 0000000..9c00300 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/subchannel-pool.d.ts @@ -0,0 +1,40 @@ +import { ChannelOptions } from './channel-options'; +import { Subchannel } from './subchannel'; +import { SubchannelAddress } from './subchannel-address'; +import { ChannelCredentials } from './channel-credentials'; +import { GrpcUri } from './uri-parser'; +export declare class SubchannelPool { + private pool; + /** + * A timer of a task performing a periodic subchannel cleanup. + */ + private cleanupTimer; + /** + * A pool of subchannels use for making connections. Subchannels with the + * exact same parameters will be reused. + */ + constructor(); + /** + * Unrefs all unused subchannels and cancels the cleanup task if all + * subchannels have been unrefed. + */ + unrefUnusedSubchannels(): void; + /** + * Ensures that the cleanup task is spawned. + */ + ensureCleanupTask(): void; + /** + * Get a subchannel if one already exists with exactly matching parameters. + * Otherwise, create and save a subchannel with those parameters. + * @param channelTarget + * @param subchannelTarget + * @param channelArguments + * @param channelCredentials + */ + getOrCreateSubchannel(channelTargetUri: GrpcUri, subchannelTarget: SubchannelAddress, channelArguments: ChannelOptions, channelCredentials: ChannelCredentials): Subchannel; +} +/** + * Get either the global subchannel pool, or a new subchannel pool. + * @param global + */ +export declare function getSubchannelPool(global: boolean): SubchannelPool; diff --git a/node_modules/@grpc/grpc-js/build/src/subchannel-pool.js b/node_modules/@grpc/grpc-js/build/src/subchannel-pool.js new file mode 100644 index 0000000..9061607 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/subchannel-pool.js @@ -0,0 +1,137 @@ +"use strict"; +/* + * Copyright 2019 gRPC authors. + * + * 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. + * + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.getSubchannelPool = exports.SubchannelPool = void 0; +const channel_options_1 = require("./channel-options"); +const subchannel_1 = require("./subchannel"); +const subchannel_address_1 = require("./subchannel-address"); +const uri_parser_1 = require("./uri-parser"); +const transport_1 = require("./transport"); +// 10 seconds in milliseconds. This value is arbitrary. +/** + * The amount of time in between checks for dropping subchannels that have no + * other references + */ +const REF_CHECK_INTERVAL = 10000; +class SubchannelPool { + /** + * A pool of subchannels use for making connections. Subchannels with the + * exact same parameters will be reused. + */ + constructor() { + this.pool = Object.create(null); + /** + * A timer of a task performing a periodic subchannel cleanup. + */ + this.cleanupTimer = null; + } + /** + * Unrefs all unused subchannels and cancels the cleanup task if all + * subchannels have been unrefed. + */ + unrefUnusedSubchannels() { + let allSubchannelsUnrefed = true; + /* These objects are created with Object.create(null), so they do not + * have a prototype, which means that for (... in ...) loops over them + * do not need to be filtered */ + // eslint-disable-disable-next-line:forin + for (const channelTarget in this.pool) { + const subchannelObjArray = this.pool[channelTarget]; + const refedSubchannels = subchannelObjArray.filter(value => !value.subchannel.unrefIfOneRef()); + if (refedSubchannels.length > 0) { + allSubchannelsUnrefed = false; + } + /* For each subchannel in the pool, try to unref it if it has + * exactly one ref (which is the ref from the pool itself). If that + * does happen, remove the subchannel from the pool */ + this.pool[channelTarget] = refedSubchannels; + } + /* Currently we do not delete keys with empty values. If that results + * in significant memory usage we should change it. */ + // Cancel the cleanup task if all subchannels have been unrefed. + if (allSubchannelsUnrefed && this.cleanupTimer !== null) { + clearInterval(this.cleanupTimer); + this.cleanupTimer = null; + } + } + /** + * Ensures that the cleanup task is spawned. + */ + ensureCleanupTask() { + var _a, _b; + if (this.cleanupTimer === null) { + this.cleanupTimer = setInterval(() => { + this.unrefUnusedSubchannels(); + }, REF_CHECK_INTERVAL); + // Unref because this timer should not keep the event loop running. + // Call unref only if it exists to address electron/electron#21162 + (_b = (_a = this.cleanupTimer).unref) === null || _b === void 0 ? void 0 : _b.call(_a); + } + } + /** + * Get a subchannel if one already exists with exactly matching parameters. + * Otherwise, create and save a subchannel with those parameters. + * @param channelTarget + * @param subchannelTarget + * @param channelArguments + * @param channelCredentials + */ + getOrCreateSubchannel(channelTargetUri, subchannelTarget, channelArguments, channelCredentials) { + this.ensureCleanupTask(); + const channelTarget = (0, uri_parser_1.uriToString)(channelTargetUri); + if (channelTarget in this.pool) { + const subchannelObjArray = this.pool[channelTarget]; + for (const subchannelObj of subchannelObjArray) { + if ((0, subchannel_address_1.subchannelAddressEqual)(subchannelTarget, subchannelObj.subchannelAddress) && + (0, channel_options_1.channelOptionsEqual)(channelArguments, subchannelObj.channelArguments) && + channelCredentials._equals(subchannelObj.channelCredentials)) { + return subchannelObj.subchannel; + } + } + } + // If we get here, no matching subchannel was found + const subchannel = new subchannel_1.Subchannel(channelTargetUri, subchannelTarget, channelArguments, channelCredentials, new transport_1.Http2SubchannelConnector(channelTargetUri)); + if (!(channelTarget in this.pool)) { + this.pool[channelTarget] = []; + } + this.pool[channelTarget].push({ + subchannelAddress: subchannelTarget, + channelArguments, + channelCredentials, + subchannel, + }); + subchannel.ref(); + return subchannel; + } +} +exports.SubchannelPool = SubchannelPool; +const globalSubchannelPool = new SubchannelPool(); +/** + * Get either the global subchannel pool, or a new subchannel pool. + * @param global + */ +function getSubchannelPool(global) { + if (global) { + return globalSubchannelPool; + } + else { + return new SubchannelPool(); + } +} +exports.getSubchannelPool = getSubchannelPool; +//# sourceMappingURL=subchannel-pool.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/subchannel-pool.js.map b/node_modules/@grpc/grpc-js/build/src/subchannel-pool.js.map new file mode 100644 index 0000000..dfb1ebf --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/subchannel-pool.js.map @@ -0,0 +1 @@ +{"version":3,"file":"subchannel-pool.js","sourceRoot":"","sources":["../../src/subchannel-pool.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;GAeG;;;AAEH,uDAAwE;AACxE,6CAA0C;AAC1C,6DAG8B;AAE9B,6CAAoD;AACpD,2CAAuD;AAEvD,uDAAuD;AACvD;;;GAGG;AACH,MAAM,kBAAkB,GAAG,KAAM,CAAC;AAElC,MAAa,cAAc;IAezB;;;OAGG;IACH;QAlBQ,SAAI,GAOR,MAAM,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC;QAExB;;WAEG;QACK,iBAAY,GAA0B,IAAI,CAAC;IAMpC,CAAC;IAEhB;;;OAGG;IACH,sBAAsB;QACpB,IAAI,qBAAqB,GAAG,IAAI,CAAC;QAEjC;;wCAEgC;QAChC,yCAAyC;QACzC,KAAK,MAAM,aAAa,IAAI,IAAI,CAAC,IAAI,EAAE,CAAC;YACtC,MAAM,kBAAkB,GAAG,IAAI,CAAC,IAAI,CAAC,aAAa,CAAC,CAAC;YAEpD,MAAM,gBAAgB,GAAG,kBAAkB,CAAC,MAAM,CAChD,KAAK,CAAC,EAAE,CAAC,CAAC,KAAK,CAAC,UAAU,CAAC,aAAa,EAAE,CAC3C,CAAC;YAEF,IAAI,gBAAgB,CAAC,MAAM,GAAG,CAAC,EAAE,CAAC;gBAChC,qBAAqB,GAAG,KA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;oBACD,OAAO,aAAa,CAAC,UAAU,CAAC;gBAClC,CAAC;YACH,CAAC;QACH,CAAC;QACD,mDAAmD;QACnD,MAAM,UAAU,GAAG,IAAI,uBAAU,CAC/B,gBAAgB,EAChB,gBAAgB,EAChB,gBAAgB,EAChB,kBAAkB,EAClB,IAAI,oCAAwB,CAAC,gBAAgB,CAAC,CAC/C,CAAC;QACF,IAAI,CAAC,CAAC,aAAa,IAAI,IAAI,CAAC,IAAI,CAAC,EAAE,CAAC;YAClC,IAAI,CAAC,IAAI,CAAC,aAAa,CAAC,GAAG,EAAE,CAAC;QAChC,CAAC;QACD,IAAI,CAAC,IAAI,CAAC,aAAa,CAAC,CAAC,IAAI,CAAC;YAC5B,iBAAiB,EAAE,gBAAgB;YACnC,gBAAgB;YAChB,kBAAkB;YAClB,UAAU;SACX,CAAC,CAAC;QACH,UAAU,CAAC,GAAG,EAAE,CAAC;QACjB,OAAO,UAAU,CAAC;IACpB,CAAC;CACF;AA/HD,wCA+HC;AAED,MAAM,oBAAoB,GAAG,IAAI,cAAc,EAAE,CAAC;AAElD;;;GAGG;AACH,SAAgB,iBAAiB,CAAC,MAAe;IAC/C,IAAI,MAAM,EAAE,CAAC;QACX,OAAO,oBAAoB,CAAC;IAC9B,CAAC;SAAM,CAAC;QACN,OAAO,IAAI,cAAc,EAAE,CAAC;IAC9B,CAAC;AACH,CAAC;AAND,8CAMC"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/subchannel.d.ts b/node_modules/@grpc/grpc-js/build/src/subchannel.d.ts new file mode 100644 index 0000000..1932363 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/subchannel.d.ts @@ -0,0 +1,122 @@ +import { ChannelCredentials } from './channel-credentials'; +import { Metadata } from './metadata'; +import { ChannelOptions } from './channel-options'; +import { ConnectivityState } from './connectivity-state'; +import { GrpcUri } from './uri-parser'; +import { SubchannelAddress } from './subchannel-address'; +import { SubchannelRef } from './channelz'; +import { ConnectivityStateListener, SubchannelInterface } from './subchannel-interface'; +import { SubchannelCallInterceptingListener } from './subchannel-call'; +import { SubchannelCall } from './subchannel-call'; +import { SubchannelConnector } from './transport'; +export declare class Subchannel { + private channelTarget; + private subchannelAddress; + private options; + private credentials; + private connector; + /** + * The subchannel's current connectivity state. Invariant: `session` === `null` + * if and only if `connectivityState` is IDLE or TRANSIENT_FAILURE. + */ + private connectivityState; + /** + * The underlying http2 session used to make requests. + */ + private transport; + /** + * Indicates that the subchannel should transition from TRANSIENT_FAILURE to + * CONNECTING instead of IDLE when the backoff timeout ends. + */ + private continueConnecting; + /** + * A list of listener functions that will be called whenever the connectivity + * state changes. Will be modified by `addConnectivityStateListener` and + * `removeConnectivityStateListener` + */ + private stateListeners; + private backoffTimeout; + private keepaliveTime; + /** + * Tracks channels and subchannel pools with references to this subchannel + */ + private refcount; + /** + * A string representation of the subchannel address, for logging/tracing + */ + private subchannelAddressString; + private readonly channelzEnabled; + private channelzRef; + private channelzTrace; + private callTracker; + private childrenTracker; + private streamTracker; + /** + * A class representing a connection to a single backend. + * @param channelTarget The target string for the channel as a whole + * @param subchannelAddress The address for the backend that this subchannel + * will connect to + * @param options The channel options, plus any specific subchannel options + * for this subchannel + * @param credentials The channel credentials used to establish this + * connection + */ + constructor(channelTarget: GrpcUri, subchannelAddress: SubchannelAddress, options: ChannelOptions, credentials: ChannelCredentials, connector: SubchannelConnector); + private getChannelzInfo; + private trace; + private refTrace; + private handleBackoffTimer; + /** + * Start a backoff timer with the current nextBackoff timeout + */ + private startBackoff; + private stopBackoff; + private startConnectingInternal; + /** + * Initiate a state transition from any element of oldStates to the new + * state. If the current connectivityState is not in oldStates, do nothing. + * @param oldStates The set of states to transition from + * @param newState The state to transition to + * @returns True if the state changed, false otherwise + */ + private transitionToState; + ref(): void; + unref(): void; + unrefIfOneRef(): boolean; + createCall(metadata: Metadata, host: string, method: string, listener: SubchannelCallInterceptingListener): SubchannelCall; + /** + * If the subchannel is currently IDLE, start connecting and switch to the + * CONNECTING state. If the subchannel is current in TRANSIENT_FAILURE, + * the next time it would transition to IDLE, start connecting again instead. + * Otherwise, do nothing. + */ + startConnecting(): void; + /** + * Get the subchannel's current connectivity state. + */ + getConnectivityState(): ConnectivityState; + /** + * Add a listener function to be called whenever the subchannel's + * connectivity state changes. + * @param listener + */ + addConnectivityStateListener(listener: ConnectivityStateListener): void; + /** + * Remove a listener previously added with `addConnectivityStateListener` + * @param listener A reference to a function previously passed to + * `addConnectivityStateListener` + */ + removeConnectivityStateListener(listener: ConnectivityStateListener): void; + /** + * Reset the backoff timeout, and immediately start connecting if in backoff. + */ + resetBackoff(): void; + getAddress(): string; + getChannelzRef(): SubchannelRef; + isHealthy(): boolean; + addHealthStateWatcher(listener: (healthy: boolean) => void): void; + removeHealthStateWatcher(listener: (healthy: boolean) => void): void; + getRealSubchannel(): this; + realSubchannelEquals(other: SubchannelInterface): boolean; + throttleKeepalive(newKeepaliveTime: number): void; +} diff --git a/node_modules/@grpc/grpc-js/build/src/subchannel.js b/node_modules/@grpc/grpc-js/build/src/subchannel.js new file mode 100644 index 0000000..06d3643 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/subchannel.js @@ -0,0 +1,361 @@ +"use strict"; +/* + * Copyright 2019 gRPC authors. + * + * 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. + * + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Subchannel = void 0; +const connectivity_state_1 = require("./connectivity-state"); +const backoff_timeout_1 = require("./backoff-timeout"); +const logging = require("./logging"); +const constants_1 = require("./constants"); +const uri_parser_1 = require("./uri-parser"); +const subchannel_address_1 = require("./subchannel-address"); +const channelz_1 = require("./channelz"); +const TRACER_NAME = 'subchannel'; +/* setInterval and setTimeout only accept signed 32 bit integers. JS doesn't + * have a constant for the max signed 32 bit integer, so this is a simple way + * to calculate it */ +const KEEPALIVE_MAX_TIME_MS = ~(1 << 31); +class Subchannel { + /** + * A class representing a connection to a single backend. + * @param channelTarget The target string for the channel as a whole + * @param subchannelAddress The address for the backend that this subchannel + * will connect to + * @param options The channel options, plus any specific subchannel options + * for this subchannel + * @param credentials The channel credentials used to establish this + * connection + */ + constructor(channelTarget, subchannelAddress, options, credentials, connector) { + var _a; + this.channelTarget = channelTarget; + this.subchannelAddress = subchannelAddress; + this.options = options; + this.credentials = credentials; + this.connector = connector; + /** + * The subchannel's current connectivity state. Invariant: `session` === `null` + * if and only if `connectivityState` is IDLE or TRANSIENT_FAILURE. + */ + this.connectivityState = connectivity_state_1.ConnectivityState.IDLE; + /** + * The underlying http2 session used to make requests. + */ + this.transport = null; + /** + * Indicates that the subchannel should transition from TRANSIENT_FAILURE to + * CONNECTING instead of IDLE when the backoff timeout ends. + */ + this.continueConnecting = false; + /** + * A list of listener functions that will be called whenever the connectivity + * state changes. Will be modified by `addConnectivityStateListener` and + * `removeConnectivityStateListener` + */ + this.stateListeners = new Set(); + /** + * Tracks channels and subchannel pools with references to this subchannel + */ + this.refcount = 0; + // Channelz info + this.channelzEnabled = true; + const backoffOptions = { + initialDelay: options['grpc.initial_reconnect_backoff_ms'], + maxDelay: options['grpc.max_reconnect_backoff_ms'], + }; + this.backoffTimeout = new backoff_timeout_1.BackoffTimeout(() => { + this.handleBackoffTimer(); + }, backoffOptions); + this.backoffTimeout.unref(); + this.subchannelAddressString = (0, subchannel_address_1.subchannelAddressToString)(subchannelAddress); + this.keepaliveTime = (_a = options['grpc.keepalive_time_ms']) !== null && _a !== void 0 ? _a : -1; + if (options['grpc.enable_channelz'] === 0) { + this.channelzEnabled = false; + this.channelzTrace = new channelz_1.ChannelzTraceStub(); + this.callTracker = new channelz_1.ChannelzCallTrackerStub(); + this.childrenTracker = new channelz_1.ChannelzChildrenTrackerStub(); + this.streamTracker = new channelz_1.ChannelzCallTrackerStub(); + } + else { + this.channelzTrace = new channelz_1.ChannelzTrace(); + this.callTracker = new channelz_1.ChannelzCallTracker(); + this.childrenTracker = new channelz_1.ChannelzChildrenTracker(); + this.streamTracker = new channelz_1.ChannelzCallTracker(); + } + this.channelzRef = (0, channelz_1.registerChannelzSubchannel)(this.subchannelAddressString, () => this.getChannelzInfo(), this.channelzEnabled); + this.channelzTrace.addTrace('CT_INFO', 'Subchannel created'); + this.trace('Subchannel constructed with options ' + + JSON.stringify(options, undefined, 2)); + } + getChannelzInfo() { + return { + state: this.connectivityState, + trace: this.channelzTrace, + callTracker: this.callTracker, + children: this.childrenTracker.getChildLists(), + target: this.subchannelAddressString, + }; + } + trace(text) { + logging.trace(constants_1.LogVerbosity.DEBUG, TRACER_NAME, '(' + + this.channelzRef.id + + ') ' + + this.subchannelAddressString + + ' ' + + text); + } + refTrace(text) { + logging.trace(constants_1.LogVerbosity.DEBUG, 'subchannel_refcount', '(' + + this.channelzRef.id + + ') ' + + this.subchannelAddressString + + ' ' + + text); + } + handleBackoffTimer() { + if (this.continueConnecting) { + this.transitionToState([connectivity_state_1.ConnectivityState.TRANSIENT_FAILURE], connectivity_state_1.ConnectivityState.CONNECTING); + } + else { + this.transitionToState([connectivity_state_1.ConnectivityState.TRANSIENT_FAILURE], connectivity_state_1.ConnectivityState.IDLE); + } + } + /** + * Start a backoff timer with the current nextBackoff timeout + */ + startBackoff() { + this.backoffTimeout.runOnce(); + } + stopBackoff() { + this.backoffTimeout.stop(); + this.backoffTimeout.reset(); + } + startConnectingInternal() { + let options = this.options; + if (options['grpc.keepalive_time_ms']) { + const adjustedKeepaliveTime = Math.min(this.keepaliveTime, KEEPALIVE_MAX_TIME_MS); + options = Object.assign(Object.assign({}, options), { 'grpc.keepalive_time_ms': adjustedKeepaliveTime }); + } + this.connector + .connect(this.subchannelAddress, this.credentials, options) + .then(transport => { + if (this.transitionToState([connectivity_state_1.ConnectivityState.CONNECTING], connectivity_state_1.ConnectivityState.READY)) { + this.transport = transport; + if (this.channelzEnabled) { + this.childrenTracker.refChild(transport.getChannelzRef()); + } + transport.addDisconnectListener(tooManyPings => { + this.transitionToState([connectivity_state_1.ConnectivityState.READY], connectivity_state_1.ConnectivityState.IDLE); + if (tooManyPings && this.keepaliveTime > 0) { + this.keepaliveTime *= 2; + logging.log(constants_1.LogVerbosity.ERROR, `Connection to ${(0, uri_parser_1.uriToString)(this.channelTarget)} at ${this.subchannelAddressString} rejected by server because of excess pings. Increasing ping interval to ${this.keepaliveTime} ms`); + } + }); + } + else { + /* If we can't transition from CONNECTING to READY here, we will + * not be using this transport, so release its resources. */ + transport.shutdown(); + } + }, error => { + this.transitionToState([connectivity_state_1.ConnectivityState.CONNECTING], connectivity_state_1.ConnectivityState.TRANSIENT_FAILURE, `${error}`); + }); + } + /** + * Initiate a state transition from any element of oldStates to the new + * state. If the current connectivityState is not in oldStates, do nothing. + * @param oldStates The set of states to transition from + * @param newState The state to transition to + * @returns True if the state changed, false otherwise + */ + transitionToState(oldStates, newState, errorMessage) { + var _a, _b; + if (oldStates.indexOf(this.connectivityState) === -1) { + return false; + } + this.trace(connectivity_state_1.ConnectivityState[this.connectivityState] + + ' -> ' + + connectivity_state_1.ConnectivityState[newState]); + if (this.channelzEnabled) { + this.channelzTrace.addTrace('CT_INFO', 'Connectivity state change to ' + connectivity_state_1.ConnectivityState[newState]); + } + const previousState = this.connectivityState; + this.connectivityState = newState; + switch (newState) { + case connectivity_state_1.ConnectivityState.READY: + this.stopBackoff(); + break; + case connectivity_state_1.ConnectivityState.CONNECTING: + this.startBackoff(); + this.startConnectingInternal(); + this.continueConnecting = false; + break; + case connectivity_state_1.ConnectivityState.TRANSIENT_FAILURE: + if (this.channelzEnabled && this.transport) { + this.childrenTracker.unrefChild(this.transport.getChannelzRef()); + } + (_a = this.transport) === null || _a === void 0 ? void 0 : _a.shutdown(); + this.transport = null; + /* If the backoff timer has already ended by the time we get to the + * TRANSIENT_FAILURE state, we want to immediately transition out of + * TRANSIENT_FAILURE as though the backoff timer is ending right now */ + if (!this.backoffTimeout.isRunning()) { + process.nextTick(() => { + this.handleBackoffTimer(); + }); + } + break; + case connectivity_state_1.ConnectivityState.IDLE: + if (this.channelzEnabled && this.transport) { + this.childrenTracker.unrefChild(this.transport.getChannelzRef()); + } + (_b = this.transport) === null || _b === void 0 ? void 0 : _b.shutdown(); + this.transport = null; + break; + default: + throw new Error(`Invalid state: unknown ConnectivityState ${newState}`); + } + for (const listener of this.stateListeners) { + listener(this, previousState, newState, this.keepaliveTime, errorMessage); + } + return true; + } + ref() { + this.refTrace('refcount ' + this.refcount + ' -> ' + (this.refcount + 1)); + this.refcount += 1; + } + unref() { + this.refTrace('refcount ' + this.refcount + ' -> ' + (this.refcount - 1)); + this.refcount -= 1; + if (this.refcount === 0) { + this.channelzTrace.addTrace('CT_INFO', 'Shutting down'); + (0, channelz_1.unregisterChannelzRef)(this.channelzRef); + process.nextTick(() => { + this.transitionToState([connectivity_state_1.ConnectivityState.CONNECTING, connectivity_state_1.ConnectivityState.READY], connectivity_state_1.ConnectivityState.IDLE); + }); + } + } + unrefIfOneRef() { + if (this.refcount === 1) { + this.unref(); + return true; + } + return false; + } + createCall(metadata, host, method, listener) { + if (!this.transport) { + throw new Error('Cannot create call, subchannel not READY'); + } + let statsTracker; + if (this.channelzEnabled) { + this.callTracker.addCallStarted(); + this.streamTracker.addCallStarted(); + statsTracker = { + onCallEnd: status => { + if (status.code === constants_1.Status.OK) { + this.callTracker.addCallSucceeded(); + } + else { + this.callTracker.addCallFailed(); + } + }, + }; + } + else { + statsTracker = {}; + } + return this.transport.createCall(metadata, host, method, listener, statsTracker); + } + /** + * If the subchannel is currently IDLE, start connecting and switch to the + * CONNECTING state. If the subchannel is current in TRANSIENT_FAILURE, + * the next time it would transition to IDLE, start connecting again instead. + * Otherwise, do nothing. + */ + startConnecting() { + process.nextTick(() => { + /* First, try to transition from IDLE to connecting. If that doesn't happen + * because the state is not currently IDLE, check if it is + * TRANSIENT_FAILURE, and if so indicate that it should go back to + * connecting after the backoff timer ends. Otherwise do nothing */ + if (!this.transitionToState([connectivity_state_1.ConnectivityState.IDLE], connectivity_state_1.ConnectivityState.CONNECTING)) { + if (this.connectivityState === connectivity_state_1.ConnectivityState.TRANSIENT_FAILURE) { + this.continueConnecting = true; + } + } + }); + } + /** + * Get the subchannel's current connectivity state. + */ + getConnectivityState() { + return this.connectivityState; + } + /** + * Add a listener function to be called whenever the subchannel's + * connectivity state changes. + * @param listener + */ + addConnectivityStateListener(listener) { + this.stateListeners.add(listener); + } + /** + * Remove a listener previously added with `addConnectivityStateListener` + * @param listener A reference to a function previously passed to + * `addConnectivityStateListener` + */ + removeConnectivityStateListener(listener) { + this.stateListeners.delete(listener); + } + /** + * Reset the backoff timeout, and immediately start connecting if in backoff. + */ + resetBackoff() { + process.nextTick(() => { + this.backoffTimeout.reset(); + this.transitionToState([connectivity_state_1.ConnectivityState.TRANSIENT_FAILURE], connectivity_state_1.ConnectivityState.CONNECTING); + }); + } + getAddress() { + return this.subchannelAddressString; + } + getChannelzRef() { + return this.channelzRef; + } + isHealthy() { + return true; + } + addHealthStateWatcher(listener) { + // Do nothing with the listener + } + removeHealthStateWatcher(listener) { + // Do nothing with the listener + } + getRealSubchannel() { + return this; + } + realSubchannelEquals(other) { + return other.getRealSubchannel() === this; + } + throttleKeepalive(newKeepaliveTime) { + if (newKeepaliveTime > this.keepaliveTime) { + this.keepaliveTime = newKeepaliveTime; + } + } +} +exports.Subchannel = Subchannel; +//# sourceMappingURL=subchannel.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/subchannel.js.map b/node_modules/@grpc/grpc-js/build/src/subchannel.js.map new file mode 100644 index 0000000..78e27ab --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/subchannel.js.map @@ -0,0 +1 @@ +{"version":3,"file":"subchannel.js","sourceRoot":"","sources":["../../src/subchannel.ts"],"names":[],"m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,IAAI,CAAC;IACd,CAAC;IAED,qBAAqB,CAAC,QAAoC;QACxD,+BAA+B;IACjC,CAAC;IAED,wBAAwB,CAAC,QAAoC;QAC3D,+BAA+B;IACjC,CAAC;IAED,iBAAiB;QACf,OAAO,IAAI,CAAC;IACd,CAAC;IAED,oBAAoB,CAAC,KAA0B;QAC7C,OAAO,KAAK,CAAC,iBAAiB,EAAE,KAAK,IAAI,CAAC;IAC5C,CAAC;IAED,iBAAiB,CAAC,gBAAwB;QACxC,IAAI,gBAAgB,GAAG,IAAI,CAAC,aAAa,EAAE,CAAC;YAC1C,IAAI,CAAC,aAAa,GAAG,gBAAgB,CAAC;QACxC,CAAC;IACH,CAAC;CACF;AA/bD,gCA+bC"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/tls-helpers.d.ts b/node_modules/@grpc/grpc-js/build/src/tls-helpers.d.ts new file mode 100644 index 0000000..54f2dba --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/tls-helpers.d.ts @@ -0,0 +1,3 @@ +/// +export declare const CIPHER_SUITES: string | undefined; +export declare function getDefaultRootsData(): Buffer | null; diff --git a/node_modules/@grpc/grpc-js/build/src/tls-helpers.js b/node_modules/@grpc/grpc-js/build/src/tls-helpers.js new file mode 100644 index 0000000..d118344 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/tls-helpers.js @@ -0,0 +1,34 @@ +"use strict"; +/* + * Copyright 2019 gRPC authors. + * + * 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. + * + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.getDefaultRootsData = exports.CIPHER_SUITES = void 0; +const fs = require("fs"); +exports.CIPHER_SUITES = process.env.GRPC_SSL_CIPHER_SUITES; +const DEFAULT_ROOTS_FILE_PATH = process.env.GRPC_DEFAULT_SSL_ROOTS_FILE_PATH; +let defaultRootsData = null; +function getDefaultRootsData() { + if (DEFAULT_ROOTS_FILE_PATH) { + if (defaultRootsData === null) { + defaultRootsData = fs.readFileSync(DEFAULT_ROOTS_FILE_PATH); + } + return defaultRootsData; + } + return null; +} +exports.getDefaultRootsData = getDefaultRootsData; +//# sourceMappingURL=tls-helpers.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/tls-helpers.js.map b/node_modules/@grpc/grpc-js/build/src/tls-helpers.js.map new file mode 100644 index 0000000..0e08214 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/tls-helpers.js.map @@ -0,0 +1 @@ +{"version":3,"file":"tls-helpers.js","sourceRoot":"","sources":["../../src/tls-helpers.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;GAeG;;;AAEH,yBAAyB;AAEZ,QAAA,aAAa,GACxB,OAAO,CAAC,GAAG,CAAC,sBAAsB,CAAC;AAErC,MAAM,uBAAuB,GAAG,OAAO,CAAC,GAAG,CAAC,gCAAgC,CAAC;AAE7E,IAAI,gBAAgB,GAAkB,IAAI,CAAC;AAE3C,SAAgB,mBAAmB;IACjC,IAAI,uBAAuB,EAAE,CAAC;QAC5B,IAAI,gBAAgB,KAAK,IAAI,EAAE,CAAC;YAC9B,gBAAgB,GAAG,EAAE,CAAC,YAAY,CAAC,uBAAuB,CAAC,CAAC;QAC9D,CAAC;QACD,OAAO,gBAAgB,CAAC;IAC1B,CAAC;IACD,OAAO,IAAI,CAAC;AACd,CAAC;AARD,kDAQC"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/transport.d.ts b/node_modules/@grpc/grpc-js/build/src/transport.d.ts new file mode 100644 index 0000000..8372cfc --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/transport.d.ts @@ -0,0 +1,131 @@ +/// +import * as http2 from 'http2'; +import { PartialStatusObject } from './call-interface'; +import { ChannelCredentials } from './channel-credentials'; +import { ChannelOptions } from './channel-options'; +import { SocketRef } from './channelz'; +import { SubchannelAddress } from './subchannel-address'; +import { GrpcUri } from './uri-parser'; +import { Http2SubchannelCall, SubchannelCall, SubchannelCallInterceptingListener } from './subchannel-call'; +import { Metadata } from './metadata'; +export interface CallEventTracker { + addMessageSent(): void; + addMessageReceived(): void; + onCallEnd(status: PartialStatusObject): void; + onStreamEnd(success: boolean): void; +} +export interface TransportDisconnectListener { + (tooManyPings: boolean): void; +} +export interface Transport { + getChannelzRef(): SocketRef; + getPeerName(): string; + createCall(metadata: Metadata, host: string, method: string, listener: SubchannelCallInterceptingListener, subchannelCallStatsTracker: Partial): SubchannelCall; + addDisconnectListener(listener: TransportDisconnectListener): void; + shutdown(): void; +} +declare class Http2Transport implements Transport { + private session; + /** + * Name of the remote server, if it is not the same as the subchannel + * address, i.e. if connecting through an HTTP CONNECT proxy. + */ + private remoteName; + /** + * The amount of time in between sending pings + */ + private keepaliveTimeMs; + /** + * The amount of time to wait for an acknowledgement after sending a ping + */ + private keepaliveTimeoutMs; + /** + * Timer reference for timeout that indicates when to send the next ping + */ + private keepaliveTimerId; + /** + * Indicates that the keepalive timer ran out while there were no active + * calls, and a ping should be sent the next time a call starts. + */ + private pendingSendKeepalivePing; + /** + * Timer reference tracking when the most recent ping will be considered lost + */ + private keepaliveTimeoutId; + /** + * Indicates whether keepalive pings should be sent without any active calls + */ + private keepaliveWithoutCalls; + private userAgent; + private activeCalls; + private subchannelAddressString; + private disconnectListeners; + private disconnectHandled; + private channelzRef; + private readonly channelzEnabled; + private streamTracker; + private keepalivesSent; + private messagesSent; + private messagesReceived; + private lastMessageSentTimestamp; + private lastMessageReceivedTimestamp; + constructor(session: http2.ClientHttp2Session, subchannelAddress: SubchannelAddress, options: ChannelOptions, + /** + * Name of the remote server, if it is not the same as the subchannel + * address, i.e. if connecting through an HTTP CONNECT proxy. + */ + remoteName: string | null); + private getChannelzInfo; + private trace; + private keepaliveTrace; + private flowControlTrace; + private internalsTrace; + /** + * Indicate to the owner of this object that this transport should no longer + * be used. That happens if the connection drops, or if the server sends a + * GOAWAY. + * @param tooManyPings If true, this was triggered by a GOAWAY with data + * indicating that the session was closed becaues the client sent too many + * pings. + * @returns + */ + private reportDisconnectToOwner; + /** + * Handle connection drops, but not GOAWAYs. + */ + private handleDisconnect; + addDisconnectListener(listener: TransportDisconnectListener): void; + private clearKeepaliveTimer; + private clearKeepaliveTimeout; + private canSendPing; + private maybeSendPing; + /** + * Starts the keepalive ping timer if appropriate. If the timer already ran + * out while there were no active requests, instead send a ping immediately. + * If the ping timer is already running or a ping is currently in flight, + * instead do nothing and wait for them to resolve. + */ + private maybeStartKeepalivePingTimer; + private stopKeepalivePings; + private removeActiveCall; + private addActiveCall; + createCall(metadata: Metadata, host: string, method: string, listener: SubchannelCallInterceptingListener, subchannelCallStatsTracker: Partial): Http2SubchannelCall; + getChannelzRef(): SocketRef; + getPeerName(): string; + shutdown(): void; +} +export interface SubchannelConnector { + connect(address: SubchannelAddress, credentials: ChannelCredentials, options: ChannelOptions): Promise; + shutdown(): void; +} +export declare class Http2SubchannelConnector implements SubchannelConnector { + private channelTarget; + private session; + private isShutdown; + constructor(channelTarget: GrpcUri); + private trace; + private createSession; + connect(address: SubchannelAddress, credentials: ChannelCredentials, options: ChannelOptions): Promise; + shutdown(): void; +} +export {}; diff --git a/node_modules/@grpc/grpc-js/build/src/transport.js b/node_modules/@grpc/grpc-js/build/src/transport.js new file mode 100644 index 0000000..ddbcec7 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/transport.js @@ -0,0 +1,649 @@ +"use strict"; +/* + * Copyright 2023 gRPC authors. + * + * 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. + * + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Http2SubchannelConnector = void 0; +const http2 = require("http2"); +const tls_1 = require("tls"); +const channelz_1 = require("./channelz"); +const constants_1 = require("./constants"); +const http_proxy_1 = require("./http_proxy"); +const logging = require("./logging"); +const resolver_1 = require("./resolver"); +const subchannel_address_1 = require("./subchannel-address"); +const uri_parser_1 = require("./uri-parser"); +const net = require("net"); +const subchannel_call_1 = require("./subchannel-call"); +const call_number_1 = require("./call-number"); +const TRACER_NAME = 'transport'; +const FLOW_CONTROL_TRACER_NAME = 'transport_flowctrl'; +const clientVersion = require('../../package.json').version; +const { HTTP2_HEADER_AUTHORITY, HTTP2_HEADER_CONTENT_TYPE, HTTP2_HEADER_METHOD, HTTP2_HEADER_PATH, HTTP2_HEADER_TE, HTTP2_HEADER_USER_AGENT, } = http2.constants; +const KEEPALIVE_TIMEOUT_MS = 20000; +const tooManyPingsData = Buffer.from('too_many_pings', 'ascii'); +class Http2Transport { + constructor(session, subchannelAddress, options, + /** + * Name of the remote server, if it is not the same as the subchannel + * address, i.e. if connecting through an HTTP CONNECT proxy. + */ + remoteName) { + this.session = session; + this.remoteName = remoteName; + /** + * The amount of time in between sending pings + */ + this.keepaliveTimeMs = -1; + /** + * The amount of time to wait for an acknowledgement after sending a ping + */ + this.keepaliveTimeoutMs = KEEPALIVE_TIMEOUT_MS; + /** + * Timer reference for timeout that indicates when to send the next ping + */ + this.keepaliveTimerId = null; + /** + * Indicates that the keepalive timer ran out while there were no active + * calls, and a ping should be sent the next time a call starts. + */ + this.pendingSendKeepalivePing = false; + /** + * Timer reference tracking when the most recent ping will be considered lost + */ + this.keepaliveTimeoutId = null; + /** + * Indicates whether keepalive pings should be sent without any active calls + */ + this.keepaliveWithoutCalls = false; + this.activeCalls = new Set(); + this.disconnectListeners = []; + this.disconnectHandled = false; + this.channelzEnabled = true; + this.keepalivesSent = 0; + this.messagesSent = 0; + this.messagesReceived = 0; + this.lastMessageSentTimestamp = null; + this.lastMessageReceivedTimestamp = null; + /* Populate subchannelAddressString and channelzRef before doing anything + * else, because they are used in the trace methods. */ + this.subchannelAddressString = (0, subchannel_address_1.subchannelAddressToString)(subchannelAddress); + if (options['grpc.enable_channelz'] === 0) { + this.channelzEnabled = false; + this.streamTracker = new channelz_1.ChannelzCallTrackerStub(); + } + else { + this.streamTracker = new channelz_1.ChannelzCallTracker(); + } + this.channelzRef = (0, channelz_1.registerChannelzSocket)(this.subchannelAddressString, () => this.getChannelzInfo(), this.channelzEnabled); + // Build user-agent string. + this.userAgent = [ + options['grpc.primary_user_agent'], + `grpc-node-js/${clientVersion}`, + options['grpc.secondary_user_agent'], + ] + .filter(e => e) + .join(' '); // remove falsey values first + if ('grpc.keepalive_time_ms' in options) { + this.keepaliveTimeMs = options['grpc.keepalive_time_ms']; + } + if ('grpc.keepalive_timeout_ms' in options) { + this.keepaliveTimeoutMs = options['grpc.keepalive_timeout_ms']; + } + if ('grpc.keepalive_permit_without_calls' in options) { + this.keepaliveWithoutCalls = + options['grpc.keepalive_permit_without_calls'] === 1; + } + else { + this.keepaliveWithoutCalls = false; + } + session.once('close', () => { + this.trace('session closed'); + this.stopKeepalivePings(); + this.handleDisconnect(); + }); + session.once('goaway', (errorCode, lastStreamID, opaqueData) => { + let tooManyPings = false; + /* See the last paragraph of + * https://github.com/grpc/proposal/blob/master/A8-client-side-keepalive.md#basic-keepalive */ + if (errorCode === http2.constants.NGHTTP2_ENHANCE_YOUR_CALM && + opaqueData && + opaqueData.equals(tooManyPingsData)) { + tooManyPings = true; + } + this.trace('connection closed by GOAWAY with code ' + + errorCode + + ' and data ' + + (opaqueData === null || opaqueData === void 0 ? void 0 : opaqueData.toString())); + this.reportDisconnectToOwner(tooManyPings); + }); + session.once('error', error => { + /* Do nothing here. Any error should also trigger a close event, which is + * where we want to handle that. */ + this.trace('connection closed with error ' + error.message); + }); + if (logging.isTracerEnabled(TRACER_NAME)) { + session.on('remoteSettings', (settings) => { + this.trace('new settings received' + + (this.session !== session ? ' on the old connection' : '') + + ': ' + + JSON.stringify(settings)); + }); + session.on('localSettings', (settings) => { + this.trace('local settings acknowledged by remote' + + (this.session !== session ? ' on the old connection' : '') + + ': ' + + JSON.stringify(settings)); + }); + } + /* Start the keepalive timer last, because this can trigger trace logs, + * which should only happen after everything else is set up. */ + if (this.keepaliveWithoutCalls) { + this.maybeStartKeepalivePingTimer(); + } + } + getChannelzInfo() { + var _a, _b, _c; + const sessionSocket = this.session.socket; + const remoteAddress = sessionSocket.remoteAddress + ? (0, subchannel_address_1.stringToSubchannelAddress)(sessionSocket.remoteAddress, sessionSocket.remotePort) + : null; + const localAddress = sessionSocket.localAddress + ? (0, subchannel_address_1.stringToSubchannelAddress)(sessionSocket.localAddress, sessionSocket.localPort) + : null; + let tlsInfo; + if (this.session.encrypted) { + const tlsSocket = sessionSocket; + const cipherInfo = tlsSocket.getCipher(); + const certificate = tlsSocket.getCertificate(); + const peerCertificate = tlsSocket.getPeerCertificate(); + tlsInfo = { + cipherSuiteStandardName: (_a = cipherInfo.standardName) !== null && _a !== void 0 ? _a : null, + cipherSuiteOtherName: cipherInfo.standardName ? null : cipherInfo.name, + localCertificate: certificate && 'raw' in certificate ? certificate.raw : null, + remoteCertificate: peerCertificate && 'raw' in peerCertificate + ? peerCertificate.raw + : null, + }; + } + else { + tlsInfo = null; + } + const socketInfo = { + remoteAddress: remoteAddress, + localAddress: localAddress, + security: tlsInfo, + remoteName: this.remoteName, + streamsStarted: this.streamTracker.callsStarted, + streamsSucceeded: this.streamTracker.callsSucceeded, + streamsFailed: this.streamTracker.callsFailed, + messagesSent: this.messagesSent, + messagesReceived: this.messagesReceived, + keepAlivesSent: this.keepalivesSent, + lastLocalStreamCreatedTimestamp: this.streamTracker.lastCallStartedTimestamp, + lastRemoteStreamCreatedTimestamp: null, + lastMessageSentTimestamp: this.lastMessageSentTimestamp, + lastMessageReceivedTimestamp: this.lastMessageReceivedTimestamp, + localFlowControlWindow: (_b = this.session.state.localWindowSize) !== null && _b !== void 0 ? _b : null, + remoteFlowControlWindow: (_c = this.session.state.remoteWindowSize) !== null && _c !== void 0 ? _c : null, + }; + return socketInfo; + } + trace(text) { + logging.trace(constants_1.LogVerbosity.DEBUG, TRACER_NAME, '(' + + this.channelzRef.id + + ') ' + + this.subchannelAddressString + + ' ' + + text); + } + keepaliveTrace(text) { + logging.trace(constants_1.LogVerbosity.DEBUG, 'keepalive', '(' + + this.channelzRef.id + + ') ' + + this.subchannelAddressString + + ' ' + + text); + } + flowControlTrace(text) { + logging.trace(constants_1.LogVerbosity.DEBUG, FLOW_CONTROL_TRACER_NAME, '(' + + this.channelzRef.id + + ') ' + + this.subchannelAddressString + + ' ' + + text); + } + internalsTrace(text) { + logging.trace(constants_1.LogVerbosity.DEBUG, 'transport_internals', '(' + + this.channelzRef.id + + ') ' + + this.subchannelAddressString + + ' ' + + text); + } + /** + * Indicate to the owner of this object that this transport should no longer + * be used. That happens if the connection drops, or if the server sends a + * GOAWAY. + * @param tooManyPings If true, this was triggered by a GOAWAY with data + * indicating that the session was closed becaues the client sent too many + * pings. + * @returns + */ + reportDisconnectToOwner(tooManyPings) { + if (this.disconnectHandled) { + return; + } + this.disconnectHandled = true; + this.disconnectListeners.forEach(listener => listener(tooManyPings)); + } + /** + * Handle connection drops, but not GOAWAYs. + */ + handleDisconnect() { + this.reportDisconnectToOwner(false); + /* Give calls an event loop cycle to finish naturally before reporting the + * disconnnection to them. */ + setImmediate(() => { + for (const call of this.activeCalls) { + call.onDisconnect(); + } + }); + } + addDisconnectListener(listener) { + this.disconnectListeners.push(listener); + } + clearKeepaliveTimer() { + if (!this.keepaliveTimerId) { + return; + } + clearTimeout(this.keepaliveTimerId); + this.keepaliveTimerId = null; + } + clearKeepaliveTimeout() { + if (!this.keepaliveTimeoutId) { + return; + } + clearTimeout(this.keepaliveTimeoutId); + this.keepaliveTimeoutId = null; + } + canSendPing() { + return (this.keepaliveTimeMs > 0 && + (this.keepaliveWithoutCalls || this.activeCalls.size > 0)); + } + maybeSendPing() { + var _a, _b; + this.clearKeepaliveTimer(); + if (!this.canSendPing()) { + this.pendingSendKeepalivePing = true; + return; + } + if (this.channelzEnabled) { + this.keepalivesSent += 1; + } + this.keepaliveTrace('Sending ping with timeout ' + this.keepaliveTimeoutMs + 'ms'); + if (!this.keepaliveTimeoutId) { + this.keepaliveTimeoutId = setTimeout(() => { + this.keepaliveTrace('Ping timeout passed without response'); + this.handleDisconnect(); + }, this.keepaliveTimeoutMs); + (_b = (_a = this.keepaliveTimeoutId).unref) === null || _b === void 0 ? void 0 : _b.call(_a); + } + try { + this.session.ping((err, duration, payload) => { + if (err) { + this.keepaliveTrace('Ping failed with error ' + err.message); + this.handleDisconnect(); + } + this.keepaliveTrace('Received ping response'); + this.clearKeepaliveTimeout(); + this.maybeStartKeepalivePingTimer(); + }); + } + catch (e) { + /* If we fail to send a ping, the connection is no longer functional, so + * we should discard it. */ + this.handleDisconnect(); + } + } + /** + * Starts the keepalive ping timer if appropriate. If the timer already ran + * out while there were no active requests, instead send a ping immediately. + * If the ping timer is already running or a ping is currently in flight, + * instead do nothing and wait for them to resolve. + */ + maybeStartKeepalivePingTimer() { + var _a, _b; + if (!this.canSendPing()) { + return; + } + if (this.pendingSendKeepalivePing) { + this.pendingSendKeepalivePing = false; + this.maybeSendPing(); + } + else if (!this.keepaliveTimerId && !this.keepaliveTimeoutId) { + this.keepaliveTrace('Starting keepalive timer for ' + this.keepaliveTimeMs + 'ms'); + this.keepaliveTimerId = setTimeout(() => { + this.maybeSendPing(); + }, this.keepaliveTimeMs); + (_b = (_a = this.keepaliveTimerId).unref) === null || _b === void 0 ? void 0 : _b.call(_a); + } + /* Otherwise, there is already either a keepalive timer or a ping pending, + * wait for those to resolve. */ + } + stopKeepalivePings() { + if (this.keepaliveTimerId) { + clearTimeout(this.keepaliveTimerId); + this.keepaliveTimerId = null; + } + this.clearKeepaliveTimeout(); + } + removeActiveCall(call) { + this.activeCalls.delete(call); + if (this.activeCalls.size === 0) { + this.session.unref(); + } + } + addActiveCall(call) { + this.activeCalls.add(call); + if (this.activeCalls.size === 1) { + this.session.ref(); + if (!this.keepaliveWithoutCalls) { + this.maybeStartKeepalivePingTimer(); + } + } + } + createCall(metadata, host, method, listener, subchannelCallStatsTracker) { + const headers = metadata.toHttp2Headers(); + headers[HTTP2_HEADER_AUTHORITY] = host; + headers[HTTP2_HEADER_USER_AGENT] = this.userAgent; + headers[HTTP2_HEADER_CONTENT_TYPE] = 'application/grpc'; + headers[HTTP2_HEADER_METHOD] = 'POST'; + headers[HTTP2_HEADER_PATH] = method; + headers[HTTP2_HEADER_TE] = 'trailers'; + let http2Stream; + /* In theory, if an error is thrown by session.request because session has + * become unusable (e.g. because it has received a goaway), this subchannel + * should soon see the corresponding close or goaway event anyway and leave + * READY. But we have seen reports that this does not happen + * (https://github.com/googleapis/nodejs-firestore/issues/1023#issuecomment-653204096) + * so for defense in depth, we just discard the session when we see an + * error here. + */ + try { + http2Stream = this.session.request(headers); + } + catch (e) { + this.handleDisconnect(); + throw e; + } + this.flowControlTrace('local window size: ' + + this.session.state.localWindowSize + + ' remote window size: ' + + this.session.state.remoteWindowSize); + this.internalsTrace('session.closed=' + + this.session.closed + + ' session.destroyed=' + + this.session.destroyed + + ' session.socket.destroyed=' + + this.session.socket.destroyed); + let eventTracker; + // eslint-disable-next-line prefer-const + let call; + if (this.channelzEnabled) { + this.streamTracker.addCallStarted(); + eventTracker = { + addMessageSent: () => { + var _a; + this.messagesSent += 1; + this.lastMessageSentTimestamp = new Date(); + (_a = subchannelCallStatsTracker.addMessageSent) === null || _a === void 0 ? void 0 : _a.call(subchannelCallStatsTracker); + }, + addMessageReceived: () => { + var _a; + this.messagesReceived += 1; + this.lastMessageReceivedTimestamp = new Date(); + (_a = subchannelCallStatsTracker.addMessageReceived) === null || _a === void 0 ? void 0 : _a.call(subchannelCallStatsTracker); + }, + onCallEnd: status => { + var _a; + (_a = subchannelCallStatsTracker.onCallEnd) === null || _a === void 0 ? void 0 : _a.call(subchannelCallStatsTracker, status); + this.removeActiveCall(call); + }, + onStreamEnd: success => { + var _a; + if (success) { + this.streamTracker.addCallSucceeded(); + } + else { + this.streamTracker.addCallFailed(); + } + (_a = subchannelCallStatsTracker.onStreamEnd) === null || _a === void 0 ? void 0 : _a.call(subchannelCallStatsTracker, success); + }, + }; + } + else { + eventTracker = { + addMessageSent: () => { + var _a; + (_a = subchannelCallStatsTracker.addMessageSent) === null || _a === void 0 ? void 0 : _a.call(subchannelCallStatsTracker); + }, + addMessageReceived: () => { + var _a; + (_a = subchannelCallStatsTracker.addMessageReceived) === null || _a === void 0 ? void 0 : _a.call(subchannelCallStatsTracker); + }, + onCallEnd: status => { + var _a; + (_a = subchannelCallStatsTracker.onCallEnd) === null || _a === void 0 ? void 0 : _a.call(subchannelCallStatsTracker, status); + this.removeActiveCall(call); + }, + onStreamEnd: success => { + var _a; + (_a = subchannelCallStatsTracker.onStreamEnd) === null || _a === void 0 ? void 0 : _a.call(subchannelCallStatsTracker, success); + }, + }; + } + call = new subchannel_call_1.Http2SubchannelCall(http2Stream, eventTracker, listener, this, (0, call_number_1.getNextCallNumber)()); + this.addActiveCall(call); + return call; + } + getChannelzRef() { + return this.channelzRef; + } + getPeerName() { + return this.subchannelAddressString; + } + shutdown() { + this.session.close(); + (0, channelz_1.unregisterChannelzRef)(this.channelzRef); + } +} +class Http2SubchannelConnector { + constructor(channelTarget) { + this.channelTarget = channelTarget; + this.session = null; + this.isShutdown = false; + } + trace(text) { + logging.trace(constants_1.LogVerbosity.DEBUG, TRACER_NAME, (0, uri_parser_1.uriToString)(this.channelTarget) + ' ' + text); + } + createSession(address, credentials, options, proxyConnectionResult) { + if (this.isShutdown) { + return Promise.reject(); + } + return new Promise((resolve, reject) => { + var _a, _b, _c, _d; + let remoteName; + if (proxyConnectionResult.realTarget) { + remoteName = (0, uri_parser_1.uriToString)(proxyConnectionResult.realTarget); + this.trace('creating HTTP/2 session through proxy to ' + + (0, uri_parser_1.uriToString)(proxyConnectionResult.realTarget)); + } + else { + remoteName = null; + this.trace('creating HTTP/2 session to ' + (0, subchannel_address_1.subchannelAddressToString)(address)); + } + const targetAuthority = (0, resolver_1.getDefaultAuthority)((_a = proxyConnectionResult.realTarget) !== null && _a !== void 0 ? _a : this.channelTarget); + let connectionOptions = credentials._getConnectionOptions() || {}; + connectionOptions.maxSendHeaderBlockLength = Number.MAX_SAFE_INTEGER; + if ('grpc-node.max_session_memory' in options) { + connectionOptions.maxSessionMemory = + options['grpc-node.max_session_memory']; + } + else { + /* By default, set a very large max session memory limit, to effectively + * disable enforcement of the limit. Some testing indicates that Node's + * behavior degrades badly when this limit is reached, so we solve that + * by disabling the check entirely. */ + connectionOptions.maxSessionMemory = Number.MAX_SAFE_INTEGER; + } + let addressScheme = 'http://'; + if ('secureContext' in connectionOptions) { + addressScheme = 'https://'; + // If provided, the value of grpc.ssl_target_name_override should be used + // to override the target hostname when checking server identity. + // This option is used for testing only. + if (options['grpc.ssl_target_name_override']) { + const sslTargetNameOverride = options['grpc.ssl_target_name_override']; + const originalCheckServerIdentity = (_b = connectionOptions.checkServerIdentity) !== null && _b !== void 0 ? _b : tls_1.checkServerIdentity; + connectionOptions.checkServerIdentity = (host, cert) => { + return originalCheckServerIdentity(sslTargetNameOverride, cert); + }; + connectionOptions.servername = sslTargetNameOverride; + } + else { + const authorityHostname = (_d = (_c = (0, uri_parser_1.splitHostPort)(targetAuthority)) === null || _c === void 0 ? void 0 : _c.host) !== null && _d !== void 0 ? _d : 'localhost'; + // We want to always set servername to support SNI + connectionOptions.servername = authorityHostname; + } + if (proxyConnectionResult.socket) { + /* This is part of the workaround for + * https://github.com/nodejs/node/issues/32922. Without that bug, + * proxyConnectionResult.socket would always be a plaintext socket and + * this would say + * connectionOptions.socket = proxyConnectionResult.socket; */ + connectionOptions.createConnection = (authority, option) => { + return proxyConnectionResult.socket; + }; + } + } + else { + /* In all but the most recent versions of Node, http2.connect does not use + * the options when establishing plaintext connections, so we need to + * establish that connection explicitly. */ + connectionOptions.createConnection = (authority, option) => { + if (proxyConnectionResult.socket) { + return proxyConnectionResult.socket; + } + else { + /* net.NetConnectOpts is declared in a way that is more restrictive + * than what net.connect will actually accept, so we use the type + * assertion to work around that. */ + return net.connect(address); + } + }; + } + connectionOptions = Object.assign(Object.assign(Object.assign({}, connectionOptions), address), { enableTrace: options['grpc-node.tls_enable_trace'] === 1 }); + /* http2.connect uses the options here: + * https://github.com/nodejs/node/blob/70c32a6d190e2b5d7b9ff9d5b6a459d14e8b7d59/lib/internal/http2/core.js#L3028-L3036 + * The spread operator overides earlier values with later ones, so any port + * or host values in the options will be used rather than any values extracted + * from the first argument. In addition, the path overrides the host and port, + * as documented for plaintext connections here: + * https://nodejs.org/api/net.html#net_socket_connect_options_connectlistener + * and for TLS connections here: + * https://nodejs.org/api/tls.html#tls_tls_connect_options_callback. In + * earlier versions of Node, http2.connect passes these options to + * tls.connect but not net.connect, so in the insecure case we still need + * to set the createConnection option above to create the connection + * explicitly. We cannot do that in the TLS case because http2.connect + * passes necessary additional options to tls.connect. + * The first argument just needs to be parseable as a URL and the scheme + * determines whether the connection will be established over TLS or not. + */ + const session = http2.connect(addressScheme + targetAuthority, connectionOptions); + this.session = session; + let errorMessage = 'Failed to connect'; + session.unref(); + session.once('connect', () => { + session.removeAllListeners(); + resolve(new Http2Transport(session, address, options, remoteName)); + this.session = null; + }); + session.once('close', () => { + this.session = null; + // Leave time for error event to happen before rejecting + setImmediate(() => { + reject(`${errorMessage} (${new Date().toISOString()})`); + }); + }); + session.once('error', error => { + errorMessage = error.message; + this.trace('connection failed with error ' + errorMessage); + }); + }); + } + connect(address, credentials, options) { + var _a, _b, _c; + if (this.isShutdown) { + return Promise.reject(); + } + /* Pass connection options through to the proxy so that it's able to + * upgrade it's connection to support tls if needed. + * This is a workaround for https://github.com/nodejs/node/issues/32922 + * See https://github.com/grpc/grpc-node/pull/1369 for more info. */ + const connectionOptions = credentials._getConnectionOptions() || {}; + if ('secureContext' in connectionOptions) { + connectionOptions.ALPNProtocols = ['h2']; + // If provided, the value of grpc.ssl_target_name_override should be used + // to override the target hostname when checking server identity. + // This option is used for testing only. + if (options['grpc.ssl_target_name_override']) { + const sslTargetNameOverride = options['grpc.ssl_target_name_override']; + const originalCheckServerIdentity = (_a = connectionOptions.checkServerIdentity) !== null && _a !== void 0 ? _a : tls_1.checkServerIdentity; + connectionOptions.checkServerIdentity = (host, cert) => { + return originalCheckServerIdentity(sslTargetNameOverride, cert); + }; + connectionOptions.servername = sslTargetNameOverride; + } + else { + if ('grpc.http_connect_target' in options) { + /* This is more or less how servername will be set in createSession + * if a connection is successfully established through the proxy. + * If the proxy is not used, these connectionOptions are discarded + * anyway */ + const targetPath = (0, resolver_1.getDefaultAuthority)((_b = (0, uri_parser_1.parseUri)(options['grpc.http_connect_target'])) !== null && _b !== void 0 ? _b : { + path: 'localhost', + }); + const hostPort = (0, uri_parser_1.splitHostPort)(targetPath); + connectionOptions.servername = (_c = hostPort === null || hostPort === void 0 ? void 0 : hostPort.host) !== null && _c !== void 0 ? _c : targetPath; + } + } + if (options['grpc-node.tls_enable_trace']) { + connectionOptions.enableTrace = true; + } + } + return (0, http_proxy_1.getProxiedConnection)(address, options, connectionOptions).then(result => this.createSession(address, credentials, options, result)); + } + shutdown() { + var _a; + this.isShutdown = true; + (_a = this.session) === null || _a === void 0 ? void 0 : _a.close(); + this.session = null; + } +} +exports.Http2SubchannelConnector = Http2SubchannelConnector; +//# sourceMappingURL=transport.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/transport.js.map b/node_modules/@grpc/grpc-js/build/src/transport.js.map new file mode 100644 index 0000000..4a9c77b --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/transport.js.map @@ -0,0 +1 @@ +{"version":3,"file":"transport.js","sourceRoot":"","sources":["../../src/transport.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;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,EACF,EAAE;oBACrB,OAAO,2BAA2B,CAAC,qBAAqB,EAAE,IAAI,CAAC,CAAC;gBAClE,CAAC,CAAC;gBACF,iBAAiB,CAAC,UAAU,GAAG,qBAAqB,CAAC;YACvD,CAAC;iBAAM,CAAC;gBACN,IAAI,0BAA0B,IAAI,OAAO,EAAE,CAAC;oBAC1C;;;gCAGY;oBACZ,MAAM,UAAU,GAAG,IAAA,8BAAmB,EACpC,MAAA,IAAA,qBAAQ,EAAC,OAAO,CAAC,0BAA0B,CAAW,CAAC,mCAAI;wBACzD,IAAI,EAAE,WAAW;qBAClB,CACF,CAAC;oBACF,MAAM,QAAQ,GAAG,IAAA,0BAAa,EAAC,UAAU,CAAC,CAAC;oBAC3C,iBAAiB,CAAC,UAAU,GAAG,MAAA,QAAQ,aAAR,QAAQ,uBAAR,QAAQ,CAAE,IAAI,mCAAI,UAAU,CAAC;gBAC9D,CAAC;YACH,CAAC;YACD,IAAI,OAAO,CAAC,4BAA4B,CAAC,EAAE,CAAC;gBAC1C,iBAAiB,CAAC,WAAW,GAAG,IAAI,CAAC;YACvC,CAAC;QACH,CAAC;QAED,OAAO,IAAA,iCAAoB,EAAC,OAAO,EAAE,OAAO,EAAE,iBAAiB,CAAC,CAAC,IAAI,CACnE,MAAM,CAAC,EAAE,CAAC,IAAI,CAAC,aAAa,CAAC,OAAO,EAAE,WAAW,EAAE,OAAO,EAAE,MAAM,CAAC,CACpE,CAAC;IACJ,CAAC;IAED,QAAQ;;QACN,IAAI,CAAC,UAAU,GAAG,IAAI,CAAC;QACvB,MAAA,IAAI,CAAC,OAAO,0CAAE,KAAK,EAAE,CAAC;QACtB,IAAI,CAAC,OAAO,GAAG,IAAI,CAAC;IACtB,CAAC;CACF;AArND,4DAqNC"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/uri-parser.d.ts b/node_modules/@grpc/grpc-js/build/src/uri-parser.d.ts new file mode 100644 index 0000000..26db9c6 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/uri-parser.d.ts @@ -0,0 +1,13 @@ +export interface GrpcUri { + scheme?: string; + authority?: string; + path: string; +} +export declare function parseUri(uriString: string): GrpcUri | null; +export interface HostPort { + host: string; + port?: number; +} +export declare function splitHostPort(path: string): HostPort | null; +export declare function combineHostPort(hostPort: HostPort): string; +export declare function uriToString(uri: GrpcUri): string; diff --git a/node_modules/@grpc/grpc-js/build/src/uri-parser.js b/node_modules/@grpc/grpc-js/build/src/uri-parser.js new file mode 100644 index 0000000..cc06941 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/uri-parser.js @@ -0,0 +1,126 @@ +"use strict"; +/* + * Copyright 2020 gRPC authors. + * + * 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. + * + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.uriToString = exports.combineHostPort = exports.splitHostPort = exports.parseUri = void 0; +/* + * The groups correspond to URI parts as follows: + * 1. scheme + * 2. authority + * 3. path + */ +const URI_REGEX = /^(?:([A-Za-z0-9+.-]+):)?(?:\/\/([^/]*)\/)?(.+)$/; +function parseUri(uriString) { + const parsedUri = URI_REGEX.exec(uriString); + if (parsedUri === null) { + return null; + } + return { + scheme: parsedUri[1], + authority: parsedUri[2], + path: parsedUri[3], + }; +} +exports.parseUri = parseUri; +const NUMBER_REGEX = /^\d+$/; +function splitHostPort(path) { + if (path.startsWith('[')) { + const hostEnd = path.indexOf(']'); + if (hostEnd === -1) { + return null; + } + const host = path.substring(1, hostEnd); + /* Only an IPv6 address should be in bracketed notation, and an IPv6 + * address should have at least one colon */ + if (host.indexOf(':') === -1) { + return null; + } + if (path.length > hostEnd + 1) { + if (path[hostEnd + 1] === ':') { + const portString = path.substring(hostEnd + 2); + if (NUMBER_REGEX.test(portString)) { + return { + host: host, + port: +portString, + }; + } + else { + return null; + } + } + else { + return null; + } + } + else { + return { + host, + }; + } + } + else { + const splitPath = path.split(':'); + /* Exactly one colon means that this is host:port. Zero colons means that + * there is no port. And multiple colons means that this is a bare IPv6 + * address with no port */ + if (splitPath.length === 2) { + if (NUMBER_REGEX.test(splitPath[1])) { + return { + host: splitPath[0], + port: +splitPath[1], + }; + } + else { + return null; + } + } + else { + return { + host: path, + }; + } + } +} +exports.splitHostPort = splitHostPort; +function combineHostPort(hostPort) { + if (hostPort.port === undefined) { + return hostPort.host; + } + else { + // Only an IPv6 host should include a colon + if (hostPort.host.includes(':')) { + return `[${hostPort.host}]:${hostPort.port}`; + } + else { + return `${hostPort.host}:${hostPort.port}`; + } + } +} +exports.combineHostPort = combineHostPort; +function uriToString(uri) { + let result = ''; + if (uri.scheme !== undefined) { + result += uri.scheme + ':'; + } + if (uri.authority !== undefined) { + result += '//' + uri.authority + '/'; + } + result += uri.path; + return result; +} +exports.uriToString = uriToString; +//# sourceMappingURL=uri-parser.js.map \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/build/src/uri-parser.js.map b/node_modules/@grpc/grpc-js/build/src/uri-parser.js.map new file mode 100644 index 0000000..abf3136 --- /dev/null +++ b/node_modules/@grpc/grpc-js/build/src/uri-parser.js.map @@ -0,0 +1 @@ +{"version":3,"file":"uri-parser.js","sourceRoot":"","sources":["../../src/uri-parser.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;GAeG;;;AAQH;;;;;GAKG;AACH,MAAM,SAAS,GAAG,iDAAiD,CAAC;AAEpE,SAAgB,QAAQ,CAAC,SAAiB;IACxC,MAAM,SAAS,GAAG,SAAS,CAAC,IAAI,CAAC,SAAS,CAAC,CAAC;IAC5C,IAAI,SAAS,KAAK,IAAI,EAAE,CAAC;QACvB,OAAO,IAAI,CAAC;IACd,CAAC;IACD,OAAO;QACL,MAAM,E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SAAS,GAAG,GAAG,CAAC;IACvC,CAAC;IACD,MAAM,IAAI,GAAG,CAAC,IAAI,CAAC;IACnB,OAAO,MAAM,CAAC;AAChB,CAAC;AAVD,kCAUC"} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/package.json b/node_modules/@grpc/grpc-js/package.json new file mode 100644 index 0000000..f8b0703 --- /dev/null +++ b/node_modules/@grpc/grpc-js/package.json @@ -0,0 +1,86 @@ +{ + "name": "@grpc/grpc-js", + "version": "1.10.8", + "description": "gRPC Library for Node - pure JS implementation", + "homepage": "https://grpc.io/", + "repository": "https://github.com/grpc/grpc-node/tree/master/packages/grpc-js", + "main": "build/src/index.js", + "engines": { + "node": ">=12.10.0" + }, + "keywords": [], + "author": { + "name": "Google Inc." + }, + "types": "build/src/index.d.ts", + "license": "Apache-2.0", + "devDependencies": { + "@types/gulp": "^4.0.17", + "@types/gulp-mocha": "0.0.37", + "@types/lodash": "^4.14.202", + "@types/mocha": "^10.0.6", + "@types/ncp": "^2.0.8", + "@types/node": ">=20.11.20", + "@types/pify": "^5.0.4", + "@types/semver": "^7.5.8", + "@typescript-eslint/eslint-plugin": "^7.1.0", + "@typescript-eslint/parser": "^7.1.0", + "@typescript-eslint/typescript-estree": "^7.1.0", + "clang-format": "^1.8.0", + "eslint": "^8.42.0", + "eslint-config-prettier": "^8.8.0", + "eslint-plugin-node": "^11.1.0", + "eslint-plugin-prettier": "^4.2.1", + "execa": "^2.0.3", + "gulp": "^4.0.2", + "gulp-mocha": "^6.0.0", + "lodash": "^4.17.21", + "madge": "^5.0.1", + "mocha-jenkins-reporter": "^0.4.1", + "ncp": "^2.0.0", + "pify": "^4.0.1", + "prettier": "^2.8.8", + "rimraf": "^3.0.2", + "semver": "^7.6.0", + "ts-node": "^10.9.2", + "typescript": "^5.3.3" + }, + "contributors": [ + { + "name": "Google Inc." + } + ], + "scripts": { + "build": "npm run compile", + "clean": "rimraf ./build", + "compile": "tsc -p .", + "format": "clang-format -i -style=\"{Language: JavaScript, BasedOnStyle: Google, ColumnLimit: 80}\" src/*.ts test/*.ts", + "lint": "eslint src/*.ts test/*.ts", + "prepare": "npm run generate-types && npm run compile", + "test": "gulp test", + "check": "npm run lint", + "fix": "eslint --fix src/*.ts test/*.ts", + "pretest": "npm run generate-types && npm run generate-test-types && npm run compile", + "posttest": "npm run check && madge -c ./build/src", + "generate-types": "proto-loader-gen-types --keepCase --longs String --enums String --defaults --oneofs --includeComments --includeDirs proto/ --include-dirs test/fixtures/ -O src/generated/ --grpcLib ../index channelz.proto", + "generate-test-types": "proto-loader-gen-types --keepCase --longs String --enums String --defaults --oneofs --includeComments --include-dirs test/fixtures/ -O test/generated/ --grpcLib ../../src/index test_service.proto" + }, + "dependencies": { + "@grpc/proto-loader": "^0.7.13", + "@js-sdsl/ordered-map": "^4.4.2" + }, + "files": [ + "src/**/*.ts", + "build/src/**/*.{js,d.ts,js.map}", + "proto/*.proto", + "LICENSE", + "deps/envoy-api/envoy/api/v2/**/*.proto", + "deps/envoy-api/envoy/config/**/*.proto", + "deps/envoy-api/envoy/service/**/*.proto", + "deps/envoy-api/envoy/type/**/*.proto", + "deps/udpa/udpa/**/*.proto", + "deps/googleapis/google/api/*.proto", + "deps/googleapis/google/rpc/*.proto", + "deps/protoc-gen-validate/validate/**/*.proto" + ] +} diff --git a/node_modules/@grpc/grpc-js/proto/channelz.proto b/node_modules/@grpc/grpc-js/proto/channelz.proto new file mode 100644 index 0000000..446e979 --- /dev/null +++ b/node_modules/@grpc/grpc-js/proto/channelz.proto @@ -0,0 +1,564 @@ +// Copyright 2018 The gRPC Authors +// +// 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. + +// This file defines an interface for exporting monitoring information +// out of gRPC servers. See the full design at +// https://github.com/grpc/proposal/blob/master/A14-channelz.md +// +// The canonical version of this proto can be found at +// https://github.com/grpc/grpc-proto/blob/master/grpc/channelz/v1/channelz.proto + +syntax = "proto3"; + +package grpc.channelz.v1; + +import "google/protobuf/any.proto"; +import "google/protobuf/duration.proto"; +import "google/protobuf/timestamp.proto"; +import "google/protobuf/wrappers.proto"; + +option go_package = "google.golang.org/grpc/channelz/grpc_channelz_v1"; +option java_multiple_files = true; +option java_package = "io.grpc.channelz.v1"; +option java_outer_classname = "ChannelzProto"; + +// Channel is a logical grouping of channels, subchannels, and sockets. +message Channel { + // The identifier for this channel. This should bet set. + ChannelRef ref = 1; + // Data specific to this channel. + ChannelData data = 2; + // At most one of 'channel_ref+subchannel_ref' and 'socket' is set. + + // There are no ordering guarantees on the order of channel refs. + // There may not be cycles in the ref graph. + // A channel ref may be present in more than one channel or subchannel. + repeated ChannelRef channel_ref = 3; + + // At most one of 'channel_ref+subchannel_ref' and 'socket' is set. + // There are no ordering guarantees on the order of subchannel refs. + // There may not be cycles in the ref graph. + // A sub channel ref may be present in more than one channel or subchannel. + repeated SubchannelRef subchannel_ref = 4; + + // There are no ordering guarantees on the order of sockets. + repeated SocketRef socket_ref = 5; +} + +// Subchannel is a logical grouping of channels, subchannels, and sockets. +// A subchannel is load balanced over by it's ancestor +message Subchannel { + // The identifier for this channel. + SubchannelRef ref = 1; + // Data specific to this channel. + ChannelData data = 2; + // At most one of 'channel_ref+subchannel_ref' and 'socket' is set. + + // There are no ordering guarantees on the order of channel refs. + // There may not be cycles in the ref graph. + // A channel ref may be present in more than one channel or subchannel. + repeated ChannelRef channel_ref = 3; + + // At most one of 'channel_ref+subchannel_ref' and 'socket' is set. + // There are no ordering guarantees on the order of subchannel refs. + // There may not be cycles in the ref graph. + // A sub channel ref may be present in more than one channel or subchannel. + repeated SubchannelRef subchannel_ref = 4; + + // There are no ordering guarantees on the order of sockets. + repeated SocketRef socket_ref = 5; +} + +// These come from the specified states in this document: +// https://github.com/grpc/grpc/blob/master/doc/connectivity-semantics-and-api.md +message ChannelConnectivityState { + enum State { + UNKNOWN = 0; + IDLE = 1; + CONNECTING = 2; + READY = 3; + TRANSIENT_FAILURE = 4; + SHUTDOWN = 5; + } + State state = 1; +} + +// Channel data is data related to a specific Channel or Subchannel. +message ChannelData { + // The connectivity state of the channel or subchannel. Implementations + // should always set this. + ChannelConnectivityState state = 1; + + // The target this channel originally tried to connect to. May be absent + string target = 2; + + // A trace of recent events on the channel. May be absent. + ChannelTrace trace = 3; + + // The number of calls started on the channel + int64 calls_started = 4; + // The number of calls that have completed with an OK status + int64 calls_succeeded = 5; + // The number of calls that have completed with a non-OK status + int64 calls_failed = 6; + + // The last time a call was started on the channel. + google.protobuf.Timestamp last_call_started_timestamp = 7; +} + +// A trace event is an interesting thing that happened to a channel or +// subchannel, such as creation, address resolution, subchannel creation, etc. +message ChannelTraceEvent { + // High level description of the event. + string description = 1; + // The supported severity levels of trace events. + enum Severity { + CT_UNKNOWN = 0; + CT_INFO = 1; + CT_WARNING = 2; + CT_ERROR = 3; + } + // the severity of the trace event + Severity severity = 2; + // When this event occurred. + google.protobuf.Timestamp timestamp = 3; + // ref of referenced channel or subchannel. + // Optional, only present if this event refers to a child object. For example, + // this field would be filled if this trace event was for a subchannel being + // created. + oneof child_ref { + ChannelRef channel_ref = 4; + SubchannelRef subchannel_ref = 5; + } +} + +// ChannelTrace represents the recent events that have occurred on the channel. +message ChannelTrace { + // Number of events ever logged in this tracing object. This can differ from + // events.size() because events can be overwritten or garbage collected by + // implementations. + int64 num_events_logged = 1; + // Time that this channel was created. + google.protobuf.Timestamp creation_timestamp = 2; + // List of events that have occurred on this channel. + repeated ChannelTraceEvent events = 3; +} + +// ChannelRef is a reference to a Channel. +message ChannelRef { + // The globally unique id for this channel. Must be a positive number. + int64 channel_id = 1; + // An optional name associated with the channel. + string name = 2; + // Intentionally don't use field numbers from other refs. + reserved 3, 4, 5, 6, 7, 8; +} + +// SubchannelRef is a reference to a Subchannel. +message SubchannelRef { + // The globally unique id for this subchannel. Must be a positive number. + int64 subchannel_id = 7; + // An optional name associated with the subchannel. + string name = 8; + // Intentionally don't use field numbers from other refs. + reserved 1, 2, 3, 4, 5, 6; +} + +// SocketRef is a reference to a Socket. +message SocketRef { + // The globally unique id for this socket. Must be a positive number. + int64 socket_id = 3; + // An optional name associated with the socket. + string name = 4; + // Intentionally don't use field numbers from other refs. + reserved 1, 2, 5, 6, 7, 8; +} + +// ServerRef is a reference to a Server. +message ServerRef { + // A globally unique identifier for this server. Must be a positive number. + int64 server_id = 5; + // An optional name associated with the server. + string name = 6; + // Intentionally don't use field numbers from other refs. + reserved 1, 2, 3, 4, 7, 8; +} + +// Server represents a single server. There may be multiple servers in a single +// program. +message Server { + // The identifier for a Server. This should be set. + ServerRef ref = 1; + // The associated data of the Server. + ServerData data = 2; + + // The sockets that the server is listening on. There are no ordering + // guarantees. This may be absent. + repeated SocketRef listen_socket = 3; +} + +// ServerData is data for a specific Server. +message ServerData { + // A trace of recent events on the server. May be absent. + ChannelTrace trace = 1; + + // The number of incoming calls started on the server + int64 calls_started = 2; + // The number of incoming calls that have completed with an OK status + int64 calls_succeeded = 3; + // The number of incoming calls that have a completed with a non-OK status + int64 calls_failed = 4; + + // The last time a call was started on the server. + google.protobuf.Timestamp last_call_started_timestamp = 5; +} + +// Information about an actual connection. Pronounced "sock-ay". +message Socket { + // The identifier for the Socket. + SocketRef ref = 1; + + // Data specific to this Socket. + SocketData data = 2; + // The locally bound address. + Address local = 3; + // The remote bound address. May be absent. + Address remote = 4; + // Security details for this socket. May be absent if not available, or + // there is no security on the socket. + Security security = 5; + + // Optional, represents the name of the remote endpoint, if different than + // the original target name. + string remote_name = 6; +} + +// SocketData is data associated for a specific Socket. The fields present +// are specific to the implementation, so there may be minor differences in +// the semantics. (e.g. flow control windows) +message SocketData { + // The number of streams that have been started. + int64 streams_started = 1; + // The number of streams that have ended successfully: + // On client side, received frame with eos bit set; + // On server side, sent frame with eos bit set. + int64 streams_succeeded = 2; + // The number of streams that have ended unsuccessfully: + // On client side, ended without receiving frame with eos bit set; + // On server side, ended without sending frame with eos bit set. + int64 streams_failed = 3; + // The number of grpc messages successfully sent on this socket. + int64 messages_sent = 4; + // The number of grpc messages received on this socket. + int64 messages_received = 5; + + // The number of keep alives sent. This is typically implemented with HTTP/2 + // ping messages. + int64 keep_alives_sent = 6; + + // The last time a stream was created by this endpoint. Usually unset for + // servers. + google.protobuf.Timestamp last_local_stream_created_timestamp = 7; + // The last time a stream was created by the remote endpoint. Usually unset + // for clients. + google.protobuf.Timestamp last_remote_stream_created_timestamp = 8; + + // The last time a message was sent by this endpoint. + google.protobuf.Timestamp last_message_sent_timestamp = 9; + // The last time a message was received by this endpoint. + google.protobuf.Timestamp last_message_received_timestamp = 10; + + // The amount of window, granted to the local endpoint by the remote endpoint. + // This may be slightly out of date due to network latency. This does NOT + // include stream level or TCP level flow control info. + google.protobuf.Int64Value local_flow_control_window = 11; + + // The amount of window, granted to the remote endpoint by the local endpoint. + // This may be slightly out of date due to network latency. This does NOT + // include stream level or TCP level flow control info. + google.protobuf.Int64Value remote_flow_control_window = 12; + + // Socket options set on this socket. May be absent if 'summary' is set + // on GetSocketRequest. + repeated SocketOption option = 13; +} + +// Address represents the address used to create the socket. +message Address { + message TcpIpAddress { + // Either the IPv4 or IPv6 address in bytes. Will be either 4 bytes or 16 + // bytes in length. + bytes ip_address = 1; + // 0-64k, or -1 if not appropriate. + int32 port = 2; + } + // A Unix Domain Socket address. + message UdsAddress { + string filename = 1; + } + // An address type not included above. + message OtherAddress { + // The human readable version of the value. This value should be set. + string name = 1; + // The actual address message. + google.protobuf.Any value = 2; + } + + oneof address { + TcpIpAddress tcpip_address = 1; + UdsAddress uds_address = 2; + OtherAddress other_address = 3; + } +} + +// Security represents details about how secure the socket is. +message Security { + message Tls { + oneof cipher_suite { + // The cipher suite name in the RFC 4346 format: + // https://tools.ietf.org/html/rfc4346#appendix-C + string standard_name = 1; + // Some other way to describe the cipher suite if + // the RFC 4346 name is not available. + string other_name = 2; + } + // the certificate used by this endpoint. + bytes local_certificate = 3; + // the certificate used by the remote endpoint. + bytes remote_certificate = 4; + } + message OtherSecurity { + // The human readable version of the value. + string name = 1; + // The actual security details message. + google.protobuf.Any value = 2; + } + oneof model { + Tls tls = 1; + OtherSecurity other = 2; + } +} + +// SocketOption represents socket options for a socket. Specifically, these +// are the options returned by getsockopt(). +message SocketOption { + // The full name of the socket option. Typically this will be the upper case + // name, such as "SO_REUSEPORT". + string name = 1; + // The human readable value of this socket option. At least one of value or + // additional will be set. + string value = 2; + // Additional data associated with the socket option. At least one of value + // or additional will be set. + google.protobuf.Any additional = 3; +} + +// For use with SocketOption's additional field. This is primarily used for +// SO_RCVTIMEO and SO_SNDTIMEO +message SocketOptionTimeout { + google.protobuf.Duration duration = 1; +} + +// For use with SocketOption's additional field. This is primarily used for +// SO_LINGER. +message SocketOptionLinger { + // active maps to `struct linger.l_onoff` + bool active = 1; + // duration maps to `struct linger.l_linger` + google.protobuf.Duration duration = 2; +} + +// For use with SocketOption's additional field. Tcp info for +// SOL_TCP and TCP_INFO. +message SocketOptionTcpInfo { + uint32 tcpi_state = 1; + + uint32 tcpi_ca_state = 2; + uint32 tcpi_retransmits = 3; + uint32 tcpi_probes = 4; + uint32 tcpi_backoff = 5; + uint32 tcpi_options = 6; + uint32 tcpi_snd_wscale = 7; + uint32 tcpi_rcv_wscale = 8; + + uint32 tcpi_rto = 9; + uint32 tcpi_ato = 10; + uint32 tcpi_snd_mss = 11; + uint32 tcpi_rcv_mss = 12; + + uint32 tcpi_unacked = 13; + uint32 tcpi_sacked = 14; + uint32 tcpi_lost = 15; + uint32 tcpi_retrans = 16; + uint32 tcpi_fackets = 17; + + uint32 tcpi_last_data_sent = 18; + uint32 tcpi_last_ack_sent = 19; + uint32 tcpi_last_data_recv = 20; + uint32 tcpi_last_ack_recv = 21; + + uint32 tcpi_pmtu = 22; + uint32 tcpi_rcv_ssthresh = 23; + uint32 tcpi_rtt = 24; + uint32 tcpi_rttvar = 25; + uint32 tcpi_snd_ssthresh = 26; + uint32 tcpi_snd_cwnd = 27; + uint32 tcpi_advmss = 28; + uint32 tcpi_reordering = 29; +} + +// Channelz is a service exposed by gRPC servers that provides detailed debug +// information. +service Channelz { + // Gets all root channels (i.e. channels the application has directly + // created). This does not include subchannels nor non-top level channels. + rpc GetTopChannels(GetTopChannelsRequest) returns (GetTopChannelsResponse); + // Gets all servers that exist in the process. + rpc GetServers(GetServersRequest) returns (GetServersResponse); + // Returns a single Server, or else a NOT_FOUND code. + rpc GetServer(GetServerRequest) returns (GetServerResponse); + // Gets all server sockets that exist in the process. + rpc GetServerSockets(GetServerSocketsRequest) returns (GetServerSocketsResponse); + // Returns a single Channel, or else a NOT_FOUND code. + rpc GetChannel(GetChannelRequest) returns (GetChannelResponse); + // Returns a single Subchannel, or else a NOT_FOUND code. + rpc GetSubchannel(GetSubchannelRequest) returns (GetSubchannelResponse); + // Returns a single Socket or else a NOT_FOUND code. + rpc GetSocket(GetSocketRequest) returns (GetSocketResponse); +} + +message GetTopChannelsRequest { + // start_channel_id indicates that only channels at or above this id should be + // included in the results. + // To request the first page, this should be set to 0. To request + // subsequent pages, the client generates this value by adding 1 to + // the highest seen result ID. + int64 start_channel_id = 1; + + // If non-zero, the server will return a page of results containing + // at most this many items. If zero, the server will choose a + // reasonable page size. Must never be negative. + int64 max_results = 2; +} + +message GetTopChannelsResponse { + // list of channels that the connection detail service knows about. Sorted in + // ascending channel_id order. + // Must contain at least 1 result, otherwise 'end' must be true. + repeated Channel channel = 1; + // If set, indicates that the list of channels is the final list. Requesting + // more channels can only return more if they are created after this RPC + // completes. + bool end = 2; +} + +message GetServersRequest { + // start_server_id indicates that only servers at or above this id should be + // included in the results. + // To request the first page, this must be set to 0. To request + // subsequent pages, the client generates this value by adding 1 to + // the highest seen result ID. + int64 start_server_id = 1; + + // If non-zero, the server will return a page of results containing + // at most this many items. If zero, the server will choose a + // reasonable page size. Must never be negative. + int64 max_results = 2; +} + +message GetServersResponse { + // list of servers that the connection detail service knows about. Sorted in + // ascending server_id order. + // Must contain at least 1 result, otherwise 'end' must be true. + repeated Server server = 1; + // If set, indicates that the list of servers is the final list. Requesting + // more servers will only return more if they are created after this RPC + // completes. + bool end = 2; +} + +message GetServerRequest { + // server_id is the identifier of the specific server to get. + int64 server_id = 1; +} + +message GetServerResponse { + // The Server that corresponds to the requested server_id. This field + // should be set. + Server server = 1; +} + +message GetServerSocketsRequest { + int64 server_id = 1; + // start_socket_id indicates that only sockets at or above this id should be + // included in the results. + // To request the first page, this must be set to 0. To request + // subsequent pages, the client generates this value by adding 1 to + // the highest seen result ID. + int64 start_socket_id = 2; + + // If non-zero, the server will return a page of results containing + // at most this many items. If zero, the server will choose a + // reasonable page size. Must never be negative. + int64 max_results = 3; +} + +message GetServerSocketsResponse { + // list of socket refs that the connection detail service knows about. Sorted in + // ascending socket_id order. + // Must contain at least 1 result, otherwise 'end' must be true. + repeated SocketRef socket_ref = 1; + // If set, indicates that the list of sockets is the final list. Requesting + // more sockets will only return more if they are created after this RPC + // completes. + bool end = 2; +} + +message GetChannelRequest { + // channel_id is the identifier of the specific channel to get. + int64 channel_id = 1; +} + +message GetChannelResponse { + // The Channel that corresponds to the requested channel_id. This field + // should be set. + Channel channel = 1; +} + +message GetSubchannelRequest { + // subchannel_id is the identifier of the specific subchannel to get. + int64 subchannel_id = 1; +} + +message GetSubchannelResponse { + // The Subchannel that corresponds to the requested subchannel_id. This + // field should be set. + Subchannel subchannel = 1; +} + +message GetSocketRequest { + // socket_id is the identifier of the specific socket to get. + int64 socket_id = 1; + + // If true, the response will contain only high level information + // that is inexpensive to obtain. Fields thay may be omitted are + // documented. + bool summary = 2; +} + +message GetSocketResponse { + // The Socket that corresponds to the requested socket_id. This field + // should be set. + Socket socket = 1; +} \ No newline at end of file diff --git a/node_modules/@grpc/grpc-js/src/admin.ts b/node_modules/@grpc/grpc-js/src/admin.ts new file mode 100644 index 0000000..4d26b89 --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/admin.ts @@ -0,0 +1,45 @@ +/* + * Copyright 2021 gRPC authors. + * + * 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. + * + */ + +import { ServiceDefinition } from './make-client'; +import { Server, UntypedServiceImplementation } from './server'; + +interface GetServiceDefinition { + (): ServiceDefinition; +} + +interface GetHandlers { + (): UntypedServiceImplementation; +} + +const registeredAdminServices: { + getServiceDefinition: GetServiceDefinition; + getHandlers: GetHandlers; +}[] = []; + +export function registerAdminService( + getServiceDefinition: GetServiceDefinition, + getHandlers: GetHandlers +) { + registeredAdminServices.push({ getServiceDefinition, getHandlers }); +} + +export function addAdminServicesToServer(server: Server): void { + for (const { getServiceDefinition, getHandlers } of registeredAdminServices) { + server.addService(getServiceDefinition(), getHandlers()); + } +} diff --git a/node_modules/@grpc/grpc-js/src/backoff-timeout.ts b/node_modules/@grpc/grpc-js/src/backoff-timeout.ts new file mode 100644 index 0000000..10d347e --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/backoff-timeout.ts @@ -0,0 +1,198 @@ +/* + * Copyright 2019 gRPC authors. + * + * 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. + * + */ + +const INITIAL_BACKOFF_MS = 1000; +const BACKOFF_MULTIPLIER = 1.6; +const MAX_BACKOFF_MS = 120000; +const BACKOFF_JITTER = 0.2; + +/** + * Get a number uniformly at random in the range [min, max) + * @param min + * @param max + */ +function uniformRandom(min: number, max: number) { + return Math.random() * (max - min) + min; +} + +export interface BackoffOptions { + initialDelay?: number; + multiplier?: number; + jitter?: number; + maxDelay?: number; +} + +export class BackoffTimeout { + /** + * The delay time at the start, and after each reset. + */ + private readonly initialDelay: number = INITIAL_BACKOFF_MS; + /** + * The exponential backoff multiplier. + */ + private readonly multiplier: number = BACKOFF_MULTIPLIER; + /** + * The maximum delay time + */ + private readonly maxDelay: number = MAX_BACKOFF_MS; + /** + * The maximum fraction by which the delay time can randomly vary after + * applying the multiplier. + */ + private readonly jitter: number = BACKOFF_JITTER; + /** + * The delay time for the next time the timer runs. + */ + private nextDelay: number; + /** + * The handle of the underlying timer. If running is false, this value refers + * to an object representing a timer that has ended, but it can still be + * interacted with without error. + */ + private timerId: NodeJS.Timeout; + /** + * Indicates whether the timer is currently running. + */ + private running = false; + /** + * Indicates whether the timer should keep the Node process running if no + * other async operation is doing so. + */ + private hasRef = true; + /** + * The time that the currently running timer was started. Only valid if + * running is true. + */ + private startTime: Date = new Date(); + /** + * The approximate time that the currently running timer will end. Only valid + * if running is true. + */ + private endTime: Date = new Date(); + + constructor(private callback: () => void, options?: BackoffOptions) { + if (options) { + if (options.initialDelay) { + this.initialDelay = options.initialDelay; + } + if (options.multiplier) { + this.multiplier = options.multiplier; + } + if (options.jitter) { + this.jitter = options.jitter; + } + if (options.maxDelay) { + this.maxDelay = options.maxDelay; + } + } + this.nextDelay = this.initialDelay; + this.timerId = setTimeout(() => {}, 0); + clearTimeout(this.timerId); + } + + private runTimer(delay: number) { + this.endTime = this.startTime; + this.endTime.setMilliseconds( + this.endTime.getMilliseconds() + this.nextDelay + ); + clearTimeout(this.timerId); + this.timerId = setTimeout(() => { + this.callback(); + this.running = false; + }, delay); + if (!this.hasRef) { + this.timerId.unref?.(); + } + } + + /** + * Call the callback after the current amount of delay time + */ + runOnce() { + this.running = true; + this.startTime = new Date(); + this.runTimer(this.nextDelay); + const nextBackoff = Math.min( + this.nextDelay * this.multiplier, + this.maxDelay + ); + const jitterMagnitude = nextBackoff * this.jitter; + this.nextDelay = + nextBackoff + uniformRandom(-jitterMagnitude, jitterMagnitude); + } + + /** + * Stop the timer. The callback will not be called until `runOnce` is called + * again. + */ + stop() { + clearTimeout(this.timerId); + this.running = false; + } + + /** + * Reset the delay time to its initial value. If the timer is still running, + * retroactively apply that reset to the current timer. + */ + reset() { + this.nextDelay = this.initialDelay; + if (this.running) { + const now = new Date(); + const newEndTime = this.startTime; + newEndTime.setMilliseconds(newEndTime.getMilliseconds() + this.nextDelay); + clearTimeout(this.timerId); + if (now < newEndTime) { + this.runTimer(newEndTime.getTime() - now.getTime()); + } else { + this.running = false; + } + } + } + + /** + * Check whether the timer is currently running. + */ + isRunning() { + return this.running; + } + + /** + * Set that while the timer is running, it should keep the Node process + * running. + */ + ref() { + this.hasRef = true; + this.timerId.ref?.(); + } + + /** + * Set that while the timer is running, it should not keep the Node process + * running. + */ + unref() { + this.hasRef = false; + this.timerId.unref?.(); + } + + /** + * Get the approximate timestamp of when the timer will fire. Only valid if + * this.isRunning() is true. + */ + getEndTime() { + return this.endTime; + } +} diff --git a/node_modules/@grpc/grpc-js/src/call-credentials.ts b/node_modules/@grpc/grpc-js/src/call-credentials.ts new file mode 100644 index 0000000..b0013ee --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/call-credentials.ts @@ -0,0 +1,226 @@ +/* + * Copyright 2019 gRPC authors. + * + * 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. + * + */ + +import { Metadata } from './metadata'; + +export interface CallMetadataOptions { + service_url: string; +} + +export type CallMetadataGenerator = ( + options: CallMetadataOptions, + cb: (err: Error | null, metadata?: Metadata) => void +) => void; + +// google-auth-library pre-v2.0.0 does not have getRequestHeaders +// but has getRequestMetadata, which is deprecated in v2.0.0 +export interface OldOAuth2Client { + getRequestMetadata: ( + url: string, + callback: ( + err: Error | null, + headers?: { + [index: string]: string; + } + ) => void + ) => void; +} + +export interface CurrentOAuth2Client { + getRequestHeaders: (url?: string) => Promise<{ [index: string]: string }>; +} + +export type OAuth2Client = OldOAuth2Client | CurrentOAuth2Client; + +function isCurrentOauth2Client( + client: OAuth2Client +): client is CurrentOAuth2Client { + return ( + 'getRequestHeaders' in client && + typeof client.getRequestHeaders === 'function' + ); +} + +/** + * A class that represents a generic method of adding authentication-related + * metadata on a per-request basis. + */ +export abstract class CallCredentials { + /** + * Asynchronously generates a new Metadata object. + * @param options Options used in generating the Metadata object. + */ + abstract generateMetadata(options: CallMetadataOptions): Promise; + /** + * Creates a new CallCredentials object from properties of both this and + * another CallCredentials object. This object's metadata generator will be + * called first. + * @param callCredentials The other CallCredentials object. + */ + abstract compose(callCredentials: CallCredentials): CallCredentials; + + /** + * Check whether two call credentials objects are equal. Separate + * SingleCallCredentials with identical metadata generator functions are + * equal. + * @param other The other CallCredentials object to compare with. + */ + abstract _equals(other: CallCredentials): boolean; + + /** + * Creates a new CallCredentials object from a given function that generates + * Metadata objects. + * @param metadataGenerator A function that accepts a set of options, and + * generates a Metadata object based on these options, which is passed back + * to the caller via a supplied (err, metadata) callback. + */ + static createFromMetadataGenerator( + metadataGenerator: CallMetadataGenerator + ): CallCredentials { + return new SingleCallCredentials(metadataGenerator); + } + + /** + * Create a gRPC credential from a Google credential object. + * @param googleCredentials The authentication client to use. + * @return The resulting CallCredentials object. + */ + static createFromGoogleCredential( + googleCredentials: OAuth2Client + ): CallCredentials { + return CallCredentials.createFromMetadataGenerator((options, callback) => { + let getHeaders: Promise<{ [index: string]: string }>; + if (isCurrentOauth2Client(googleCredentials)) { + getHeaders = googleCredentials.getRequestHeaders(options.service_url); + } else { + getHeaders = new Promise((resolve, reject) => { + googleCredentials.getRequestMetadata( + options.service_url, + (err, headers) => { + if (err) { + reject(err); + return; + } + if (!headers) { + reject(new Error('Headers not set by metadata plugin')); + return; + } + resolve(headers); + } + ); + }); + } + getHeaders.then( + headers => { + const metadata = new Metadata(); + for (const key of Object.keys(headers)) { + metadata.add(key, headers[key]); + } + callback(null, metadata); + }, + err => { + callback(err); + } + ); + }); + } + + static createEmpty(): CallCredentials { + return new EmptyCallCredentials(); + } +} + +class ComposedCallCredentials extends CallCredentials { + constructor(private creds: CallCredentials[]) { + super(); + } + + async generateMetadata(options: CallMetadataOptions): Promise { + const base: Metadata = new Metadata(); + const generated: Metadata[] = await Promise.all( + this.creds.map(cred => cred.generateMetadata(options)) + ); + for (const gen of generated) { + base.merge(gen); + } + return base; + } + + compose(other: CallCredentials): CallCredentials { + return new ComposedCallCredentials(this.creds.concat([other])); + } + + _equals(other: CallCredentials): boolean { + if (this === other) { + return true; + } + if (other instanceof ComposedCallCredentials) { + return this.creds.every((value, index) => + value._equals(other.creds[index]) + ); + } else { + return false; + } + } +} + +class SingleCallCredentials extends CallCredentials { + constructor(private metadataGenerator: CallMetadataGenerator) { + super(); + } + + generateMetadata(options: CallMetadataOptions): Promise { + return new Promise((resolve, reject) => { + this.metadataGenerator(options, (err, metadata) => { + if (metadata !== undefined) { + resolve(metadata); + } else { + reject(err); + } + }); + }); + } + + compose(other: CallCredentials): CallCredentials { + return new ComposedCallCredentials([this, other]); + } + + _equals(other: CallCredentials): boolean { + if (this === other) { + return true; + } + if (other instanceof SingleCallCredentials) { + return this.metadataGenerator === other.metadataGenerator; + } else { + return false; + } + } +} + +class EmptyCallCredentials extends CallCredentials { + generateMetadata(options: CallMetadataOptions): Promise { + return Promise.resolve(new Metadata()); + } + + compose(other: CallCredentials): CallCredentials { + return other; + } + + _equals(other: CallCredentials): boolean { + return other instanceof EmptyCallCredentials; + } +} diff --git a/node_modules/@grpc/grpc-js/src/call-interface.ts b/node_modules/@grpc/grpc-js/src/call-interface.ts new file mode 100644 index 0000000..c93c504 --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/call-interface.ts @@ -0,0 +1,177 @@ +/* + * Copyright 2022 gRPC authors. + * + * 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. + * + */ + +import { CallCredentials } from './call-credentials'; +import { Status } from './constants'; +import { Deadline } from './deadline'; +import { Metadata } from './metadata'; +import { ServerSurfaceCall } from './server-call'; + +export interface CallStreamOptions { + deadline: Deadline; + flags: number; + host: string; + parentCall: ServerSurfaceCall | null; +} + +export type PartialCallStreamOptions = Partial; + +export interface StatusObject { + code: Status; + details: string; + metadata: Metadata; +} + +export type PartialStatusObject = Pick & { + metadata?: Metadata | null | undefined; +}; + +export const enum WriteFlags { + BufferHint = 1, + NoCompress = 2, + WriteThrough = 4, +} + +export interface WriteObject { + message: Buffer; + flags?: number; +} + +export interface MetadataListener { + (metadata: Metadata, next: (metadata: Metadata) => void): void; +} + +export interface MessageListener { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + (message: any, next: (message: any) => void): void; +} + +export interface StatusListener { + (status: StatusObject, next: (status: StatusObject) => void): void; +} + +export interface FullListener { + onReceiveMetadata: MetadataListener; + onReceiveMessage: MessageListener; + onReceiveStatus: StatusListener; +} + +export type Listener = Partial; + +/** + * An object with methods for handling the responses to a call. + */ +export interface InterceptingListener { + onReceiveMetadata(metadata: Metadata): void; + // eslint-disable-next-line @typescript-eslint/no-explicit-any + onReceiveMessage(message: any): void; + onReceiveStatus(status: StatusObject): void; +} + +export function isInterceptingListener( + listener: Listener | InterceptingListener +): listener is InterceptingListener { + return ( + listener.onReceiveMetadata !== undefined && + listener.onReceiveMetadata.length === 1 + ); +} + +export class InterceptingListenerImpl implements InterceptingListener { + private processingMetadata = false; + private hasPendingMessage = false; + private pendingMessage: any; + private processingMessage = false; + private pendingStatus: StatusObject | null = null; + constructor( + private listener: FullListener, + private nextListener: InterceptingListener + ) {} + + private processPendingMessage() { + if (this.hasPendingMessage) { + this.nextListener.onReceiveMessage(this.pendingMessage); + this.pendingMessage = null; + this.hasPendingMessage = false; + } + } + + private processPendingStatus() { + if (this.pendingStatus) { + this.nextListener.onReceiveStatus(this.pendingStatus); + } + } + + onReceiveMetadata(metadata: Metadata): void { + this.processingMetadata = true; + this.listener.onReceiveMetadata(metadata, metadata => { + this.processingMetadata = false; + this.nextListener.onReceiveMetadata(metadata); + this.processPendingMessage(); + this.processPendingStatus(); + }); + } + // eslint-disable-next-line @typescript-eslint/no-explicit-any + onReceiveMessage(message: any): void { + /* If this listener processes messages asynchronously, the last message may + * be reordered with respect to the status */ + this.processingMessage = true; + this.listener.onReceiveMessage(message, msg => { + this.processingMessage = false; + if (this.processingMetadata) { + this.pendingMessage = msg; + this.hasPendingMessage = true; + } else { + this.nextListener.onReceiveMessage(msg); + this.processPendingStatus(); + } + }); + } + onReceiveStatus(status: StatusObject): void { + this.listener.onReceiveStatus(status, processedStatus => { + if (this.processingMetadata || this.processingMessage) { + this.pendingStatus = processedStatus; + } else { + this.nextListener.onReceiveStatus(processedStatus); + } + }); + } +} + +export interface WriteCallback { + (error?: Error | null): void; +} + +export interface MessageContext { + callback?: WriteCallback; + flags?: number; +} + +export interface Call { + cancelWithStatus(status: Status, details: string): void; + getPeer(): string; + start(metadata: Metadata, listener: InterceptingListener): void; + sendMessageWithContext(context: MessageContext, message: Buffer): void; + startRead(): void; + halfClose(): void; + getCallNumber(): number; + setCredentials(credentials: CallCredentials): void; +} + +export interface DeadlineInfoProvider { + getDeadlineInfo(): string[]; +} diff --git a/node_modules/@grpc/grpc-js/src/call-number.ts b/node_modules/@grpc/grpc-js/src/call-number.ts new file mode 100644 index 0000000..8c37d3f --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/call-number.ts @@ -0,0 +1,22 @@ +/* + * Copyright 2022 gRPC authors. + * + * 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. + * + */ + +let nextCallNumber = 0; + +export function getNextCallNumber() { + return nextCallNumber++; +} diff --git a/node_modules/@grpc/grpc-js/src/call.ts b/node_modules/@grpc/grpc-js/src/call.ts new file mode 100644 index 0000000..a147c98 --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/call.ts @@ -0,0 +1,200 @@ +/* + * Copyright 2019 gRPC authors. + * + * 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. + * + */ + +import { EventEmitter } from 'events'; +import { Duplex, Readable, Writable } from 'stream'; + +import { StatusObject, MessageContext } from './call-interface'; +import { Status } from './constants'; +import { EmitterAugmentation1 } from './events'; +import { Metadata } from './metadata'; +import { ObjectReadable, ObjectWritable, WriteCallback } from './object-stream'; +import { InterceptingCallInterface } from './client-interceptors'; + +/** + * A type extending the built-in Error object with additional fields. + */ +export type ServiceError = StatusObject & Error; + +/** + * A base type for all user-facing values returned by client-side method calls. + */ +export type SurfaceCall = { + call?: InterceptingCallInterface; + cancel(): void; + getPeer(): string; +} & EmitterAugmentation1<'metadata', Metadata> & + EmitterAugmentation1<'status', StatusObject> & + EventEmitter; + +/** + * A type representing the return value of a unary method call. + */ +export type ClientUnaryCall = SurfaceCall; + +/** + * A type representing the return value of a server stream method call. + */ +export type ClientReadableStream = { + deserialize: (chunk: Buffer) => ResponseType; +} & SurfaceCall & + ObjectReadable; + +/** + * A type representing the return value of a client stream method call. + */ +export type ClientWritableStream = { + serialize: (value: RequestType) => Buffer; +} & SurfaceCall & + ObjectWritable; + +/** + * A type representing the return value of a bidirectional stream method call. + */ +export type ClientDuplexStream = + ClientWritableStream & ClientReadableStream; + +/** + * Construct a ServiceError from a StatusObject. This function exists primarily + * as an attempt to make the error stack trace clearly communicate that the + * error is not necessarily a problem in gRPC itself. + * @param status + */ +export function callErrorFromStatus( + status: StatusObject, + callerStack: string +): ServiceError { + const message = `${status.code} ${Status[status.code]}: ${status.details}`; + const error = new Error(message); + const stack = `${error.stack}\nfor call at\n${callerStack}`; + return Object.assign(new Error(message), status, { stack }); +} + +export class ClientUnaryCallImpl + extends EventEmitter + implements ClientUnaryCall +{ + public call?: InterceptingCallInterface; + constructor() { + super(); + } + + cancel(): void { + this.call?.cancelWithStatus(Status.CANCELLED, 'Cancelled on client'); + } + + getPeer(): string { + return this.call?.getPeer() ?? 'unknown'; + } +} + +export class ClientReadableStreamImpl + extends Readable + implements ClientReadableStream +{ + public call?: InterceptingCallInterface; + constructor(readonly deserialize: (chunk: Buffer) => ResponseType) { + super({ objectMode: true }); + } + + cancel(): void { + this.call?.cancelWithStatus(Status.CANCELLED, 'Cancelled on client'); + } + + getPeer(): string { + return this.call?.getPeer() ?? 'unknown'; + } + + _read(_size: number): void { + this.call?.startRead(); + } +} + +export class ClientWritableStreamImpl + extends Writable + implements ClientWritableStream +{ + public call?: InterceptingCallInterface; + constructor(readonly serialize: (value: RequestType) => Buffer) { + super({ objectMode: true }); + } + + cancel(): void { + this.call?.cancelWithStatus(Status.CANCELLED, 'Cancelled on client'); + } + + getPeer(): string { + return this.call?.getPeer() ?? 'unknown'; + } + + _write(chunk: RequestType, encoding: string, cb: WriteCallback) { + const context: MessageContext = { + callback: cb, + }; + const flags = Number(encoding); + if (!Number.isNaN(flags)) { + context.flags = flags; + } + this.call?.sendMessageWithContext(context, chunk); + } + + _final(cb: Function) { + this.call?.halfClose(); + cb(); + } +} + +export class ClientDuplexStreamImpl + extends Duplex + implements ClientDuplexStream +{ + public call?: InterceptingCallInterface; + constructor( + readonly serialize: (value: RequestType) => Buffer, + readonly deserialize: (chunk: Buffer) => ResponseType + ) { + super({ objectMode: true }); + } + + cancel(): void { + this.call?.cancelWithStatus(Status.CANCELLED, 'Cancelled on client'); + } + + getPeer(): string { + return this.call?.getPeer() ?? 'unknown'; + } + + _read(_size: number): void { + this.call?.startRead(); + } + + _write(chunk: RequestType, encoding: string, cb: WriteCallback) { + const context: MessageContext = { + callback: cb, + }; + const flags = Number(encoding); + if (!Number.isNaN(flags)) { + context.flags = flags; + } + this.call?.sendMessageWithContext(context, chunk); + } + + _final(cb: Function) { + this.call?.halfClose(); + cb(); + } +} diff --git a/node_modules/@grpc/grpc-js/src/channel-credentials.ts b/node_modules/@grpc/grpc-js/src/channel-credentials.ts new file mode 100644 index 0000000..2ed1850 --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/channel-credentials.ts @@ -0,0 +1,267 @@ +/* + * Copyright 2019 gRPC authors. + * + * 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. + * + */ + +import { + ConnectionOptions, + createSecureContext, + PeerCertificate, + SecureContext, +} from 'tls'; + +import { CallCredentials } from './call-credentials'; +import { CIPHER_SUITES, getDefaultRootsData } from './tls-helpers'; + +// eslint-disable-next-line @typescript-eslint/no-explicit-any +function verifyIsBufferOrNull(obj: any, friendlyName: string): void { + if (obj && !(obj instanceof Buffer)) { + throw new TypeError(`${friendlyName}, if provided, must be a Buffer.`); + } +} + +/** + * A callback that will receive the expected hostname and presented peer + * certificate as parameters. The callback should return an error to + * indicate that the presented certificate is considered invalid and + * otherwise returned undefined. + */ +export type CheckServerIdentityCallback = ( + hostname: string, + cert: PeerCertificate +) => Error | undefined; + +/** + * Additional peer verification options that can be set when creating + * SSL credentials. + */ +export interface VerifyOptions { + /** + * If set, this callback will be invoked after the usual hostname verification + * has been performed on the peer certificate. + */ + checkServerIdentity?: CheckServerIdentityCallback; +} + +/** + * A class that contains credentials for communicating over a channel, as well + * as a set of per-call credentials, which are applied to every method call made + * over a channel initialized with an instance of this class. + */ +export abstract class ChannelCredentials { + protected callCredentials: CallCredentials; + + protected constructor(callCredentials?: CallCredentials) { + this.callCredentials = callCredentials || CallCredentials.createEmpty(); + } + /** + * Returns a copy of this object with the included set of per-call credentials + * expanded to include callCredentials. + * @param callCredentials A CallCredentials object to associate with this + * instance. + */ + abstract compose(callCredentials: CallCredentials): ChannelCredentials; + + /** + * Gets the set of per-call credentials associated with this instance. + */ + _getCallCredentials(): CallCredentials { + return this.callCredentials; + } + + /** + * Gets a SecureContext object generated from input parameters if this + * instance was created with createSsl, or null if this instance was created + * with createInsecure. + */ + abstract _getConnectionOptions(): ConnectionOptions | null; + + /** + * Indicates whether this credentials object creates a secure channel. + */ + abstract _isSecure(): boolean; + + /** + * Check whether two channel credentials objects are equal. Two secure + * credentials are equal if they were constructed with the same parameters. + * @param other The other ChannelCredentials Object + */ + abstract _equals(other: ChannelCredentials): boolean; + + /** + * Return a new ChannelCredentials instance with a given set of credentials. + * The resulting instance can be used to construct a Channel that communicates + * over TLS. + * @param rootCerts The root certificate data. + * @param privateKey The client certificate private key, if available. + * @param certChain The client certificate key chain, if available. + * @param verifyOptions Additional options to modify certificate verification + */ + static createSsl( + rootCerts?: Buffer | null, + privateKey?: Buffer | null, + certChain?: Buffer | null, + verifyOptions?: VerifyOptions + ): ChannelCredentials { + verifyIsBufferOrNull(rootCerts, 'Root certificate'); + verifyIsBufferOrNull(privateKey, 'Private key'); + verifyIsBufferOrNull(certChain, 'Certificate chain'); + if (privateKey && !certChain) { + throw new Error( + 'Private key must be given with accompanying certificate chain' + ); + } + if (!privateKey && certChain) { + throw new Error( + 'Certificate chain must be given with accompanying private key' + ); + } + const secureContext = createSecureContext({ + ca: rootCerts ?? getDefaultRootsData() ?? undefined, + key: privateKey ?? undefined, + cert: certChain ?? undefined, + ciphers: CIPHER_SUITES, + }); + return new SecureChannelCredentialsImpl(secureContext, verifyOptions ?? {}); + } + + /** + * Return a new ChannelCredentials instance with credentials created using + * the provided secureContext. The resulting instances can be used to + * construct a Channel that communicates over TLS. gRPC will not override + * anything in the provided secureContext, so the environment variables + * GRPC_SSL_CIPHER_SUITES and GRPC_DEFAULT_SSL_ROOTS_FILE_PATH will + * not be applied. + * @param secureContext The return value of tls.createSecureContext() + * @param verifyOptions Additional options to modify certificate verification + */ + static createFromSecureContext( + secureContext: SecureContext, + verifyOptions?: VerifyOptions + ): ChannelCredentials { + return new SecureChannelCredentialsImpl(secureContext, verifyOptions ?? {}); + } + + /** + * Return a new ChannelCredentials instance with no credentials. + */ + static createInsecure(): ChannelCredentials { + return new InsecureChannelCredentialsImpl(); + } +} + +class InsecureChannelCredentialsImpl extends ChannelCredentials { + constructor() { + super(); + } + + compose(callCredentials: CallCredentials): never { + throw new Error('Cannot compose insecure credentials'); + } + + _getConnectionOptions(): ConnectionOptions | null { + return null; + } + _isSecure(): boolean { + return false; + } + _equals(other: ChannelCredentials): boolean { + return other instanceof InsecureChannelCredentialsImpl; + } +} + +class SecureChannelCredentialsImpl extends ChannelCredentials { + connectionOptions: ConnectionOptions; + + constructor( + private secureContext: SecureContext, + private verifyOptions: VerifyOptions + ) { + super(); + this.connectionOptions = { + secureContext, + }; + // Node asserts that this option is a function, so we cannot pass undefined + if (verifyOptions?.checkServerIdentity) { + this.connectionOptions.checkServerIdentity = + verifyOptions.checkServerIdentity; + } + } + + compose(callCredentials: CallCredentials): ChannelCredentials { + const combinedCallCredentials = + this.callCredentials.compose(callCredentials); + return new ComposedChannelCredentialsImpl(this, combinedCallCredentials); + } + + _getConnectionOptions(): ConnectionOptions | null { + // Copy to prevent callers from mutating this.connectionOptions + return { ...this.connectionOptions }; + } + _isSecure(): boolean { + return true; + } + _equals(other: ChannelCredentials): boolean { + if (this === other) { + return true; + } + if (other instanceof SecureChannelCredentialsImpl) { + return ( + this.secureContext === other.secureContext && + this.verifyOptions.checkServerIdentity === + other.verifyOptions.checkServerIdentity + ); + } else { + return false; + } + } +} + +class ComposedChannelCredentialsImpl extends ChannelCredentials { + constructor( + private channelCredentials: SecureChannelCredentialsImpl, + callCreds: CallCredentials + ) { + super(callCreds); + } + compose(callCredentials: CallCredentials) { + const combinedCallCredentials = + this.callCredentials.compose(callCredentials); + return new ComposedChannelCredentialsImpl( + this.channelCredentials, + combinedCallCredentials + ); + } + + _getConnectionOptions(): ConnectionOptions | null { + return this.channelCredentials._getConnectionOptions(); + } + _isSecure(): boolean { + return true; + } + _equals(other: ChannelCredentials): boolean { + if (this === other) { + return true; + } + if (other instanceof ComposedChannelCredentialsImpl) { + return ( + this.channelCredentials._equals(other.channelCredentials) && + this.callCredentials._equals(other.callCredentials) + ); + } else { + return false; + } + } +} diff --git a/node_modules/@grpc/grpc-js/src/channel-options.ts b/node_modules/@grpc/grpc-js/src/channel-options.ts new file mode 100644 index 0000000..6804852 --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/channel-options.ts @@ -0,0 +1,122 @@ +/* + * Copyright 2019 gRPC authors. + * + * 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. + * + */ + +import { CompressionAlgorithms } from './compression-algorithms'; + +/** + * An interface that contains options used when initializing a Channel instance. + */ +export interface ChannelOptions { + 'grpc.ssl_target_name_override'?: string; + 'grpc.primary_user_agent'?: string; + 'grpc.secondary_user_agent'?: string; + 'grpc.default_authority'?: string; + 'grpc.keepalive_time_ms'?: number; + 'grpc.keepalive_timeout_ms'?: number; + 'grpc.keepalive_permit_without_calls'?: number; + 'grpc.service_config'?: string; + 'grpc.max_concurrent_streams'?: number; + 'grpc.initial_reconnect_backoff_ms'?: number; + 'grpc.max_reconnect_backoff_ms'?: number; + 'grpc.use_local_subchannel_pool'?: number; + 'grpc.max_send_message_length'?: number; + 'grpc.max_receive_message_length'?: number; + 'grpc.enable_http_proxy'?: number; + /* http_connect_target and http_connect_creds are used for passing data + * around internally, and should not be documented as public-facing options + */ + 'grpc.http_connect_target'?: string; + 'grpc.http_connect_creds'?: string; + 'grpc.default_compression_algorithm'?: CompressionAlgorithms; + 'grpc.enable_channelz'?: number; + 'grpc.dns_min_time_between_resolutions_ms'?: number; + 'grpc.enable_retries'?: number; + 'grpc.per_rpc_retry_buffer_size'?: number; + /* This option is pattered like a core option, but the core does not have + * this option. It is closely related to the option + * grpc.per_rpc_retry_buffer_size, which is in the core. The core will likely + * implement this functionality using the ResourceQuota mechanism, so there + * will probably not be any collision or other inconsistency. */ + 'grpc.retry_buffer_size'?: number; + 'grpc.max_connection_age_ms'?: number; + 'grpc.max_connection_age_grace_ms'?: number; + 'grpc.max_connection_idle_ms'?: number; + 'grpc-node.max_session_memory'?: number; + 'grpc.service_config_disable_resolution'?: number; + 'grpc.client_idle_timeout_ms'?: number; + /** + * Set the enableTrace option in TLS clients and servers + */ + 'grpc-node.tls_enable_trace'?: number; + 'grpc.lb.ring_hash.ring_size_cap'?: number; + // eslint-disable-next-line @typescript-eslint/no-explicit-any + [key: string]: any; +} + +/** + * This is for checking provided options at runtime. This is an object for + * easier membership checking. + */ +export const recognizedOptions = { + 'grpc.ssl_target_name_override': true, + 'grpc.primary_user_agent': true, + 'grpc.secondary_user_agent': true, + 'grpc.default_authority': true, + 'grpc.keepalive_time_ms': true, + 'grpc.keepalive_timeout_ms': true, + 'grpc.keepalive_permit_without_calls': true, + 'grpc.service_config': true, + 'grpc.max_concurrent_streams': true, + 'grpc.initial_reconnect_backoff_ms': true, + 'grpc.max_reconnect_backoff_ms': true, + 'grpc.use_local_subchannel_pool': true, + 'grpc.max_send_message_length': true, + 'grpc.max_receive_message_length': true, + 'grpc.enable_http_proxy': true, + 'grpc.enable_channelz': true, + 'grpc.dns_min_time_between_resolutions_ms': true, + 'grpc.enable_retries': true, + 'grpc.per_rpc_retry_buffer_size': true, + 'grpc.retry_buffer_size': true, + 'grpc.max_connection_age_ms': true, + 'grpc.max_connection_age_grace_ms': true, + 'grpc-node.max_session_memory': true, + 'grpc.service_config_disable_resolution': true, + 'grpc.client_idle_timeout_ms': true, + 'grpc-node.tls_enable_trace': true, + 'grpc.lb.ring_hash.ring_size_cap': true, +}; + +export function channelOptionsEqual( + options1: ChannelOptions, + options2: ChannelOptions +) { + const keys1 = Object.keys(options1).sort(); + const keys2 = Object.keys(options2).sort(); + if (keys1.length !== keys2.length) { + return false; + } + for (let i = 0; i < keys1.length; i += 1) { + if (keys1[i] !== keys2[i]) { + return false; + } + if (options1[keys1[i]] !== options2[keys2[i]]) { + return false; + } + } + return true; +} diff --git a/node_modules/@grpc/grpc-js/src/channel.ts b/node_modules/@grpc/grpc-js/src/channel.ts new file mode 100644 index 0000000..514920c --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/channel.ts @@ -0,0 +1,174 @@ +/* + * Copyright 2019 gRPC authors. + * + * 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. + * + */ + +import { ChannelCredentials } from './channel-credentials'; +import { ChannelOptions } from './channel-options'; +import { ServerSurfaceCall } from './server-call'; + +import { ConnectivityState } from './connectivity-state'; +import type { ChannelRef } from './channelz'; +import { Call } from './call-interface'; +import { InternalChannel } from './internal-channel'; +import { Deadline } from './deadline'; + +/** + * An interface that represents a communication channel to a server specified + * by a given address. + */ +export interface Channel { + /** + * Close the channel. This has the same functionality as the existing + * grpc.Client.prototype.close + */ + close(): void; + /** + * Return the target that this channel connects to + */ + getTarget(): string; + /** + * Get the channel's current connectivity state. This method is here mainly + * because it is in the existing internal Channel class, and there isn't + * another good place to put it. + * @param tryToConnect If true, the channel will start connecting if it is + * idle. Otherwise, idle channels will only start connecting when a + * call starts. + */ + getConnectivityState(tryToConnect: boolean): ConnectivityState; + /** + * Watch for connectivity state changes. This is also here mainly because + * it is in the existing external Channel class. + * @param currentState The state to watch for transitions from. This should + * always be populated by calling getConnectivityState immediately + * before. + * @param deadline A deadline for waiting for a state change + * @param callback Called with no error when a state change, or with an + * error if the deadline passes without a state change. + */ + watchConnectivityState( + currentState: ConnectivityState, + deadline: Date | number, + callback: (error?: Error) => void + ): void; + /** + * Get the channelz reference object for this channel. A request to the + * channelz service for the id in this object will provide information + * about this channel. + */ + getChannelzRef(): ChannelRef; + /** + * Create a call object. Call is an opaque type that is used by the Client + * class. This function is called by the gRPC library when starting a + * request. Implementers should return an instance of Call that is returned + * from calling createCall on an instance of the provided Channel class. + * @param method The full method string to request. + * @param deadline The call deadline + * @param host A host string override for making the request + * @param parentCall A server call to propagate some information from + * @param propagateFlags A bitwise combination of elements of grpc.propagate + * that indicates what information to propagate from parentCall. + */ + createCall( + method: string, + deadline: Deadline, + host: string | null | undefined, + parentCall: ServerSurfaceCall | null, + propagateFlags: number | null | undefined + ): Call; +} + +export class ChannelImplementation implements Channel { + private internalChannel: InternalChannel; + + constructor( + target: string, + credentials: ChannelCredentials, + options: ChannelOptions + ) { + if (typeof target !== 'string') { + throw new TypeError('Channel target must be a string'); + } + if (!(credentials instanceof ChannelCredentials)) { + throw new TypeError( + 'Channel credentials must be a ChannelCredentials object' + ); + } + if (options) { + if (typeof options !== 'object') { + throw new TypeError('Channel options must be an object'); + } + } + + this.internalChannel = new InternalChannel(target, credentials, options); + } + + close() { + this.internalChannel.close(); + } + + getTarget() { + return this.internalChannel.getTarget(); + } + + getConnectivityState(tryToConnect: boolean) { + return this.internalChannel.getConnectivityState(tryToConnect); + } + + watchConnectivityState( + currentState: ConnectivityState, + deadline: Date | number, + callback: (error?: Error) => void + ): void { + this.internalChannel.watchConnectivityState( + currentState, + deadline, + callback + ); + } + + /** + * Get the channelz reference object for this channel. The returned value is + * garbage if channelz is disabled for this channel. + * @returns + */ + getChannelzRef() { + return this.internalChannel.getChannelzRef(); + } + + createCall( + method: string, + deadline: Deadline, + host: string | null | undefined, + parentCall: ServerSurfaceCall | null, + propagateFlags: number | null | undefined + ): Call { + if (typeof method !== 'string') { + throw new TypeError('Channel#createCall: method must be a string'); + } + if (!(typeof deadline === 'number' || deadline instanceof Date)) { + throw new TypeError( + 'Channel#createCall: deadline must be a number or Date' + ); + } + return this.internalChannel.createCall( + method, + deadline, + host, + parentCall, + propagateFlags + ); + } +} diff --git a/node_modules/@grpc/grpc-js/src/channelz.ts b/node_modules/@grpc/grpc-js/src/channelz.ts new file mode 100644 index 0000000..c207e56 --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/channelz.ts @@ -0,0 +1,894 @@ +/* + * Copyright 2021 gRPC authors. + * + * 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. + * + */ + +import { isIPv4, isIPv6 } from 'net'; +import { OrderedMap, type OrderedMapIterator } from '@js-sdsl/ordered-map'; +import { ConnectivityState } from './connectivity-state'; +import { Status } from './constants'; +import { Timestamp } from './generated/google/protobuf/Timestamp'; +import { Channel as ChannelMessage } from './generated/grpc/channelz/v1/Channel'; +import { ChannelConnectivityState__Output } from './generated/grpc/channelz/v1/ChannelConnectivityState'; +import { ChannelRef as ChannelRefMessage } from './generated/grpc/channelz/v1/ChannelRef'; +import { ChannelTrace } from './generated/grpc/channelz/v1/ChannelTrace'; +import { GetChannelRequest__Output } from './generated/grpc/channelz/v1/GetChannelRequest'; +import { GetChannelResponse } from './generated/grpc/channelz/v1/GetChannelResponse'; +import { sendUnaryData, ServerUnaryCall } from './server-call'; +import { ServerRef as ServerRefMessage } from './generated/grpc/channelz/v1/ServerRef'; +import { SocketRef as SocketRefMessage } from './generated/grpc/channelz/v1/SocketRef'; +import { + isTcpSubchannelAddress, + SubchannelAddress, +} from './subchannel-address'; +import { SubchannelRef as SubchannelRefMessage } from './generated/grpc/channelz/v1/SubchannelRef'; +import { GetServerRequest__Output } from './generated/grpc/channelz/v1/GetServerRequest'; +import { GetServerResponse } from './generated/grpc/channelz/v1/GetServerResponse'; +import { Server as ServerMessage } from './generated/grpc/channelz/v1/Server'; +import { GetServersRequest__Output } from './generated/grpc/channelz/v1/GetServersRequest'; +import { GetServersResponse } from './generated/grpc/channelz/v1/GetServersResponse'; +import { GetTopChannelsRequest__Output } from './generated/grpc/channelz/v1/GetTopChannelsRequest'; +import { GetTopChannelsResponse } from './generated/grpc/channelz/v1/GetTopChannelsResponse'; +import { GetSubchannelRequest__Output } from './generated/grpc/channelz/v1/GetSubchannelRequest'; +import { GetSubchannelResponse } from './generated/grpc/channelz/v1/GetSubchannelResponse'; +import { Subchannel as SubchannelMessage } from './generated/grpc/channelz/v1/Subchannel'; +import { GetSocketRequest__Output } from './generated/grpc/channelz/v1/GetSocketRequest'; +import { GetSocketResponse } from './generated/grpc/channelz/v1/GetSocketResponse'; +import { Socket as SocketMessage } from './generated/grpc/channelz/v1/Socket'; +import { Address } from './generated/grpc/channelz/v1/Address'; +import { Security } from './generated/grpc/channelz/v1/Security'; +import { GetServerSocketsRequest__Output } from './generated/grpc/channelz/v1/GetServerSocketsRequest'; +import { GetServerSocketsResponse } from './generated/grpc/channelz/v1/GetServerSocketsResponse'; +import { + ChannelzDefinition, + ChannelzHandlers, +} from './generated/grpc/channelz/v1/Channelz'; +import { ProtoGrpcType as ChannelzProtoGrpcType } from './generated/channelz'; +import type { loadSync } from '@grpc/proto-loader'; +import { registerAdminService } from './admin'; +import { loadPackageDefinition } from './make-client'; + +export type TraceSeverity = + | 'CT_UNKNOWN' + | 'CT_INFO' + | 'CT_WARNING' + | 'CT_ERROR'; + +interface Ref { + kind: EntityTypes; + id: number; + name: string; +} + +export interface ChannelRef extends Ref { + kind: EntityTypes.channel; +} + +export interface SubchannelRef extends Ref { + kind: EntityTypes.subchannel; +} + +export interface ServerRef extends Ref { + kind: EntityTypes.server; +} + +export interface SocketRef extends Ref { + kind: EntityTypes.socket; +} + +function channelRefToMessage(ref: ChannelRef): ChannelRefMessage { + return { + channel_id: ref.id, + name: ref.name, + }; +} + +function subchannelRefToMessage(ref: SubchannelRef): SubchannelRefMessage { + return { + subchannel_id: ref.id, + name: ref.name, + }; +} + +function serverRefToMessage(ref: ServerRef): ServerRefMessage { + return { + server_id: ref.id, + }; +} + +function socketRefToMessage(ref: SocketRef): SocketRefMessage { + return { + socket_id: ref.id, + name: ref.name, + }; +} + +interface TraceEvent { + description: string; + severity: TraceSeverity; + timestamp: Date; + childChannel?: ChannelRef; + childSubchannel?: SubchannelRef; +} + +/** + * The loose upper bound on the number of events that should be retained in a + * trace. This may be exceeded by up to a factor of 2. Arbitrarily chosen as a + * number that should be large enough to contain the recent relevant + * information, but small enough to not use excessive memory. + */ +const TARGET_RETAINED_TRACES = 32; + +/** + * Default number of sockets/servers/channels/subchannels to return + */ +const DEFAULT_MAX_RESULTS = 100; + +export class ChannelzTraceStub { + readonly events: TraceEvent[] = []; + readonly creationTimestamp: Date = new Date(); + readonly eventsLogged = 0; + + addTrace(): void {} + getTraceMessage(): ChannelTrace { + return { + creation_timestamp: dateToProtoTimestamp(this.creationTimestamp), + num_events_logged: this.eventsLogged, + events: [], + }; + } +} + +export class ChannelzTrace { + events: TraceEvent[] = []; + creationTimestamp: Date; + eventsLogged = 0; + + constructor() { + this.creationTimestamp = new Date(); + } + + addTrace( + severity: TraceSeverity, + description: string, + child?: ChannelRef | SubchannelRef + ) { + const timestamp = new Date(); + this.events.push({ + description: description, + severity: severity, + timestamp: timestamp, + childChannel: child?.kind === 'channel' ? child : undefined, + childSubchannel: child?.kind === 'subchannel' ? child : undefined, + }); + // Whenever the trace array gets too large, discard the first half + if (this.events.length >= TARGET_RETAINED_TRACES * 2) { + this.events = this.events.slice(TARGET_RETAINED_TRACES); + } + this.eventsLogged += 1; + } + + getTraceMessage(): ChannelTrace { + return { + creation_timestamp: dateToProtoTimestamp(this.creationTimestamp), + num_events_logged: this.eventsLogged, + events: this.events.map(event => { + return { + description: event.description, + severity: event.severity, + timestamp: dateToProtoTimestamp(event.timestamp), + channel_ref: event.childChannel + ? channelRefToMessage(event.childChannel) + : null, + subchannel_ref: event.childSubchannel + ? subchannelRefToMessage(event.childSubchannel) + : null, + }; + }), + }; + } +} + +type RefOrderedMap = OrderedMap< + number, + { ref: { id: number; kind: EntityTypes; name: string }; count: number } +>; + +export class ChannelzChildrenTracker { + private channelChildren: RefOrderedMap = new OrderedMap(); + private subchannelChildren: RefOrderedMap = new OrderedMap(); + private socketChildren: RefOrderedMap = new OrderedMap(); + private trackerMap = { + [EntityTypes.channel]: this.channelChildren, + [EntityTypes.subchannel]: this.subchannelChildren, + [EntityTypes.socket]: this.socketChildren, + } as const; + + refChild(child: ChannelRef | SubchannelRef | SocketRef) { + const tracker = this.trackerMap[child.kind]; + const trackedChild = tracker.find(child.id); + + if (trackedChild.equals(tracker.end())) { + tracker.setElement( + child.id, + { + ref: child, + count: 1, + }, + trackedChild + ); + } else { + trackedChild.pointer[1].count += 1; + } + } + + unrefChild(child: ChannelRef | SubchannelRef | SocketRef) { + const tracker = this.trackerMap[child.kind]; + const trackedChild = tracker.getElementByKey(child.id); + if (trackedChild !== undefined) { + trackedChild.count -= 1; + if (trackedChild.count === 0) { + tracker.eraseElementByKey(child.id); + } + } + } + + getChildLists(): ChannelzChildren { + return { + channels: this.channelChildren as ChannelzChildren['channels'], + subchannels: this.subchannelChildren as ChannelzChildren['subchannels'], + sockets: this.socketChildren as ChannelzChildren['sockets'], + }; + } +} + +export class ChannelzChildrenTrackerStub extends ChannelzChildrenTracker { + override refChild(): void {} + override unrefChild(): void {} +} + +export class ChannelzCallTracker { + callsStarted = 0; + callsSucceeded = 0; + callsFailed = 0; + lastCallStartedTimestamp: Date | null = null; + + addCallStarted() { + this.callsStarted += 1; + this.lastCallStartedTimestamp = new Date(); + } + addCallSucceeded() { + this.callsSucceeded += 1; + } + addCallFailed() { + this.callsFailed += 1; + } +} + +export class ChannelzCallTrackerStub extends ChannelzCallTracker { + override addCallStarted() {} + override addCallSucceeded() {} + override addCallFailed() {} +} + +export interface ChannelzChildren { + channels: OrderedMap; + subchannels: OrderedMap; + sockets: OrderedMap; +} + +export interface ChannelInfo { + target: string; + state: ConnectivityState; + trace: ChannelzTrace | ChannelzTraceStub; + callTracker: ChannelzCallTracker | ChannelzCallTrackerStub; + children: ChannelzChildren; +} + +export type SubchannelInfo = ChannelInfo; + +export interface ServerInfo { + trace: ChannelzTrace; + callTracker: ChannelzCallTracker; + listenerChildren: ChannelzChildren; + sessionChildren: ChannelzChildren; +} + +export interface TlsInfo { + cipherSuiteStandardName: string | null; + cipherSuiteOtherName: string | null; + localCertificate: Buffer | null; + remoteCertificate: Buffer | null; +} + +export interface SocketInfo { + localAddress: SubchannelAddress | null; + remoteAddress: SubchannelAddress | null; + security: TlsInfo | null; + remoteName: string | null; + streamsStarted: number; + streamsSucceeded: number; + streamsFailed: number; + messagesSent: number; + messagesReceived: number; + keepAlivesSent: number; + lastLocalStreamCreatedTimestamp: Date | null; + lastRemoteStreamCreatedTimestamp: Date | null; + lastMessageSentTimestamp: Date | null; + lastMessageReceivedTimestamp: Date | null; + localFlowControlWindow: number | null; + remoteFlowControlWindow: number | null; +} + +interface ChannelEntry { + ref: ChannelRef; + getInfo(): ChannelInfo; +} + +interface SubchannelEntry { + ref: SubchannelRef; + getInfo(): SubchannelInfo; +} + +interface ServerEntry { + ref: ServerRef; + getInfo(): ServerInfo; +} + +interface SocketEntry { + ref: SocketRef; + getInfo(): SocketInfo; +} + +export const enum EntityTypes { + channel = 'channel', + subchannel = 'subchannel', + server = 'server', + socket = 'socket', +} + +type EntryOrderedMap = OrderedMap any }>; + +const entityMaps = { + [EntityTypes.channel]: new OrderedMap(), + [EntityTypes.subchannel]: new OrderedMap(), + [EntityTypes.server]: new OrderedMap(), + [EntityTypes.socket]: new OrderedMap(), +} as const; + +export type RefByType = T extends EntityTypes.channel + ? ChannelRef + : T extends EntityTypes.server + ? ServerRef + : T extends EntityTypes.socket + ? SocketRef + : T extends EntityTypes.subchannel + ? SubchannelRef + : never; + +export type EntryByType = T extends EntityTypes.channel + ? ChannelEntry + : T extends EntityTypes.server + ? ServerEntry + : T extends EntityTypes.socket + ? SocketEntry + : T extends EntityTypes.subchannel + ? SubchannelEntry + : never; + +export type InfoByType = T extends EntityTypes.channel + ? ChannelInfo + : T extends EntityTypes.subchannel + ? SubchannelInfo + : T extends EntityTypes.server + ? ServerInfo + : T extends EntityTypes.socket + ? SocketInfo + : never; + +const generateRegisterFn = (kind: R) => { + let nextId = 1; + function getNextId(): number { + return nextId++; + } + + const entityMap: EntryOrderedMap = entityMaps[kind]; + + return ( + name: string, + getInfo: () => InfoByType, + channelzEnabled: boolean + ): RefByType => { + const id = getNextId(); + const ref = { id, name, kind } as RefByType; + if (channelzEnabled) { + entityMap.setElement(id, { ref, getInfo }); + } + return ref; + }; +}; + +export const registerChannelzChannel = generateRegisterFn(EntityTypes.channel); +export const registerChannelzSubchannel = generateRegisterFn( + EntityTypes.subchannel +); +export const registerChannelzServer = generateRegisterFn(EntityTypes.server); +export const registerChannelzSocket = generateRegisterFn(EntityTypes.socket); + +export function unregisterChannelzRef( + ref: ChannelRef | SubchannelRef | ServerRef | SocketRef +) { + entityMaps[ref.kind].eraseElementByKey(ref.id); +} + +/** + * Parse a single section of an IPv6 address as two bytes + * @param addressSection A hexadecimal string of length up to 4 + * @returns The pair of bytes representing this address section + */ +function parseIPv6Section(addressSection: string): [number, number] { + const numberValue = Number.parseInt(addressSection, 16); + return [(numberValue / 256) | 0, numberValue % 256]; +} + +/** + * Parse a chunk of an IPv6 address string to some number of bytes + * @param addressChunk Some number of segments of up to 4 hexadecimal + * characters each, joined by colons. + * @returns The list of bytes representing this address chunk + */ +function parseIPv6Chunk(addressChunk: string): number[] { + if (addressChunk === '') { + return []; + } + const bytePairs = addressChunk + .split(':') + .map(section => parseIPv6Section(section)); + const result: number[] = []; + return result.concat(...bytePairs); +} + +/** + * Converts an IPv4 or IPv6 address from string representation to binary + * representation + * @param ipAddress an IP address in standard IPv4 or IPv6 text format + * @returns + */ +function ipAddressStringToBuffer(ipAddress: string): Buffer | null { + if (isIPv4(ipAddress)) { + return Buffer.from( + Uint8Array.from( + ipAddress.split('.').map(segment => Number.parseInt(segment)) + ) + ); + } else if (isIPv6(ipAddress)) { + let leftSection: string; + let rightSection: string; + const doubleColonIndex = ipAddress.indexOf('::'); + if (doubleColonIndex === -1) { + leftSection = ipAddress; + rightSection = ''; + } else { + leftSection = ipAddress.substring(0, doubleColonIndex); + rightSection = ipAddress.substring(doubleColonIndex + 2); + } + const leftBuffer = Buffer.from(parseIPv6Chunk(leftSection)); + const rightBuffer = Buffer.from(parseIPv6Chunk(rightSection)); + const middleBuffer = Buffer.alloc( + 16 - leftBuffer.length - rightBuffer.length, + 0 + ); + return Buffer.concat([leftBuffer, middleBuffer, rightBuffer]); + } else { + return null; + } +} + +function connectivityStateToMessage( + state: ConnectivityState +): ChannelConnectivityState__Output { + switch (state) { + case ConnectivityState.CONNECTING: + return { + state: 'CONNECTING', + }; + case ConnectivityState.IDLE: + return { + state: 'IDLE', + }; + case ConnectivityState.READY: + return { + state: 'READY', + }; + case ConnectivityState.SHUTDOWN: + return { + state: 'SHUTDOWN', + }; + case ConnectivityState.TRANSIENT_FAILURE: + return { + state: 'TRANSIENT_FAILURE', + }; + default: + return { + state: 'UNKNOWN', + }; + } +} + +function dateToProtoTimestamp(date?: Date | null): Timestamp | null { + if (!date) { + return null; + } + const millisSinceEpoch = date.getTime(); + return { + seconds: (millisSinceEpoch / 1000) | 0, + nanos: (millisSinceEpoch % 1000) * 1_000_000, + }; +} + +function getChannelMessage(channelEntry: ChannelEntry): ChannelMessage { + const resolvedInfo = channelEntry.getInfo(); + const channelRef: ChannelRefMessage[] = []; + const subchannelRef: SubchannelRefMessage[] = []; + + resolvedInfo.children.channels.forEach(el => { + channelRef.push(channelRefToMessage(el[1].ref)); + }); + + resolvedInfo.children.subchannels.forEach(el => { + subchannelRef.push(subchannelRefToMessage(el[1].ref)); + }); + + return { + ref: channelRefToMessage(channelEntry.ref), + data: { + target: resolvedInfo.target, + state: connectivityStateToMessage(resolvedInfo.state), + calls_started: resolvedInfo.callTracker.callsStarted, + calls_succeeded: resolvedInfo.callTracker.callsSucceeded, + calls_failed: resolvedInfo.callTracker.callsFailed, + last_call_started_timestamp: dateToProtoTimestamp( + resolvedInfo.callTracker.lastCallStartedTimestamp + ), + trace: resolvedInfo.trace.getTraceMessage(), + }, + channel_ref: channelRef, + subchannel_ref: subchannelRef, + }; +} + +function GetChannel( + call: ServerUnaryCall, + callback: sendUnaryData +): void { + const channelId = parseInt(call.request.channel_id, 10); + const channelEntry = + entityMaps[EntityTypes.channel].getElementByKey(channelId); + if (channelEntry === undefined) { + callback({ + code: Status.NOT_FOUND, + details: 'No channel data found for id ' + channelId, + }); + return; + } + callback(null, { channel: getChannelMessage(channelEntry) }); +} + +function GetTopChannels( + call: ServerUnaryCall, + callback: sendUnaryData +): void { + const maxResults = + parseInt(call.request.max_results, 10) || DEFAULT_MAX_RESULTS; + const resultList: ChannelMessage[] = []; + const startId = parseInt(call.request.start_channel_id, 10); + const channelEntries = entityMaps[EntityTypes.channel]; + + let i: OrderedMapIterator; + for ( + i = channelEntries.lowerBound(startId); + !i.equals(channelEntries.end()) && resultList.length < maxResults; + i = i.next() + ) { + resultList.push(getChannelMessage(i.pointer[1])); + } + + callback(null, { + channel: resultList, + end: i.equals(channelEntries.end()), + }); +} + +function getServerMessage(serverEntry: ServerEntry): ServerMessage { + const resolvedInfo = serverEntry.getInfo(); + const listenSocket: SocketRefMessage[] = []; + + resolvedInfo.listenerChildren.sockets.forEach(el => { + listenSocket.push(socketRefToMessage(el[1].ref)); + }); + + return { + ref: serverRefToMessage(serverEntry.ref), + data: { + calls_started: resolvedInfo.callTracker.callsStarted, + calls_succeeded: resolvedInfo.callTracker.callsSucceeded, + calls_failed: resolvedInfo.callTracker.callsFailed, + last_call_started_timestamp: dateToProtoTimestamp( + resolvedInfo.callTracker.lastCallStartedTimestamp + ), + trace: resolvedInfo.trace.getTraceMessage(), + }, + listen_socket: listenSocket, + }; +} + +function GetServer( + call: ServerUnaryCall, + callback: sendUnaryData +): void { + const serverId = parseInt(call.request.server_id, 10); + const serverEntries = entityMaps[EntityTypes.server]; + const serverEntry = serverEntries.getElementByKey(serverId); + if (serverEntry === undefined) { + callback({ + code: Status.NOT_FOUND, + details: 'No server data found for id ' + serverId, + }); + return; + } + callback(null, { server: getServerMessage(serverEntry) }); +} + +function GetServers( + call: ServerUnaryCall, + callback: sendUnaryData +): void { + const maxResults = + parseInt(call.request.max_results, 10) || DEFAULT_MAX_RESULTS; + const startId = parseInt(call.request.start_server_id, 10); + const serverEntries = entityMaps[EntityTypes.server]; + const resultList: ServerMessage[] = []; + + let i: OrderedMapIterator; + for ( + i = serverEntries.lowerBound(startId); + !i.equals(serverEntries.end()) && resultList.length < maxResults; + i = i.next() + ) { + resultList.push(getServerMessage(i.pointer[1])); + } + + callback(null, { + server: resultList, + end: i.equals(serverEntries.end()), + }); +} + +function GetSubchannel( + call: ServerUnaryCall, + callback: sendUnaryData +): void { + const subchannelId = parseInt(call.request.subchannel_id, 10); + const subchannelEntry = + entityMaps[EntityTypes.subchannel].getElementByKey(subchannelId); + if (subchannelEntry === undefined) { + callback({ + code: Status.NOT_FOUND, + details: 'No subchannel data found for id ' + subchannelId, + }); + return; + } + const resolvedInfo = subchannelEntry.getInfo(); + const listenSocket: SocketRefMessage[] = []; + + resolvedInfo.children.sockets.forEach(el => { + listenSocket.push(socketRefToMessage(el[1].ref)); + }); + + const subchannelMessage: SubchannelMessage = { + ref: subchannelRefToMessage(subchannelEntry.ref), + data: { + target: resolvedInfo.target, + state: connectivityStateToMessage(resolvedInfo.state), + calls_started: resolvedInfo.callTracker.callsStarted, + calls_succeeded: resolvedInfo.callTracker.callsSucceeded, + calls_failed: resolvedInfo.callTracker.callsFailed, + last_call_started_timestamp: dateToProtoTimestamp( + resolvedInfo.callTracker.lastCallStartedTimestamp + ), + trace: resolvedInfo.trace.getTraceMessage(), + }, + socket_ref: listenSocket, + }; + callback(null, { subchannel: subchannelMessage }); +} + +function subchannelAddressToAddressMessage( + subchannelAddress: SubchannelAddress +): Address { + if (isTcpSubchannelAddress(subchannelAddress)) { + return { + address: 'tcpip_address', + tcpip_address: { + ip_address: + ipAddressStringToBuffer(subchannelAddress.host) ?? undefined, + port: subchannelAddress.port, + }, + }; + } else { + return { + address: 'uds_address', + uds_address: { + filename: subchannelAddress.path, + }, + }; + } +} + +function GetSocket( + call: ServerUnaryCall, + callback: sendUnaryData +): void { + const socketId = parseInt(call.request.socket_id, 10); + const socketEntry = entityMaps[EntityTypes.socket].getElementByKey(socketId); + if (socketEntry === undefined) { + callback({ + code: Status.NOT_FOUND, + details: 'No socket data found for id ' + socketId, + }); + return; + } + const resolvedInfo = socketEntry.getInfo(); + const securityMessage: Security | null = resolvedInfo.security + ? { + model: 'tls', + tls: { + cipher_suite: resolvedInfo.security.cipherSuiteStandardName + ? 'standard_name' + : 'other_name', + standard_name: + resolvedInfo.security.cipherSuiteStandardName ?? undefined, + other_name: resolvedInfo.security.cipherSuiteOtherName ?? undefined, + local_certificate: + resolvedInfo.security.localCertificate ?? undefined, + remote_certificate: + resolvedInfo.security.remoteCertificate ?? undefined, + }, + } + : null; + const socketMessage: SocketMessage = { + ref: socketRefToMessage(socketEntry.ref), + local: resolvedInfo.localAddress + ? subchannelAddressToAddressMessage(resolvedInfo.localAddress) + : null, + remote: resolvedInfo.remoteAddress + ? subchannelAddressToAddressMessage(resolvedInfo.remoteAddress) + : null, + remote_name: resolvedInfo.remoteName ?? undefined, + security: securityMessage, + data: { + keep_alives_sent: resolvedInfo.keepAlivesSent, + streams_started: resolvedInfo.streamsStarted, + streams_succeeded: resolvedInfo.streamsSucceeded, + streams_failed: resolvedInfo.streamsFailed, + last_local_stream_created_timestamp: dateToProtoTimestamp( + resolvedInfo.lastLocalStreamCreatedTimestamp + ), + last_remote_stream_created_timestamp: dateToProtoTimestamp( + resolvedInfo.lastRemoteStreamCreatedTimestamp + ), + messages_received: resolvedInfo.messagesReceived, + messages_sent: resolvedInfo.messagesSent, + last_message_received_timestamp: dateToProtoTimestamp( + resolvedInfo.lastMessageReceivedTimestamp + ), + last_message_sent_timestamp: dateToProtoTimestamp( + resolvedInfo.lastMessageSentTimestamp + ), + local_flow_control_window: resolvedInfo.localFlowControlWindow + ? { value: resolvedInfo.localFlowControlWindow } + : null, + remote_flow_control_window: resolvedInfo.remoteFlowControlWindow + ? { value: resolvedInfo.remoteFlowControlWindow } + : null, + }, + }; + callback(null, { socket: socketMessage }); +} + +function GetServerSockets( + call: ServerUnaryCall< + GetServerSocketsRequest__Output, + GetServerSocketsResponse + >, + callback: sendUnaryData +): void { + const serverId = parseInt(call.request.server_id, 10); + const serverEntry = entityMaps[EntityTypes.server].getElementByKey(serverId); + + if (serverEntry === undefined) { + callback({ + code: Status.NOT_FOUND, + details: 'No server data found for id ' + serverId, + }); + return; + } + + const startId = parseInt(call.request.start_socket_id, 10); + const maxResults = + parseInt(call.request.max_results, 10) || DEFAULT_MAX_RESULTS; + const resolvedInfo = serverEntry.getInfo(); + // If we wanted to include listener sockets in the result, this line would + // instead say + // const allSockets = resolvedInfo.listenerChildren.sockets.concat(resolvedInfo.sessionChildren.sockets).sort((ref1, ref2) => ref1.id - ref2.id); + const allSockets = resolvedInfo.sessionChildren.sockets; + const resultList: SocketRefMessage[] = []; + + let i: OrderedMapIterator; + for ( + i = allSockets.lowerBound(startId); + !i.equals(allSockets.end()) && resultList.length < maxResults; + i = i.next() + ) { + resultList.push(socketRefToMessage(i.pointer[1].ref)); + } + + callback(null, { + socket_ref: resultList, + end: i.equals(allSockets.end()), + }); +} + +export function getChannelzHandlers(): ChannelzHandlers { + return { + GetChannel, + GetTopChannels, + GetServer, + GetServers, + GetSubchannel, + GetSocket, + GetServerSockets, + }; +} + +let loadedChannelzDefinition: ChannelzDefinition | null = null; + +export function getChannelzServiceDefinition(): ChannelzDefinition { + if (loadedChannelzDefinition) { + return loadedChannelzDefinition; + } + /* The purpose of this complexity is to avoid loading @grpc/proto-loader at + * runtime for users who will not use/enable channelz. */ + const loaderLoadSync = require('@grpc/proto-loader') + .loadSync as typeof loadSync; + const loadedProto = loaderLoadSync('channelz.proto', { + keepCase: true, + longs: String, + enums: String, + defaults: true, + oneofs: true, + includeDirs: [`${__dirname}/../../proto`], + }); + const channelzGrpcObject = loadPackageDefinition( + loadedProto + ) as unknown as ChannelzProtoGrpcType; + loadedChannelzDefinition = + channelzGrpcObject.grpc.channelz.v1.Channelz.service; + return loadedChannelzDefinition; +} + +export function setup() { + registerAdminService(getChannelzServiceDefinition, getChannelzHandlers); +} diff --git a/node_modules/@grpc/grpc-js/src/client-interceptors.ts b/node_modules/@grpc/grpc-js/src/client-interceptors.ts new file mode 100644 index 0000000..4f53d17 --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/client-interceptors.ts @@ -0,0 +1,577 @@ +/* + * Copyright 2019 gRPC authors. + * + * 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. + * + */ + +import { Metadata } from './metadata'; +import { + StatusObject, + Listener, + MetadataListener, + MessageListener, + StatusListener, + FullListener, + InterceptingListener, + InterceptingListenerImpl, + isInterceptingListener, + MessageContext, + Call, +} from './call-interface'; +import { Status } from './constants'; +import { Channel } from './channel'; +import { CallOptions } from './client'; +import { ClientMethodDefinition } from './make-client'; +import { getErrorMessage } from './error'; + +/** + * Error class associated with passing both interceptors and interceptor + * providers to a client constructor or as call options. + */ +export class InterceptorConfigurationError extends Error { + constructor(message: string) { + super(message); + this.name = 'InterceptorConfigurationError'; + Error.captureStackTrace(this, InterceptorConfigurationError); + } +} + +export interface MetadataRequester { + ( + metadata: Metadata, + listener: InterceptingListener, + next: ( + metadata: Metadata, + listener: InterceptingListener | Listener + ) => void + ): void; +} + +export interface MessageRequester { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + (message: any, next: (message: any) => void): void; +} + +export interface CloseRequester { + (next: () => void): void; +} + +export interface CancelRequester { + (next: () => void): void; +} + +/** + * An object with methods for intercepting and modifying outgoing call operations. + */ +export interface FullRequester { + start: MetadataRequester; + sendMessage: MessageRequester; + halfClose: CloseRequester; + cancel: CancelRequester; +} + +export type Requester = Partial; + +export class ListenerBuilder { + private metadata: MetadataListener | undefined = undefined; + private message: MessageListener | undefined = undefined; + private status: StatusListener | undefined = undefined; + + withOnReceiveMetadata(onReceiveMetadata: MetadataListener): this { + this.metadata = onReceiveMetadata; + return this; + } + + withOnReceiveMessage(onReceiveMessage: MessageListener): this { + this.message = onReceiveMessage; + return this; + } + + withOnReceiveStatus(onReceiveStatus: StatusListener): this { + this.status = onReceiveStatus; + return this; + } + + build(): Listener { + return { + onReceiveMetadata: this.metadata, + onReceiveMessage: this.message, + onReceiveStatus: this.status, + }; + } +} + +export class RequesterBuilder { + private start: MetadataRequester | undefined = undefined; + private message: MessageRequester | undefined = undefined; + private halfClose: CloseRequester | undefined = undefined; + private cancel: CancelRequester | undefined = undefined; + + withStart(start: MetadataRequester): this { + this.start = start; + return this; + } + + withSendMessage(sendMessage: MessageRequester): this { + this.message = sendMessage; + return this; + } + + withHalfClose(halfClose: CloseRequester): this { + this.halfClose = halfClose; + return this; + } + + withCancel(cancel: CancelRequester): this { + this.cancel = cancel; + return this; + } + + build(): Requester { + return { + start: this.start, + sendMessage: this.message, + halfClose: this.halfClose, + cancel: this.cancel, + }; + } +} + +/** + * A Listener with a default pass-through implementation of each method. Used + * for filling out Listeners with some methods omitted. + */ +const defaultListener: FullListener = { + onReceiveMetadata: (metadata, next) => { + next(metadata); + }, + onReceiveMessage: (message, next) => { + next(message); + }, + onReceiveStatus: (status, next) => { + next(status); + }, +}; + +/** + * A Requester with a default pass-through implementation of each method. Used + * for filling out Requesters with some methods omitted. + */ +const defaultRequester: FullRequester = { + start: (metadata, listener, next) => { + next(metadata, listener); + }, + sendMessage: (message, next) => { + next(message); + }, + halfClose: next => { + next(); + }, + cancel: next => { + next(); + }, +}; + +export interface InterceptorOptions extends CallOptions { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + method_definition: ClientMethodDefinition; +} + +export interface InterceptingCallInterface { + cancelWithStatus(status: Status, details: string): void; + getPeer(): string; + start(metadata: Metadata, listener?: Partial): void; + // eslint-disable-next-line @typescript-eslint/no-explicit-any + sendMessageWithContext(context: MessageContext, message: any): void; + // eslint-disable-next-line @typescript-eslint/no-explicit-any + sendMessage(message: any): void; + startRead(): void; + halfClose(): void; +} + +export class InterceptingCall implements InterceptingCallInterface { + /** + * The requester that this InterceptingCall uses to modify outgoing operations + */ + private requester: FullRequester; + /** + * Indicates that metadata has been passed to the requester's start + * method but it has not been passed to the corresponding next callback + */ + private processingMetadata = false; + /** + * Message context for a pending message that is waiting for + */ + private pendingMessageContext: MessageContext | null = null; + private pendingMessage: any; + /** + * Indicates that a message has been passed to the requester's sendMessage + * method but it has not been passed to the corresponding next callback + */ + private processingMessage = false; + /** + * Indicates that a status was received but could not be propagated because + * a message was still being processed. + */ + private pendingHalfClose = false; + constructor( + private nextCall: InterceptingCallInterface, + requester?: Requester + ) { + if (requester) { + this.requester = { + start: requester.start ?? defaultRequester.start, + sendMessage: requester.sendMessage ?? defaultRequester.sendMessage, + halfClose: requester.halfClose ?? defaultRequester.halfClose, + cancel: requester.cancel ?? defaultRequester.cancel, + }; + } else { + this.requester = defaultRequester; + } + } + + cancelWithStatus(status: Status, details: string) { + this.requester.cancel(() => { + this.nextCall.cancelWithStatus(status, details); + }); + } + + getPeer() { + return this.nextCall.getPeer(); + } + + private processPendingMessage() { + if (this.pendingMessageContext) { + this.nextCall.sendMessageWithContext( + this.pendingMessageContext, + this.pendingMessage + ); + this.pendingMessageContext = null; + this.pendingMessage = null; + } + } + + private processPendingHalfClose() { + if (this.pendingHalfClose) { + this.nextCall.halfClose(); + } + } + + start( + metadata: Metadata, + interceptingListener?: Partial + ): void { + const fullInterceptingListener: InterceptingListener = { + onReceiveMetadata: + interceptingListener?.onReceiveMetadata?.bind(interceptingListener) ?? + (metadata => {}), + onReceiveMessage: + interceptingListener?.onReceiveMessage?.bind(interceptingListener) ?? + (message => {}), + onReceiveStatus: + interceptingListener?.onReceiveStatus?.bind(interceptingListener) ?? + (status => {}), + }; + this.processingMetadata = true; + this.requester.start(metadata, fullInterceptingListener, (md, listener) => { + this.processingMetadata = false; + let finalInterceptingListener: InterceptingListener; + if (isInterceptingListener(listener)) { + finalInterceptingListener = listener; + } else { + const fullListener: FullListener = { + onReceiveMetadata: + listener.onReceiveMetadata ?? defaultListener.onReceiveMetadata, + onReceiveMessage: + listener.onReceiveMessage ?? defaultListener.onReceiveMessage, + onReceiveStatus: + listener.onReceiveStatus ?? defaultListener.onReceiveStatus, + }; + finalInterceptingListener = new InterceptingListenerImpl( + fullListener, + fullInterceptingListener + ); + } + this.nextCall.start(md, finalInterceptingListener); + this.processPendingMessage(); + this.processPendingHalfClose(); + }); + } + // eslint-disable-next-line @typescript-eslint/no-explicit-any + sendMessageWithContext(context: MessageContext, message: any): void { + this.processingMessage = true; + this.requester.sendMessage(message, finalMessage => { + this.processingMessage = false; + if (this.processingMetadata) { + this.pendingMessageContext = context; + this.pendingMessage = message; + } else { + this.nextCall.sendMessageWithContext(context, finalMessage); + this.processPendingHalfClose(); + } + }); + } + // eslint-disable-next-line @typescript-eslint/no-explicit-any + sendMessage(message: any): void { + this.sendMessageWithContext({}, message); + } + startRead(): void { + this.nextCall.startRead(); + } + halfClose(): void { + this.requester.halfClose(() => { + if (this.processingMetadata || this.processingMessage) { + this.pendingHalfClose = true; + } else { + this.nextCall.halfClose(); + } + }); + } +} + +function getCall(channel: Channel, path: string, options: CallOptions): Call { + const deadline = options.deadline ?? Infinity; + const host = options.host; + const parent = options.parent ?? null; + const propagateFlags = options.propagate_flags; + const credentials = options.credentials; + const call = channel.createCall(path, deadline, host, parent, propagateFlags); + if (credentials) { + call.setCredentials(credentials); + } + return call; +} + +/** + * InterceptingCall implementation that directly owns the underlying Call + * object and handles serialization and deseraizliation. + */ +class BaseInterceptingCall implements InterceptingCallInterface { + constructor( + protected call: Call, + // eslint-disable-next-line @typescript-eslint/no-explicit-any + protected methodDefinition: ClientMethodDefinition + ) {} + cancelWithStatus(status: Status, details: string): void { + this.call.cancelWithStatus(status, details); + } + getPeer(): string { + return this.call.getPeer(); + } + // eslint-disable-next-line @typescript-eslint/no-explicit-any + sendMessageWithContext(context: MessageContext, message: any): void { + let serialized: Buffer; + try { + serialized = this.methodDefinition.requestSerialize(message); + } catch (e) { + this.call.cancelWithStatus( + Status.INTERNAL, + `Request message serialization failure: ${getErrorMessage(e)}` + ); + return; + } + this.call.sendMessageWithContext(context, serialized); + } + // eslint-disable-next-line @typescript-eslint/no-explicit-any + sendMessage(message: any) { + this.sendMessageWithContext({}, message); + } + start( + metadata: Metadata, + interceptingListener?: Partial + ): void { + let readError: StatusObject | null = null; + this.call.start(metadata, { + onReceiveMetadata: metadata => { + interceptingListener?.onReceiveMetadata?.(metadata); + }, + onReceiveMessage: message => { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + let deserialized: any; + try { + deserialized = this.methodDefinition.responseDeserialize(message); + } catch (e) { + readError = { + code: Status.INTERNAL, + details: `Response message parsing error: ${getErrorMessage(e)}`, + metadata: new Metadata(), + }; + this.call.cancelWithStatus(readError.code, readError.details); + return; + } + interceptingListener?.onReceiveMessage?.(deserialized); + }, + onReceiveStatus: status => { + if (readError) { + interceptingListener?.onReceiveStatus?.(readError); + } else { + interceptingListener?.onReceiveStatus?.(status); + } + }, + }); + } + startRead() { + this.call.startRead(); + } + halfClose(): void { + this.call.halfClose(); + } +} + +/** + * BaseInterceptingCall with special-cased behavior for methods with unary + * responses. + */ +class BaseUnaryInterceptingCall + extends BaseInterceptingCall + implements InterceptingCallInterface +{ + // eslint-disable-next-line @typescript-eslint/no-explicit-any + constructor(call: Call, methodDefinition: ClientMethodDefinition) { + super(call, methodDefinition); + } + start(metadata: Metadata, listener?: Partial): void { + let receivedMessage = false; + const wrapperListener: InterceptingListener = { + onReceiveMetadata: + listener?.onReceiveMetadata?.bind(listener) ?? (metadata => {}), + // eslint-disable-next-line @typescript-eslint/no-explicit-any + onReceiveMessage: (message: any) => { + receivedMessage = true; + listener?.onReceiveMessage?.(message); + }, + onReceiveStatus: (status: StatusObject) => { + if (!receivedMessage) { + listener?.onReceiveMessage?.(null); + } + listener?.onReceiveStatus?.(status); + }, + }; + super.start(metadata, wrapperListener); + this.call.startRead(); + } +} + +/** + * BaseInterceptingCall with special-cased behavior for methods with streaming + * responses. + */ +class BaseStreamingInterceptingCall + extends BaseInterceptingCall + implements InterceptingCallInterface {} + +function getBottomInterceptingCall( + channel: Channel, + options: InterceptorOptions, + // eslint-disable-next-line @typescript-eslint/no-explicit-any + methodDefinition: ClientMethodDefinition +) { + const call = getCall(channel, methodDefinition.path, options); + if (methodDefinition.responseStream) { + return new BaseStreamingInterceptingCall(call, methodDefinition); + } else { + return new BaseUnaryInterceptingCall(call, methodDefinition); + } +} + +export interface NextCall { + (options: InterceptorOptions): InterceptingCallInterface; +} + +export interface Interceptor { + (options: InterceptorOptions, nextCall: NextCall): InterceptingCall; +} + +export interface InterceptorProvider { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + (methodDefinition: ClientMethodDefinition): Interceptor; +} + +export interface InterceptorArguments { + clientInterceptors: Interceptor[]; + clientInterceptorProviders: InterceptorProvider[]; + callInterceptors: Interceptor[]; + callInterceptorProviders: InterceptorProvider[]; +} + +export function getInterceptingCall( + interceptorArgs: InterceptorArguments, + // eslint-disable-next-line @typescript-eslint/no-explicit-any + methodDefinition: ClientMethodDefinition, + options: CallOptions, + channel: Channel +): InterceptingCallInterface { + if ( + interceptorArgs.clientInterceptors.length > 0 && + interceptorArgs.clientInterceptorProviders.length > 0 + ) { + throw new InterceptorConfigurationError( + 'Both interceptors and interceptor_providers were passed as options ' + + 'to the client constructor. Only one of these is allowed.' + ); + } + if ( + interceptorArgs.callInterceptors.length > 0 && + interceptorArgs.callInterceptorProviders.length > 0 + ) { + throw new InterceptorConfigurationError( + 'Both interceptors and interceptor_providers were passed as call ' + + 'options. Only one of these is allowed.' + ); + } + let interceptors: Interceptor[] = []; + // Interceptors passed to the call override interceptors passed to the client constructor + if ( + interceptorArgs.callInterceptors.length > 0 || + interceptorArgs.callInterceptorProviders.length > 0 + ) { + interceptors = ([] as Interceptor[]) + .concat( + interceptorArgs.callInterceptors, + interceptorArgs.callInterceptorProviders.map(provider => + provider(methodDefinition) + ) + ) + .filter(interceptor => interceptor); + // Filter out falsy values when providers return nothing + } else { + interceptors = ([] as Interceptor[]) + .concat( + interceptorArgs.clientInterceptors, + interceptorArgs.clientInterceptorProviders.map(provider => + provider(methodDefinition) + ) + ) + .filter(interceptor => interceptor); + // Filter out falsy values when providers return nothing + } + const interceptorOptions = Object.assign({}, options, { + method_definition: methodDefinition, + }); + /* For each interceptor in the list, the nextCall function passed to it is + * based on the next interceptor in the list, using a nextCall function + * constructed with the following interceptor in the list, and so on. The + * initialValue, which is effectively at the end of the list, is a nextCall + * function that invokes getBottomInterceptingCall, the result of which + * handles (de)serialization and also gets the underlying call from the + * channel. */ + const getCall: NextCall = interceptors.reduceRight( + (nextCall: NextCall, nextInterceptor: Interceptor) => { + return currentOptions => nextInterceptor(currentOptions, nextCall); + }, + (finalOptions: InterceptorOptions) => + getBottomInterceptingCall(channel, finalOptions, methodDefinition) + ); + return getCall(interceptorOptions); +} diff --git a/node_modules/@grpc/grpc-js/src/client.ts b/node_modules/@grpc/grpc-js/src/client.ts new file mode 100644 index 0000000..995d5b3 --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/client.ts @@ -0,0 +1,715 @@ +/* + * Copyright 2019 gRPC authors. + * + * 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. + * + */ + +import { + ClientDuplexStream, + ClientDuplexStreamImpl, + ClientReadableStream, + ClientReadableStreamImpl, + ClientUnaryCall, + ClientUnaryCallImpl, + ClientWritableStream, + ClientWritableStreamImpl, + ServiceError, + callErrorFromStatus, + SurfaceCall, +} from './call'; +import { CallCredentials } from './call-credentials'; +import { StatusObject } from './call-interface'; +import { Channel, ChannelImplementation } from './channel'; +import { ConnectivityState } from './connectivity-state'; +import { ChannelCredentials } from './channel-credentials'; +import { ChannelOptions } from './channel-options'; +import { Status } from './constants'; +import { Metadata } from './metadata'; +import { ClientMethodDefinition } from './make-client'; +import { + getInterceptingCall, + Interceptor, + InterceptorProvider, + InterceptorArguments, + InterceptingCallInterface, +} from './client-interceptors'; +import { + ServerUnaryCall, + ServerReadableStream, + ServerWritableStream, + ServerDuplexStream, +} from './server-call'; +import { Deadline } from './deadline'; + +const CHANNEL_SYMBOL = Symbol(); +const INTERCEPTOR_SYMBOL = Symbol(); +const INTERCEPTOR_PROVIDER_SYMBOL = Symbol(); +const CALL_INVOCATION_TRANSFORMER_SYMBOL = Symbol(); + +function isFunction( + arg: Metadata | CallOptions | UnaryCallback | undefined +): arg is UnaryCallback { + return typeof arg === 'function'; +} + +export interface UnaryCallback { + (err: ServiceError | null, value?: ResponseType): void; +} + +/* eslint-disable @typescript-eslint/no-explicit-any */ +export interface CallOptions { + deadline?: Deadline; + host?: string; + parent?: + | ServerUnaryCall + | ServerReadableStream + | ServerWritableStream + | ServerDuplexStream; + propagate_flags?: number; + credentials?: CallCredentials; + interceptors?: Interceptor[]; + interceptor_providers?: InterceptorProvider[]; +} +/* eslint-enable @typescript-eslint/no-explicit-any */ + +export interface CallProperties { + argument?: RequestType; + metadata: Metadata; + call: SurfaceCall; + channel: Channel; + methodDefinition: ClientMethodDefinition; + callOptions: CallOptions; + callback?: UnaryCallback; +} + +export interface CallInvocationTransformer { + (callProperties: CallProperties): CallProperties; // eslint-disable-line @typescript-eslint/no-explicit-any +} + +export type ClientOptions = Partial & { + channelOverride?: Channel; + channelFactoryOverride?: ( + address: string, + credentials: ChannelCredentials, + options: ClientOptions + ) => Channel; + interceptors?: Interceptor[]; + interceptor_providers?: InterceptorProvider[]; + callInvocationTransformer?: CallInvocationTransformer; +}; + +function getErrorStackString(error: Error): string { + return error.stack?.split('\n').slice(1).join('\n') || 'no stack trace available'; +} + +/** + * A generic gRPC client. Primarily useful as a base class for all generated + * clients. + */ +export class Client { + private readonly [CHANNEL_SYMBOL]: Channel; + private readonly [INTERCEPTOR_SYMBOL]: Interceptor[]; + private readonly [INTERCEPTOR_PROVIDER_SYMBOL]: InterceptorProvider[]; + private readonly [CALL_INVOCATION_TRANSFORMER_SYMBOL]?: CallInvocationTransformer; + constructor( + address: string, + credentials: ChannelCredentials, + options: ClientOptions = {} + ) { + options = Object.assign({}, options); + this[INTERCEPTOR_SYMBOL] = options.interceptors ?? []; + delete options.interceptors; + this[INTERCEPTOR_PROVIDER_SYMBOL] = options.interceptor_providers ?? []; + delete options.interceptor_providers; + if ( + this[INTERCEPTOR_SYMBOL].length > 0 && + this[INTERCEPTOR_PROVIDER_SYMBOL].length > 0 + ) { + throw new Error( + 'Both interceptors and interceptor_providers were passed as options ' + + 'to the client constructor. Only one of these is allowed.' + ); + } + this[CALL_INVOCATION_TRANSFORMER_SYMBOL] = + options.callInvocationTransformer; + delete options.callInvocationTransformer; + if (options.channelOverride) { + this[CHANNEL_SYMBOL] = options.channelOverride; + } else if (options.channelFactoryOverride) { + const channelFactoryOverride = options.channelFactoryOverride; + delete options.channelFactoryOverride; + this[CHANNEL_SYMBOL] = channelFactoryOverride( + address, + credentials, + options + ); + } else { + this[CHANNEL_SYMBOL] = new ChannelImplementation( + address, + credentials, + options + ); + } + } + + close(): void { + this[CHANNEL_SYMBOL].close(); + } + + getChannel(): Channel { + return this[CHANNEL_SYMBOL]; + } + + waitForReady(deadline: Deadline, callback: (error?: Error) => void): void { + const checkState = (err?: Error) => { + if (err) { + callback(new Error('Failed to connect before the deadline')); + return; + } + let newState; + try { + newState = this[CHANNEL_SYMBOL].getConnectivityState(true); + } catch (e) { + callback(new Error('The channel has been closed')); + return; + } + if (newState === ConnectivityState.READY) { + callback(); + } else { + try { + this[CHANNEL_SYMBOL].watchConnectivityState( + newState, + deadline, + checkState + ); + } catch (e) { + callback(new Error('The channel has been closed')); + } + } + }; + setImmediate(checkState); + } + + private checkOptionalUnaryResponseArguments( + arg1: Metadata | CallOptions | UnaryCallback, + arg2?: CallOptions | UnaryCallback, + arg3?: UnaryCallback + ): { + metadata: Metadata; + options: CallOptions; + callback: UnaryCallback; + } { + if (isFunction(arg1)) { + return { metadata: new Metadata(), options: {}, callback: arg1 }; + } else if (isFunction(arg2)) { + if (arg1 instanceof Metadata) { + return { metadata: arg1, options: {}, callback: arg2 }; + } else { + return { metadata: new Metadata(), options: arg1, callback: arg2 }; + } + } else { + if ( + !( + arg1 instanceof Metadata && + arg2 instanceof Object && + isFunction(arg3) + ) + ) { + throw new Error('Incorrect arguments passed'); + } + return { metadata: arg1, options: arg2, callback: arg3 }; + } + } + + makeUnaryRequest( + method: string, + serialize: (value: RequestType) => Buffer, + deserialize: (value: Buffer) => ResponseType, + argument: RequestType, + metadata: Metadata, + options: CallOptions, + callback: UnaryCallback + ): ClientUnaryCall; + makeUnaryRequest( + method: string, + serialize: (value: RequestType) => Buffer, + deserialize: (value: Buffer) => ResponseType, + argument: RequestType, + metadata: Metadata, + callback: UnaryCallback + ): ClientUnaryCall; + makeUnaryRequest( + method: string, + serialize: (value: RequestType) => Buffer, + deserialize: (value: Buffer) => ResponseType, + argument: RequestType, + options: CallOptions, + callback: UnaryCallback + ): ClientUnaryCall; + makeUnaryRequest( + method: string, + serialize: (value: RequestType) => Buffer, + deserialize: (value: Buffer) => ResponseType, + argument: RequestType, + callback: UnaryCallback + ): ClientUnaryCall; + makeUnaryRequest( + method: string, + serialize: (value: RequestType) => Buffer, + deserialize: (value: Buffer) => ResponseType, + argument: RequestType, + metadata: Metadata | CallOptions | UnaryCallback, + options?: CallOptions | UnaryCallback, + callback?: UnaryCallback + ): ClientUnaryCall { + const checkedArguments = + this.checkOptionalUnaryResponseArguments( + metadata, + options, + callback + ); + const methodDefinition: ClientMethodDefinition = + { + path: method, + requestStream: false, + responseStream: false, + requestSerialize: serialize, + responseDeserialize: deserialize, + }; + let callProperties: CallProperties = { + argument: argument, + metadata: checkedArguments.metadata, + call: new ClientUnaryCallImpl(), + channel: this[CHANNEL_SYMBOL], + methodDefinition: methodDefinition, + callOptions: checkedArguments.options, + callback: checkedArguments.callback, + }; + if (this[CALL_INVOCATION_TRANSFORMER_SYMBOL]) { + callProperties = this[CALL_INVOCATION_TRANSFORMER_SYMBOL]!( + callProperties + ) as CallProperties; + } + const emitter: ClientUnaryCall = callProperties.call; + const interceptorArgs: InterceptorArguments = { + clientInterceptors: this[INTERCEPTOR_SYMBOL], + clientInterceptorProviders: this[INTERCEPTOR_PROVIDER_SYMBOL], + callInterceptors: callProperties.callOptions.interceptors ?? [], + callInterceptorProviders: + callProperties.callOptions.interceptor_providers ?? [], + }; + const call: InterceptingCallInterface = getInterceptingCall( + interceptorArgs, + callProperties.methodDefinition, + callProperties.callOptions, + callProperties.channel + ); + /* This needs to happen before the emitter is used. Unfortunately we can't + * enforce this with the type system. We need to construct this emitter + * before calling the CallInvocationTransformer, and we need to create the + * call after that. */ + emitter.call = call; + let responseMessage: ResponseType | null = null; + let receivedStatus = false; + let callerStackError: Error | null = new Error(); + call.start(callProperties.metadata, { + onReceiveMetadata: metadata => { + emitter.emit('metadata', metadata); + }, + // eslint-disable-next-line @typescript-eslint/no-explicit-any + onReceiveMessage(message: any) { + if (responseMessage !== null) { + call.cancelWithStatus(Status.INTERNAL, 'Too many responses received'); + } + responseMessage = message; + }, + onReceiveStatus(status: StatusObject) { + if (receivedStatus) { + return; + } + receivedStatus = true; + if (status.code === Status.OK) { + if (responseMessage === null) { + const callerStack = getErrorStackString(callerStackError!); + callProperties.callback!( + callErrorFromStatus( + { + code: Status.INTERNAL, + details: 'No message received', + metadata: status.metadata, + }, + callerStack + ) + ); + } else { + callProperties.callback!(null, responseMessage); + } + } else { + const callerStack = getErrorStackString(callerStackError!); + callProperties.callback!(callErrorFromStatus(status, callerStack)); + } + /* Avoid retaining the callerStackError object in the call context of + * the status event handler. */ + callerStackError = null; + emitter.emit('status', status); + }, + }); + call.sendMessage(argument); + call.halfClose(); + return emitter; + } + + makeClientStreamRequest( + method: string, + serialize: (value: RequestType) => Buffer, + deserialize: (value: Buffer) => ResponseType, + metadata: Metadata, + options: CallOptions, + callback: UnaryCallback + ): ClientWritableStream; + makeClientStreamRequest( + method: string, + serialize: (value: RequestType) => Buffer, + deserialize: (value: Buffer) => ResponseType, + metadata: Metadata, + callback: UnaryCallback + ): ClientWritableStream; + makeClientStreamRequest( + method: string, + serialize: (value: RequestType) => Buffer, + deserialize: (value: Buffer) => ResponseType, + options: CallOptions, + callback: UnaryCallback + ): ClientWritableStream; + makeClientStreamRequest( + method: string, + serialize: (value: RequestType) => Buffer, + deserialize: (value: Buffer) => ResponseType, + callback: UnaryCallback + ): ClientWritableStream; + makeClientStreamRequest( + method: string, + serialize: (value: RequestType) => Buffer, + deserialize: (value: Buffer) => ResponseType, + metadata: Metadata | CallOptions | UnaryCallback, + options?: CallOptions | UnaryCallback, + callback?: UnaryCallback + ): ClientWritableStream { + const checkedArguments = + this.checkOptionalUnaryResponseArguments( + metadata, + options, + callback + ); + const methodDefinition: ClientMethodDefinition = + { + path: method, + requestStream: true, + responseStream: false, + requestSerialize: serialize, + responseDeserialize: deserialize, + }; + let callProperties: CallProperties = { + metadata: checkedArguments.metadata, + call: new ClientWritableStreamImpl(serialize), + channel: this[CHANNEL_SYMBOL], + methodDefinition: methodDefinition, + callOptions: checkedArguments.options, + callback: checkedArguments.callback, + }; + if (this[CALL_INVOCATION_TRANSFORMER_SYMBOL]) { + callProperties = this[CALL_INVOCATION_TRANSFORMER_SYMBOL]!( + callProperties + ) as CallProperties; + } + const emitter: ClientWritableStream = + callProperties.call as ClientWritableStream; + const interceptorArgs: InterceptorArguments = { + clientInterceptors: this[INTERCEPTOR_SYMBOL], + clientInterceptorProviders: this[INTERCEPTOR_PROVIDER_SYMBOL], + callInterceptors: callProperties.callOptions.interceptors ?? [], + callInterceptorProviders: + callProperties.callOptions.interceptor_providers ?? [], + }; + const call: InterceptingCallInterface = getInterceptingCall( + interceptorArgs, + callProperties.methodDefinition, + callProperties.callOptions, + callProperties.channel + ); + /* This needs to happen before the emitter is used. Unfortunately we can't + * enforce this with the type system. We need to construct this emitter + * before calling the CallInvocationTransformer, and we need to create the + * call after that. */ + emitter.call = call; + let responseMessage: ResponseType | null = null; + let receivedStatus = false; + let callerStackError: Error | null = new Error(); + call.start(callProperties.metadata, { + onReceiveMetadata: metadata => { + emitter.emit('metadata', metadata); + }, + // eslint-disable-next-line @typescript-eslint/no-explicit-any + onReceiveMessage(message: any) { + if (responseMessage !== null) { + call.cancelWithStatus(Status.INTERNAL, 'Too many responses received'); + } + responseMessage = message; + }, + onReceiveStatus(status: StatusObject) { + if (receivedStatus) { + return; + } + receivedStatus = true; + if (status.code === Status.OK) { + if (responseMessage === null) { + const callerStack = getErrorStackString(callerStackError!); + callProperties.callback!( + callErrorFromStatus( + { + code: Status.INTERNAL, + details: 'No message received', + metadata: status.metadata, + }, + callerStack + ) + ); + } else { + callProperties.callback!(null, responseMessage); + } + } else { + const callerStack = getErrorStackString(callerStackError!); + callProperties.callback!(callErrorFromStatus(status, callerStack)); + } + /* Avoid retaining the callerStackError object in the call context of + * the status event handler. */ + callerStackError = null; + emitter.emit('status', status); + }, + }); + return emitter; + } + + private checkMetadataAndOptions( + arg1?: Metadata | CallOptions, + arg2?: CallOptions + ): { metadata: Metadata; options: CallOptions } { + let metadata: Metadata; + let options: CallOptions; + if (arg1 instanceof Metadata) { + metadata = arg1; + if (arg2) { + options = arg2; + } else { + options = {}; + } + } else { + if (arg1) { + options = arg1; + } else { + options = {}; + } + metadata = new Metadata(); + } + return { metadata, options }; + } + + makeServerStreamRequest( + method: string, + serialize: (value: RequestType) => Buffer, + deserialize: (value: Buffer) => ResponseType, + argument: RequestType, + metadata: Metadata, + options?: CallOptions + ): ClientReadableStream; + makeServerStreamRequest( + method: string, + serialize: (value: RequestType) => Buffer, + deserialize: (value: Buffer) => ResponseType, + argument: RequestType, + options?: CallOptions + ): ClientReadableStream; + makeServerStreamRequest( + method: string, + serialize: (value: RequestType) => Buffer, + deserialize: (value: Buffer) => ResponseType, + argument: RequestType, + metadata?: Metadata | CallOptions, + options?: CallOptions + ): ClientReadableStream { + const checkedArguments = this.checkMetadataAndOptions(metadata, options); + const methodDefinition: ClientMethodDefinition = + { + path: method, + requestStream: false, + responseStream: true, + requestSerialize: serialize, + responseDeserialize: deserialize, + }; + let callProperties: CallProperties = { + argument: argument, + metadata: checkedArguments.metadata, + call: new ClientReadableStreamImpl(deserialize), + channel: this[CHANNEL_SYMBOL], + methodDefinition: methodDefinition, + callOptions: checkedArguments.options, + }; + if (this[CALL_INVOCATION_TRANSFORMER_SYMBOL]) { + callProperties = this[CALL_INVOCATION_TRANSFORMER_SYMBOL]!( + callProperties + ) as CallProperties; + } + const stream: ClientReadableStream = + callProperties.call as ClientReadableStream; + const interceptorArgs: InterceptorArguments = { + clientInterceptors: this[INTERCEPTOR_SYMBOL], + clientInterceptorProviders: this[INTERCEPTOR_PROVIDER_SYMBOL], + callInterceptors: callProperties.callOptions.interceptors ?? [], + callInterceptorProviders: + callProperties.callOptions.interceptor_providers ?? [], + }; + const call: InterceptingCallInterface = getInterceptingCall( + interceptorArgs, + callProperties.methodDefinition, + callProperties.callOptions, + callProperties.channel + ); + /* This needs to happen before the emitter is used. Unfortunately we can't + * enforce this with the type system. We need to construct this emitter + * before calling the CallInvocationTransformer, and we need to create the + * call after that. */ + stream.call = call; + let receivedStatus = false; + let callerStackError: Error | null = new Error(); + call.start(callProperties.metadata, { + onReceiveMetadata(metadata: Metadata) { + stream.emit('metadata', metadata); + }, + // eslint-disable-next-line @typescript-eslint/no-explicit-any + onReceiveMessage(message: any) { + stream.push(message); + }, + onReceiveStatus(status: StatusObject) { + if (receivedStatus) { + return; + } + receivedStatus = true; + stream.push(null); + if (status.code !== Status.OK) { + const callerStack = getErrorStackString(callerStackError!); + stream.emit('error', callErrorFromStatus(status, callerStack)); + } + /* Avoid retaining the callerStackError object in the call context of + * the status event handler. */ + callerStackError = null; + stream.emit('status', status); + }, + }); + call.sendMessage(argument); + call.halfClose(); + return stream; + } + + makeBidiStreamRequest( + method: string, + serialize: (value: RequestType) => Buffer, + deserialize: (value: Buffer) => ResponseType, + metadata: Metadata, + options?: CallOptions + ): ClientDuplexStream; + makeBidiStreamRequest( + method: string, + serialize: (value: RequestType) => Buffer, + deserialize: (value: Buffer) => ResponseType, + options?: CallOptions + ): ClientDuplexStream; + makeBidiStreamRequest( + method: string, + serialize: (value: RequestType) => Buffer, + deserialize: (value: Buffer) => ResponseType, + metadata?: Metadata | CallOptions, + options?: CallOptions + ): ClientDuplexStream { + const checkedArguments = this.checkMetadataAndOptions(metadata, options); + const methodDefinition: ClientMethodDefinition = + { + path: method, + requestStream: true, + responseStream: true, + requestSerialize: serialize, + responseDeserialize: deserialize, + }; + let callProperties: CallProperties = { + metadata: checkedArguments.metadata, + call: new ClientDuplexStreamImpl( + serialize, + deserialize + ), + channel: this[CHANNEL_SYMBOL], + methodDefinition: methodDefinition, + callOptions: checkedArguments.options, + }; + if (this[CALL_INVOCATION_TRANSFORMER_SYMBOL]) { + callProperties = this[CALL_INVOCATION_TRANSFORMER_SYMBOL]!( + callProperties + ) as CallProperties; + } + const stream: ClientDuplexStream = + callProperties.call as ClientDuplexStream; + const interceptorArgs: InterceptorArguments = { + clientInterceptors: this[INTERCEPTOR_SYMBOL], + clientInterceptorProviders: this[INTERCEPTOR_PROVIDER_SYMBOL], + callInterceptors: callProperties.callOptions.interceptors ?? [], + callInterceptorProviders: + callProperties.callOptions.interceptor_providers ?? [], + }; + const call: InterceptingCallInterface = getInterceptingCall( + interceptorArgs, + callProperties.methodDefinition, + callProperties.callOptions, + callProperties.channel + ); + /* This needs to happen before the emitter is used. Unfortunately we can't + * enforce this with the type system. We need to construct this emitter + * before calling the CallInvocationTransformer, and we need to create the + * call after that. */ + stream.call = call; + let receivedStatus = false; + let callerStackError: Error | null = new Error(); + call.start(callProperties.metadata, { + onReceiveMetadata(metadata: Metadata) { + stream.emit('metadata', metadata); + }, + onReceiveMessage(message: Buffer) { + stream.push(message); + }, + onReceiveStatus(status: StatusObject) { + if (receivedStatus) { + return; + } + receivedStatus = true; + stream.push(null); + if (status.code !== Status.OK) { + const callerStack = getErrorStackString(callerStackError!); + stream.emit('error', callErrorFromStatus(status, callerStack)); + } + /* Avoid retaining the callerStackError object in the call context of + * the status event handler. */ + callerStackError = null; + stream.emit('status', status); + }, + }); + return stream; + } +} diff --git a/node_modules/@grpc/grpc-js/src/compression-algorithms.ts b/node_modules/@grpc/grpc-js/src/compression-algorithms.ts new file mode 100644 index 0000000..67fdcf1 --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/compression-algorithms.ts @@ -0,0 +1,22 @@ +/* + * Copyright 2021 gRPC authors. + * + * 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. + * + */ + +export enum CompressionAlgorithms { + identity = 0, + deflate = 1, + gzip = 2, +} diff --git a/node_modules/@grpc/grpc-js/src/compression-filter.ts b/node_modules/@grpc/grpc-js/src/compression-filter.ts new file mode 100644 index 0000000..136311a --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/compression-filter.ts @@ -0,0 +1,315 @@ +/* + * Copyright 2019 gRPC authors. + * + * 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. + * + */ + +import * as zlib from 'zlib'; + +import { WriteObject, WriteFlags } from './call-interface'; +import { Channel } from './channel'; +import { ChannelOptions } from './channel-options'; +import { CompressionAlgorithms } from './compression-algorithms'; +import { LogVerbosity } from './constants'; +import { BaseFilter, Filter, FilterFactory } from './filter'; +import * as logging from './logging'; +import { Metadata, MetadataValue } from './metadata'; + +const isCompressionAlgorithmKey = ( + key: number +): key is CompressionAlgorithms => { + return ( + typeof key === 'number' && typeof CompressionAlgorithms[key] === 'string' + ); +}; + +type CompressionAlgorithm = keyof typeof CompressionAlgorithms; + +type SharedCompressionFilterConfig = { + serverSupportedEncodingHeader?: string; +}; + +abstract class CompressionHandler { + protected abstract compressMessage(message: Buffer): Promise; + protected abstract decompressMessage(data: Buffer): Promise; + /** + * @param message Raw uncompressed message bytes + * @param compress Indicates whether the message should be compressed + * @return Framed message, compressed if applicable + */ + async writeMessage(message: Buffer, compress: boolean): Promise { + let messageBuffer = message; + if (compress) { + messageBuffer = await this.compressMessage(messageBuffer); + } + const output = Buffer.allocUnsafe(messageBuffer.length + 5); + output.writeUInt8(compress ? 1 : 0, 0); + output.writeUInt32BE(messageBuffer.length, 1); + messageBuffer.copy(output, 5); + return output; + } + /** + * @param data Framed message, possibly compressed + * @return Uncompressed message + */ + async readMessage(data: Buffer): Promise { + const compressed = data.readUInt8(0) === 1; + let messageBuffer = data.slice(5); + if (compressed) { + messageBuffer = await this.decompressMessage(messageBuffer); + } + return messageBuffer; + } +} + +class IdentityHandler extends CompressionHandler { + async compressMessage(message: Buffer) { + return message; + } + + async writeMessage(message: Buffer, compress: boolean): Promise { + const output = Buffer.allocUnsafe(message.length + 5); + /* With "identity" compression, messages should always be marked as + * uncompressed */ + output.writeUInt8(0, 0); + output.writeUInt32BE(message.length, 1); + message.copy(output, 5); + return output; + } + + decompressMessage(message: Buffer): Promise { + return Promise.reject( + new Error( + 'Received compressed message but "grpc-encoding" header was identity' + ) + ); + } +} + +class DeflateHandler extends CompressionHandler { + compressMessage(message: Buffer) { + return new Promise((resolve, reject) => { + zlib.deflate(message, (err, output) => { + if (err) { + reject(err); + } else { + resolve(output); + } + }); + }); + } + + decompressMessage(message: Buffer) { + return new Promise((resolve, reject) => { + zlib.inflate(message, (err, output) => { + if (err) { + reject(err); + } else { + resolve(output); + } + }); + }); + } +} + +class GzipHandler extends CompressionHandler { + compressMessage(message: Buffer) { + return new Promise((resolve, reject) => { + zlib.gzip(message, (err, output) => { + if (err) { + reject(err); + } else { + resolve(output); + } + }); + }); + } + + decompressMessage(message: Buffer) { + return new Promise((resolve, reject) => { + zlib.unzip(message, (err, output) => { + if (err) { + reject(err); + } else { + resolve(output); + } + }); + }); + } +} + +class UnknownHandler extends CompressionHandler { + constructor(private readonly compressionName: string) { + super(); + } + compressMessage(message: Buffer): Promise { + return Promise.reject( + new Error( + `Received message compressed with unsupported compression method ${this.compressionName}` + ) + ); + } + + decompressMessage(message: Buffer): Promise { + // This should be unreachable + return Promise.reject( + new Error(`Compression method not supported: ${this.compressionName}`) + ); + } +} + +function getCompressionHandler(compressionName: string): CompressionHandler { + switch (compressionName) { + case 'identity': + return new IdentityHandler(); + case 'deflate': + return new DeflateHandler(); + case 'gzip': + return new GzipHandler(); + default: + return new UnknownHandler(compressionName); + } +} + +export class CompressionFilter extends BaseFilter implements Filter { + private sendCompression: CompressionHandler = new IdentityHandler(); + private receiveCompression: CompressionHandler = new IdentityHandler(); + private currentCompressionAlgorithm: CompressionAlgorithm = 'identity'; + + constructor( + channelOptions: ChannelOptions, + private sharedFilterConfig: SharedCompressionFilterConfig + ) { + super(); + + const compressionAlgorithmKey = + channelOptions['grpc.default_compression_algorithm']; + if (compressionAlgorithmKey !== undefined) { + if (isCompressionAlgorithmKey(compressionAlgorithmKey)) { + const clientSelectedEncoding = CompressionAlgorithms[ + compressionAlgorithmKey + ] as CompressionAlgorithm; + const serverSupportedEncodings = + sharedFilterConfig.serverSupportedEncodingHeader?.split(','); + /** + * There are two possible situations here: + * 1) We don't have any info yet from the server about what compression it supports + * In that case we should just use what the client tells us to use + * 2) We've previously received a response from the server including a grpc-accept-encoding header + * In that case we only want to use the encoding chosen by the client if the server supports it + */ + if ( + !serverSupportedEncodings || + serverSupportedEncodings.includes(clientSelectedEncoding) + ) { + this.currentCompressionAlgorithm = clientSelectedEncoding; + this.sendCompression = getCompressionHandler( + this.currentCompressionAlgorithm + ); + } + } else { + logging.log( + LogVerbosity.ERROR, + `Invalid value provided for grpc.default_compression_algorithm option: ${compressionAlgorithmKey}` + ); + } + } + } + + async sendMetadata(metadata: Promise): Promise { + const headers: Metadata = await metadata; + headers.set('grpc-accept-encoding', 'identity,deflate,gzip'); + headers.set('accept-encoding', 'identity'); + + // No need to send the header if it's "identity" - behavior is identical; save the bandwidth + if (this.currentCompressionAlgorithm === 'identity') { + headers.remove('grpc-encoding'); + } else { + headers.set('grpc-encoding', this.currentCompressionAlgorithm); + } + + return headers; + } + + receiveMetadata(metadata: Metadata): Metadata { + const receiveEncoding: MetadataValue[] = metadata.get('grpc-encoding'); + if (receiveEncoding.length > 0) { + const encoding: MetadataValue = receiveEncoding[0]; + if (typeof encoding === 'string') { + this.receiveCompression = getCompressionHandler(encoding); + } + } + metadata.remove('grpc-encoding'); + + /* Check to see if the compression we're using to send messages is supported by the server + * If not, reset the sendCompression filter and have it use the default IdentityHandler */ + const serverSupportedEncodingsHeader = metadata.get( + 'grpc-accept-encoding' + )[0] as string | undefined; + if (serverSupportedEncodingsHeader) { + this.sharedFilterConfig.serverSupportedEncodingHeader = + serverSupportedEncodingsHeader; + const serverSupportedEncodings = + serverSupportedEncodingsHeader.split(','); + + if ( + !serverSupportedEncodings.includes(this.currentCompressionAlgorithm) + ) { + this.sendCompression = new IdentityHandler(); + this.currentCompressionAlgorithm = 'identity'; + } + } + metadata.remove('grpc-accept-encoding'); + return metadata; + } + + async sendMessage(message: Promise): Promise { + /* This filter is special. The input message is the bare message bytes, + * and the output is a framed and possibly compressed message. For this + * reason, this filter should be at the bottom of the filter stack */ + const resolvedMessage: WriteObject = await message; + let compress: boolean; + if (this.sendCompression instanceof IdentityHandler) { + compress = false; + } else { + compress = ((resolvedMessage.flags ?? 0) & WriteFlags.NoCompress) === 0; + } + + return { + message: await this.sendCompression.writeMessage( + resolvedMessage.message, + compress + ), + flags: resolvedMessage.flags, + }; + } + + async receiveMessage(message: Promise) { + /* This filter is also special. The input message is framed and possibly + * compressed, and the output message is deframed and uncompressed. So + * this is another reason that this filter should be at the bottom of the + * filter stack. */ + return this.receiveCompression.readMessage(await message); + } +} + +export class CompressionFilterFactory + implements FilterFactory +{ + private sharedFilterConfig: SharedCompressionFilterConfig = {}; + constructor(channel: Channel, private readonly options: ChannelOptions) {} + createFilter(): CompressionFilter { + return new CompressionFilter(this.options, this.sharedFilterConfig); + } +} diff --git a/node_modules/@grpc/grpc-js/src/connectivity-state.ts b/node_modules/@grpc/grpc-js/src/connectivity-state.ts new file mode 100644 index 0000000..560ab9c --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/connectivity-state.ts @@ -0,0 +1,24 @@ +/* + * Copyright 2021 gRPC authors. + * + * 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. + * + */ + +export enum ConnectivityState { + IDLE, + CONNECTING, + READY, + TRANSIENT_FAILURE, + SHUTDOWN, +} diff --git a/node_modules/@grpc/grpc-js/src/constants.ts b/node_modules/@grpc/grpc-js/src/constants.ts new file mode 100644 index 0000000..865b24c --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/constants.ts @@ -0,0 +1,66 @@ +/* + * Copyright 2019 gRPC authors. + * + * 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. + * + */ + +export enum Status { + OK = 0, + CANCELLED, + UNKNOWN, + INVALID_ARGUMENT, + DEADLINE_EXCEEDED, + NOT_FOUND, + ALREADY_EXISTS, + PERMISSION_DENIED, + RESOURCE_EXHAUSTED, + FAILED_PRECONDITION, + ABORTED, + OUT_OF_RANGE, + UNIMPLEMENTED, + INTERNAL, + UNAVAILABLE, + DATA_LOSS, + UNAUTHENTICATED, +} + +export enum LogVerbosity { + DEBUG = 0, + INFO, + ERROR, + NONE, +} + +/** + * NOTE: This enum is not currently used in any implemented API in this + * library. It is included only for type parity with the other implementation. + */ +export enum Propagate { + DEADLINE = 1, + CENSUS_STATS_CONTEXT = 2, + CENSUS_TRACING_CONTEXT = 4, + CANCELLATION = 8, + // https://github.com/grpc/grpc/blob/master/include/grpc/impl/codegen/propagation_bits.h#L43 + DEFAULTS = 0xffff | + Propagate.DEADLINE | + Propagate.CENSUS_STATS_CONTEXT | + Propagate.CENSUS_TRACING_CONTEXT | + Propagate.CANCELLATION, +} + +// -1 means unlimited +export const DEFAULT_MAX_SEND_MESSAGE_LENGTH = -1; + +// 4 MB default +export const DEFAULT_MAX_RECEIVE_MESSAGE_LENGTH = 4 * 1024 * 1024; diff --git a/node_modules/@grpc/grpc-js/src/control-plane-status.ts b/node_modules/@grpc/grpc-js/src/control-plane-status.ts new file mode 100644 index 0000000..1d10cb3 --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/control-plane-status.ts @@ -0,0 +1,43 @@ +/* + * Copyright 2022 gRPC authors. + * + * 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. + * + */ + +import { Status } from './constants'; + +const INAPPROPRIATE_CONTROL_PLANE_CODES: Status[] = [ + Status.OK, + Status.INVALID_ARGUMENT, + Status.NOT_FOUND, + Status.ALREADY_EXISTS, + Status.FAILED_PRECONDITION, + Status.ABORTED, + Status.OUT_OF_RANGE, + Status.DATA_LOSS, +]; + +export function restrictControlPlaneStatusCode( + code: Status, + details: string +): { code: Status; details: string } { + if (INAPPROPRIATE_CONTROL_PLANE_CODES.includes(code)) { + return { + code: Status.INTERNAL, + details: `Invalid status from control plane: ${code} ${Status[code]} ${details}`, + }; + } else { + return { code, details }; + } +} diff --git a/node_modules/@grpc/grpc-js/src/deadline.ts b/node_modules/@grpc/grpc-js/src/deadline.ts new file mode 100644 index 0000000..de05e38 --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/deadline.ts @@ -0,0 +1,106 @@ +/* + * Copyright 2019 gRPC authors. + * + * 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. + * + */ + +export type Deadline = Date | number; + +export function minDeadline(...deadlineList: Deadline[]): Deadline { + let minValue = Infinity; + for (const deadline of deadlineList) { + const deadlineMsecs = + deadline instanceof Date ? deadline.getTime() : deadline; + if (deadlineMsecs < minValue) { + minValue = deadlineMsecs; + } + } + return minValue; +} + +const units: Array<[string, number]> = [ + ['m', 1], + ['S', 1000], + ['M', 60 * 1000], + ['H', 60 * 60 * 1000], +]; + +export function getDeadlineTimeoutString(deadline: Deadline) { + const now = new Date().getTime(); + if (deadline instanceof Date) { + deadline = deadline.getTime(); + } + const timeoutMs = Math.max(deadline - now, 0); + for (const [unit, factor] of units) { + const amount = timeoutMs / factor; + if (amount < 1e8) { + return String(Math.ceil(amount)) + unit; + } + } + throw new Error('Deadline is too far in the future'); +} + +/** + * See https://nodejs.org/api/timers.html#settimeoutcallback-delay-args + * In particular, "When delay is larger than 2147483647 or less than 1, the + * delay will be set to 1. Non-integer delays are truncated to an integer." + * This number of milliseconds is almost 25 days. + */ +const MAX_TIMEOUT_TIME = 2147483647; + +/** + * Get the timeout value that should be passed to setTimeout now for the timer + * to end at the deadline. For any deadline before now, the timer should end + * immediately, represented by a value of 0. For any deadline more than + * MAX_TIMEOUT_TIME milliseconds in the future, a timer cannot be set that will + * end at that time, so it is treated as infinitely far in the future. + * @param deadline + * @returns + */ +export function getRelativeTimeout(deadline: Deadline) { + const deadlineMs = deadline instanceof Date ? deadline.getTime() : deadline; + const now = new Date().getTime(); + const timeout = deadlineMs - now; + if (timeout < 0) { + return 0; + } else if (timeout > MAX_TIMEOUT_TIME) { + return Infinity; + } else { + return timeout; + } +} + +export function deadlineToString(deadline: Deadline): string { + if (deadline instanceof Date) { + return deadline.toISOString(); + } else { + const dateDeadline = new Date(deadline); + if (Number.isNaN(dateDeadline.getTime())) { + return '' + deadline; + } else { + return dateDeadline.toISOString(); + } + } +} + +/** + * Calculate the difference between two dates as a number of seconds and format + * it as a string. + * @param startDate + * @param endDate + * @returns + */ +export function formatDateDifference(startDate: Date, endDate: Date): string { + return ((endDate.getTime() - startDate.getTime()) / 1000).toFixed(3) + 's'; +} diff --git a/node_modules/@grpc/grpc-js/src/duration.ts b/node_modules/@grpc/grpc-js/src/duration.ts new file mode 100644 index 0000000..ff77dba --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/duration.ts @@ -0,0 +1,36 @@ +/* + * Copyright 2022 gRPC authors. + * + * 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. + * + */ + +export interface Duration { + seconds: number; + nanos: number; +} + +export function msToDuration(millis: number): Duration { + return { + seconds: (millis / 1000) | 0, + nanos: ((millis % 1000) * 1_000_000) | 0, + }; +} + +export function durationToMs(duration: Duration): number { + return (duration.seconds * 1000 + duration.nanos / 1_000_000) | 0; +} + +export function isDuration(value: any): value is Duration { + return typeof value.seconds === 'number' && typeof value.nanos === 'number'; +} diff --git a/node_modules/@grpc/grpc-js/src/error.ts b/node_modules/@grpc/grpc-js/src/error.ts new file mode 100644 index 0000000..105a3ee --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/error.ts @@ -0,0 +1,37 @@ +/* + * Copyright 2022 gRPC authors. + * + * 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. + * + */ + +export function getErrorMessage(error: unknown): string { + if (error instanceof Error) { + return error.message; + } else { + return String(error); + } +} + +export function getErrorCode(error: unknown): number | null { + if ( + typeof error === 'object' && + error !== null && + 'code' in error && + typeof (error as Record).code === 'number' + ) { + return (error as Record).code; + } else { + return null; + } +} diff --git a/node_modules/@grpc/grpc-js/src/events.ts b/node_modules/@grpc/grpc-js/src/events.ts new file mode 100644 index 0000000..7718746 --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/events.ts @@ -0,0 +1,26 @@ +/* + * Copyright 2019 gRPC authors. + * + * 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. + * + */ + +export interface EmitterAugmentation1 { + addListener(event: Name, listener: (arg1: Arg) => void): this; + emit(event: Name, arg1: Arg): boolean; + on(event: Name, listener: (arg1: Arg) => void): this; + once(event: Name, listener: (arg1: Arg) => void): this; + prependListener(event: Name, listener: (arg1: Arg) => void): this; + prependOnceListener(event: Name, listener: (arg1: Arg) => void): this; + removeListener(event: Name, listener: (arg1: Arg) => void): this; +} diff --git a/node_modules/@grpc/grpc-js/src/experimental.ts b/node_modules/@grpc/grpc-js/src/experimental.ts new file mode 100644 index 0000000..1e7a1e1 --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/experimental.ts @@ -0,0 +1,54 @@ +export { trace, log } from './logging'; +export { + Resolver, + ResolverListener, + registerResolver, + ConfigSelector, + createResolver, +} from './resolver'; +export { GrpcUri, uriToString } from './uri-parser'; +export { Duration, durationToMs } from './duration'; +export { BackoffTimeout } from './backoff-timeout'; +export { + LoadBalancer, + TypedLoadBalancingConfig, + ChannelControlHelper, + createChildChannelControlHelper, + registerLoadBalancerType, + selectLbConfigFromList, + parseLoadBalancingConfig, + isLoadBalancerNameRegistered, +} from './load-balancer'; +export { LeafLoadBalancer } from './load-balancer-pick-first'; +export { + SubchannelAddress, + subchannelAddressToString, + Endpoint, + endpointToString, + endpointHasAddress, + EndpointMap, +} from './subchannel-address'; +export { ChildLoadBalancerHandler } from './load-balancer-child-handler'; +export { + Picker, + UnavailablePicker, + QueuePicker, + PickResult, + PickArgs, + PickResultType, +} from './picker'; +export { Call as CallStream } from './call-interface'; +export { Filter, BaseFilter, FilterFactory } from './filter'; +export { FilterStackFactory } from './filter-stack'; +export { registerAdminService } from './admin'; +export { + SubchannelInterface, + BaseSubchannelWrapper, + ConnectivityStateListener, + HealthListener, +} from './subchannel-interface'; +export { + OutlierDetectionRawConfig, + SuccessRateEjectionConfig, + FailurePercentageEjectionConfig, +} from './load-balancer-outlier-detection'; diff --git a/node_modules/@grpc/grpc-js/src/filter-stack.ts b/node_modules/@grpc/grpc-js/src/filter-stack.ts new file mode 100644 index 0000000..910f5aa --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/filter-stack.ts @@ -0,0 +1,100 @@ +/* + * Copyright 2019 gRPC authors. + * + * 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. + * + */ + +import { StatusObject, WriteObject } from './call-interface'; +import { Filter, FilterFactory } from './filter'; +import { Metadata } from './metadata'; + +export class FilterStack implements Filter { + constructor(private readonly filters: Filter[]) {} + + sendMetadata(metadata: Promise): Promise { + let result: Promise = metadata; + + for (let i = 0; i < this.filters.length; i++) { + result = this.filters[i].sendMetadata(result); + } + + return result; + } + + receiveMetadata(metadata: Metadata) { + let result: Metadata = metadata; + + for (let i = this.filters.length - 1; i >= 0; i--) { + result = this.filters[i].receiveMetadata(result); + } + + return result; + } + + sendMessage(message: Promise): Promise { + let result: Promise = message; + + for (let i = 0; i < this.filters.length; i++) { + result = this.filters[i].sendMessage(result); + } + + return result; + } + + receiveMessage(message: Promise): Promise { + let result: Promise = message; + + for (let i = this.filters.length - 1; i >= 0; i--) { + result = this.filters[i].receiveMessage(result); + } + + return result; + } + + receiveTrailers(status: StatusObject): StatusObject { + let result: StatusObject = status; + + for (let i = this.filters.length - 1; i >= 0; i--) { + result = this.filters[i].receiveTrailers(result); + } + + return result; + } + + push(filters: Filter[]) { + this.filters.unshift(...filters); + } + + getFilters(): Filter[] { + return this.filters; + } +} + +export class FilterStackFactory implements FilterFactory { + constructor(private readonly factories: Array>) {} + + push(filterFactories: FilterFactory[]) { + this.factories.unshift(...filterFactories); + } + + clone(): FilterStackFactory { + return new FilterStackFactory([...this.factories]); + } + + createFilter(): FilterStack { + return new FilterStack( + this.factories.map(factory => factory.createFilter()) + ); + } +} diff --git a/node_modules/@grpc/grpc-js/src/filter.ts b/node_modules/@grpc/grpc-js/src/filter.ts new file mode 100644 index 0000000..5313f91 --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/filter.ts @@ -0,0 +1,63 @@ +/* + * Copyright 2019 gRPC authors. + * + * 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. + * + */ + +import { StatusObject, WriteObject } from './call-interface'; +import { Metadata } from './metadata'; + +/** + * Filter classes represent related per-call logic and state that is primarily + * used to modify incoming and outgoing data. All async filters can be + * rejected. The rejection error must be a StatusObject, and a rejection will + * cause the call to end with that status. + */ +export interface Filter { + sendMetadata(metadata: Promise): Promise; + + receiveMetadata(metadata: Metadata): Metadata; + + sendMessage(message: Promise): Promise; + + receiveMessage(message: Promise): Promise; + + receiveTrailers(status: StatusObject): StatusObject; +} + +export abstract class BaseFilter implements Filter { + async sendMetadata(metadata: Promise): Promise { + return metadata; + } + + receiveMetadata(metadata: Metadata): Metadata { + return metadata; + } + + async sendMessage(message: Promise): Promise { + return message; + } + + async receiveMessage(message: Promise): Promise { + return message; + } + + receiveTrailers(status: StatusObject): StatusObject { + return status; + } +} + +export interface FilterFactory { + createFilter(): T; +} diff --git a/node_modules/@grpc/grpc-js/src/generated/channelz.ts b/node_modules/@grpc/grpc-js/src/generated/channelz.ts new file mode 100644 index 0000000..367cf27 --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/generated/channelz.ts @@ -0,0 +1,73 @@ +import type * as grpc from '../index'; +import type { MessageTypeDefinition } from '@grpc/proto-loader'; + +import type { ChannelzClient as _grpc_channelz_v1_ChannelzClient, ChannelzDefinition as _grpc_channelz_v1_ChannelzDefinition } from './grpc/channelz/v1/Channelz'; + +type SubtypeConstructor any, Subtype> = { + new(...args: ConstructorParameters): Subtype; +}; + +export interface ProtoGrpcType { + google: { + protobuf: { + Any: MessageTypeDefinition + BoolValue: MessageTypeDefinition + BytesValue: MessageTypeDefinition + DoubleValue: MessageTypeDefinition + Duration: MessageTypeDefinition + FloatValue: MessageTypeDefinition + Int32Value: MessageTypeDefinition + Int64Value: MessageTypeDefinition + StringValue: MessageTypeDefinition + Timestamp: MessageTypeDefinition + UInt32Value: MessageTypeDefinition + UInt64Value: MessageTypeDefinition + } + } + grpc: { + channelz: { + v1: { + Address: MessageTypeDefinition + Channel: MessageTypeDefinition + ChannelConnectivityState: MessageTypeDefinition + ChannelData: MessageTypeDefinition + ChannelRef: MessageTypeDefinition + ChannelTrace: MessageTypeDefinition + ChannelTraceEvent: MessageTypeDefinition + /** + * Channelz is a service exposed by gRPC servers that provides detailed debug + * information. + */ + Channelz: SubtypeConstructor & { service: _grpc_channelz_v1_ChannelzDefinition } + GetChannelRequest: MessageTypeDefinition + GetChannelResponse: MessageTypeDefinition + GetServerRequest: MessageTypeDefinition + GetServerResponse: MessageTypeDefinition + GetServerSocketsRequest: MessageTypeDefinition + GetServerSocketsResponse: MessageTypeDefinition + GetServersRequest: MessageTypeDefinition + GetServersResponse: MessageTypeDefinition + GetSocketRequest: MessageTypeDefinition + GetSocketResponse: MessageTypeDefinition + GetSubchannelRequest: MessageTypeDefinition + GetSubchannelResponse: MessageTypeDefinition + GetTopChannelsRequest: MessageTypeDefinition + GetTopChannelsResponse: MessageTypeDefinition + Security: MessageTypeDefinition + Server: MessageTypeDefinition + ServerData: MessageTypeDefinition + ServerRef: MessageTypeDefinition + Socket: MessageTypeDefinition + SocketData: MessageTypeDefinition + SocketOption: MessageTypeDefinition + SocketOptionLinger: MessageTypeDefinition + SocketOptionTcpInfo: MessageTypeDefinition + SocketOptionTimeout: MessageTypeDefinition + SocketRef: MessageTypeDefinition + Subchannel: MessageTypeDefinition + SubchannelRef: MessageTypeDefinition + } + } + } +} + diff --git a/node_modules/@grpc/grpc-js/src/generated/google/protobuf/Any.ts b/node_modules/@grpc/grpc-js/src/generated/google/protobuf/Any.ts new file mode 100644 index 0000000..fcaa672 --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/generated/google/protobuf/Any.ts @@ -0,0 +1,13 @@ +// Original file: null + +import type { AnyExtension } from '@grpc/proto-loader'; + +export type Any = AnyExtension | { + type_url: string; + value: Buffer | Uint8Array | string; +} + +export interface Any__Output { + 'type_url': (string); + 'value': (Buffer); +} diff --git a/node_modules/@grpc/grpc-js/src/generated/google/protobuf/BoolValue.ts b/node_modules/@grpc/grpc-js/src/generated/google/protobuf/BoolValue.ts new file mode 100644 index 0000000..86507ea --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/generated/google/protobuf/BoolValue.ts @@ -0,0 +1,10 @@ +// Original file: null + + +export interface BoolValue { + 'value'?: (boolean); +} + +export interface BoolValue__Output { + 'value': (boolean); +} diff --git a/node_modules/@grpc/grpc-js/src/generated/google/protobuf/BytesValue.ts b/node_modules/@grpc/grpc-js/src/generated/google/protobuf/BytesValue.ts new file mode 100644 index 0000000..9cec76f --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/generated/google/protobuf/BytesValue.ts @@ -0,0 +1,10 @@ +// Original file: null + + +export interface BytesValue { + 'value'?: (Buffer | Uint8Array | string); +} + +export interface BytesValue__Output { + 'value': (Buffer); +} diff --git a/node_modules/@grpc/grpc-js/src/generated/google/protobuf/DoubleValue.ts b/node_modules/@grpc/grpc-js/src/generated/google/protobuf/DoubleValue.ts new file mode 100644 index 0000000..d70b303 --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/generated/google/protobuf/DoubleValue.ts @@ -0,0 +1,10 @@ +// Original file: null + + +export interface DoubleValue { + 'value'?: (number | string); +} + +export interface DoubleValue__Output { + 'value': (number); +} diff --git a/node_modules/@grpc/grpc-js/src/generated/google/protobuf/Duration.ts b/node_modules/@grpc/grpc-js/src/generated/google/protobuf/Duration.ts new file mode 100644 index 0000000..8595377 --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/generated/google/protobuf/Duration.ts @@ -0,0 +1,13 @@ +// Original file: null + +import type { Long } from '@grpc/proto-loader'; + +export interface Duration { + 'seconds'?: (number | string | Long); + 'nanos'?: (number); +} + +export interface Duration__Output { + 'seconds': (string); + 'nanos': (number); +} diff --git a/node_modules/@grpc/grpc-js/src/generated/google/protobuf/FloatValue.ts b/node_modules/@grpc/grpc-js/src/generated/google/protobuf/FloatValue.ts new file mode 100644 index 0000000..54a655f --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/generated/google/protobuf/FloatValue.ts @@ -0,0 +1,10 @@ +// Original file: null + + +export interface FloatValue { + 'value'?: (number | string); +} + +export interface FloatValue__Output { + 'value': (number); +} diff --git a/node_modules/@grpc/grpc-js/src/generated/google/protobuf/Int32Value.ts b/node_modules/@grpc/grpc-js/src/generated/google/protobuf/Int32Value.ts new file mode 100644 index 0000000..ec4eeb7 --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/generated/google/protobuf/Int32Value.ts @@ -0,0 +1,10 @@ +// Original file: null + + +export interface Int32Value { + 'value'?: (number); +} + +export interface Int32Value__Output { + 'value': (number); +} diff --git a/node_modules/@grpc/grpc-js/src/generated/google/protobuf/Int64Value.ts b/node_modules/@grpc/grpc-js/src/generated/google/protobuf/Int64Value.ts new file mode 100644 index 0000000..f737519 --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/generated/google/protobuf/Int64Value.ts @@ -0,0 +1,11 @@ +// Original file: null + +import type { Long } from '@grpc/proto-loader'; + +export interface Int64Value { + 'value'?: (number | string | Long); +} + +export interface Int64Value__Output { + 'value': (string); +} diff --git a/node_modules/@grpc/grpc-js/src/generated/google/protobuf/StringValue.ts b/node_modules/@grpc/grpc-js/src/generated/google/protobuf/StringValue.ts new file mode 100644 index 0000000..673090e --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/generated/google/protobuf/StringValue.ts @@ -0,0 +1,10 @@ +// Original file: null + + +export interface StringValue { + 'value'?: (string); +} + +export interface StringValue__Output { + 'value': (string); +} diff --git a/node_modules/@grpc/grpc-js/src/generated/google/protobuf/Timestamp.ts b/node_modules/@grpc/grpc-js/src/generated/google/protobuf/Timestamp.ts new file mode 100644 index 0000000..ceaa32b --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/generated/google/protobuf/Timestamp.ts @@ -0,0 +1,13 @@ +// Original file: null + +import type { Long } from '@grpc/proto-loader'; + +export interface Timestamp { + 'seconds'?: (number | string | Long); + 'nanos'?: (number); +} + +export interface Timestamp__Output { + 'seconds': (string); + 'nanos': (number); +} diff --git a/node_modules/@grpc/grpc-js/src/generated/google/protobuf/UInt32Value.ts b/node_modules/@grpc/grpc-js/src/generated/google/protobuf/UInt32Value.ts new file mode 100644 index 0000000..973ab34 --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/generated/google/protobuf/UInt32Value.ts @@ -0,0 +1,10 @@ +// Original file: null + + +export interface UInt32Value { + 'value'?: (number); +} + +export interface UInt32Value__Output { + 'value': (number); +} diff --git a/node_modules/@grpc/grpc-js/src/generated/google/protobuf/UInt64Value.ts b/node_modules/@grpc/grpc-js/src/generated/google/protobuf/UInt64Value.ts new file mode 100644 index 0000000..7a85c39 --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/generated/google/protobuf/UInt64Value.ts @@ -0,0 +1,11 @@ +// Original file: null + +import type { Long } from '@grpc/proto-loader'; + +export interface UInt64Value { + 'value'?: (number | string | Long); +} + +export interface UInt64Value__Output { + 'value': (string); +} diff --git a/node_modules/@grpc/grpc-js/src/generated/grpc/channelz/v1/Address.ts b/node_modules/@grpc/grpc-js/src/generated/grpc/channelz/v1/Address.ts new file mode 100644 index 0000000..259cfea --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/generated/grpc/channelz/v1/Address.ts @@ -0,0 +1,89 @@ +// Original file: proto/channelz.proto + +import type { Any as _google_protobuf_Any, Any__Output as _google_protobuf_Any__Output } from '../../../google/protobuf/Any'; + +/** + * An address type not included above. + */ +export interface _grpc_channelz_v1_Address_OtherAddress { + /** + * The human readable version of the value. This value should be set. + */ + 'name'?: (string); + /** + * The actual address message. + */ + 'value'?: (_google_protobuf_Any | null); +} + +/** + * An address type not included above. + */ +export interface _grpc_channelz_v1_Address_OtherAddress__Output { + /** + * The human readable version of the value. This value should be set. + */ + 'name': (string); + /** + * The actual address message. + */ + 'value': (_google_protobuf_Any__Output | null); +} + +export interface _grpc_channelz_v1_Address_TcpIpAddress { + /** + * Either the IPv4 or IPv6 address in bytes. Will be either 4 bytes or 16 + * bytes in length. + */ + 'ip_address'?: (Buffer | Uint8Array | string); + /** + * 0-64k, or -1 if not appropriate. + */ + 'port'?: (number); +} + +export interface _grpc_channelz_v1_Address_TcpIpAddress__Output { + /** + * Either the IPv4 or IPv6 address in bytes. Will be either 4 bytes or 16 + * bytes in length. + */ + 'ip_address': (Buffer); + /** + * 0-64k, or -1 if not appropriate. + */ + 'port': (number); +} + +/** + * A Unix Domain Socket address. + */ +export interface _grpc_channelz_v1_Address_UdsAddress { + 'filename'?: (string); +} + +/** + * A Unix Domain Socket address. + */ +export interface _grpc_channelz_v1_Address_UdsAddress__Output { + 'filename': (string); +} + +/** + * Address represents the address used to create the socket. + */ +export interface Address { + 'tcpip_address'?: (_grpc_channelz_v1_Address_TcpIpAddress | null); + 'uds_address'?: (_grpc_channelz_v1_Address_UdsAddress | null); + 'other_address'?: (_grpc_channelz_v1_Address_OtherAddress | null); + 'address'?: "tcpip_address"|"uds_address"|"other_address"; +} + +/** + * Address represents the address used to create the socket. + */ +export interface Address__Output { + 'tcpip_address'?: (_grpc_channelz_v1_Address_TcpIpAddress__Output | null); + 'uds_address'?: (_grpc_channelz_v1_Address_UdsAddress__Output | null); + 'other_address'?: (_grpc_channelz_v1_Address_OtherAddress__Output | null); + 'address': "tcpip_address"|"uds_address"|"other_address"; +} diff --git a/node_modules/@grpc/grpc-js/src/generated/grpc/channelz/v1/Channel.ts b/node_modules/@grpc/grpc-js/src/generated/grpc/channelz/v1/Channel.ts new file mode 100644 index 0000000..93b4a26 --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/generated/grpc/channelz/v1/Channel.ts @@ -0,0 +1,68 @@ +// Original file: proto/channelz.proto + +import type { ChannelRef as _grpc_channelz_v1_ChannelRef, ChannelRef__Output as _grpc_channelz_v1_ChannelRef__Output } from '../../../grpc/channelz/v1/ChannelRef'; +import type { ChannelData as _grpc_channelz_v1_ChannelData, ChannelData__Output as _grpc_channelz_v1_ChannelData__Output } from '../../../grpc/channelz/v1/ChannelData'; +import type { SubchannelRef as _grpc_channelz_v1_SubchannelRef, SubchannelRef__Output as _grpc_channelz_v1_SubchannelRef__Output } from '../../../grpc/channelz/v1/SubchannelRef'; +import type { SocketRef as _grpc_channelz_v1_SocketRef, SocketRef__Output as _grpc_channelz_v1_SocketRef__Output } from '../../../grpc/channelz/v1/SocketRef'; + +/** + * Channel is a logical grouping of channels, subchannels, and sockets. + */ +export interface Channel { + /** + * The identifier for this channel. This should bet set. + */ + 'ref'?: (_grpc_channelz_v1_ChannelRef | null); + /** + * Data specific to this channel. + */ + 'data'?: (_grpc_channelz_v1_ChannelData | null); + /** + * There are no ordering guarantees on the order of channel refs. + * There may not be cycles in the ref graph. + * A channel ref may be present in more than one channel or subchannel. + */ + 'channel_ref'?: (_grpc_channelz_v1_ChannelRef)[]; + /** + * At most one of 'channel_ref+subchannel_ref' and 'socket' is set. + * There are no ordering guarantees on the order of subchannel refs. + * There may not be cycles in the ref graph. + * A sub channel ref may be present in more than one channel or subchannel. + */ + 'subchannel_ref'?: (_grpc_channelz_v1_SubchannelRef)[]; + /** + * There are no ordering guarantees on the order of sockets. + */ + 'socket_ref'?: (_grpc_channelz_v1_SocketRef)[]; +} + +/** + * Channel is a logical grouping of channels, subchannels, and sockets. + */ +export interface Channel__Output { + /** + * The identifier for this channel. This should bet set. + */ + 'ref': (_grpc_channelz_v1_ChannelRef__Output | null); + /** + * Data specific to this channel. + */ + 'data': (_grpc_channelz_v1_ChannelData__Output | null); + /** + * There are no ordering guarantees on the order of channel refs. + * There may not be cycles in the ref graph. + * A channel ref may be present in more than one channel or subchannel. + */ + 'channel_ref': (_grpc_channelz_v1_ChannelRef__Output)[]; + /** + * At most one of 'channel_ref+subchannel_ref' and 'socket' is set. + * There are no ordering guarantees on the order of subchannel refs. + * There may not be cycles in the ref graph. + * A sub channel ref may be present in more than one channel or subchannel. + */ + 'subchannel_ref': (_grpc_channelz_v1_SubchannelRef__Output)[]; + /** + * There are no ordering guarantees on the order of sockets. + */ + 'socket_ref': (_grpc_channelz_v1_SocketRef__Output)[]; +} diff --git a/node_modules/@grpc/grpc-js/src/generated/grpc/channelz/v1/ChannelConnectivityState.ts b/node_modules/@grpc/grpc-js/src/generated/grpc/channelz/v1/ChannelConnectivityState.ts new file mode 100644 index 0000000..78fb069 --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/generated/grpc/channelz/v1/ChannelConnectivityState.ts @@ -0,0 +1,45 @@ +// Original file: proto/channelz.proto + + +// Original file: proto/channelz.proto + +export const _grpc_channelz_v1_ChannelConnectivityState_State = { + UNKNOWN: 'UNKNOWN', + IDLE: 'IDLE', + CONNECTING: 'CONNECTING', + READY: 'READY', + TRANSIENT_FAILURE: 'TRANSIENT_FAILURE', + SHUTDOWN: 'SHUTDOWN', +} as const; + +export type _grpc_channelz_v1_ChannelConnectivityState_State = + | 'UNKNOWN' + | 0 + | 'IDLE' + | 1 + | 'CONNECTING' + | 2 + | 'READY' + | 3 + | 'TRANSIENT_FAILURE' + | 4 + | 'SHUTDOWN' + | 5 + +export type _grpc_channelz_v1_ChannelConnectivityState_State__Output = typeof _grpc_channelz_v1_ChannelConnectivityState_State[keyof typeof _grpc_channelz_v1_ChannelConnectivityState_State] + +/** + * These come from the specified states in this document: + * https://github.com/grpc/grpc/blob/master/doc/connectivity-semantics-and-api.md + */ +export interface ChannelConnectivityState { + 'state'?: (_grpc_channelz_v1_ChannelConnectivityState_State); +} + +/** + * These come from the specified states in this document: + * https://github.com/grpc/grpc/blob/master/doc/connectivity-semantics-and-api.md + */ +export interface ChannelConnectivityState__Output { + 'state': (_grpc_channelz_v1_ChannelConnectivityState_State__Output); +} diff --git a/node_modules/@grpc/grpc-js/src/generated/grpc/channelz/v1/ChannelData.ts b/node_modules/@grpc/grpc-js/src/generated/grpc/channelz/v1/ChannelData.ts new file mode 100644 index 0000000..6d6824a --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/generated/grpc/channelz/v1/ChannelData.ts @@ -0,0 +1,76 @@ +// Original file: proto/channelz.proto + +import type { ChannelConnectivityState as _grpc_channelz_v1_ChannelConnectivityState, ChannelConnectivityState__Output as _grpc_channelz_v1_ChannelConnectivityState__Output } from '../../../grpc/channelz/v1/ChannelConnectivityState'; +import type { ChannelTrace as _grpc_channelz_v1_ChannelTrace, ChannelTrace__Output as _grpc_channelz_v1_ChannelTrace__Output } from '../../../grpc/channelz/v1/ChannelTrace'; +import type { Timestamp as _google_protobuf_Timestamp, Timestamp__Output as _google_protobuf_Timestamp__Output } from '../../../google/protobuf/Timestamp'; +import type { Long } from '@grpc/proto-loader'; + +/** + * Channel data is data related to a specific Channel or Subchannel. + */ +export interface ChannelData { + /** + * The connectivity state of the channel or subchannel. Implementations + * should always set this. + */ + 'state'?: (_grpc_channelz_v1_ChannelConnectivityState | null); + /** + * The target this channel originally tried to connect to. May be absent + */ + 'target'?: (string); + /** + * A trace of recent events on the channel. May be absent. + */ + 'trace'?: (_grpc_channelz_v1_ChannelTrace | null); + /** + * The number of calls started on the channel + */ + 'calls_started'?: (number | string | Long); + /** + * The number of calls that have completed with an OK status + */ + 'calls_succeeded'?: (number | string | Long); + /** + * The number of calls that have completed with a non-OK status + */ + 'calls_failed'?: (number | string | Long); + /** + * The last time a call was started on the channel. + */ + 'last_call_started_timestamp'?: (_google_protobuf_Timestamp | null); +} + +/** + * Channel data is data related to a specific Channel or Subchannel. + */ +export interface ChannelData__Output { + /** + * The connectivity state of the channel or subchannel. Implementations + * should always set this. + */ + 'state': (_grpc_channelz_v1_ChannelConnectivityState__Output | null); + /** + * The target this channel originally tried to connect to. May be absent + */ + 'target': (string); + /** + * A trace of recent events on the channel. May be absent. + */ + 'trace': (_grpc_channelz_v1_ChannelTrace__Output | null); + /** + * The number of calls started on the channel + */ + 'calls_started': (string); + /** + * The number of calls that have completed with an OK status + */ + 'calls_succeeded': (string); + /** + * The number of calls that have completed with a non-OK status + */ + 'calls_failed': (string); + /** + * The last time a call was started on the channel. + */ + 'last_call_started_timestamp': (_google_protobuf_Timestamp__Output | null); +} diff --git a/node_modules/@grpc/grpc-js/src/generated/grpc/channelz/v1/ChannelRef.ts b/node_modules/@grpc/grpc-js/src/generated/grpc/channelz/v1/ChannelRef.ts new file mode 100644 index 0000000..231d008 --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/generated/grpc/channelz/v1/ChannelRef.ts @@ -0,0 +1,31 @@ +// Original file: proto/channelz.proto + +import type { Long } from '@grpc/proto-loader'; + +/** + * ChannelRef is a reference to a Channel. + */ +export interface ChannelRef { + /** + * The globally unique id for this channel. Must be a positive number. + */ + 'channel_id'?: (number | string | Long); + /** + * An optional name associated with the channel. + */ + 'name'?: (string); +} + +/** + * ChannelRef is a reference to a Channel. + */ +export interface ChannelRef__Output { + /** + * The globally unique id for this channel. Must be a positive number. + */ + 'channel_id': (string); + /** + * An optional name associated with the channel. + */ + 'name': (string); +} diff --git a/node_modules/@grpc/grpc-js/src/generated/grpc/channelz/v1/ChannelTrace.ts b/node_modules/@grpc/grpc-js/src/generated/grpc/channelz/v1/ChannelTrace.ts new file mode 100644 index 0000000..7dbc8d9 --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/generated/grpc/channelz/v1/ChannelTrace.ts @@ -0,0 +1,45 @@ +// Original file: proto/channelz.proto + +import type { Timestamp as _google_protobuf_Timestamp, Timestamp__Output as _google_protobuf_Timestamp__Output } from '../../../google/protobuf/Timestamp'; +import type { ChannelTraceEvent as _grpc_channelz_v1_ChannelTraceEvent, ChannelTraceEvent__Output as _grpc_channelz_v1_ChannelTraceEvent__Output } from '../../../grpc/channelz/v1/ChannelTraceEvent'; +import type { Long } from '@grpc/proto-loader'; + +/** + * ChannelTrace represents the recent events that have occurred on the channel. + */ +export interface ChannelTrace { + /** + * Number of events ever logged in this tracing object. This can differ from + * events.size() because events can be overwritten or garbage collected by + * implementations. + */ + 'num_events_logged'?: (number | string | Long); + /** + * Time that this channel was created. + */ + 'creation_timestamp'?: (_google_protobuf_Timestamp | null); + /** + * List of events that have occurred on this channel. + */ + 'events'?: (_grpc_channelz_v1_ChannelTraceEvent)[]; +} + +/** + * ChannelTrace represents the recent events that have occurred on the channel. + */ +export interface ChannelTrace__Output { + /** + * Number of events ever logged in this tracing object. This can differ from + * events.size() because events can be overwritten or garbage collected by + * implementations. + */ + 'num_events_logged': (string); + /** + * Time that this channel was created. + */ + 'creation_timestamp': (_google_protobuf_Timestamp__Output | null); + /** + * List of events that have occurred on this channel. + */ + 'events': (_grpc_channelz_v1_ChannelTraceEvent__Output)[]; +} diff --git a/node_modules/@grpc/grpc-js/src/generated/grpc/channelz/v1/ChannelTraceEvent.ts b/node_modules/@grpc/grpc-js/src/generated/grpc/channelz/v1/ChannelTraceEvent.ts new file mode 100644 index 0000000..403e4f1 --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/generated/grpc/channelz/v1/ChannelTraceEvent.ts @@ -0,0 +1,91 @@ +// Original file: proto/channelz.proto + +import type { Timestamp as _google_protobuf_Timestamp, Timestamp__Output as _google_protobuf_Timestamp__Output } from '../../../google/protobuf/Timestamp'; +import type { ChannelRef as _grpc_channelz_v1_ChannelRef, ChannelRef__Output as _grpc_channelz_v1_ChannelRef__Output } from '../../../grpc/channelz/v1/ChannelRef'; +import type { SubchannelRef as _grpc_channelz_v1_SubchannelRef, SubchannelRef__Output as _grpc_channelz_v1_SubchannelRef__Output } from '../../../grpc/channelz/v1/SubchannelRef'; + +// Original file: proto/channelz.proto + +/** + * The supported severity levels of trace events. + */ +export const _grpc_channelz_v1_ChannelTraceEvent_Severity = { + CT_UNKNOWN: 'CT_UNKNOWN', + CT_INFO: 'CT_INFO', + CT_WARNING: 'CT_WARNING', + CT_ERROR: 'CT_ERROR', +} as const; + +/** + * The supported severity levels of trace events. + */ +export type _grpc_channelz_v1_ChannelTraceEvent_Severity = + | 'CT_UNKNOWN' + | 0 + | 'CT_INFO' + | 1 + | 'CT_WARNING' + | 2 + | 'CT_ERROR' + | 3 + +/** + * The supported severity levels of trace events. + */ +export type _grpc_channelz_v1_ChannelTraceEvent_Severity__Output = typeof _grpc_channelz_v1_ChannelTraceEvent_Severity[keyof typeof _grpc_channelz_v1_ChannelTraceEvent_Severity] + +/** + * A trace event is an interesting thing that happened to a channel or + * subchannel, such as creation, address resolution, subchannel creation, etc. + */ +export interface ChannelTraceEvent { + /** + * High level description of the event. + */ + 'description'?: (string); + /** + * the severity of the trace event + */ + 'severity'?: (_grpc_channelz_v1_ChannelTraceEvent_Severity); + /** + * When this event occurred. + */ + 'timestamp'?: (_google_protobuf_Timestamp | null); + 'channel_ref'?: (_grpc_channelz_v1_ChannelRef | null); + 'subchannel_ref'?: (_grpc_channelz_v1_SubchannelRef | null); + /** + * ref of referenced channel or subchannel. + * Optional, only present if this event refers to a child object. For example, + * this field would be filled if this trace event was for a subchannel being + * created. + */ + 'child_ref'?: "channel_ref"|"subchannel_ref"; +} + +/** + * A trace event is an interesting thing that happened to a channel or + * subchannel, such as creation, address resolution, subchannel creation, etc. + */ +export interface ChannelTraceEvent__Output { + /** + * High level description of the event. + */ + 'description': (string); + /** + * the severity of the trace event + */ + 'severity': (_grpc_channelz_v1_ChannelTraceEvent_Severity__Output); + /** + * When this event occurred. + */ + 'timestamp': (_google_protobuf_Timestamp__Output | null); + 'channel_ref'?: (_grpc_channelz_v1_ChannelRef__Output | null); + 'subchannel_ref'?: (_grpc_channelz_v1_SubchannelRef__Output | null); + /** + * ref of referenced channel or subchannel. + * Optional, only present if this event refers to a child object. For example, + * this field would be filled if this trace event was for a subchannel being + * created. + */ + 'child_ref': "channel_ref"|"subchannel_ref"; +} diff --git a/node_modules/@grpc/grpc-js/src/generated/grpc/channelz/v1/Channelz.ts b/node_modules/@grpc/grpc-js/src/generated/grpc/channelz/v1/Channelz.ts new file mode 100644 index 0000000..4c8c18a --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/generated/grpc/channelz/v1/Channelz.ts @@ -0,0 +1,178 @@ +// Original file: proto/channelz.proto + +import type * as grpc from '../../../../index' +import type { MethodDefinition } from '@grpc/proto-loader' +import type { GetChannelRequest as _grpc_channelz_v1_GetChannelRequest, GetChannelRequest__Output as _grpc_channelz_v1_GetChannelRequest__Output } from '../../../grpc/channelz/v1/GetChannelRequest'; +import type { GetChannelResponse as _grpc_channelz_v1_GetChannelResponse, GetChannelResponse__Output as _grpc_channelz_v1_GetChannelResponse__Output } from '../../../grpc/channelz/v1/GetChannelResponse'; +import type { GetServerRequest as _grpc_channelz_v1_GetServerRequest, GetServerRequest__Output as _grpc_channelz_v1_GetServerRequest__Output } from '../../../grpc/channelz/v1/GetServerRequest'; +import type { GetServerResponse as _grpc_channelz_v1_GetServerResponse, GetServerResponse__Output as _grpc_channelz_v1_GetServerResponse__Output } from '../../../grpc/channelz/v1/GetServerResponse'; +import type { GetServerSocketsRequest as _grpc_channelz_v1_GetServerSocketsRequest, GetServerSocketsRequest__Output as _grpc_channelz_v1_GetServerSocketsRequest__Output } from '../../../grpc/channelz/v1/GetServerSocketsRequest'; +import type { GetServerSocketsResponse as _grpc_channelz_v1_GetServerSocketsResponse, GetServerSocketsResponse__Output as _grpc_channelz_v1_GetServerSocketsResponse__Output } from '../../../grpc/channelz/v1/GetServerSocketsResponse'; +import type { GetServersRequest as _grpc_channelz_v1_GetServersRequest, GetServersRequest__Output as _grpc_channelz_v1_GetServersRequest__Output } from '../../../grpc/channelz/v1/GetServersRequest'; +import type { GetServersResponse as _grpc_channelz_v1_GetServersResponse, GetServersResponse__Output as _grpc_channelz_v1_GetServersResponse__Output } from '../../../grpc/channelz/v1/GetServersResponse'; +import type { GetSocketRequest as _grpc_channelz_v1_GetSocketRequest, GetSocketRequest__Output as _grpc_channelz_v1_GetSocketRequest__Output } from '../../../grpc/channelz/v1/GetSocketRequest'; +import type { GetSocketResponse as _grpc_channelz_v1_GetSocketResponse, GetSocketResponse__Output as _grpc_channelz_v1_GetSocketResponse__Output } from '../../../grpc/channelz/v1/GetSocketResponse'; +import type { GetSubchannelRequest as _grpc_channelz_v1_GetSubchannelRequest, GetSubchannelRequest__Output as _grpc_channelz_v1_GetSubchannelRequest__Output } from '../../../grpc/channelz/v1/GetSubchannelRequest'; +import type { GetSubchannelResponse as _grpc_channelz_v1_GetSubchannelResponse, GetSubchannelResponse__Output as _grpc_channelz_v1_GetSubchannelResponse__Output } from '../../../grpc/channelz/v1/GetSubchannelResponse'; +import type { GetTopChannelsRequest as _grpc_channelz_v1_GetTopChannelsRequest, GetTopChannelsRequest__Output as _grpc_channelz_v1_GetTopChannelsRequest__Output } from '../../../grpc/channelz/v1/GetTopChannelsRequest'; +import type { GetTopChannelsResponse as _grpc_channelz_v1_GetTopChannelsResponse, GetTopChannelsResponse__Output as _grpc_channelz_v1_GetTopChannelsResponse__Output } from '../../../grpc/channelz/v1/GetTopChannelsResponse'; + +/** + * Channelz is a service exposed by gRPC servers that provides detailed debug + * information. + */ +export interface ChannelzClient extends grpc.Client { + /** + * Returns a single Channel, or else a NOT_FOUND code. + */ + GetChannel(argument: _grpc_channelz_v1_GetChannelRequest, metadata: grpc.Metadata, options: grpc.CallOptions, callback: grpc.requestCallback<_grpc_channelz_v1_GetChannelResponse__Output>): grpc.ClientUnaryCall; + GetChannel(argument: _grpc_channelz_v1_GetChannelRequest, metadata: grpc.Metadata, callback: grpc.requestCallback<_grpc_channelz_v1_GetChannelResponse__Output>): grpc.ClientUnaryCall; + GetChannel(argument: _grpc_channelz_v1_GetChannelRequest, options: grpc.CallOptions, callback: grpc.requestCallback<_grpc_channelz_v1_GetChannelResponse__Output>): grpc.ClientUnaryCall; + GetChannel(argument: _grpc_channelz_v1_GetChannelRequest, callback: grpc.requestCallback<_grpc_channelz_v1_GetChannelResponse__Output>): grpc.ClientUnaryCall; + + /** + * Returns a single Server, or else a NOT_FOUND code. + */ + GetServer(argument: _grpc_channelz_v1_GetServerRequest, metadata: grpc.Metadata, options: grpc.CallOptions, callback: grpc.requestCallback<_grpc_channelz_v1_GetServerResponse__Output>): grpc.ClientUnaryCall; + GetServer(argument: _grpc_channelz_v1_GetServerRequest, metadata: grpc.Metadata, callback: grpc.requestCallback<_grpc_channelz_v1_GetServerResponse__Output>): grpc.ClientUnaryCall; + GetServer(argument: _grpc_channelz_v1_GetServerRequest, options: grpc.CallOptions, callback: grpc.requestCallback<_grpc_channelz_v1_GetServerResponse__Output>): grpc.ClientUnaryCall; + GetServer(argument: _grpc_channelz_v1_GetServerRequest, callback: grpc.requestCallback<_grpc_channelz_v1_GetServerResponse__Output>): grpc.ClientUnaryCall; + /** + * Returns a single Server, or else a NOT_FOUND code. + */ + getServer(argument: _grpc_channelz_v1_GetServerRequest, metadata: grpc.Metadata, options: grpc.CallOptions, callback: grpc.requestCallback<_grpc_channelz_v1_GetServerResponse__Output>): grpc.ClientUnaryCall; + getServer(argument: _grpc_channelz_v1_GetServerRequest, metadata: grpc.Metadata, callback: grpc.requestCallback<_grpc_channelz_v1_GetServerResponse__Output>): grpc.ClientUnaryCall; + getServer(argument: _grpc_channelz_v1_GetServerRequest, options: grpc.CallOptions, callback: grpc.requestCallback<_grpc_channelz_v1_GetServerResponse__Output>): grpc.ClientUnaryCall; + getServer(argument: _grpc_channelz_v1_GetServerRequest, callback: grpc.requestCallback<_grpc_channelz_v1_GetServerResponse__Output>): grpc.ClientUnaryCall; + + /** + * Gets all server sockets that exist in the process. + */ + GetServerSockets(argument: _grpc_channelz_v1_GetServerSocketsRequest, metadata: grpc.Metadata, options: grpc.CallOptions, callback: grpc.requestCallback<_grpc_channelz_v1_GetServerSocketsResponse__Output>): grpc.ClientUnaryCall; + GetServerSockets(argument: _grpc_channelz_v1_GetServerSocketsRequest, metadata: grpc.Metadata, callback: grpc.requestCallback<_grpc_channelz_v1_GetServerSocketsResponse__Output>): grpc.ClientUnaryCall; + GetServerSockets(argument: _grpc_channelz_v1_GetServerSocketsRequest, options: grpc.CallOptions, callback: grpc.requestCallback<_grpc_channelz_v1_GetServerSocketsResponse__Output>): grpc.ClientUnaryCall; + GetServerSockets(argument: _grpc_channelz_v1_GetServerSocketsRequest, callback: grpc.requestCallback<_grpc_channelz_v1_GetServerSocketsResponse__Output>): grpc.ClientUnaryCall; + /** + * Gets all server sockets that exist in the process. + */ + getServerSockets(argument: _grpc_channelz_v1_GetServerSocketsRequest, metadata: grpc.Metadata, options: grpc.CallOptions, callback: grpc.requestCallback<_grpc_channelz_v1_GetServerSocketsResponse__Output>): grpc.ClientUnaryCall; + getServerSockets(argument: _grpc_channelz_v1_GetServerSocketsRequest, metadata: grpc.Metadata, callback: grpc.requestCallback<_grpc_channelz_v1_GetServerSocketsResponse__Output>): grpc.ClientUnaryCall; + getServerSockets(argument: _grpc_channelz_v1_GetServerSocketsRequest, options: grpc.CallOptions, callback: grpc.requestCallback<_grpc_channelz_v1_GetServerSocketsResponse__Output>): grpc.ClientUnaryCall; + getServerSockets(argument: _grpc_channelz_v1_GetServerSocketsRequest, callback: grpc.requestCallback<_grpc_channelz_v1_GetServerSocketsResponse__Output>): grpc.ClientUnaryCall; + + /** + * Gets all servers that exist in the process. + */ + GetServers(argument: _grpc_channelz_v1_GetServersRequest, metadata: grpc.Metadata, options: grpc.CallOptions, callback: grpc.requestCallback<_grpc_channelz_v1_GetServersResponse__Output>): grpc.ClientUnaryCall; + GetServers(argument: _grpc_channelz_v1_GetServersRequest, metadata: grpc.Metadata, callback: grpc.requestCallback<_grpc_channelz_v1_GetServersResponse__Output>): grpc.ClientUnaryCall; + GetServers(argument: _grpc_channelz_v1_GetServersRequest, options: grpc.CallOptions, callback: grpc.requestCallback<_grpc_channelz_v1_GetServersResponse__Output>): grpc.ClientUnaryCall; + GetServers(argument: _grpc_channelz_v1_GetServersRequest, callback: grpc.requestCallback<_grpc_channelz_v1_GetServersResponse__Output>): grpc.ClientUnaryCall; + /** + * Gets all servers that exist in the process. + */ + getServers(argument: _grpc_channelz_v1_GetServersRequest, metadata: grpc.Metadata, options: grpc.CallOptions, callback: grpc.requestCallback<_grpc_channelz_v1_GetServersResponse__Output>): grpc.ClientUnaryCall; + getServers(argument: _grpc_channelz_v1_GetServersRequest, metadata: grpc.Metadata, callback: grpc.requestCallback<_grpc_channelz_v1_GetServersResponse__Output>): grpc.ClientUnaryCall; + getServers(argument: _grpc_channelz_v1_GetServersRequest, options: grpc.CallOptions, callback: grpc.requestCallback<_grpc_channelz_v1_GetServersResponse__Output>): grpc.ClientUnaryCall; + getServers(argument: _grpc_channelz_v1_GetServersRequest, callback: grpc.requestCallback<_grpc_channelz_v1_GetServersResponse__Output>): grpc.ClientUnaryCall; + + /** + * Returns a single Socket or else a NOT_FOUND code. + */ + GetSocket(argument: _grpc_channelz_v1_GetSocketRequest, metadata: grpc.Metadata, options: grpc.CallOptions, callback: grpc.requestCallback<_grpc_channelz_v1_GetSocketResponse__Output>): grpc.ClientUnaryCall; + GetSocket(argument: _grpc_channelz_v1_GetSocketRequest, metadata: grpc.Metadata, callback: grpc.requestCallback<_grpc_channelz_v1_GetSocketResponse__Output>): grpc.ClientUnaryCall; + GetSocket(argument: _grpc_channelz_v1_GetSocketRequest, options: grpc.CallOptions, callback: grpc.requestCallback<_grpc_channelz_v1_GetSocketResponse__Output>): grpc.ClientUnaryCall; + GetSocket(argument: _grpc_channelz_v1_GetSocketRequest, callback: grpc.requestCallback<_grpc_channelz_v1_GetSocketResponse__Output>): grpc.ClientUnaryCall; + /** + * Returns a single Socket or else a NOT_FOUND code. + */ + getSocket(argument: _grpc_channelz_v1_GetSocketRequest, metadata: grpc.Metadata, options: grpc.CallOptions, callback: grpc.requestCallback<_grpc_channelz_v1_GetSocketResponse__Output>): grpc.ClientUnaryCall; + getSocket(argument: _grpc_channelz_v1_GetSocketRequest, metadata: grpc.Metadata, callback: grpc.requestCallback<_grpc_channelz_v1_GetSocketResponse__Output>): grpc.ClientUnaryCall; + getSocket(argument: _grpc_channelz_v1_GetSocketRequest, options: grpc.CallOptions, callback: grpc.requestCallback<_grpc_channelz_v1_GetSocketResponse__Output>): grpc.ClientUnaryCall; + getSocket(argument: _grpc_channelz_v1_GetSocketRequest, callback: grpc.requestCallback<_grpc_channelz_v1_GetSocketResponse__Output>): grpc.ClientUnaryCall; + + /** + * Returns a single Subchannel, or else a NOT_FOUND code. + */ + GetSubchannel(argument: _grpc_channelz_v1_GetSubchannelRequest, metadata: grpc.Metadata, options: grpc.CallOptions, callback: grpc.requestCallback<_grpc_channelz_v1_GetSubchannelResponse__Output>): grpc.ClientUnaryCall; + GetSubchannel(argument: _grpc_channelz_v1_GetSubchannelRequest, metadata: grpc.Metadata, callback: grpc.requestCallback<_grpc_channelz_v1_GetSubchannelResponse__Output>): grpc.ClientUnaryCall; + GetSubchannel(argument: _grpc_channelz_v1_GetSubchannelRequest, options: grpc.CallOptions, callback: grpc.requestCallback<_grpc_channelz_v1_GetSubchannelResponse__Output>): grpc.ClientUnaryCall; + GetSubchannel(argument: _grpc_channelz_v1_GetSubchannelRequest, callback: grpc.requestCallback<_grpc_channelz_v1_GetSubchannelResponse__Output>): grpc.ClientUnaryCall; + /** + * Returns a single Subchannel, or else a NOT_FOUND code. + */ + getSubchannel(argument: _grpc_channelz_v1_GetSubchannelRequest, metadata: grpc.Metadata, options: grpc.CallOptions, callback: grpc.requestCallback<_grpc_channelz_v1_GetSubchannelResponse__Output>): grpc.ClientUnaryCall; + getSubchannel(argument: _grpc_channelz_v1_GetSubchannelRequest, metadata: grpc.Metadata, callback: grpc.requestCallback<_grpc_channelz_v1_GetSubchannelResponse__Output>): grpc.ClientUnaryCall; + getSubchannel(argument: _grpc_channelz_v1_GetSubchannelRequest, options: grpc.CallOptions, callback: grpc.requestCallback<_grpc_channelz_v1_GetSubchannelResponse__Output>): grpc.ClientUnaryCall; + getSubchannel(argument: _grpc_channelz_v1_GetSubchannelRequest, callback: grpc.requestCallback<_grpc_channelz_v1_GetSubchannelResponse__Output>): grpc.ClientUnaryCall; + + /** + * Gets all root channels (i.e. channels the application has directly + * created). This does not include subchannels nor non-top level channels. + */ + GetTopChannels(argument: _grpc_channelz_v1_GetTopChannelsRequest, metadata: grpc.Metadata, options: grpc.CallOptions, callback: grpc.requestCallback<_grpc_channelz_v1_GetTopChannelsResponse__Output>): grpc.ClientUnaryCall; + GetTopChannels(argument: _grpc_channelz_v1_GetTopChannelsRequest, metadata: grpc.Metadata, callback: grpc.requestCallback<_grpc_channelz_v1_GetTopChannelsResponse__Output>): grpc.ClientUnaryCall; + GetTopChannels(argument: _grpc_channelz_v1_GetTopChannelsRequest, options: grpc.CallOptions, callback: grpc.requestCallback<_grpc_channelz_v1_GetTopChannelsResponse__Output>): grpc.ClientUnaryCall; + GetTopChannels(argument: _grpc_channelz_v1_GetTopChannelsRequest, callback: grpc.requestCallback<_grpc_channelz_v1_GetTopChannelsResponse__Output>): grpc.ClientUnaryCall; + /** + * Gets all root channels (i.e. channels the application has directly + * created). This does not include subchannels nor non-top level channels. + */ + getTopChannels(argument: _grpc_channelz_v1_GetTopChannelsRequest, metadata: grpc.Metadata, options: grpc.CallOptions, callback: grpc.requestCallback<_grpc_channelz_v1_GetTopChannelsResponse__Output>): grpc.ClientUnaryCall; + getTopChannels(argument: _grpc_channelz_v1_GetTopChannelsRequest, metadata: grpc.Metadata, callback: grpc.requestCallback<_grpc_channelz_v1_GetTopChannelsResponse__Output>): grpc.ClientUnaryCall; + getTopChannels(argument: _grpc_channelz_v1_GetTopChannelsRequest, options: grpc.CallOptions, callback: grpc.requestCallback<_grpc_channelz_v1_GetTopChannelsResponse__Output>): grpc.ClientUnaryCall; + getTopChannels(argument: _grpc_channelz_v1_GetTopChannelsRequest, callback: grpc.requestCallback<_grpc_channelz_v1_GetTopChannelsResponse__Output>): grpc.ClientUnaryCall; + +} + +/** + * Channelz is a service exposed by gRPC servers that provides detailed debug + * information. + */ +export interface ChannelzHandlers extends grpc.UntypedServiceImplementation { + /** + * Returns a single Channel, or else a NOT_FOUND code. + */ + GetChannel: grpc.handleUnaryCall<_grpc_channelz_v1_GetChannelRequest__Output, _grpc_channelz_v1_GetChannelResponse>; + + /** + * Returns a single Server, or else a NOT_FOUND code. + */ + GetServer: grpc.handleUnaryCall<_grpc_channelz_v1_GetServerRequest__Output, _grpc_channelz_v1_GetServerResponse>; + + /** + * Gets all server sockets that exist in the process. + */ + GetServerSockets: grpc.handleUnaryCall<_grpc_channelz_v1_GetServerSocketsRequest__Output, _grpc_channelz_v1_GetServerSocketsResponse>; + + /** + * Gets all servers that exist in the process. + */ + GetServers: grpc.handleUnaryCall<_grpc_channelz_v1_GetServersRequest__Output, _grpc_channelz_v1_GetServersResponse>; + + /** + * Returns a single Socket or else a NOT_FOUND code. + */ + GetSocket: grpc.handleUnaryCall<_grpc_channelz_v1_GetSocketRequest__Output, _grpc_channelz_v1_GetSocketResponse>; + + /** + * Returns a single Subchannel, or else a NOT_FOUND code. + */ + GetSubchannel: grpc.handleUnaryCall<_grpc_channelz_v1_GetSubchannelRequest__Output, _grpc_channelz_v1_GetSubchannelResponse>; + + /** + * Gets all root channels (i.e. channels the application has directly + * created). This does not include subchannels nor non-top level channels. + */ + GetTopChannels: grpc.handleUnaryCall<_grpc_channelz_v1_GetTopChannelsRequest__Output, _grpc_channelz_v1_GetTopChannelsResponse>; + +} + +export interface ChannelzDefinition extends grpc.ServiceDefinition { + GetChannel: MethodDefinition<_grpc_channelz_v1_GetChannelRequest, _grpc_channelz_v1_GetChannelResponse, _grpc_channelz_v1_GetChannelRequest__Output, _grpc_channelz_v1_GetChannelResponse__Output> + GetServer: MethodDefinition<_grpc_channelz_v1_GetServerRequest, _grpc_channelz_v1_GetServerResponse, _grpc_channelz_v1_GetServerRequest__Output, _grpc_channelz_v1_GetServerResponse__Output> + GetServerSockets: MethodDefinition<_grpc_channelz_v1_GetServerSocketsRequest, _grpc_channelz_v1_GetServerSocketsResponse, _grpc_channelz_v1_GetServerSocketsRequest__Output, _grpc_channelz_v1_GetServerSocketsResponse__Output> + GetServers: MethodDefinition<_grpc_channelz_v1_GetServersRequest, _grpc_channelz_v1_GetServersResponse, _grpc_channelz_v1_GetServersRequest__Output, _grpc_channelz_v1_GetServersResponse__Output> + GetSocket: MethodDefinition<_grpc_channelz_v1_GetSocketRequest, _grpc_channelz_v1_GetSocketResponse, _grpc_channelz_v1_GetSocketRequest__Output, _grpc_channelz_v1_GetSocketResponse__Output> + GetSubchannel: MethodDefinition<_grpc_channelz_v1_GetSubchannelRequest, _grpc_channelz_v1_GetSubchannelResponse, _grpc_channelz_v1_GetSubchannelRequest__Output, _grpc_channelz_v1_GetSubchannelResponse__Output> + GetTopChannels: MethodDefinition<_grpc_channelz_v1_GetTopChannelsRequest, _grpc_channelz_v1_GetTopChannelsResponse, _grpc_channelz_v1_GetTopChannelsRequest__Output, _grpc_channelz_v1_GetTopChannelsResponse__Output> +} diff --git a/node_modules/@grpc/grpc-js/src/generated/grpc/channelz/v1/GetChannelRequest.ts b/node_modules/@grpc/grpc-js/src/generated/grpc/channelz/v1/GetChannelRequest.ts new file mode 100644 index 0000000..437e2d6 --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/generated/grpc/channelz/v1/GetChannelRequest.ts @@ -0,0 +1,17 @@ +// Original file: proto/channelz.proto + +import type { Long } from '@grpc/proto-loader'; + +export interface GetChannelRequest { + /** + * channel_id is the identifier of the specific channel to get. + */ + 'channel_id'?: (number | string | Long); +} + +export interface GetChannelRequest__Output { + /** + * channel_id is the identifier of the specific channel to get. + */ + 'channel_id': (string); +} diff --git a/node_modules/@grpc/grpc-js/src/generated/grpc/channelz/v1/GetChannelResponse.ts b/node_modules/@grpc/grpc-js/src/generated/grpc/channelz/v1/GetChannelResponse.ts new file mode 100644 index 0000000..2e967a4 --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/generated/grpc/channelz/v1/GetChannelResponse.ts @@ -0,0 +1,19 @@ +// Original file: proto/channelz.proto + +import type { Channel as _grpc_channelz_v1_Channel, Channel__Output as _grpc_channelz_v1_Channel__Output } from '../../../grpc/channelz/v1/Channel'; + +export interface GetChannelResponse { + /** + * The Channel that corresponds to the requested channel_id. This field + * should be set. + */ + 'channel'?: (_grpc_channelz_v1_Channel | null); +} + +export interface GetChannelResponse__Output { + /** + * The Channel that corresponds to the requested channel_id. This field + * should be set. + */ + 'channel': (_grpc_channelz_v1_Channel__Output | null); +} diff --git a/node_modules/@grpc/grpc-js/src/generated/grpc/channelz/v1/GetServerRequest.ts b/node_modules/@grpc/grpc-js/src/generated/grpc/channelz/v1/GetServerRequest.ts new file mode 100644 index 0000000..f5d4a29 --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/generated/grpc/channelz/v1/GetServerRequest.ts @@ -0,0 +1,17 @@ +// Original file: proto/channelz.proto + +import type { Long } from '@grpc/proto-loader'; + +export interface GetServerRequest { + /** + * server_id is the identifier of the specific server to get. + */ + 'server_id'?: (number | string | Long); +} + +export interface GetServerRequest__Output { + /** + * server_id is the identifier of the specific server to get. + */ + 'server_id': (string); +} diff --git a/node_modules/@grpc/grpc-js/src/generated/grpc/channelz/v1/GetServerResponse.ts b/node_modules/@grpc/grpc-js/src/generated/grpc/channelz/v1/GetServerResponse.ts new file mode 100644 index 0000000..fe00782 --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/generated/grpc/channelz/v1/GetServerResponse.ts @@ -0,0 +1,19 @@ +// Original file: proto/channelz.proto + +import type { Server as _grpc_channelz_v1_Server, Server__Output as _grpc_channelz_v1_Server__Output } from '../../../grpc/channelz/v1/Server'; + +export interface GetServerResponse { + /** + * The Server that corresponds to the requested server_id. This field + * should be set. + */ + 'server'?: (_grpc_channelz_v1_Server | null); +} + +export interface GetServerResponse__Output { + /** + * The Server that corresponds to the requested server_id. This field + * should be set. + */ + 'server': (_grpc_channelz_v1_Server__Output | null); +} diff --git a/node_modules/@grpc/grpc-js/src/generated/grpc/channelz/v1/GetServerSocketsRequest.ts b/node_modules/@grpc/grpc-js/src/generated/grpc/channelz/v1/GetServerSocketsRequest.ts new file mode 100644 index 0000000..c33056e --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/generated/grpc/channelz/v1/GetServerSocketsRequest.ts @@ -0,0 +1,39 @@ +// Original file: proto/channelz.proto + +import type { Long } from '@grpc/proto-loader'; + +export interface GetServerSocketsRequest { + 'server_id'?: (number | string | Long); + /** + * start_socket_id indicates that only sockets at or above this id should be + * included in the results. + * To request the first page, this must be set to 0. To request + * subsequent pages, the client generates this value by adding 1 to + * the highest seen result ID. + */ + 'start_socket_id'?: (number | string | Long); + /** + * If non-zero, the server will return a page of results containing + * at most this many items. If zero, the server will choose a + * reasonable page size. Must never be negative. + */ + 'max_results'?: (number | string | Long); +} + +export interface GetServerSocketsRequest__Output { + 'server_id': (string); + /** + * start_socket_id indicates that only sockets at or above this id should be + * included in the results. + * To request the first page, this must be set to 0. To request + * subsequent pages, the client generates this value by adding 1 to + * the highest seen result ID. + */ + 'start_socket_id': (string); + /** + * If non-zero, the server will return a page of results containing + * at most this many items. If zero, the server will choose a + * reasonable page size. Must never be negative. + */ + 'max_results': (string); +} diff --git a/node_modules/@grpc/grpc-js/src/generated/grpc/channelz/v1/GetServerSocketsResponse.ts b/node_modules/@grpc/grpc-js/src/generated/grpc/channelz/v1/GetServerSocketsResponse.ts new file mode 100644 index 0000000..112f277 --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/generated/grpc/channelz/v1/GetServerSocketsResponse.ts @@ -0,0 +1,33 @@ +// Original file: proto/channelz.proto + +import type { SocketRef as _grpc_channelz_v1_SocketRef, SocketRef__Output as _grpc_channelz_v1_SocketRef__Output } from '../../../grpc/channelz/v1/SocketRef'; + +export interface GetServerSocketsResponse { + /** + * list of socket refs that the connection detail service knows about. Sorted in + * ascending socket_id order. + * Must contain at least 1 result, otherwise 'end' must be true. + */ + 'socket_ref'?: (_grpc_channelz_v1_SocketRef)[]; + /** + * If set, indicates that the list of sockets is the final list. Requesting + * more sockets will only return more if they are created after this RPC + * completes. + */ + 'end'?: (boolean); +} + +export interface GetServerSocketsResponse__Output { + /** + * list of socket refs that the connection detail service knows about. Sorted in + * ascending socket_id order. + * Must contain at least 1 result, otherwise 'end' must be true. + */ + 'socket_ref': (_grpc_channelz_v1_SocketRef__Output)[]; + /** + * If set, indicates that the list of sockets is the final list. Requesting + * more sockets will only return more if they are created after this RPC + * completes. + */ + 'end': (boolean); +} diff --git a/node_modules/@grpc/grpc-js/src/generated/grpc/channelz/v1/GetServersRequest.ts b/node_modules/@grpc/grpc-js/src/generated/grpc/channelz/v1/GetServersRequest.ts new file mode 100644 index 0000000..2defea6 --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/generated/grpc/channelz/v1/GetServersRequest.ts @@ -0,0 +1,37 @@ +// Original file: proto/channelz.proto + +import type { Long } from '@grpc/proto-loader'; + +export interface GetServersRequest { + /** + * start_server_id indicates that only servers at or above this id should be + * included in the results. + * To request the first page, this must be set to 0. To request + * subsequent pages, the client generates this value by adding 1 to + * the highest seen result ID. + */ + 'start_server_id'?: (number | string | Long); + /** + * If non-zero, the server will return a page of results containing + * at most this many items. If zero, the server will choose a + * reasonable page size. Must never be negative. + */ + 'max_results'?: (number | string | Long); +} + +export interface GetServersRequest__Output { + /** + * start_server_id indicates that only servers at or above this id should be + * included in the results. + * To request the first page, this must be set to 0. To request + * subsequent pages, the client generates this value by adding 1 to + * the highest seen result ID. + */ + 'start_server_id': (string); + /** + * If non-zero, the server will return a page of results containing + * at most this many items. If zero, the server will choose a + * reasonable page size. Must never be negative. + */ + 'max_results': (string); +} diff --git a/node_modules/@grpc/grpc-js/src/generated/grpc/channelz/v1/GetServersResponse.ts b/node_modules/@grpc/grpc-js/src/generated/grpc/channelz/v1/GetServersResponse.ts new file mode 100644 index 0000000..b07893b --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/generated/grpc/channelz/v1/GetServersResponse.ts @@ -0,0 +1,33 @@ +// Original file: proto/channelz.proto + +import type { Server as _grpc_channelz_v1_Server, Server__Output as _grpc_channelz_v1_Server__Output } from '../../../grpc/channelz/v1/Server'; + +export interface GetServersResponse { + /** + * list of servers that the connection detail service knows about. Sorted in + * ascending server_id order. + * Must contain at least 1 result, otherwise 'end' must be true. + */ + 'server'?: (_grpc_channelz_v1_Server)[]; + /** + * If set, indicates that the list of servers is the final list. Requesting + * more servers will only return more if they are created after this RPC + * completes. + */ + 'end'?: (boolean); +} + +export interface GetServersResponse__Output { + /** + * list of servers that the connection detail service knows about. Sorted in + * ascending server_id order. + * Must contain at least 1 result, otherwise 'end' must be true. + */ + 'server': (_grpc_channelz_v1_Server__Output)[]; + /** + * If set, indicates that the list of servers is the final list. Requesting + * more servers will only return more if they are created after this RPC + * completes. + */ + 'end': (boolean); +} diff --git a/node_modules/@grpc/grpc-js/src/generated/grpc/channelz/v1/GetSocketRequest.ts b/node_modules/@grpc/grpc-js/src/generated/grpc/channelz/v1/GetSocketRequest.ts new file mode 100644 index 0000000..b3dc160 --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/generated/grpc/channelz/v1/GetSocketRequest.ts @@ -0,0 +1,29 @@ +// Original file: proto/channelz.proto + +import type { Long } from '@grpc/proto-loader'; + +export interface GetSocketRequest { + /** + * socket_id is the identifier of the specific socket to get. + */ + 'socket_id'?: (number | string | Long); + /** + * If true, the response will contain only high level information + * that is inexpensive to obtain. Fields thay may be omitted are + * documented. + */ + 'summary'?: (boolean); +} + +export interface GetSocketRequest__Output { + /** + * socket_id is the identifier of the specific socket to get. + */ + 'socket_id': (string); + /** + * If true, the response will contain only high level information + * that is inexpensive to obtain. Fields thay may be omitted are + * documented. + */ + 'summary': (boolean); +} diff --git a/node_modules/@grpc/grpc-js/src/generated/grpc/channelz/v1/GetSocketResponse.ts b/node_modules/@grpc/grpc-js/src/generated/grpc/channelz/v1/GetSocketResponse.ts new file mode 100644 index 0000000..b6304b7 --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/generated/grpc/channelz/v1/GetSocketResponse.ts @@ -0,0 +1,19 @@ +// Original file: proto/channelz.proto + +import type { Socket as _grpc_channelz_v1_Socket, Socket__Output as _grpc_channelz_v1_Socket__Output } from '../../../grpc/channelz/v1/Socket'; + +export interface GetSocketResponse { + /** + * The Socket that corresponds to the requested socket_id. This field + * should be set. + */ + 'socket'?: (_grpc_channelz_v1_Socket | null); +} + +export interface GetSocketResponse__Output { + /** + * The Socket that corresponds to the requested socket_id. This field + * should be set. + */ + 'socket': (_grpc_channelz_v1_Socket__Output | null); +} diff --git a/node_modules/@grpc/grpc-js/src/generated/grpc/channelz/v1/GetSubchannelRequest.ts b/node_modules/@grpc/grpc-js/src/generated/grpc/channelz/v1/GetSubchannelRequest.ts new file mode 100644 index 0000000..f481a81 --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/generated/grpc/channelz/v1/GetSubchannelRequest.ts @@ -0,0 +1,17 @@ +// Original file: proto/channelz.proto + +import type { Long } from '@grpc/proto-loader'; + +export interface GetSubchannelRequest { + /** + * subchannel_id is the identifier of the specific subchannel to get. + */ + 'subchannel_id'?: (number | string | Long); +} + +export interface GetSubchannelRequest__Output { + /** + * subchannel_id is the identifier of the specific subchannel to get. + */ + 'subchannel_id': (string); +} diff --git a/node_modules/@grpc/grpc-js/src/generated/grpc/channelz/v1/GetSubchannelResponse.ts b/node_modules/@grpc/grpc-js/src/generated/grpc/channelz/v1/GetSubchannelResponse.ts new file mode 100644 index 0000000..57d2bf2 --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/generated/grpc/channelz/v1/GetSubchannelResponse.ts @@ -0,0 +1,19 @@ +// Original file: proto/channelz.proto + +import type { Subchannel as _grpc_channelz_v1_Subchannel, Subchannel__Output as _grpc_channelz_v1_Subchannel__Output } from '../../../grpc/channelz/v1/Subchannel'; + +export interface GetSubchannelResponse { + /** + * The Subchannel that corresponds to the requested subchannel_id. This + * field should be set. + */ + 'subchannel'?: (_grpc_channelz_v1_Subchannel | null); +} + +export interface GetSubchannelResponse__Output { + /** + * The Subchannel that corresponds to the requested subchannel_id. This + * field should be set. + */ + 'subchannel': (_grpc_channelz_v1_Subchannel__Output | null); +} diff --git a/node_modules/@grpc/grpc-js/src/generated/grpc/channelz/v1/GetTopChannelsRequest.ts b/node_modules/@grpc/grpc-js/src/generated/grpc/channelz/v1/GetTopChannelsRequest.ts new file mode 100644 index 0000000..a122d7a --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/generated/grpc/channelz/v1/GetTopChannelsRequest.ts @@ -0,0 +1,37 @@ +// Original file: proto/channelz.proto + +import type { Long } from '@grpc/proto-loader'; + +export interface GetTopChannelsRequest { + /** + * start_channel_id indicates that only channels at or above this id should be + * included in the results. + * To request the first page, this should be set to 0. To request + * subsequent pages, the client generates this value by adding 1 to + * the highest seen result ID. + */ + 'start_channel_id'?: (number | string | Long); + /** + * If non-zero, the server will return a page of results containing + * at most this many items. If zero, the server will choose a + * reasonable page size. Must never be negative. + */ + 'max_results'?: (number | string | Long); +} + +export interface GetTopChannelsRequest__Output { + /** + * start_channel_id indicates that only channels at or above this id should be + * included in the results. + * To request the first page, this should be set to 0. To request + * subsequent pages, the client generates this value by adding 1 to + * the highest seen result ID. + */ + 'start_channel_id': (string); + /** + * If non-zero, the server will return a page of results containing + * at most this many items. If zero, the server will choose a + * reasonable page size. Must never be negative. + */ + 'max_results': (string); +} diff --git a/node_modules/@grpc/grpc-js/src/generated/grpc/channelz/v1/GetTopChannelsResponse.ts b/node_modules/@grpc/grpc-js/src/generated/grpc/channelz/v1/GetTopChannelsResponse.ts new file mode 100644 index 0000000..d96e636 --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/generated/grpc/channelz/v1/GetTopChannelsResponse.ts @@ -0,0 +1,33 @@ +// Original file: proto/channelz.proto + +import type { Channel as _grpc_channelz_v1_Channel, Channel__Output as _grpc_channelz_v1_Channel__Output } from '../../../grpc/channelz/v1/Channel'; + +export interface GetTopChannelsResponse { + /** + * list of channels that the connection detail service knows about. Sorted in + * ascending channel_id order. + * Must contain at least 1 result, otherwise 'end' must be true. + */ + 'channel'?: (_grpc_channelz_v1_Channel)[]; + /** + * If set, indicates that the list of channels is the final list. Requesting + * more channels can only return more if they are created after this RPC + * completes. + */ + 'end'?: (boolean); +} + +export interface GetTopChannelsResponse__Output { + /** + * list of channels that the connection detail service knows about. Sorted in + * ascending channel_id order. + * Must contain at least 1 result, otherwise 'end' must be true. + */ + 'channel': (_grpc_channelz_v1_Channel__Output)[]; + /** + * If set, indicates that the list of channels is the final list. Requesting + * more channels can only return more if they are created after this RPC + * completes. + */ + 'end': (boolean); +} diff --git a/node_modules/@grpc/grpc-js/src/generated/grpc/channelz/v1/Security.ts b/node_modules/@grpc/grpc-js/src/generated/grpc/channelz/v1/Security.ts new file mode 100644 index 0000000..e555d69 --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/generated/grpc/channelz/v1/Security.ts @@ -0,0 +1,87 @@ +// Original file: proto/channelz.proto + +import type { Any as _google_protobuf_Any, Any__Output as _google_protobuf_Any__Output } from '../../../google/protobuf/Any'; + +export interface _grpc_channelz_v1_Security_OtherSecurity { + /** + * The human readable version of the value. + */ + 'name'?: (string); + /** + * The actual security details message. + */ + 'value'?: (_google_protobuf_Any | null); +} + +export interface _grpc_channelz_v1_Security_OtherSecurity__Output { + /** + * The human readable version of the value. + */ + 'name': (string); + /** + * The actual security details message. + */ + 'value': (_google_protobuf_Any__Output | null); +} + +export interface _grpc_channelz_v1_Security_Tls { + /** + * The cipher suite name in the RFC 4346 format: + * https://tools.ietf.org/html/rfc4346#appendix-C + */ + 'standard_name'?: (string); + /** + * Some other way to describe the cipher suite if + * the RFC 4346 name is not available. + */ + 'other_name'?: (string); + /** + * the certificate used by this endpoint. + */ + 'local_certificate'?: (Buffer | Uint8Array | string); + /** + * the certificate used by the remote endpoint. + */ + 'remote_certificate'?: (Buffer | Uint8Array | string); + 'cipher_suite'?: "standard_name"|"other_name"; +} + +export interface _grpc_channelz_v1_Security_Tls__Output { + /** + * The cipher suite name in the RFC 4346 format: + * https://tools.ietf.org/html/rfc4346#appendix-C + */ + 'standard_name'?: (string); + /** + * Some other way to describe the cipher suite if + * the RFC 4346 name is not available. + */ + 'other_name'?: (string); + /** + * the certificate used by this endpoint. + */ + 'local_certificate': (Buffer); + /** + * the certificate used by the remote endpoint. + */ + 'remote_certificate': (Buffer); + 'cipher_suite': "standard_name"|"other_name"; +} + +/** + * Security represents details about how secure the socket is. + */ +export interface Security { + 'tls'?: (_grpc_channelz_v1_Security_Tls | null); + 'other'?: (_grpc_channelz_v1_Security_OtherSecurity | null); + 'model'?: "tls"|"other"; +} + +/** + * Security represents details about how secure the socket is. + */ +export interface Security__Output { + 'tls'?: (_grpc_channelz_v1_Security_Tls__Output | null); + 'other'?: (_grpc_channelz_v1_Security_OtherSecurity__Output | null); + 'model': "tls"|"other"; +} diff --git a/node_modules/@grpc/grpc-js/src/generated/grpc/channelz/v1/Server.ts b/node_modules/@grpc/grpc-js/src/generated/grpc/channelz/v1/Server.ts new file mode 100644 index 0000000..9583433 --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/generated/grpc/channelz/v1/Server.ts @@ -0,0 +1,45 @@ +// Original file: proto/channelz.proto + +import type { ServerRef as _grpc_channelz_v1_ServerRef, ServerRef__Output as _grpc_channelz_v1_ServerRef__Output } from '../../../grpc/channelz/v1/ServerRef'; +import type { ServerData as _grpc_channelz_v1_ServerData, ServerData__Output as _grpc_channelz_v1_ServerData__Output } from '../../../grpc/channelz/v1/ServerData'; +import type { SocketRef as _grpc_channelz_v1_SocketRef, SocketRef__Output as _grpc_channelz_v1_SocketRef__Output } from '../../../grpc/channelz/v1/SocketRef'; + +/** + * Server represents a single server. There may be multiple servers in a single + * program. + */ +export interface Server { + /** + * The identifier for a Server. This should be set. + */ + 'ref'?: (_grpc_channelz_v1_ServerRef | null); + /** + * The associated data of the Server. + */ + 'data'?: (_grpc_channelz_v1_ServerData | null); + /** + * The sockets that the server is listening on. There are no ordering + * guarantees. This may be absent. + */ + 'listen_socket'?: (_grpc_channelz_v1_SocketRef)[]; +} + +/** + * Server represents a single server. There may be multiple servers in a single + * program. + */ +export interface Server__Output { + /** + * The identifier for a Server. This should be set. + */ + 'ref': (_grpc_channelz_v1_ServerRef__Output | null); + /** + * The associated data of the Server. + */ + 'data': (_grpc_channelz_v1_ServerData__Output | null); + /** + * The sockets that the server is listening on. There are no ordering + * guarantees. This may be absent. + */ + 'listen_socket': (_grpc_channelz_v1_SocketRef__Output)[]; +} diff --git a/node_modules/@grpc/grpc-js/src/generated/grpc/channelz/v1/ServerData.ts b/node_modules/@grpc/grpc-js/src/generated/grpc/channelz/v1/ServerData.ts new file mode 100644 index 0000000..ce48e36 --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/generated/grpc/channelz/v1/ServerData.ts @@ -0,0 +1,57 @@ +// Original file: proto/channelz.proto + +import type { ChannelTrace as _grpc_channelz_v1_ChannelTrace, ChannelTrace__Output as _grpc_channelz_v1_ChannelTrace__Output } from '../../../grpc/channelz/v1/ChannelTrace'; +import type { Timestamp as _google_protobuf_Timestamp, Timestamp__Output as _google_protobuf_Timestamp__Output } from '../../../google/protobuf/Timestamp'; +import type { Long } from '@grpc/proto-loader'; + +/** + * ServerData is data for a specific Server. + */ +export interface ServerData { + /** + * A trace of recent events on the server. May be absent. + */ + 'trace'?: (_grpc_channelz_v1_ChannelTrace | null); + /** + * The number of incoming calls started on the server + */ + 'calls_started'?: (number | string | Long); + /** + * The number of incoming calls that have completed with an OK status + */ + 'calls_succeeded'?: (number | string | Long); + /** + * The number of incoming calls that have a completed with a non-OK status + */ + 'calls_failed'?: (number | string | Long); + /** + * The last time a call was started on the server. + */ + 'last_call_started_timestamp'?: (_google_protobuf_Timestamp | null); +} + +/** + * ServerData is data for a specific Server. + */ +export interface ServerData__Output { + /** + * A trace of recent events on the server. May be absent. + */ + 'trace': (_grpc_channelz_v1_ChannelTrace__Output | null); + /** + * The number of incoming calls started on the server + */ + 'calls_started': (string); + /** + * The number of incoming calls that have completed with an OK status + */ + 'calls_succeeded': (string); + /** + * The number of incoming calls that have a completed with a non-OK status + */ + 'calls_failed': (string); + /** + * The last time a call was started on the server. + */ + 'last_call_started_timestamp': (_google_protobuf_Timestamp__Output | null); +} diff --git a/node_modules/@grpc/grpc-js/src/generated/grpc/channelz/v1/ServerRef.ts b/node_modules/@grpc/grpc-js/src/generated/grpc/channelz/v1/ServerRef.ts new file mode 100644 index 0000000..389183b --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/generated/grpc/channelz/v1/ServerRef.ts @@ -0,0 +1,31 @@ +// Original file: proto/channelz.proto + +import type { Long } from '@grpc/proto-loader'; + +/** + * ServerRef is a reference to a Server. + */ +export interface ServerRef { + /** + * A globally unique identifier for this server. Must be a positive number. + */ + 'server_id'?: (number | string | Long); + /** + * An optional name associated with the server. + */ + 'name'?: (string); +} + +/** + * ServerRef is a reference to a Server. + */ +export interface ServerRef__Output { + /** + * A globally unique identifier for this server. Must be a positive number. + */ + 'server_id': (string); + /** + * An optional name associated with the server. + */ + 'name': (string); +} diff --git a/node_modules/@grpc/grpc-js/src/generated/grpc/channelz/v1/Socket.ts b/node_modules/@grpc/grpc-js/src/generated/grpc/channelz/v1/Socket.ts new file mode 100644 index 0000000..5829afe --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/generated/grpc/channelz/v1/Socket.ts @@ -0,0 +1,70 @@ +// Original file: proto/channelz.proto + +import type { SocketRef as _grpc_channelz_v1_SocketRef, SocketRef__Output as _grpc_channelz_v1_SocketRef__Output } from '../../../grpc/channelz/v1/SocketRef'; +import type { SocketData as _grpc_channelz_v1_SocketData, SocketData__Output as _grpc_channelz_v1_SocketData__Output } from '../../../grpc/channelz/v1/SocketData'; +import type { Address as _grpc_channelz_v1_Address, Address__Output as _grpc_channelz_v1_Address__Output } from '../../../grpc/channelz/v1/Address'; +import type { Security as _grpc_channelz_v1_Security, Security__Output as _grpc_channelz_v1_Security__Output } from '../../../grpc/channelz/v1/Security'; + +/** + * Information about an actual connection. Pronounced "sock-ay". + */ +export interface Socket { + /** + * The identifier for the Socket. + */ + 'ref'?: (_grpc_channelz_v1_SocketRef | null); + /** + * Data specific to this Socket. + */ + 'data'?: (_grpc_channelz_v1_SocketData | null); + /** + * The locally bound address. + */ + 'local'?: (_grpc_channelz_v1_Address | null); + /** + * The remote bound address. May be absent. + */ + 'remote'?: (_grpc_channelz_v1_Address | null); + /** + * Security details for this socket. May be absent if not available, or + * there is no security on the socket. + */ + 'security'?: (_grpc_channelz_v1_Security | null); + /** + * Optional, represents the name of the remote endpoint, if different than + * the original target name. + */ + 'remote_name'?: (string); +} + +/** + * Information about an actual connection. Pronounced "sock-ay". + */ +export interface Socket__Output { + /** + * The identifier for the Socket. + */ + 'ref': (_grpc_channelz_v1_SocketRef__Output | null); + /** + * Data specific to this Socket. + */ + 'data': (_grpc_channelz_v1_SocketData__Output | null); + /** + * The locally bound address. + */ + 'local': (_grpc_channelz_v1_Address__Output | null); + /** + * The remote bound address. May be absent. + */ + 'remote': (_grpc_channelz_v1_Address__Output | null); + /** + * Security details for this socket. May be absent if not available, or + * there is no security on the socket. + */ + 'security': (_grpc_channelz_v1_Security__Output | null); + /** + * Optional, represents the name of the remote endpoint, if different than + * the original target name. + */ + 'remote_name': (string); +} diff --git a/node_modules/@grpc/grpc-js/src/generated/grpc/channelz/v1/SocketData.ts b/node_modules/@grpc/grpc-js/src/generated/grpc/channelz/v1/SocketData.ts new file mode 100644 index 0000000..c62d4d1 --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/generated/grpc/channelz/v1/SocketData.ts @@ -0,0 +1,150 @@ +// Original file: proto/channelz.proto + +import type { Timestamp as _google_protobuf_Timestamp, Timestamp__Output as _google_protobuf_Timestamp__Output } from '../../../google/protobuf/Timestamp'; +import type { Int64Value as _google_protobuf_Int64Value, Int64Value__Output as _google_protobuf_Int64Value__Output } from '../../../google/protobuf/Int64Value'; +import type { SocketOption as _grpc_channelz_v1_SocketOption, SocketOption__Output as _grpc_channelz_v1_SocketOption__Output } from '../../../grpc/channelz/v1/SocketOption'; +import type { Long } from '@grpc/proto-loader'; + +/** + * SocketData is data associated for a specific Socket. The fields present + * are specific to the implementation, so there may be minor differences in + * the semantics. (e.g. flow control windows) + */ +export interface SocketData { + /** + * The number of streams that have been started. + */ + 'streams_started'?: (number | string | Long); + /** + * The number of streams that have ended successfully: + * On client side, received frame with eos bit set; + * On server side, sent frame with eos bit set. + */ + 'streams_succeeded'?: (number | string | Long); + /** + * The number of streams that have ended unsuccessfully: + * On client side, ended without receiving frame with eos bit set; + * On server side, ended without sending frame with eos bit set. + */ + 'streams_failed'?: (number | string | Long); + /** + * The number of grpc messages successfully sent on this socket. + */ + 'messages_sent'?: (number | string | Long); + /** + * The number of grpc messages received on this socket. + */ + 'messages_received'?: (number | string | Long); + /** + * The number of keep alives sent. This is typically implemented with HTTP/2 + * ping messages. + */ + 'keep_alives_sent'?: (number | string | Long); + /** + * The last time a stream was created by this endpoint. Usually unset for + * servers. + */ + 'last_local_stream_created_timestamp'?: (_google_protobuf_Timestamp | null); + /** + * The last time a stream was created by the remote endpoint. Usually unset + * for clients. + */ + 'last_remote_stream_created_timestamp'?: (_google_protobuf_Timestamp | null); + /** + * The last time a message was sent by this endpoint. + */ + 'last_message_sent_timestamp'?: (_google_protobuf_Timestamp | null); + /** + * The last time a message was received by this endpoint. + */ + 'last_message_received_timestamp'?: (_google_protobuf_Timestamp | null); + /** + * The amount of window, granted to the local endpoint by the remote endpoint. + * This may be slightly out of date due to network latency. This does NOT + * include stream level or TCP level flow control info. + */ + 'local_flow_control_window'?: (_google_protobuf_Int64Value | null); + /** + * The amount of window, granted to the remote endpoint by the local endpoint. + * This may be slightly out of date due to network latency. This does NOT + * include stream level or TCP level flow control info. + */ + 'remote_flow_control_window'?: (_google_protobuf_Int64Value | null); + /** + * Socket options set on this socket. May be absent if 'summary' is set + * on GetSocketRequest. + */ + 'option'?: (_grpc_channelz_v1_SocketOption)[]; +} + +/** + * SocketData is data associated for a specific Socket. The fields present + * are specific to the implementation, so there may be minor differences in + * the semantics. (e.g. flow control windows) + */ +export interface SocketData__Output { + /** + * The number of streams that have been started. + */ + 'streams_started': (string); + /** + * The number of streams that have ended successfully: + * On client side, received frame with eos bit set; + * On server side, sent frame with eos bit set. + */ + 'streams_succeeded': (string); + /** + * The number of streams that have ended unsuccessfully: + * On client side, ended without receiving frame with eos bit set; + * On server side, ended without sending frame with eos bit set. + */ + 'streams_failed': (string); + /** + * The number of grpc messages successfully sent on this socket. + */ + 'messages_sent': (string); + /** + * The number of grpc messages received on this socket. + */ + 'messages_received': (string); + /** + * The number of keep alives sent. This is typically implemented with HTTP/2 + * ping messages. + */ + 'keep_alives_sent': (string); + /** + * The last time a stream was created by this endpoint. Usually unset for + * servers. + */ + 'last_local_stream_created_timestamp': (_google_protobuf_Timestamp__Output | null); + /** + * The last time a stream was created by the remote endpoint. Usually unset + * for clients. + */ + 'last_remote_stream_created_timestamp': (_google_protobuf_Timestamp__Output | null); + /** + * The last time a message was sent by this endpoint. + */ + 'last_message_sent_timestamp': (_google_protobuf_Timestamp__Output | null); + /** + * The last time a message was received by this endpoint. + */ + 'last_message_received_timestamp': (_google_protobuf_Timestamp__Output | null); + /** + * The amount of window, granted to the local endpoint by the remote endpoint. + * This may be slightly out of date due to network latency. This does NOT + * include stream level or TCP level flow control info. + */ + 'local_flow_control_window': (_google_protobuf_Int64Value__Output | null); + /** + * The amount of window, granted to the remote endpoint by the local endpoint. + * This may be slightly out of date due to network latency. This does NOT + * include stream level or TCP level flow control info. + */ + 'remote_flow_control_window': (_google_protobuf_Int64Value__Output | null); + /** + * Socket options set on this socket. May be absent if 'summary' is set + * on GetSocketRequest. + */ + 'option': (_grpc_channelz_v1_SocketOption__Output)[]; +} diff --git a/node_modules/@grpc/grpc-js/src/generated/grpc/channelz/v1/SocketOption.ts b/node_modules/@grpc/grpc-js/src/generated/grpc/channelz/v1/SocketOption.ts new file mode 100644 index 0000000..115b36a --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/generated/grpc/channelz/v1/SocketOption.ts @@ -0,0 +1,47 @@ +// Original file: proto/channelz.proto + +import type { Any as _google_protobuf_Any, Any__Output as _google_protobuf_Any__Output } from '../../../google/protobuf/Any'; + +/** + * SocketOption represents socket options for a socket. Specifically, these + * are the options returned by getsockopt(). + */ +export interface SocketOption { + /** + * The full name of the socket option. Typically this will be the upper case + * name, such as "SO_REUSEPORT". + */ + 'name'?: (string); + /** + * The human readable value of this socket option. At least one of value or + * additional will be set. + */ + 'value'?: (string); + /** + * Additional data associated with the socket option. At least one of value + * or additional will be set. + */ + 'additional'?: (_google_protobuf_Any | null); +} + +/** + * SocketOption represents socket options for a socket. Specifically, these + * are the options returned by getsockopt(). + */ +export interface SocketOption__Output { + /** + * The full name of the socket option. Typically this will be the upper case + * name, such as "SO_REUSEPORT". + */ + 'name': (string); + /** + * The human readable value of this socket option. At least one of value or + * additional will be set. + */ + 'value': (string); + /** + * Additional data associated with the socket option. At least one of value + * or additional will be set. + */ + 'additional': (_google_protobuf_Any__Output | null); +} diff --git a/node_modules/@grpc/grpc-js/src/generated/grpc/channelz/v1/SocketOptionLinger.ts b/node_modules/@grpc/grpc-js/src/generated/grpc/channelz/v1/SocketOptionLinger.ts new file mode 100644 index 0000000..d83fa32 --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/generated/grpc/channelz/v1/SocketOptionLinger.ts @@ -0,0 +1,33 @@ +// Original file: proto/channelz.proto + +import type { Duration as _google_protobuf_Duration, Duration__Output as _google_protobuf_Duration__Output } from '../../../google/protobuf/Duration'; + +/** + * For use with SocketOption's additional field. This is primarily used for + * SO_LINGER. + */ +export interface SocketOptionLinger { + /** + * active maps to `struct linger.l_onoff` + */ + 'active'?: (boolean); + /** + * duration maps to `struct linger.l_linger` + */ + 'duration'?: (_google_protobuf_Duration | null); +} + +/** + * For use with SocketOption's additional field. This is primarily used for + * SO_LINGER. + */ +export interface SocketOptionLinger__Output { + /** + * active maps to `struct linger.l_onoff` + */ + 'active': (boolean); + /** + * duration maps to `struct linger.l_linger` + */ + 'duration': (_google_protobuf_Duration__Output | null); +} diff --git a/node_modules/@grpc/grpc-js/src/generated/grpc/channelz/v1/SocketOptionTcpInfo.ts b/node_modules/@grpc/grpc-js/src/generated/grpc/channelz/v1/SocketOptionTcpInfo.ts new file mode 100644 index 0000000..2f8affe --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/generated/grpc/channelz/v1/SocketOptionTcpInfo.ts @@ -0,0 +1,74 @@ +// Original file: proto/channelz.proto + + +/** + * For use with SocketOption's additional field. Tcp info for + * SOL_TCP and TCP_INFO. + */ +export interface SocketOptionTcpInfo { + 'tcpi_state'?: (number); + 'tcpi_ca_state'?: (number); + 'tcpi_retransmits'?: (number); + 'tcpi_probes'?: (number); + 'tcpi_backoff'?: (number); + 'tcpi_options'?: (number); + 'tcpi_snd_wscale'?: (number); + 'tcpi_rcv_wscale'?: (number); + 'tcpi_rto'?: (number); + 'tcpi_ato'?: (number); + 'tcpi_snd_mss'?: (number); + 'tcpi_rcv_mss'?: (number); + 'tcpi_unacked'?: (number); + 'tcpi_sacked'?: (number); + 'tcpi_lost'?: (number); + 'tcpi_retrans'?: (number); + 'tcpi_fackets'?: (number); + 'tcpi_last_data_sent'?: (number); + 'tcpi_last_ack_sent'?: (number); + 'tcpi_last_data_recv'?: (number); + 'tcpi_last_ack_recv'?: (number); + 'tcpi_pmtu'?: (number); + 'tcpi_rcv_ssthresh'?: (number); + 'tcpi_rtt'?: (number); + 'tcpi_rttvar'?: (number); + 'tcpi_snd_ssthresh'?: (number); + 'tcpi_snd_cwnd'?: (number); + 'tcpi_advmss'?: (number); + 'tcpi_reordering'?: (number); +} + +/** + * For use with SocketOption's additional field. Tcp info for + * SOL_TCP and TCP_INFO. + */ +export interface SocketOptionTcpInfo__Output { + 'tcpi_state': (number); + 'tcpi_ca_state': (number); + 'tcpi_retransmits': (number); + 'tcpi_probes': (number); + 'tcpi_backoff': (number); + 'tcpi_options': (number); + 'tcpi_snd_wscale': (number); + 'tcpi_rcv_wscale': (number); + 'tcpi_rto': (number); + 'tcpi_ato': (number); + 'tcpi_snd_mss': (number); + 'tcpi_rcv_mss': (number); + 'tcpi_unacked': (number); + 'tcpi_sacked': (number); + 'tcpi_lost': (number); + 'tcpi_retrans': (number); + 'tcpi_fackets': (number); + 'tcpi_last_data_sent': (number); + 'tcpi_last_ack_sent': (number); + 'tcpi_last_data_recv': (number); + 'tcpi_last_ack_recv': (number); + 'tcpi_pmtu': (number); + 'tcpi_rcv_ssthresh': (number); + 'tcpi_rtt': (number); + 'tcpi_rttvar': (number); + 'tcpi_snd_ssthresh': (number); + 'tcpi_snd_cwnd': (number); + 'tcpi_advmss': (number); + 'tcpi_reordering': (number); +} diff --git a/node_modules/@grpc/grpc-js/src/generated/grpc/channelz/v1/SocketOptionTimeout.ts b/node_modules/@grpc/grpc-js/src/generated/grpc/channelz/v1/SocketOptionTimeout.ts new file mode 100644 index 0000000..185839b --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/generated/grpc/channelz/v1/SocketOptionTimeout.ts @@ -0,0 +1,19 @@ +// Original file: proto/channelz.proto + +import type { Duration as _google_protobuf_Duration, Duration__Output as _google_protobuf_Duration__Output } from '../../../google/protobuf/Duration'; + +/** + * For use with SocketOption's additional field. This is primarily used for + * SO_RCVTIMEO and SO_SNDTIMEO + */ +export interface SocketOptionTimeout { + 'duration'?: (_google_protobuf_Duration | null); +} + +/** + * For use with SocketOption's additional field. This is primarily used for + * SO_RCVTIMEO and SO_SNDTIMEO + */ +export interface SocketOptionTimeout__Output { + 'duration': (_google_protobuf_Duration__Output | null); +} diff --git a/node_modules/@grpc/grpc-js/src/generated/grpc/channelz/v1/SocketRef.ts b/node_modules/@grpc/grpc-js/src/generated/grpc/channelz/v1/SocketRef.ts new file mode 100644 index 0000000..52fdb2b --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/generated/grpc/channelz/v1/SocketRef.ts @@ -0,0 +1,31 @@ +// Original file: proto/channelz.proto + +import type { Long } from '@grpc/proto-loader'; + +/** + * SocketRef is a reference to a Socket. + */ +export interface SocketRef { + /** + * The globally unique id for this socket. Must be a positive number. + */ + 'socket_id'?: (number | string | Long); + /** + * An optional name associated with the socket. + */ + 'name'?: (string); +} + +/** + * SocketRef is a reference to a Socket. + */ +export interface SocketRef__Output { + /** + * The globally unique id for this socket. Must be a positive number. + */ + 'socket_id': (string); + /** + * An optional name associated with the socket. + */ + 'name': (string); +} diff --git a/node_modules/@grpc/grpc-js/src/generated/grpc/channelz/v1/Subchannel.ts b/node_modules/@grpc/grpc-js/src/generated/grpc/channelz/v1/Subchannel.ts new file mode 100644 index 0000000..7122fac --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/generated/grpc/channelz/v1/Subchannel.ts @@ -0,0 +1,70 @@ +// Original file: proto/channelz.proto + +import type { SubchannelRef as _grpc_channelz_v1_SubchannelRef, SubchannelRef__Output as _grpc_channelz_v1_SubchannelRef__Output } from '../../../grpc/channelz/v1/SubchannelRef'; +import type { ChannelData as _grpc_channelz_v1_ChannelData, ChannelData__Output as _grpc_channelz_v1_ChannelData__Output } from '../../../grpc/channelz/v1/ChannelData'; +import type { ChannelRef as _grpc_channelz_v1_ChannelRef, ChannelRef__Output as _grpc_channelz_v1_ChannelRef__Output } from '../../../grpc/channelz/v1/ChannelRef'; +import type { SocketRef as _grpc_channelz_v1_SocketRef, SocketRef__Output as _grpc_channelz_v1_SocketRef__Output } from '../../../grpc/channelz/v1/SocketRef'; + +/** + * Subchannel is a logical grouping of channels, subchannels, and sockets. + * A subchannel is load balanced over by it's ancestor + */ +export interface Subchannel { + /** + * The identifier for this channel. + */ + 'ref'?: (_grpc_channelz_v1_SubchannelRef | null); + /** + * Data specific to this channel. + */ + 'data'?: (_grpc_channelz_v1_ChannelData | null); + /** + * There are no ordering guarantees on the order of channel refs. + * There may not be cycles in the ref graph. + * A channel ref may be present in more than one channel or subchannel. + */ + 'channel_ref'?: (_grpc_channelz_v1_ChannelRef)[]; + /** + * At most one of 'channel_ref+subchannel_ref' and 'socket' is set. + * There are no ordering guarantees on the order of subchannel refs. + * There may not be cycles in the ref graph. + * A sub channel ref may be present in more than one channel or subchannel. + */ + 'subchannel_ref'?: (_grpc_channelz_v1_SubchannelRef)[]; + /** + * There are no ordering guarantees on the order of sockets. + */ + 'socket_ref'?: (_grpc_channelz_v1_SocketRef)[]; +} + +/** + * Subchannel is a logical grouping of channels, subchannels, and sockets. + * A subchannel is load balanced over by it's ancestor + */ +export interface Subchannel__Output { + /** + * The identifier for this channel. + */ + 'ref': (_grpc_channelz_v1_SubchannelRef__Output | null); + /** + * Data specific to this channel. + */ + 'data': (_grpc_channelz_v1_ChannelData__Output | null); + /** + * There are no ordering guarantees on the order of channel refs. + * There may not be cycles in the ref graph. + * A channel ref may be present in more than one channel or subchannel. + */ + 'channel_ref': (_grpc_channelz_v1_ChannelRef__Output)[]; + /** + * At most one of 'channel_ref+subchannel_ref' and 'socket' is set. + * There are no ordering guarantees on the order of subchannel refs. + * There may not be cycles in the ref graph. + * A sub channel ref may be present in more than one channel or subchannel. + */ + 'subchannel_ref': (_grpc_channelz_v1_SubchannelRef__Output)[]; + /** + * There are no ordering guarantees on the order of sockets. + */ + 'socket_ref': (_grpc_channelz_v1_SocketRef__Output)[]; +} diff --git a/node_modules/@grpc/grpc-js/src/generated/grpc/channelz/v1/SubchannelRef.ts b/node_modules/@grpc/grpc-js/src/generated/grpc/channelz/v1/SubchannelRef.ts new file mode 100644 index 0000000..b6911c7 --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/generated/grpc/channelz/v1/SubchannelRef.ts @@ -0,0 +1,31 @@ +// Original file: proto/channelz.proto + +import type { Long } from '@grpc/proto-loader'; + +/** + * SubchannelRef is a reference to a Subchannel. + */ +export interface SubchannelRef { + /** + * The globally unique id for this subchannel. Must be a positive number. + */ + 'subchannel_id'?: (number | string | Long); + /** + * An optional name associated with the subchannel. + */ + 'name'?: (string); +} + +/** + * SubchannelRef is a reference to a Subchannel. + */ +export interface SubchannelRef__Output { + /** + * The globally unique id for this subchannel. Must be a positive number. + */ + 'subchannel_id': (string); + /** + * An optional name associated with the subchannel. + */ + 'name': (string); +} diff --git a/node_modules/@grpc/grpc-js/src/http_proxy.ts b/node_modules/@grpc/grpc-js/src/http_proxy.ts new file mode 100644 index 0000000..3e905c4 --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/http_proxy.ts @@ -0,0 +1,311 @@ +/* + * Copyright 2019 gRPC authors. + * + * 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. + * + */ + +import { log } from './logging'; +import { LogVerbosity } from './constants'; +import { getDefaultAuthority } from './resolver'; +import { Socket } from 'net'; +import * as http from 'http'; +import * as tls from 'tls'; +import * as logging from './logging'; +import { + SubchannelAddress, + isTcpSubchannelAddress, + subchannelAddressToString, +} from './subchannel-address'; +import { ChannelOptions } from './channel-options'; +import { GrpcUri, parseUri, splitHostPort, uriToString } from './uri-parser'; +import { URL } from 'url'; +import { DEFAULT_PORT } from './resolver-dns'; + +const TRACER_NAME = 'proxy'; + +function trace(text: string): void { + logging.trace(LogVerbosity.DEBUG, TRACER_NAME, text); +} + +interface ProxyInfo { + address?: string; + creds?: string; +} + +function getProxyInfo(): ProxyInfo { + let proxyEnv = ''; + let envVar = ''; + /* Prefer using 'grpc_proxy'. Fallback on 'http_proxy' if it is not set. + * Also prefer using 'https_proxy' with fallback on 'http_proxy'. The + * fallback behavior can be removed if there's a demand for it. + */ + if (process.env.grpc_proxy) { + envVar = 'grpc_proxy'; + proxyEnv = process.env.grpc_proxy; + } else if (process.env.https_proxy) { + envVar = 'https_proxy'; + proxyEnv = process.env.https_proxy; + } else if (process.env.http_proxy) { + envVar = 'http_proxy'; + proxyEnv = process.env.http_proxy; + } else { + return {}; + } + let proxyUrl: URL; + try { + proxyUrl = new URL(proxyEnv); + } catch (e) { + log(LogVerbosity.ERROR, `cannot parse value of "${envVar}" env var`); + return {}; + } + if (proxyUrl.protocol !== 'http:') { + log( + LogVerbosity.ERROR, + `"${proxyUrl.protocol}" scheme not supported in proxy URI` + ); + return {}; + } + let userCred: string | null = null; + if (proxyUrl.username) { + if (proxyUrl.password) { + log(LogVerbosity.INFO, 'userinfo found in proxy URI'); + userCred = `${proxyUrl.username}:${proxyUrl.password}`; + } else { + userCred = proxyUrl.username; + } + } + const hostname = proxyUrl.hostname; + let port = proxyUrl.port; + /* The proxy URL uses the scheme "http:", which has a default port number of + * 80. We need to set that explicitly here if it is omitted because otherwise + * it will use gRPC's default port 443. */ + if (port === '') { + port = '80'; + } + const result: ProxyInfo = { + address: `${hostname}:${port}`, + }; + if (userCred) { + result.creds = userCred; + } + trace( + 'Proxy server ' + result.address + ' set by environment variable ' + envVar + ); + return result; +} + +function getNoProxyHostList(): string[] { + /* Prefer using 'no_grpc_proxy'. Fallback on 'no_proxy' if it is not set. */ + let noProxyStr: string | undefined = process.env.no_grpc_proxy; + let envVar = 'no_grpc_proxy'; + if (!noProxyStr) { + noProxyStr = process.env.no_proxy; + envVar = 'no_proxy'; + } + if (noProxyStr) { + trace('No proxy server list set by environment variable ' + envVar); + return noProxyStr.split(','); + } else { + return []; + } +} + +export interface ProxyMapResult { + target: GrpcUri; + extraOptions: ChannelOptions; +} + +export function mapProxyName( + target: GrpcUri, + options: ChannelOptions +): ProxyMapResult { + const noProxyResult: ProxyMapResult = { + target: target, + extraOptions: {}, + }; + if ((options['grpc.enable_http_proxy'] ?? 1) === 0) { + return noProxyResult; + } + if (target.scheme === 'unix') { + return noProxyResult; + } + const proxyInfo = getProxyInfo(); + if (!proxyInfo.address) { + return noProxyResult; + } + const hostPort = splitHostPort(target.path); + if (!hostPort) { + return noProxyResult; + } + const serverHost = hostPort.host; + for (const host of getNoProxyHostList()) { + if (host === serverHost) { + trace( + 'Not using proxy for target in no_proxy list: ' + uriToString(target) + ); + return noProxyResult; + } + } + const extraOptions: ChannelOptions = { + 'grpc.http_connect_target': uriToString(target), + }; + if (proxyInfo.creds) { + extraOptions['grpc.http_connect_creds'] = proxyInfo.creds; + } + return { + target: { + scheme: 'dns', + path: proxyInfo.address, + }, + extraOptions: extraOptions, + }; +} + +export interface ProxyConnectionResult { + socket?: Socket; + realTarget?: GrpcUri; +} + +export function getProxiedConnection( + address: SubchannelAddress, + channelOptions: ChannelOptions, + connectionOptions: tls.ConnectionOptions +): Promise { + if (!('grpc.http_connect_target' in channelOptions)) { + return Promise.resolve({}); + } + const realTarget = channelOptions['grpc.http_connect_target'] as string; + const parsedTarget = parseUri(realTarget); + if (parsedTarget === null) { + return Promise.resolve({}); + } + const splitHostPost = splitHostPort(parsedTarget.path); + if (splitHostPost === null) { + return Promise.resolve({}); + } + const hostPort = `${splitHostPost.host}:${ + splitHostPost.port ?? DEFAULT_PORT + }`; + const options: http.RequestOptions = { + method: 'CONNECT', + path: hostPort, + }; + const headers: http.OutgoingHttpHeaders = { + Host: hostPort, + }; + // Connect to the subchannel address as a proxy + if (isTcpSubchannelAddress(address)) { + options.host = address.host; + options.port = address.port; + } else { + options.socketPath = address.path; + } + if ('grpc.http_connect_creds' in channelOptions) { + headers['Proxy-Authorization'] = + 'Basic ' + + Buffer.from(channelOptions['grpc.http_connect_creds'] as string).toString( + 'base64' + ); + } + options.headers = headers; + const proxyAddressString = subchannelAddressToString(address); + trace('Using proxy ' + proxyAddressString + ' to connect to ' + options.path); + return new Promise((resolve, reject) => { + const request = http.request(options); + request.once('connect', (res, socket, head) => { + request.removeAllListeners(); + socket.removeAllListeners(); + if (res.statusCode === 200) { + trace( + 'Successfully connected to ' + + options.path + + ' through proxy ' + + proxyAddressString + ); + if ('secureContext' in connectionOptions) { + /* The proxy is connecting to a TLS server, so upgrade this socket + * connection to a TLS connection. + * This is a workaround for https://github.com/nodejs/node/issues/32922 + * See https://github.com/grpc/grpc-node/pull/1369 for more info. */ + const targetPath = getDefaultAuthority(parsedTarget); + const hostPort = splitHostPort(targetPath); + const remoteHost = hostPort?.host ?? targetPath; + + const cts = tls.connect( + { + host: remoteHost, + servername: remoteHost, + socket: socket, + ...connectionOptions, + }, + () => { + trace( + 'Successfully established a TLS connection to ' + + options.path + + ' through proxy ' + + proxyAddressString + ); + resolve({ socket: cts, realTarget: parsedTarget }); + } + ); + cts.on('error', (error: Error) => { + trace( + 'Failed to establish a TLS connection to ' + + options.path + + ' through proxy ' + + proxyAddressString + + ' with error ' + + error.message + ); + reject(); + }); + } else { + trace( + 'Successfully established a plaintext connection to ' + + options.path + + ' through proxy ' + + proxyAddressString + ); + resolve({ + socket, + realTarget: parsedTarget, + }); + } + } else { + log( + LogVerbosity.ERROR, + 'Failed to connect to ' + + options.path + + ' through proxy ' + + proxyAddressString + + ' with status ' + + res.statusCode + ); + reject(); + } + }); + request.once('error', err => { + request.removeAllListeners(); + log( + LogVerbosity.ERROR, + 'Failed to connect to proxy ' + + proxyAddressString + + ' with error ' + + err.message + ); + reject(); + }); + request.end(); + }); +} diff --git a/node_modules/@grpc/grpc-js/src/index.ts b/node_modules/@grpc/grpc-js/src/index.ts new file mode 100644 index 0000000..c766a37 --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/index.ts @@ -0,0 +1,305 @@ +/* + * Copyright 2019 gRPC authors. + * + * 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. + * + */ + +import { + ClientDuplexStream, + ClientReadableStream, + ClientUnaryCall, + ClientWritableStream, + ServiceError, +} from './call'; +import { CallCredentials, OAuth2Client } from './call-credentials'; +import { StatusObject } from './call-interface'; +import { Channel, ChannelImplementation } from './channel'; +import { CompressionAlgorithms } from './compression-algorithms'; +import { ConnectivityState } from './connectivity-state'; +import { ChannelCredentials, VerifyOptions } from './channel-credentials'; +import { + CallOptions, + Client, + ClientOptions, + CallInvocationTransformer, + CallProperties, + UnaryCallback, +} from './client'; +import { LogVerbosity, Status, Propagate } from './constants'; +import * as logging from './logging'; +import { + Deserialize, + loadPackageDefinition, + makeClientConstructor, + MethodDefinition, + Serialize, + ServiceDefinition, +} from './make-client'; +import { Metadata, MetadataOptions, MetadataValue } from './metadata'; +import { + Server, + ServerOptions, + UntypedHandleCall, + UntypedServiceImplementation, +} from './server'; +import { KeyCertPair, ServerCredentials } from './server-credentials'; +import { StatusBuilder } from './status-builder'; +import { + handleBidiStreamingCall, + handleServerStreamingCall, + handleClientStreamingCall, + handleUnaryCall, + sendUnaryData, + ServerUnaryCall, + ServerReadableStream, + ServerWritableStream, + ServerDuplexStream, + ServerErrorResponse, +} from './server-call'; + +export { OAuth2Client }; + +/**** Client Credentials ****/ + +// Using assign only copies enumerable properties, which is what we want +export const credentials = { + /** + * Combine a ChannelCredentials with any number of CallCredentials into a + * single ChannelCredentials object. + * @param channelCredentials The ChannelCredentials object. + * @param callCredentials Any number of CallCredentials objects. + * @return The resulting ChannelCredentials object. + */ + combineChannelCredentials: ( + channelCredentials: ChannelCredentials, + ...callCredentials: CallCredentials[] + ): ChannelCredentials => { + return callCredentials.reduce( + (acc, other) => acc.compose(other), + channelCredentials + ); + }, + + /** + * Combine any number of CallCredentials into a single CallCredentials + * object. + * @param first The first CallCredentials object. + * @param additional Any number of additional CallCredentials objects. + * @return The resulting CallCredentials object. + */ + combineCallCredentials: ( + first: CallCredentials, + ...additional: CallCredentials[] + ): CallCredentials => { + return additional.reduce((acc, other) => acc.compose(other), first); + }, + + // from channel-credentials.ts + createInsecure: ChannelCredentials.createInsecure, + createSsl: ChannelCredentials.createSsl, + createFromSecureContext: ChannelCredentials.createFromSecureContext, + + // from call-credentials.ts + createFromMetadataGenerator: CallCredentials.createFromMetadataGenerator, + createFromGoogleCredential: CallCredentials.createFromGoogleCredential, + createEmpty: CallCredentials.createEmpty, +}; + +/**** Metadata ****/ + +export { Metadata, MetadataOptions, MetadataValue }; + +/**** Constants ****/ + +export { + LogVerbosity as logVerbosity, + Status as status, + ConnectivityState as connectivityState, + Propagate as propagate, + CompressionAlgorithms as compressionAlgorithms, + // TODO: Other constants as well +}; + +/**** Client ****/ + +export { + Client, + ClientOptions, + loadPackageDefinition, + makeClientConstructor, + makeClientConstructor as makeGenericClientConstructor, + CallProperties, + CallInvocationTransformer, + ChannelImplementation as Channel, + Channel as ChannelInterface, + UnaryCallback as requestCallback, +}; + +/** + * Close a Client object. + * @param client The client to close. + */ +export const closeClient = (client: Client) => client.close(); + +export const waitForClientReady = ( + client: Client, + deadline: Date | number, + callback: (error?: Error) => void +) => client.waitForReady(deadline, callback); + +/* Interfaces */ + +export { + sendUnaryData, + ChannelCredentials, + CallCredentials, + Deadline, + Serialize as serialize, + Deserialize as deserialize, + ClientUnaryCall, + ClientReadableStream, + ClientWritableStream, + ClientDuplexStream, + CallOptions, + MethodDefinition, + StatusObject, + ServiceError, + ServerUnaryCall, + ServerReadableStream, + ServerWritableStream, + ServerDuplexStream, + ServerErrorResponse, + ServiceDefinition, + UntypedHandleCall, + UntypedServiceImplementation, + VerifyOptions, +}; + +/**** Server ****/ + +export { + handleBidiStreamingCall, + handleServerStreamingCall, + handleUnaryCall, + handleClientStreamingCall, +}; + +/* eslint-disable @typescript-eslint/no-explicit-any */ +export type Call = + | ClientUnaryCall + | ClientReadableStream + | ClientWritableStream + | ClientDuplexStream; +/* eslint-enable @typescript-eslint/no-explicit-any */ + +/**** Unimplemented function stubs ****/ + +/* eslint-disable @typescript-eslint/no-explicit-any */ + +export const loadObject = (value: any, options: any): never => { + throw new Error( + 'Not available in this library. Use @grpc/proto-loader and loadPackageDefinition instead' + ); +}; + +export const load = (filename: any, format: any, options: any): never => { + throw new Error( + 'Not available in this library. Use @grpc/proto-loader and loadPackageDefinition instead' + ); +}; + +export const setLogger = (logger: Partial): void => { + logging.setLogger(logger); +}; + +export const setLogVerbosity = (verbosity: LogVerbosity): void => { + logging.setLoggerVerbosity(verbosity); +}; + +export { Server, ServerOptions }; +export { ServerCredentials }; +export { KeyCertPair }; + +export const getClientChannel = (client: Client) => { + return Client.prototype.getChannel.call(client); +}; + +export { StatusBuilder }; + +export { Listener, InterceptingListener } from './call-interface'; + +export { + Requester, + ListenerBuilder, + RequesterBuilder, + Interceptor, + InterceptorOptions, + InterceptorProvider, + InterceptingCall, + InterceptorConfigurationError, + NextCall, +} from './client-interceptors'; + +export { + GrpcObject, + ServiceClientConstructor, + ProtobufTypeDefinition, +} from './make-client'; + +export { ChannelOptions } from './channel-options'; + +export { getChannelzServiceDefinition, getChannelzHandlers } from './channelz'; + +export { addAdminServicesToServer } from './admin'; + +export { + ServiceConfig, + LoadBalancingConfig, + MethodConfig, + RetryPolicy, +} from './service-config'; + +export { + ServerListener, + FullServerListener, + ServerListenerBuilder, + Responder, + FullResponder, + ResponderBuilder, + ServerInterceptingCallInterface, + ServerInterceptingCall, + ServerInterceptor, +} from './server-interceptors'; + +import * as experimental from './experimental'; +export { experimental }; + +import * as resolver_dns from './resolver-dns'; +import * as resolver_uds from './resolver-uds'; +import * as resolver_ip from './resolver-ip'; +import * as load_balancer_pick_first from './load-balancer-pick-first'; +import * as load_balancer_round_robin from './load-balancer-round-robin'; +import * as load_balancer_outlier_detection from './load-balancer-outlier-detection'; +import * as channelz from './channelz'; +import { Deadline } from './deadline'; + +(() => { + resolver_dns.setup(); + resolver_uds.setup(); + resolver_ip.setup(); + load_balancer_pick_first.setup(); + load_balancer_round_robin.setup(); + load_balancer_outlier_detection.setup(); + channelz.setup(); +})(); diff --git a/node_modules/@grpc/grpc-js/src/internal-channel.ts b/node_modules/@grpc/grpc-js/src/internal-channel.ts new file mode 100644 index 0000000..469ace5 --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/internal-channel.ts @@ -0,0 +1,845 @@ +/* + * Copyright 2019 gRPC authors. + * + * 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. + * + */ + +import { ChannelCredentials } from './channel-credentials'; +import { ChannelOptions } from './channel-options'; +import { ResolvingLoadBalancer } from './resolving-load-balancer'; +import { SubchannelPool, getSubchannelPool } from './subchannel-pool'; +import { ChannelControlHelper } from './load-balancer'; +import { UnavailablePicker, Picker, QueuePicker } from './picker'; +import { Metadata } from './metadata'; +import { Status, LogVerbosity, Propagate } from './constants'; +import { FilterStackFactory } from './filter-stack'; +import { CompressionFilterFactory } from './compression-filter'; +import { + CallConfig, + ConfigSelector, + getDefaultAuthority, + mapUriDefaultScheme, +} from './resolver'; +import { trace } from './logging'; +import { SubchannelAddress } from './subchannel-address'; +import { MaxMessageSizeFilterFactory } from './max-message-size-filter'; +import { mapProxyName } from './http_proxy'; +import { GrpcUri, parseUri, uriToString } from './uri-parser'; +import { ServerSurfaceCall } from './server-call'; + +import { ConnectivityState } from './connectivity-state'; +import { + ChannelInfo, + ChannelRef, + ChannelzCallTracker, + ChannelzChildrenTracker, + ChannelzTrace, + registerChannelzChannel, + SubchannelRef, + unregisterChannelzRef, +} from './channelz'; +import { LoadBalancingCall } from './load-balancing-call'; +import { CallCredentials } from './call-credentials'; +import { Call, CallStreamOptions, StatusObject } from './call-interface'; +import { Deadline, deadlineToString } from './deadline'; +import { ResolvingCall } from './resolving-call'; +import { getNextCallNumber } from './call-number'; +import { restrictControlPlaneStatusCode } from './control-plane-status'; +import { + MessageBufferTracker, + RetryingCall, + RetryThrottler, +} from './retrying-call'; +import { + BaseSubchannelWrapper, + ConnectivityStateListener, + SubchannelInterface, +} from './subchannel-interface'; + +/** + * See https://nodejs.org/api/timers.html#timers_setinterval_callback_delay_args + */ +const MAX_TIMEOUT_TIME = 2147483647; + +const MIN_IDLE_TIMEOUT_MS = 1000; + +// 30 minutes +const DEFAULT_IDLE_TIMEOUT_MS = 30 * 60 * 1000; + +interface ConnectivityStateWatcher { + currentState: ConnectivityState; + timer: NodeJS.Timeout | null; + callback: (error?: Error) => void; +} + +interface NoneConfigResult { + type: 'NONE'; +} + +interface SuccessConfigResult { + type: 'SUCCESS'; + config: CallConfig; +} + +interface ErrorConfigResult { + type: 'ERROR'; + error: StatusObject; +} + +type GetConfigResult = + | NoneConfigResult + | SuccessConfigResult + | ErrorConfigResult; + +const RETRY_THROTTLER_MAP: Map = new Map(); + +const DEFAULT_RETRY_BUFFER_SIZE_BYTES = 1 << 24; // 16 MB +const DEFAULT_PER_RPC_RETRY_BUFFER_SIZE_BYTES = 1 << 20; // 1 MB + +class ChannelSubchannelWrapper + extends BaseSubchannelWrapper + implements SubchannelInterface +{ + private refCount = 0; + private subchannelStateListener: ConnectivityStateListener; + constructor( + childSubchannel: SubchannelInterface, + private channel: InternalChannel + ) { + super(childSubchannel); + this.subchannelStateListener = ( + subchannel, + previousState, + newState, + keepaliveTime + ) => { + channel.throttleKeepalive(keepaliveTime); + }; + childSubchannel.addConnectivityStateListener(this.subchannelStateListener); + } + + ref(): void { + this.child.ref(); + this.refCount += 1; + } + + unref(): void { + this.child.unref(); + this.refCount -= 1; + if (this.refCount <= 0) { + this.child.removeConnectivityStateListener(this.subchannelStateListener); + this.channel.removeWrappedSubchannel(this); + } + } +} + +export class InternalChannel { + private readonly resolvingLoadBalancer: ResolvingLoadBalancer; + private readonly subchannelPool: SubchannelPool; + private connectivityState: ConnectivityState = ConnectivityState.IDLE; + private currentPicker: Picker = new UnavailablePicker(); + /** + * Calls queued up to get a call config. Should only be populated before the + * first time the resolver returns a result, which includes the ConfigSelector. + */ + private configSelectionQueue: ResolvingCall[] = []; + private pickQueue: LoadBalancingCall[] = []; + private connectivityStateWatchers: ConnectivityStateWatcher[] = []; + private readonly defaultAuthority: string; + private readonly filterStackFactory: FilterStackFactory; + private readonly target: GrpcUri; + /** + * This timer does not do anything on its own. Its purpose is to hold the + * event loop open while there are any pending calls for the channel that + * have not yet been assigned to specific subchannels. In other words, + * the invariant is that callRefTimer is reffed if and only if pickQueue + * is non-empty. + */ + private readonly callRefTimer: NodeJS.Timeout; + private configSelector: ConfigSelector | null = null; + /** + * This is the error from the name resolver if it failed most recently. It + * is only used to end calls that start while there is no config selector + * and the name resolver is in backoff, so it should be nulled if + * configSelector becomes set or the channel state becomes anything other + * than TRANSIENT_FAILURE. + */ + private currentResolutionError: StatusObject | null = null; + private readonly retryBufferTracker: MessageBufferTracker; + private keepaliveTime: number; + private readonly wrappedSubchannels: Set = + new Set(); + + private callCount = 0; + private idleTimer: NodeJS.Timeout | null = null; + private readonly idleTimeoutMs: number; + private lastActivityTimestamp: Date; + + // Channelz info + private readonly channelzEnabled: boolean = true; + private readonly originalTarget: string; + private readonly channelzRef: ChannelRef; + private readonly channelzTrace: ChannelzTrace; + private readonly callTracker = new ChannelzCallTracker(); + private readonly childrenTracker = new ChannelzChildrenTracker(); + + /** + * Randomly generated ID to be passed to the config selector, for use by + * ring_hash in xDS. An integer distributed approximately uniformly between + * 0 and MAX_SAFE_INTEGER. + */ + private readonly randomChannelId = Math.floor( + Math.random() * Number.MAX_SAFE_INTEGER + ); + + constructor( + target: string, + private readonly credentials: ChannelCredentials, + private readonly options: ChannelOptions + ) { + if (typeof target !== 'string') { + throw new TypeError('Channel target must be a string'); + } + if (!(credentials instanceof ChannelCredentials)) { + throw new TypeError( + 'Channel credentials must be a ChannelCredentials object' + ); + } + if (options) { + if (typeof options !== 'object') { + throw new TypeError('Channel options must be an object'); + } + } + this.originalTarget = target; + const originalTargetUri = parseUri(target); + if (originalTargetUri === null) { + throw new Error(`Could not parse target name "${target}"`); + } + /* This ensures that the target has a scheme that is registered with the + * resolver */ + const defaultSchemeMapResult = mapUriDefaultScheme(originalTargetUri); + if (defaultSchemeMapResult === null) { + throw new Error( + `Could not find a default scheme for target name "${target}"` + ); + } + + this.callRefTimer = setInterval(() => {}, MAX_TIMEOUT_TIME); + this.callRefTimer.unref?.(); + + if (this.options['grpc.enable_channelz'] === 0) { + this.channelzEnabled = false; + } + + this.channelzTrace = new ChannelzTrace(); + this.channelzRef = registerChannelzChannel( + target, + () => this.getChannelzInfo(), + this.channelzEnabled + ); + if (this.channelzEnabled) { + this.channelzTrace.addTrace('CT_INFO', 'Channel created'); + } + + if (this.options['grpc.default_authority']) { + this.defaultAuthority = this.options['grpc.default_authority'] as string; + } else { + this.defaultAuthority = getDefaultAuthority(defaultSchemeMapResult); + } + const proxyMapResult = mapProxyName(defaultSchemeMapResult, options); + this.target = proxyMapResult.target; + this.options = Object.assign({}, this.options, proxyMapResult.extraOptions); + + /* The global boolean parameter to getSubchannelPool has the inverse meaning to what + * the grpc.use_local_subchannel_pool channel option means. */ + this.subchannelPool = getSubchannelPool( + (options['grpc.use_local_subchannel_pool'] ?? 0) === 0 + ); + this.retryBufferTracker = new MessageBufferTracker( + options['grpc.retry_buffer_size'] ?? DEFAULT_RETRY_BUFFER_SIZE_BYTES, + options['grpc.per_rpc_retry_buffer_size'] ?? + DEFAULT_PER_RPC_RETRY_BUFFER_SIZE_BYTES + ); + this.keepaliveTime = options['grpc.keepalive_time_ms'] ?? -1; + this.idleTimeoutMs = Math.max( + options['grpc.client_idle_timeout_ms'] ?? DEFAULT_IDLE_TIMEOUT_MS, + MIN_IDLE_TIMEOUT_MS + ); + const channelControlHelper: ChannelControlHelper = { + createSubchannel: ( + subchannelAddress: SubchannelAddress, + subchannelArgs: ChannelOptions + ) => { + const subchannel = this.subchannelPool.getOrCreateSubchannel( + this.target, + subchannelAddress, + Object.assign({}, this.options, subchannelArgs), + this.credentials + ); + subchannel.throttleKeepalive(this.keepaliveTime); + if (this.channelzEnabled) { + this.channelzTrace.addTrace( + 'CT_INFO', + 'Created subchannel or used existing subchannel', + subchannel.getChannelzRef() + ); + } + const wrappedSubchannel = new ChannelSubchannelWrapper( + subchannel, + this + ); + this.wrappedSubchannels.add(wrappedSubchannel); + return wrappedSubchannel; + }, + updateState: (connectivityState: ConnectivityState, picker: Picker) => { + this.currentPicker = picker; + const queueCopy = this.pickQueue.slice(); + this.pickQueue = []; + if (queueCopy.length > 0) { + this.callRefTimerUnref(); + } + for (const call of queueCopy) { + call.doPick(); + } + this.updateState(connectivityState); + }, + requestReresolution: () => { + // This should never be called. + throw new Error( + 'Resolving load balancer should never call requestReresolution' + ); + }, + addChannelzChild: (child: ChannelRef | SubchannelRef) => { + if (this.channelzEnabled) { + this.childrenTracker.refChild(child); + } + }, + removeChannelzChild: (child: ChannelRef | SubchannelRef) => { + if (this.channelzEnabled) { + this.childrenTracker.unrefChild(child); + } + }, + }; + this.resolvingLoadBalancer = new ResolvingLoadBalancer( + this.target, + channelControlHelper, + options, + (serviceConfig, configSelector) => { + if (serviceConfig.retryThrottling) { + RETRY_THROTTLER_MAP.set( + this.getTarget(), + new RetryThrottler( + serviceConfig.retryThrottling.maxTokens, + serviceConfig.retryThrottling.tokenRatio, + RETRY_THROTTLER_MAP.get(this.getTarget()) + ) + ); + } else { + RETRY_THROTTLER_MAP.delete(this.getTarget()); + } + if (this.channelzEnabled) { + this.channelzTrace.addTrace( + 'CT_INFO', + 'Address resolution succeeded' + ); + } + this.configSelector = configSelector; + this.currentResolutionError = null; + /* We process the queue asynchronously to ensure that the corresponding + * load balancer update has completed. */ + process.nextTick(() => { + const localQueue = this.configSelectionQueue; + this.configSelectionQueue = []; + if (localQueue.length > 0) { + this.callRefTimerUnref(); + } + for (const call of localQueue) { + call.getConfig(); + } + }); + }, + status => { + if (this.channelzEnabled) { + this.channelzTrace.addTrace( + 'CT_WARNING', + 'Address resolution failed with code ' + + status.code + + ' and details "' + + status.details + + '"' + ); + } + if (this.configSelectionQueue.length > 0) { + this.trace( + 'Name resolution failed with calls queued for config selection' + ); + } + if (this.configSelector === null) { + this.currentResolutionError = { + ...restrictControlPlaneStatusCode(status.code, status.details), + metadata: status.metadata, + }; + } + const localQueue = this.configSelectionQueue; + this.configSelectionQueue = []; + if (localQueue.length > 0) { + this.callRefTimerUnref(); + } + for (const call of localQueue) { + call.reportResolverError(status); + } + } + ); + this.filterStackFactory = new FilterStackFactory([ + new MaxMessageSizeFilterFactory(this.options), + new CompressionFilterFactory(this, this.options), + ]); + this.trace( + 'Channel constructed with options ' + + JSON.stringify(options, undefined, 2) + ); + const error = new Error(); + trace( + LogVerbosity.DEBUG, + 'channel_stacktrace', + '(' + + this.channelzRef.id + + ') ' + + 'Channel constructed \n' + + error.stack?.substring(error.stack.indexOf('\n') + 1) + ); + this.lastActivityTimestamp = new Date(); + } + + private getChannelzInfo(): ChannelInfo { + return { + target: this.originalTarget, + state: this.connectivityState, + trace: this.channelzTrace, + callTracker: this.callTracker, + children: this.childrenTracker.getChildLists(), + }; + } + + private trace(text: string, verbosityOverride?: LogVerbosity) { + trace( + verbosityOverride ?? LogVerbosity.DEBUG, + 'channel', + '(' + this.channelzRef.id + ') ' + uriToString(this.target) + ' ' + text + ); + } + + private callRefTimerRef() { + // If the hasRef function does not exist, always run the code + if (!this.callRefTimer.hasRef?.()) { + this.trace( + 'callRefTimer.ref | configSelectionQueue.length=' + + this.configSelectionQueue.length + + ' pickQueue.length=' + + this.pickQueue.length + ); + this.callRefTimer.ref?.(); + } + } + + private callRefTimerUnref() { + // If the hasRef function does not exist, always run the code + if (!this.callRefTimer.hasRef || this.callRefTimer.hasRef()) { + this.trace( + 'callRefTimer.unref | configSelectionQueue.length=' + + this.configSelectionQueue.length + + ' pickQueue.length=' + + this.pickQueue.length + ); + this.callRefTimer.unref?.(); + } + } + + private removeConnectivityStateWatcher( + watcherObject: ConnectivityStateWatcher + ) { + const watcherIndex = this.connectivityStateWatchers.findIndex( + value => value === watcherObject + ); + if (watcherIndex >= 0) { + this.connectivityStateWatchers.splice(watcherIndex, 1); + } + } + + private updateState(newState: ConnectivityState): void { + trace( + LogVerbosity.DEBUG, + 'connectivity_state', + '(' + + this.channelzRef.id + + ') ' + + uriToString(this.target) + + ' ' + + ConnectivityState[this.connectivityState] + + ' -> ' + + ConnectivityState[newState] + ); + if (this.channelzEnabled) { + this.channelzTrace.addTrace( + 'CT_INFO', + 'Connectivity state change to ' + ConnectivityState[newState] + ); + } + this.connectivityState = newState; + const watchersCopy = this.connectivityStateWatchers.slice(); + for (const watcherObject of watchersCopy) { + if (newState !== watcherObject.currentState) { + if (watcherObject.timer) { + clearTimeout(watcherObject.timer); + } + this.removeConnectivityStateWatcher(watcherObject); + watcherObject.callback(); + } + } + if (newState !== ConnectivityState.TRANSIENT_FAILURE) { + this.currentResolutionError = null; + } + } + + throttleKeepalive(newKeepaliveTime: number) { + if (newKeepaliveTime > this.keepaliveTime) { + this.keepaliveTime = newKeepaliveTime; + for (const wrappedSubchannel of this.wrappedSubchannels) { + wrappedSubchannel.throttleKeepalive(newKeepaliveTime); + } + } + } + + removeWrappedSubchannel(wrappedSubchannel: ChannelSubchannelWrapper) { + this.wrappedSubchannels.delete(wrappedSubchannel); + } + + doPick(metadata: Metadata, extraPickInfo: { [key: string]: string }) { + return this.currentPicker.pick({ + metadata: metadata, + extraPickInfo: extraPickInfo, + }); + } + + queueCallForPick(call: LoadBalancingCall) { + this.pickQueue.push(call); + this.callRefTimerRef(); + } + + getConfig(method: string, metadata: Metadata): GetConfigResult { + this.resolvingLoadBalancer.exitIdle(); + if (this.configSelector) { + return { + type: 'SUCCESS', + config: this.configSelector(method, metadata, this.randomChannelId), + }; + } else { + if (this.currentResolutionError) { + return { + type: 'ERROR', + error: this.currentResolutionError, + }; + } else { + return { + type: 'NONE', + }; + } + } + } + + queueCallForConfig(call: ResolvingCall) { + this.configSelectionQueue.push(call); + this.callRefTimerRef(); + } + + private enterIdle() { + this.resolvingLoadBalancer.destroy(); + this.updateState(ConnectivityState.IDLE); + this.currentPicker = new QueuePicker(this.resolvingLoadBalancer); + if (this.idleTimer) { + clearTimeout(this.idleTimer); + this.idleTimer = null; + } + } + + private startIdleTimeout(timeoutMs: number) { + this.idleTimer = setTimeout(() => { + if (this.callCount > 0) { + /* If there is currently a call, the channel will not go idle for a + * period of at least idleTimeoutMs, so check again after that time. + */ + this.startIdleTimeout(this.idleTimeoutMs); + return; + } + const now = new Date(); + const timeSinceLastActivity = + now.valueOf() - this.lastActivityTimestamp.valueOf(); + if (timeSinceLastActivity >= this.idleTimeoutMs) { + this.trace( + 'Idle timer triggered after ' + + this.idleTimeoutMs + + 'ms of inactivity' + ); + this.enterIdle(); + } else { + /* Whenever the timer fires with the latest activity being too recent, + * set the timer again for the time when the time since the last + * activity is equal to the timeout. This should result in the timer + * firing no more than once every idleTimeoutMs/2 on average. */ + this.startIdleTimeout(this.idleTimeoutMs - timeSinceLastActivity); + } + }, timeoutMs); + this.idleTimer.unref?.(); + } + + private maybeStartIdleTimer() { + if ( + this.connectivityState !== ConnectivityState.SHUTDOWN && + !this.idleTimer + ) { + this.startIdleTimeout(this.idleTimeoutMs); + } + } + + private onCallStart() { + if (this.channelzEnabled) { + this.callTracker.addCallStarted(); + } + this.callCount += 1; + } + + private onCallEnd(status: StatusObject) { + if (this.channelzEnabled) { + if (status.code === Status.OK) { + this.callTracker.addCallSucceeded(); + } else { + this.callTracker.addCallFailed(); + } + } + this.callCount -= 1; + this.lastActivityTimestamp = new Date(); + this.maybeStartIdleTimer(); + } + + createLoadBalancingCall( + callConfig: CallConfig, + method: string, + host: string, + credentials: CallCredentials, + deadline: Deadline + ): LoadBalancingCall { + const callNumber = getNextCallNumber(); + this.trace( + 'createLoadBalancingCall [' + callNumber + '] method="' + method + '"' + ); + return new LoadBalancingCall( + this, + callConfig, + method, + host, + credentials, + deadline, + callNumber + ); + } + + createRetryingCall( + callConfig: CallConfig, + method: string, + host: string, + credentials: CallCredentials, + deadline: Deadline + ): RetryingCall { + const callNumber = getNextCallNumber(); + this.trace( + 'createRetryingCall [' + callNumber + '] method="' + method + '"' + ); + return new RetryingCall( + this, + callConfig, + method, + host, + credentials, + deadline, + callNumber, + this.retryBufferTracker, + RETRY_THROTTLER_MAP.get(this.getTarget()) + ); + } + + createInnerCall( + callConfig: CallConfig, + method: string, + host: string, + credentials: CallCredentials, + deadline: Deadline + ): LoadBalancingCall | RetryingCall { + // Create a RetryingCall if retries are enabled + if (this.options['grpc.enable_retries'] === 0) { + return this.createLoadBalancingCall( + callConfig, + method, + host, + credentials, + deadline + ); + } else { + return this.createRetryingCall( + callConfig, + method, + host, + credentials, + deadline + ); + } + } + + createResolvingCall( + method: string, + deadline: Deadline, + host: string | null | undefined, + parentCall: ServerSurfaceCall | null, + propagateFlags: number | null | undefined + ): ResolvingCall { + const callNumber = getNextCallNumber(); + this.trace( + 'createResolvingCall [' + + callNumber + + '] method="' + + method + + '", deadline=' + + deadlineToString(deadline) + ); + const finalOptions: CallStreamOptions = { + deadline: deadline, + flags: propagateFlags ?? Propagate.DEFAULTS, + host: host ?? this.defaultAuthority, + parentCall: parentCall, + }; + + const call = new ResolvingCall( + this, + method, + finalOptions, + this.filterStackFactory.clone(), + this.credentials._getCallCredentials(), + callNumber + ); + + this.onCallStart(); + call.addStatusWatcher(status => { + this.onCallEnd(status); + }); + return call; + } + + close() { + this.resolvingLoadBalancer.destroy(); + this.updateState(ConnectivityState.SHUTDOWN); + clearInterval(this.callRefTimer); + if (this.idleTimer) { + clearTimeout(this.idleTimer); + } + if (this.channelzEnabled) { + unregisterChannelzRef(this.channelzRef); + } + + this.subchannelPool.unrefUnusedSubchannels(); + } + + getTarget() { + return uriToString(this.target); + } + + getConnectivityState(tryToConnect: boolean) { + const connectivityState = this.connectivityState; + if (tryToConnect) { + this.resolvingLoadBalancer.exitIdle(); + this.lastActivityTimestamp = new Date(); + this.maybeStartIdleTimer(); + } + return connectivityState; + } + + watchConnectivityState( + currentState: ConnectivityState, + deadline: Date | number, + callback: (error?: Error) => void + ): void { + if (this.connectivityState === ConnectivityState.SHUTDOWN) { + throw new Error('Channel has been shut down'); + } + let timer = null; + if (deadline !== Infinity) { + const deadlineDate: Date = + deadline instanceof Date ? deadline : new Date(deadline); + const now = new Date(); + if (deadline === -Infinity || deadlineDate <= now) { + process.nextTick( + callback, + new Error('Deadline passed without connectivity state change') + ); + return; + } + timer = setTimeout(() => { + this.removeConnectivityStateWatcher(watcherObject); + callback( + new Error('Deadline passed without connectivity state change') + ); + }, deadlineDate.getTime() - now.getTime()); + } + const watcherObject = { + currentState, + callback, + timer, + }; + this.connectivityStateWatchers.push(watcherObject); + } + + /** + * Get the channelz reference object for this channel. The returned value is + * garbage if channelz is disabled for this channel. + * @returns + */ + getChannelzRef() { + return this.channelzRef; + } + + createCall( + method: string, + deadline: Deadline, + host: string | null | undefined, + parentCall: ServerSurfaceCall | null, + propagateFlags: number | null | undefined + ): Call { + if (typeof method !== 'string') { + throw new TypeError('Channel#createCall: method must be a string'); + } + if (!(typeof deadline === 'number' || deadline instanceof Date)) { + throw new TypeError( + 'Channel#createCall: deadline must be a number or Date' + ); + } + if (this.connectivityState === ConnectivityState.SHUTDOWN) { + throw new Error('Channel has been shut down'); + } + return this.createResolvingCall( + method, + deadline, + host, + parentCall, + propagateFlags + ); + } +} diff --git a/node_modules/@grpc/grpc-js/src/load-balancer-child-handler.ts b/node_modules/@grpc/grpc-js/src/load-balancer-child-handler.ts new file mode 100644 index 0000000..352ea7b --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/load-balancer-child-handler.ts @@ -0,0 +1,172 @@ +/* + * Copyright 2020 gRPC authors. + * + * 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. + * + */ + +import { + LoadBalancer, + ChannelControlHelper, + TypedLoadBalancingConfig, + createLoadBalancer, +} from './load-balancer'; +import { Endpoint, SubchannelAddress } from './subchannel-address'; +import { ChannelOptions } from './channel-options'; +import { ConnectivityState } from './connectivity-state'; +import { Picker } from './picker'; +import type { ChannelRef, SubchannelRef } from './channelz'; +import { SubchannelInterface } from './subchannel-interface'; + +const TYPE_NAME = 'child_load_balancer_helper'; + +export class ChildLoadBalancerHandler implements LoadBalancer { + private currentChild: LoadBalancer | null = null; + private pendingChild: LoadBalancer | null = null; + private latestConfig: TypedLoadBalancingConfig | null = null; + + private ChildPolicyHelper = class { + private child: LoadBalancer | null = null; + constructor(private parent: ChildLoadBalancerHandler) {} + createSubchannel( + subchannelAddress: SubchannelAddress, + subchannelArgs: ChannelOptions + ): SubchannelInterface { + return this.parent.channelControlHelper.createSubchannel( + subchannelAddress, + subchannelArgs + ); + } + updateState(connectivityState: ConnectivityState, picker: Picker): void { + if (this.calledByPendingChild()) { + if (connectivityState === ConnectivityState.CONNECTING) { + return; + } + this.parent.currentChild?.destroy(); + this.parent.currentChild = this.parent.pendingChild; + this.parent.pendingChild = null; + } else if (!this.calledByCurrentChild()) { + return; + } + this.parent.channelControlHelper.updateState(connectivityState, picker); + } + requestReresolution(): void { + const latestChild = this.parent.pendingChild ?? this.parent.currentChild; + if (this.child === latestChild) { + this.parent.channelControlHelper.requestReresolution(); + } + } + setChild(newChild: LoadBalancer) { + this.child = newChild; + } + addChannelzChild(child: ChannelRef | SubchannelRef) { + this.parent.channelControlHelper.addChannelzChild(child); + } + removeChannelzChild(child: ChannelRef | SubchannelRef) { + this.parent.channelControlHelper.removeChannelzChild(child); + } + + private calledByPendingChild(): boolean { + return this.child === this.parent.pendingChild; + } + private calledByCurrentChild(): boolean { + return this.child === this.parent.currentChild; + } + }; + + constructor( + private readonly channelControlHelper: ChannelControlHelper, + private readonly options: ChannelOptions + ) {} + + protected configUpdateRequiresNewPolicyInstance( + oldConfig: TypedLoadBalancingConfig, + newConfig: TypedLoadBalancingConfig + ): boolean { + return oldConfig.getLoadBalancerName() !== newConfig.getLoadBalancerName(); + } + + /** + * Prerequisites: lbConfig !== null and lbConfig.name is registered + * @param endpointList + * @param lbConfig + * @param attributes + */ + updateAddressList( + endpointList: Endpoint[], + lbConfig: TypedLoadBalancingConfig, + attributes: { [key: string]: unknown } + ): void { + let childToUpdate: LoadBalancer; + if ( + this.currentChild === null || + this.latestConfig === null || + this.configUpdateRequiresNewPolicyInstance(this.latestConfig, lbConfig) + ) { + const newHelper = new this.ChildPolicyHelper(this); + const newChild = createLoadBalancer(lbConfig, newHelper, this.options)!; + newHelper.setChild(newChild); + if (this.currentChild === null) { + this.currentChild = newChild; + childToUpdate = this.currentChild; + } else { + if (this.pendingChild) { + this.pendingChild.destroy(); + } + this.pendingChild = newChild; + childToUpdate = this.pendingChild; + } + } else { + if (this.pendingChild === null) { + childToUpdate = this.currentChild; + } else { + childToUpdate = this.pendingChild; + } + } + this.latestConfig = lbConfig; + childToUpdate.updateAddressList(endpointList, lbConfig, attributes); + } + exitIdle(): void { + if (this.currentChild) { + this.currentChild.exitIdle(); + if (this.pendingChild) { + this.pendingChild.exitIdle(); + } + } + } + resetBackoff(): void { + if (this.currentChild) { + this.currentChild.resetBackoff(); + if (this.pendingChild) { + this.pendingChild.resetBackoff(); + } + } + } + destroy(): void { + /* Note: state updates are only propagated from the child balancer if that + * object is equal to this.currentChild or this.pendingChild. Since this + * function sets both of those to null, no further state updates will + * occur after this function returns. */ + if (this.currentChild) { + this.currentChild.destroy(); + this.currentChild = null; + } + if (this.pendingChild) { + this.pendingChild.destroy(); + this.pendingChild = null; + } + } + getTypeName(): string { + return TYPE_NAME; + } +} diff --git a/node_modules/@grpc/grpc-js/src/load-balancer-outlier-detection.ts b/node_modules/@grpc/grpc-js/src/load-balancer-outlier-detection.ts new file mode 100644 index 0000000..8f2097f --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/load-balancer-outlier-detection.ts @@ -0,0 +1,835 @@ +/* + * Copyright 2022 gRPC authors. + * + * 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. + * + */ + +import { ChannelOptions } from './channel-options'; +import { ConnectivityState } from './connectivity-state'; +import { LogVerbosity, Status } from './constants'; +import { Duration, durationToMs, isDuration, msToDuration } from './duration'; +import { + ChannelControlHelper, + createChildChannelControlHelper, + registerLoadBalancerType, +} from './experimental'; +import { + selectLbConfigFromList, + LoadBalancer, + TypedLoadBalancingConfig, +} from './load-balancer'; +import { ChildLoadBalancerHandler } from './load-balancer-child-handler'; +import { PickArgs, Picker, PickResult, PickResultType } from './picker'; +import { + Endpoint, + EndpointMap, + SubchannelAddress, + endpointToString, +} from './subchannel-address'; +import { + BaseSubchannelWrapper, + SubchannelInterface, +} from './subchannel-interface'; +import * as logging from './logging'; +import { LoadBalancingConfig } from './service-config'; + +const TRACER_NAME = 'outlier_detection'; + +function trace(text: string): void { + logging.trace(LogVerbosity.DEBUG, TRACER_NAME, text); +} + +const TYPE_NAME = 'outlier_detection'; + +const OUTLIER_DETECTION_ENABLED = + (process.env.GRPC_EXPERIMENTAL_ENABLE_OUTLIER_DETECTION ?? 'true') === 'true'; + +export interface SuccessRateEjectionConfig { + readonly stdev_factor: number; + readonly enforcement_percentage: number; + readonly minimum_hosts: number; + readonly request_volume: number; +} + +export interface FailurePercentageEjectionConfig { + readonly threshold: number; + readonly enforcement_percentage: number; + readonly minimum_hosts: number; + readonly request_volume: number; +} + +export interface OutlierDetectionRawConfig { + interval?: Duration; + base_ejection_time?: Duration; + max_ejection_time?: Duration; + max_ejection_percent?: number; + success_rate_ejection?: Partial; + failure_percentage_ejection?: Partial; + child_policy: LoadBalancingConfig[]; +} + +const defaultSuccessRateEjectionConfig: SuccessRateEjectionConfig = { + stdev_factor: 1900, + enforcement_percentage: 100, + minimum_hosts: 5, + request_volume: 100, +}; + +const defaultFailurePercentageEjectionConfig: FailurePercentageEjectionConfig = + { + threshold: 85, + enforcement_percentage: 100, + minimum_hosts: 5, + request_volume: 50, + }; + +type TypeofValues = + | 'object' + | 'boolean' + | 'function' + | 'number' + | 'string' + | 'undefined'; + +function validateFieldType( + obj: any, + fieldName: string, + expectedType: TypeofValues, + objectName?: string +) { + if ( + fieldName in obj && + obj[fieldName] !== undefined && + typeof obj[fieldName] !== expectedType + ) { + const fullFieldName = objectName ? `${objectName}.${fieldName}` : fieldName; + throw new Error( + `outlier detection config ${fullFieldName} parse error: expected ${expectedType}, got ${typeof obj[ + fieldName + ]}` + ); + } +} + +function validatePositiveDuration( + obj: any, + fieldName: string, + objectName?: string +) { + const fullFieldName = objectName ? `${objectName}.${fieldName}` : fieldName; + if (fieldName in obj && obj[fieldName] !== undefined) { + if (!isDuration(obj[fieldName])) { + throw new Error( + `outlier detection config ${fullFieldName} parse error: expected Duration, got ${typeof obj[ + fieldName + ]}` + ); + } + if ( + !( + obj[fieldName].seconds >= 0 && + obj[fieldName].seconds <= 315_576_000_000 && + obj[fieldName].nanos >= 0 && + obj[fieldName].nanos <= 999_999_999 + ) + ) { + throw new Error( + `outlier detection config ${fullFieldName} parse error: values out of range for non-negative Duaration` + ); + } + } +} + +function validatePercentage(obj: any, fieldName: string, objectName?: string) { + const fullFieldName = objectName ? `${objectName}.${fieldName}` : fieldName; + validateFieldType(obj, fieldName, 'number', objectName); + if ( + fieldName in obj && + obj[fieldName] !== undefined && + !(obj[fieldName] >= 0 && obj[fieldName] <= 100) + ) { + throw new Error( + `outlier detection config ${fullFieldName} parse error: value out of range for percentage (0-100)` + ); + } +} + +export class OutlierDetectionLoadBalancingConfig + implements TypedLoadBalancingConfig +{ + private readonly intervalMs: number; + private readonly baseEjectionTimeMs: number; + private readonly maxEjectionTimeMs: number; + private readonly maxEjectionPercent: number; + private readonly successRateEjection: SuccessRateEjectionConfig | null; + private readonly failurePercentageEjection: FailurePercentageEjectionConfig | null; + + constructor( + intervalMs: number | null, + baseEjectionTimeMs: number | null, + maxEjectionTimeMs: number | null, + maxEjectionPercent: number | null, + successRateEjection: Partial | null, + failurePercentageEjection: Partial | null, + private readonly childPolicy: TypedLoadBalancingConfig + ) { + if (childPolicy.getLoadBalancerName() === 'pick_first') { + throw new Error( + 'outlier_detection LB policy cannot have a pick_first child policy' + ); + } + this.intervalMs = intervalMs ?? 10_000; + this.baseEjectionTimeMs = baseEjectionTimeMs ?? 30_000; + this.maxEjectionTimeMs = maxEjectionTimeMs ?? 300_000; + this.maxEjectionPercent = maxEjectionPercent ?? 10; + this.successRateEjection = successRateEjection + ? { ...defaultSuccessRateEjectionConfig, ...successRateEjection } + : null; + this.failurePercentageEjection = failurePercentageEjection + ? { + ...defaultFailurePercentageEjectionConfig, + ...failurePercentageEjection, + } + : null; + } + getLoadBalancerName(): string { + return TYPE_NAME; + } + toJsonObject(): object { + return { + outlier_detection: { + interval: msToDuration(this.intervalMs), + base_ejection_time: msToDuration(this.baseEjectionTimeMs), + max_ejection_time: msToDuration(this.maxEjectionTimeMs), + max_ejection_percent: this.maxEjectionPercent, + success_rate_ejection: this.successRateEjection ?? undefined, + failure_percentage_ejection: + this.failurePercentageEjection ?? undefined, + child_policy: [this.childPolicy.toJsonObject()], + }, + }; + } + + getIntervalMs(): number { + return this.intervalMs; + } + getBaseEjectionTimeMs(): number { + return this.baseEjectionTimeMs; + } + getMaxEjectionTimeMs(): number { + return this.maxEjectionTimeMs; + } + getMaxEjectionPercent(): number { + return this.maxEjectionPercent; + } + getSuccessRateEjectionConfig(): SuccessRateEjectionConfig | null { + return this.successRateEjection; + } + getFailurePercentageEjectionConfig(): FailurePercentageEjectionConfig | null { + return this.failurePercentageEjection; + } + getChildPolicy(): TypedLoadBalancingConfig { + return this.childPolicy; + } + + static createFromJson(obj: any): OutlierDetectionLoadBalancingConfig { + validatePositiveDuration(obj, 'interval'); + validatePositiveDuration(obj, 'base_ejection_time'); + validatePositiveDuration(obj, 'max_ejection_time'); + validatePercentage(obj, 'max_ejection_percent'); + if ( + 'success_rate_ejection' in obj && + obj.success_rate_ejection !== undefined + ) { + if (typeof obj.success_rate_ejection !== 'object') { + throw new Error( + 'outlier detection config success_rate_ejection must be an object' + ); + } + validateFieldType( + obj.success_rate_ejection, + 'stdev_factor', + 'number', + 'success_rate_ejection' + ); + validatePercentage( + obj.success_rate_ejection, + 'enforcement_percentage', + 'success_rate_ejection' + ); + validateFieldType( + obj.success_rate_ejection, + 'minimum_hosts', + 'number', + 'success_rate_ejection' + ); + validateFieldType( + obj.success_rate_ejection, + 'request_volume', + 'number', + 'success_rate_ejection' + ); + } + if ( + 'failure_percentage_ejection' in obj && + obj.failure_percentage_ejection !== undefined + ) { + if (typeof obj.failure_percentage_ejection !== 'object') { + throw new Error( + 'outlier detection config failure_percentage_ejection must be an object' + ); + } + validatePercentage( + obj.failure_percentage_ejection, + 'threshold', + 'failure_percentage_ejection' + ); + validatePercentage( + obj.failure_percentage_ejection, + 'enforcement_percentage', + 'failure_percentage_ejection' + ); + validateFieldType( + obj.failure_percentage_ejection, + 'minimum_hosts', + 'number', + 'failure_percentage_ejection' + ); + validateFieldType( + obj.failure_percentage_ejection, + 'request_volume', + 'number', + 'failure_percentage_ejection' + ); + } + + if (!('child_policy' in obj) || !Array.isArray(obj.child_policy)) { + throw new Error('outlier detection config child_policy must be an array'); + } + const childPolicy = selectLbConfigFromList(obj.child_policy); + if (!childPolicy) { + throw new Error( + 'outlier detection config child_policy: no valid recognized policy found' + ); + } + + return new OutlierDetectionLoadBalancingConfig( + obj.interval ? durationToMs(obj.interval) : null, + obj.base_ejection_time ? durationToMs(obj.base_ejection_time) : null, + obj.max_ejection_time ? durationToMs(obj.max_ejection_time) : null, + obj.max_ejection_percent ?? null, + obj.success_rate_ejection, + obj.failure_percentage_ejection, + childPolicy + ); + } +} + +class OutlierDetectionSubchannelWrapper + extends BaseSubchannelWrapper + implements SubchannelInterface +{ + private refCount = 0; + constructor( + childSubchannel: SubchannelInterface, + private mapEntry?: MapEntry + ) { + super(childSubchannel); + } + + ref() { + this.child.ref(); + this.refCount += 1; + } + + unref() { + this.child.unref(); + this.refCount -= 1; + if (this.refCount <= 0) { + if (this.mapEntry) { + const index = this.mapEntry.subchannelWrappers.indexOf(this); + if (index >= 0) { + this.mapEntry.subchannelWrappers.splice(index, 1); + } + } + } + } + + eject() { + this.setHealthy(false); + } + + uneject() { + this.setHealthy(true); + } + + getMapEntry(): MapEntry | undefined { + return this.mapEntry; + } + + getWrappedSubchannel(): SubchannelInterface { + return this.child; + } +} + +interface CallCountBucket { + success: number; + failure: number; +} + +function createEmptyBucket(): CallCountBucket { + return { + success: 0, + failure: 0, + }; +} + +class CallCounter { + private activeBucket: CallCountBucket = createEmptyBucket(); + private inactiveBucket: CallCountBucket = createEmptyBucket(); + addSuccess() { + this.activeBucket.success += 1; + } + addFailure() { + this.activeBucket.failure += 1; + } + switchBuckets() { + this.inactiveBucket = this.activeBucket; + this.activeBucket = createEmptyBucket(); + } + getLastSuccesses() { + return this.inactiveBucket.success; + } + getLastFailures() { + return this.inactiveBucket.failure; + } +} + +class OutlierDetectionPicker implements Picker { + constructor(private wrappedPicker: Picker, private countCalls: boolean) {} + pick(pickArgs: PickArgs): PickResult { + const wrappedPick = this.wrappedPicker.pick(pickArgs); + if (wrappedPick.pickResultType === PickResultType.COMPLETE) { + const subchannelWrapper = + wrappedPick.subchannel as OutlierDetectionSubchannelWrapper; + const mapEntry = subchannelWrapper.getMapEntry(); + if (mapEntry) { + let onCallEnded = wrappedPick.onCallEnded; + if (this.countCalls) { + onCallEnded = statusCode => { + if (statusCode === Status.OK) { + mapEntry.counter.addSuccess(); + } else { + mapEntry.counter.addFailure(); + } + wrappedPick.onCallEnded?.(statusCode); + }; + } + return { + ...wrappedPick, + subchannel: subchannelWrapper.getWrappedSubchannel(), + onCallEnded: onCallEnded, + }; + } else { + return { + ...wrappedPick, + subchannel: subchannelWrapper.getWrappedSubchannel(), + }; + } + } else { + return wrappedPick; + } + } +} + +interface MapEntry { + counter: CallCounter; + currentEjectionTimestamp: Date | null; + ejectionTimeMultiplier: number; + subchannelWrappers: OutlierDetectionSubchannelWrapper[]; +} + +export class OutlierDetectionLoadBalancer implements LoadBalancer { + private childBalancer: ChildLoadBalancerHandler; + private entryMap = new EndpointMap(); + private latestConfig: OutlierDetectionLoadBalancingConfig | null = null; + private ejectionTimer: NodeJS.Timeout; + private timerStartTime: Date | null = null; + + constructor( + channelControlHelper: ChannelControlHelper, + options: ChannelOptions + ) { + this.childBalancer = new ChildLoadBalancerHandler( + createChildChannelControlHelper(channelControlHelper, { + createSubchannel: ( + subchannelAddress: SubchannelAddress, + subchannelArgs: ChannelOptions + ) => { + const originalSubchannel = channelControlHelper.createSubchannel( + subchannelAddress, + subchannelArgs + ); + const mapEntry = + this.entryMap.getForSubchannelAddress(subchannelAddress); + const subchannelWrapper = new OutlierDetectionSubchannelWrapper( + originalSubchannel, + mapEntry + ); + if (mapEntry?.currentEjectionTimestamp !== null) { + // If the address is ejected, propagate that to the new subchannel wrapper + subchannelWrapper.eject(); + } + mapEntry?.subchannelWrappers.push(subchannelWrapper); + return subchannelWrapper; + }, + updateState: (connectivityState: ConnectivityState, picker: Picker) => { + if (connectivityState === ConnectivityState.READY) { + channelControlHelper.updateState( + connectivityState, + new OutlierDetectionPicker(picker, this.isCountingEnabled()) + ); + } else { + channelControlHelper.updateState(connectivityState, picker); + } + }, + }), + options + ); + this.ejectionTimer = setInterval(() => {}, 0); + clearInterval(this.ejectionTimer); + } + + private isCountingEnabled(): boolean { + return ( + this.latestConfig !== null && + (this.latestConfig.getSuccessRateEjectionConfig() !== null || + this.latestConfig.getFailurePercentageEjectionConfig() !== null) + ); + } + + private getCurrentEjectionPercent() { + let ejectionCount = 0; + for (const mapEntry of this.entryMap.values()) { + if (mapEntry.currentEjectionTimestamp !== null) { + ejectionCount += 1; + } + } + return (ejectionCount * 100) / this.entryMap.size; + } + + private runSuccessRateCheck(ejectionTimestamp: Date) { + if (!this.latestConfig) { + return; + } + const successRateConfig = this.latestConfig.getSuccessRateEjectionConfig(); + if (!successRateConfig) { + return; + } + trace('Running success rate check'); + // Step 1 + const targetRequestVolume = successRateConfig.request_volume; + let addresesWithTargetVolume = 0; + const successRates: number[] = []; + for (const [endpoint, mapEntry] of this.entryMap.entries()) { + const successes = mapEntry.counter.getLastSuccesses(); + const failures = mapEntry.counter.getLastFailures(); + trace( + 'Stats for ' + + endpointToString(endpoint) + + ': successes=' + + successes + + ' failures=' + + failures + + ' targetRequestVolume=' + + targetRequestVolume + ); + if (successes + failures >= targetRequestVolume) { + addresesWithTargetVolume += 1; + successRates.push(successes / (successes + failures)); + } + } + trace( + 'Found ' + + addresesWithTargetVolume + + ' success rate candidates; currentEjectionPercent=' + + this.getCurrentEjectionPercent() + + ' successRates=[' + + successRates + + ']' + ); + if (addresesWithTargetVolume < successRateConfig.minimum_hosts) { + return; + } + + // Step 2 + const successRateMean = + successRates.reduce((a, b) => a + b) / successRates.length; + let successRateDeviationSum = 0; + for (const rate of successRates) { + const deviation = rate - successRateMean; + successRateDeviationSum += deviation * deviation; + } + const successRateVariance = successRateDeviationSum / successRates.length; + const successRateStdev = Math.sqrt(successRateVariance); + const ejectionThreshold = + successRateMean - + successRateStdev * (successRateConfig.stdev_factor / 1000); + trace( + 'stdev=' + successRateStdev + ' ejectionThreshold=' + ejectionThreshold + ); + + // Step 3 + for (const [address, mapEntry] of this.entryMap.entries()) { + // Step 3.i + if ( + this.getCurrentEjectionPercent() >= + this.latestConfig.getMaxEjectionPercent() + ) { + break; + } + // Step 3.ii + const successes = mapEntry.counter.getLastSuccesses(); + const failures = mapEntry.counter.getLastFailures(); + if (successes + failures < targetRequestVolume) { + continue; + } + // Step 3.iii + const successRate = successes / (successes + failures); + trace('Checking candidate ' + address + ' successRate=' + successRate); + if (successRate < ejectionThreshold) { + const randomNumber = Math.random() * 100; + trace( + 'Candidate ' + + address + + ' randomNumber=' + + randomNumber + + ' enforcement_percentage=' + + successRateConfig.enforcement_percentage + ); + if (randomNumber < successRateConfig.enforcement_percentage) { + trace('Ejecting candidate ' + address); + this.eject(mapEntry, ejectionTimestamp); + } + } + } + } + + private runFailurePercentageCheck(ejectionTimestamp: Date) { + if (!this.latestConfig) { + return; + } + const failurePercentageConfig = + this.latestConfig.getFailurePercentageEjectionConfig(); + if (!failurePercentageConfig) { + return; + } + trace( + 'Running failure percentage check. threshold=' + + failurePercentageConfig.threshold + + ' request volume threshold=' + + failurePercentageConfig.request_volume + ); + // Step 1 + let addressesWithTargetVolume = 0; + for (const mapEntry of this.entryMap.values()) { + const successes = mapEntry.counter.getLastSuccesses(); + const failures = mapEntry.counter.getLastFailures(); + if (successes + failures >= failurePercentageConfig.request_volume) { + addressesWithTargetVolume += 1; + } + } + if (addressesWithTargetVolume < failurePercentageConfig.minimum_hosts) { + return; + } + + // Step 2 + for (const [address, mapEntry] of this.entryMap.entries()) { + // Step 2.i + if ( + this.getCurrentEjectionPercent() >= + this.latestConfig.getMaxEjectionPercent() + ) { + break; + } + // Step 2.ii + const successes = mapEntry.counter.getLastSuccesses(); + const failures = mapEntry.counter.getLastFailures(); + trace('Candidate successes=' + successes + ' failures=' + failures); + if (successes + failures < failurePercentageConfig.request_volume) { + continue; + } + // Step 2.iii + const failurePercentage = (failures * 100) / (failures + successes); + if (failurePercentage > failurePercentageConfig.threshold) { + const randomNumber = Math.random() * 100; + trace( + 'Candidate ' + + address + + ' randomNumber=' + + randomNumber + + ' enforcement_percentage=' + + failurePercentageConfig.enforcement_percentage + ); + if (randomNumber < failurePercentageConfig.enforcement_percentage) { + trace('Ejecting candidate ' + address); + this.eject(mapEntry, ejectionTimestamp); + } + } + } + } + + private eject(mapEntry: MapEntry, ejectionTimestamp: Date) { + mapEntry.currentEjectionTimestamp = new Date(); + mapEntry.ejectionTimeMultiplier += 1; + for (const subchannelWrapper of mapEntry.subchannelWrappers) { + subchannelWrapper.eject(); + } + } + + private uneject(mapEntry: MapEntry) { + mapEntry.currentEjectionTimestamp = null; + for (const subchannelWrapper of mapEntry.subchannelWrappers) { + subchannelWrapper.uneject(); + } + } + + private switchAllBuckets() { + for (const mapEntry of this.entryMap.values()) { + mapEntry.counter.switchBuckets(); + } + } + + private startTimer(delayMs: number) { + this.ejectionTimer = setTimeout(() => this.runChecks(), delayMs); + this.ejectionTimer.unref?.(); + } + + private runChecks() { + const ejectionTimestamp = new Date(); + trace('Ejection timer running'); + + this.switchAllBuckets(); + + if (!this.latestConfig) { + return; + } + this.timerStartTime = ejectionTimestamp; + this.startTimer(this.latestConfig.getIntervalMs()); + + this.runSuccessRateCheck(ejectionTimestamp); + this.runFailurePercentageCheck(ejectionTimestamp); + + for (const [address, mapEntry] of this.entryMap.entries()) { + if (mapEntry.currentEjectionTimestamp === null) { + if (mapEntry.ejectionTimeMultiplier > 0) { + mapEntry.ejectionTimeMultiplier -= 1; + } + } else { + const baseEjectionTimeMs = this.latestConfig.getBaseEjectionTimeMs(); + const maxEjectionTimeMs = this.latestConfig.getMaxEjectionTimeMs(); + const returnTime = new Date( + mapEntry.currentEjectionTimestamp.getTime() + ); + returnTime.setMilliseconds( + returnTime.getMilliseconds() + + Math.min( + baseEjectionTimeMs * mapEntry.ejectionTimeMultiplier, + Math.max(baseEjectionTimeMs, maxEjectionTimeMs) + ) + ); + if (returnTime < new Date()) { + trace('Unejecting ' + address); + this.uneject(mapEntry); + } + } + } + } + + updateAddressList( + endpointList: Endpoint[], + lbConfig: TypedLoadBalancingConfig, + attributes: { [key: string]: unknown } + ): void { + if (!(lbConfig instanceof OutlierDetectionLoadBalancingConfig)) { + return; + } + for (const endpoint of endpointList) { + if (!this.entryMap.has(endpoint)) { + trace('Adding map entry for ' + endpointToString(endpoint)); + this.entryMap.set(endpoint, { + counter: new CallCounter(), + currentEjectionTimestamp: null, + ejectionTimeMultiplier: 0, + subchannelWrappers: [], + }); + } + } + this.entryMap.deleteMissing(endpointList); + const childPolicy = lbConfig.getChildPolicy(); + this.childBalancer.updateAddressList(endpointList, childPolicy, attributes); + + if ( + lbConfig.getSuccessRateEjectionConfig() || + lbConfig.getFailurePercentageEjectionConfig() + ) { + if (this.timerStartTime) { + trace('Previous timer existed. Replacing timer'); + clearTimeout(this.ejectionTimer); + const remainingDelay = + lbConfig.getIntervalMs() - + (new Date().getTime() - this.timerStartTime.getTime()); + this.startTimer(remainingDelay); + } else { + trace('Starting new timer'); + this.timerStartTime = new Date(); + this.startTimer(lbConfig.getIntervalMs()); + this.switchAllBuckets(); + } + } else { + trace('Counting disabled. Cancelling timer.'); + this.timerStartTime = null; + clearTimeout(this.ejectionTimer); + for (const mapEntry of this.entryMap.values()) { + this.uneject(mapEntry); + mapEntry.ejectionTimeMultiplier = 0; + } + } + + this.latestConfig = lbConfig; + } + exitIdle(): void { + this.childBalancer.exitIdle(); + } + resetBackoff(): void { + this.childBalancer.resetBackoff(); + } + destroy(): void { + clearTimeout(this.ejectionTimer); + this.childBalancer.destroy(); + } + getTypeName(): string { + return TYPE_NAME; + } +} + +export function setup() { + if (OUTLIER_DETECTION_ENABLED) { + registerLoadBalancerType( + TYPE_NAME, + OutlierDetectionLoadBalancer, + OutlierDetectionLoadBalancingConfig + ); + } +} diff --git a/node_modules/@grpc/grpc-js/src/load-balancer-pick-first.ts b/node_modules/@grpc/grpc-js/src/load-balancer-pick-first.ts new file mode 100644 index 0000000..f6c43b3 --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/load-balancer-pick-first.ts @@ -0,0 +1,640 @@ +/* + * Copyright 2019 gRPC authors. + * + * 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. + * + */ + +import { + LoadBalancer, + ChannelControlHelper, + TypedLoadBalancingConfig, + registerDefaultLoadBalancerType, + registerLoadBalancerType, + createChildChannelControlHelper, +} from './load-balancer'; +import { ConnectivityState } from './connectivity-state'; +import { + QueuePicker, + Picker, + PickArgs, + CompletePickResult, + PickResultType, + UnavailablePicker, +} from './picker'; +import { Endpoint, SubchannelAddress } from './subchannel-address'; +import * as logging from './logging'; +import { LogVerbosity } from './constants'; +import { + SubchannelInterface, + ConnectivityStateListener, + HealthListener, +} from './subchannel-interface'; +import { isTcpSubchannelAddress } from './subchannel-address'; +import { isIPv6 } from 'net'; +import { ChannelOptions } from './channel-options'; + +const TRACER_NAME = 'pick_first'; + +function trace(text: string): void { + logging.trace(LogVerbosity.DEBUG, TRACER_NAME, text); +} + +const TYPE_NAME = 'pick_first'; + +/** + * Delay after starting a connection on a subchannel before starting a + * connection on the next subchannel in the list, for Happy Eyeballs algorithm. + */ +const CONNECTION_DELAY_INTERVAL_MS = 250; + +export class PickFirstLoadBalancingConfig implements TypedLoadBalancingConfig { + constructor(private readonly shuffleAddressList: boolean) {} + + getLoadBalancerName(): string { + return TYPE_NAME; + } + + toJsonObject(): object { + return { + [TYPE_NAME]: { + shuffleAddressList: this.shuffleAddressList, + }, + }; + } + + getShuffleAddressList() { + return this.shuffleAddressList; + } + + // eslint-disable-next-line @typescript-eslint/no-explicit-any + static createFromJson(obj: any) { + if ( + 'shuffleAddressList' in obj && + !(typeof obj.shuffleAddressList === 'boolean') + ) { + throw new Error( + 'pick_first config field shuffleAddressList must be a boolean if provided' + ); + } + return new PickFirstLoadBalancingConfig(obj.shuffleAddressList === true); + } +} + +/** + * Picker for a `PickFirstLoadBalancer` in the READY state. Always returns the + * picked subchannel. + */ +class PickFirstPicker implements Picker { + constructor(private subchannel: SubchannelInterface) {} + + pick(pickArgs: PickArgs): CompletePickResult { + return { + pickResultType: PickResultType.COMPLETE, + subchannel: this.subchannel, + status: null, + onCallStarted: null, + onCallEnded: null, + }; + } +} + +interface SubchannelChild { + subchannel: SubchannelInterface; + hasReportedTransientFailure: boolean; +} + +/** + * Return a new array with the elements of the input array in a random order + * @param list The input array + * @returns A shuffled array of the elements of list + */ +export function shuffled(list: T[]): T[] { + const result = list.slice(); + for (let i = result.length - 1; i > 1; i--) { + const j = Math.floor(Math.random() * (i + 1)); + const temp = result[i]; + result[i] = result[j]; + result[j] = temp; + } + return result; +} + +/** + * Interleave addresses in addressList by family in accordance with RFC-8304 section 4 + * @param addressList + * @returns + */ +function interleaveAddressFamilies( + addressList: SubchannelAddress[] +): SubchannelAddress[] { + const result: SubchannelAddress[] = []; + const ipv6Addresses: SubchannelAddress[] = []; + const ipv4Addresses: SubchannelAddress[] = []; + const ipv6First = + isTcpSubchannelAddress(addressList[0]) && isIPv6(addressList[0].host); + for (const address of addressList) { + if (isTcpSubchannelAddress(address) && isIPv6(address.host)) { + ipv6Addresses.push(address); + } else { + ipv4Addresses.push(address); + } + } + const firstList = ipv6First ? ipv6Addresses : ipv4Addresses; + const secondList = ipv6First ? ipv4Addresses : ipv6Addresses; + for (let i = 0; i < Math.max(firstList.length, secondList.length); i++) { + if (i < firstList.length) { + result.push(firstList[i]); + } + if (i < secondList.length) { + result.push(secondList[i]); + } + } + return result; +} + +const REPORT_HEALTH_STATUS_OPTION_NAME = + 'grpc-node.internal.pick-first.report_health_status'; + +export class PickFirstLoadBalancer implements LoadBalancer { + /** + * The list of subchannels this load balancer is currently attempting to + * connect to. + */ + private children: SubchannelChild[] = []; + /** + * The current connectivity state of the load balancer. + */ + private currentState: ConnectivityState = ConnectivityState.IDLE; + /** + * The index within the `subchannels` array of the subchannel with the most + * recently started connection attempt. + */ + private currentSubchannelIndex = 0; + /** + * The currently picked subchannel used for making calls. Populated if + * and only if the load balancer's current state is READY. In that case, + * the subchannel's current state is also READY. + */ + private currentPick: SubchannelInterface | null = null; + /** + * Listener callback attached to each subchannel in the `subchannels` list + * while establishing a connection. + */ + private subchannelStateListener: ConnectivityStateListener = ( + subchannel, + previousState, + newState, + keepaliveTime, + errorMessage + ) => { + this.onSubchannelStateUpdate( + subchannel, + previousState, + newState, + errorMessage + ); + }; + + private pickedSubchannelHealthListener: HealthListener = () => + this.calculateAndReportNewState(); + /** + * Timer reference for the timer tracking when to start + */ + private connectionDelayTimeout: NodeJS.Timeout; + + private triedAllSubchannels = false; + + /** + * The LB policy enters sticky TRANSIENT_FAILURE mode when all + * subchannels have failed to connect at least once, and it stays in that + * mode until a connection attempt is successful. While in sticky TF mode, + * the LB policy continuously attempts to connect to all of its subchannels. + */ + private stickyTransientFailureMode = false; + + private reportHealthStatus: boolean; + + /** + * Indicates whether we called channelControlHelper.requestReresolution since + * the last call to updateAddressList + */ + private requestedResolutionSinceLastUpdate = false; + + /** + * The most recent error reported by any subchannel as it transitioned to + * TRANSIENT_FAILURE. + */ + private lastError: string | null = null; + + private latestAddressList: SubchannelAddress[] | null = null; + + /** + * Load balancer that attempts to connect to each backend in the address list + * in order, and picks the first one that connects, using it for every + * request. + * @param channelControlHelper `ChannelControlHelper` instance provided by + * this load balancer's owner. + */ + constructor( + private readonly channelControlHelper: ChannelControlHelper, + options: ChannelOptions + ) { + this.connectionDelayTimeout = setTimeout(() => {}, 0); + clearTimeout(this.connectionDelayTimeout); + this.reportHealthStatus = options[REPORT_HEALTH_STATUS_OPTION_NAME]; + } + + private allChildrenHaveReportedTF(): boolean { + return this.children.every(child => child.hasReportedTransientFailure); + } + + private calculateAndReportNewState() { + if (this.currentPick) { + if (this.reportHealthStatus && !this.currentPick.isHealthy()) { + this.updateState( + ConnectivityState.TRANSIENT_FAILURE, + new UnavailablePicker({ + details: `Picked subchannel ${this.currentPick.getAddress()} is unhealthy`, + }) + ); + } else { + this.updateState( + ConnectivityState.READY, + new PickFirstPicker(this.currentPick) + ); + } + } else if (this.children.length === 0) { + this.updateState(ConnectivityState.IDLE, new QueuePicker(this)); + } else { + if (this.stickyTransientFailureMode) { + this.updateState( + ConnectivityState.TRANSIENT_FAILURE, + new UnavailablePicker({ + details: `No connection established. Last error: ${this.lastError}`, + }) + ); + } else { + this.updateState(ConnectivityState.CONNECTING, new QueuePicker(this)); + } + } + } + + private requestReresolution() { + this.requestedResolutionSinceLastUpdate = true; + this.channelControlHelper.requestReresolution(); + } + + private maybeEnterStickyTransientFailureMode() { + if (!this.allChildrenHaveReportedTF()) { + return; + } + if (!this.requestedResolutionSinceLastUpdate) { + /* Each time we get an update we reset each subchannel's + * hasReportedTransientFailure flag, so the next time we get to this + * point after that, each subchannel has reported TRANSIENT_FAILURE + * at least once since then. That is the trigger for requesting + * reresolution, whether or not the LB policy is already in sticky TF + * mode. */ + this.requestReresolution(); + } + if (this.stickyTransientFailureMode) { + return; + } + this.stickyTransientFailureMode = true; + for (const { subchannel } of this.children) { + subchannel.startConnecting(); + } + this.calculateAndReportNewState(); + } + + private removeCurrentPick() { + if (this.currentPick !== null) { + /* Unref can cause a state change, which can cause a change in the value + * of this.currentPick, so we hold a local reference to make sure that + * does not impact this function. */ + const currentPick = this.currentPick; + this.currentPick = null; + currentPick.unref(); + currentPick.removeConnectivityStateListener(this.subchannelStateListener); + this.channelControlHelper.removeChannelzChild( + currentPick.getChannelzRef() + ); + if (this.reportHealthStatus) { + currentPick.removeHealthStateWatcher( + this.pickedSubchannelHealthListener + ); + } + } + } + + private onSubchannelStateUpdate( + subchannel: SubchannelInterface, + previousState: ConnectivityState, + newState: ConnectivityState, + errorMessage?: string + ) { + if (this.currentPick?.realSubchannelEquals(subchannel)) { + if (newState !== ConnectivityState.READY) { + this.removeCurrentPick(); + this.calculateAndReportNewState(); + this.requestReresolution(); + } + return; + } + for (const [index, child] of this.children.entries()) { + if (subchannel.realSubchannelEquals(child.subchannel)) { + if (newState === ConnectivityState.READY) { + this.pickSubchannel(child.subchannel); + } + if (newState === ConnectivityState.TRANSIENT_FAILURE) { + child.hasReportedTransientFailure = true; + if (errorMessage) { + this.lastError = errorMessage; + } + this.maybeEnterStickyTransientFailureMode(); + if (index === this.currentSubchannelIndex) { + this.startNextSubchannelConnecting(index + 1); + } + } + child.subchannel.startConnecting(); + return; + } + } + } + + private startNextSubchannelConnecting(startIndex: number) { + clearTimeout(this.connectionDelayTimeout); + if (this.triedAllSubchannels) { + return; + } + for (const [index, child] of this.children.entries()) { + if (index >= startIndex) { + const subchannelState = child.subchannel.getConnectivityState(); + if ( + subchannelState === ConnectivityState.IDLE || + subchannelState === ConnectivityState.CONNECTING + ) { + this.startConnecting(index); + return; + } + } + } + this.triedAllSubchannels = true; + this.maybeEnterStickyTransientFailureMode(); + } + + /** + * Have a single subchannel in the `subchannels` list start connecting. + * @param subchannelIndex The index into the `subchannels` list. + */ + private startConnecting(subchannelIndex: number) { + clearTimeout(this.connectionDelayTimeout); + this.currentSubchannelIndex = subchannelIndex; + if ( + this.children[subchannelIndex].subchannel.getConnectivityState() === + ConnectivityState.IDLE + ) { + trace( + 'Start connecting to subchannel with address ' + + this.children[subchannelIndex].subchannel.getAddress() + ); + process.nextTick(() => { + this.children[subchannelIndex]?.subchannel.startConnecting(); + }); + } + this.connectionDelayTimeout = setTimeout(() => { + this.startNextSubchannelConnecting(subchannelIndex + 1); + }, CONNECTION_DELAY_INTERVAL_MS); + this.connectionDelayTimeout.unref?.(); + } + + private pickSubchannel(subchannel: SubchannelInterface) { + if (this.currentPick && subchannel.realSubchannelEquals(this.currentPick)) { + return; + } + trace('Pick subchannel with address ' + subchannel.getAddress()); + this.stickyTransientFailureMode = false; + this.removeCurrentPick(); + this.currentPick = subchannel; + subchannel.ref(); + if (this.reportHealthStatus) { + subchannel.addHealthStateWatcher(this.pickedSubchannelHealthListener); + } + this.channelControlHelper.addChannelzChild(subchannel.getChannelzRef()); + this.resetSubchannelList(); + clearTimeout(this.connectionDelayTimeout); + this.calculateAndReportNewState(); + } + + private updateState(newState: ConnectivityState, picker: Picker) { + trace( + ConnectivityState[this.currentState] + + ' -> ' + + ConnectivityState[newState] + ); + this.currentState = newState; + this.channelControlHelper.updateState(newState, picker); + } + + private resetSubchannelList() { + for (const child of this.children) { + if ( + !( + this.currentPick && + child.subchannel.realSubchannelEquals(this.currentPick) + ) + ) { + /* The connectivity state listener is the same whether the subchannel + * is in the list of children or it is the currentPick, so if it is in + * both, removing it here would cause problems. In particular, that + * always happens immediately after the subchannel is picked. */ + child.subchannel.removeConnectivityStateListener( + this.subchannelStateListener + ); + } + /* Refs are counted independently for the children list and the + * currentPick, so we call unref whether or not the child is the + * currentPick. Channelz child references are also refcounted, so + * removeChannelzChild can be handled the same way. */ + child.subchannel.unref(); + this.channelControlHelper.removeChannelzChild( + child.subchannel.getChannelzRef() + ); + } + this.currentSubchannelIndex = 0; + this.children = []; + this.triedAllSubchannels = false; + this.requestedResolutionSinceLastUpdate = false; + } + + private connectToAddressList(addressList: SubchannelAddress[]) { + const newChildrenList = addressList.map(address => ({ + subchannel: this.channelControlHelper.createSubchannel(address, {}), + hasReportedTransientFailure: false, + })); + /* Ref each subchannel before resetting the list, to ensure that + * subchannels shared between the list don't drop to 0 refs during the + * transition. */ + for (const { subchannel } of newChildrenList) { + subchannel.ref(); + this.channelControlHelper.addChannelzChild(subchannel.getChannelzRef()); + } + this.resetSubchannelList(); + this.children = newChildrenList; + for (const { subchannel } of this.children) { + subchannel.addConnectivityStateListener(this.subchannelStateListener); + if (subchannel.getConnectivityState() === ConnectivityState.READY) { + this.pickSubchannel(subchannel); + return; + } + } + for (const child of this.children) { + if ( + child.subchannel.getConnectivityState() === + ConnectivityState.TRANSIENT_FAILURE + ) { + child.hasReportedTransientFailure = true; + } + } + this.startNextSubchannelConnecting(0); + this.calculateAndReportNewState(); + } + + updateAddressList( + endpointList: Endpoint[], + lbConfig: TypedLoadBalancingConfig + ): void { + if (!(lbConfig instanceof PickFirstLoadBalancingConfig)) { + return; + } + /* Previously, an update would be discarded if it was identical to the + * previous update, to minimize churn. Now the DNS resolver is + * rate-limited, so that is less of a concern. */ + if (lbConfig.getShuffleAddressList()) { + endpointList = shuffled(endpointList); + } + const rawAddressList = ([] as SubchannelAddress[]).concat( + ...endpointList.map(endpoint => endpoint.addresses) + ); + if (rawAddressList.length === 0) { + throw new Error('No addresses in endpoint list passed to pick_first'); + } + const addressList = interleaveAddressFamilies(rawAddressList); + this.latestAddressList = addressList; + this.connectToAddressList(addressList); + } + + exitIdle() { + if ( + this.currentState === ConnectivityState.IDLE && + this.latestAddressList + ) { + this.connectToAddressList(this.latestAddressList); + } + } + + resetBackoff() { + /* The pick first load balancer does not have a connection backoff, so this + * does nothing */ + } + + destroy() { + this.resetSubchannelList(); + this.removeCurrentPick(); + } + + getTypeName(): string { + return TYPE_NAME; + } +} + +const LEAF_CONFIG = new PickFirstLoadBalancingConfig(false); + +/** + * This class handles the leaf load balancing operations for a single endpoint. + * It is a thin wrapper around a PickFirstLoadBalancer with a different API + * that more closely reflects how it will be used as a leaf balancer. + */ +export class LeafLoadBalancer { + private pickFirstBalancer: PickFirstLoadBalancer; + private latestState: ConnectivityState = ConnectivityState.IDLE; + private latestPicker: Picker; + constructor( + private endpoint: Endpoint, + channelControlHelper: ChannelControlHelper, + options: ChannelOptions + ) { + const childChannelControlHelper = createChildChannelControlHelper( + channelControlHelper, + { + updateState: (connectivityState, picker) => { + this.latestState = connectivityState; + this.latestPicker = picker; + channelControlHelper.updateState(connectivityState, picker); + }, + } + ); + this.pickFirstBalancer = new PickFirstLoadBalancer( + childChannelControlHelper, + { ...options, [REPORT_HEALTH_STATUS_OPTION_NAME]: true } + ); + this.latestPicker = new QueuePicker(this.pickFirstBalancer); + } + + startConnecting() { + this.pickFirstBalancer.updateAddressList([this.endpoint], LEAF_CONFIG); + } + + /** + * Update the endpoint associated with this LeafLoadBalancer to a new + * endpoint. Does not trigger connection establishment if a connection + * attempt is not already in progress. + * @param newEndpoint + */ + updateEndpoint(newEndpoint: Endpoint) { + this.endpoint = newEndpoint; + if (this.latestState !== ConnectivityState.IDLE) { + this.startConnecting(); + } + } + + getConnectivityState() { + return this.latestState; + } + + getPicker() { + return this.latestPicker; + } + + getEndpoint() { + return this.endpoint; + } + + exitIdle() { + this.pickFirstBalancer.exitIdle(); + } + + destroy() { + this.pickFirstBalancer.destroy(); + } +} + +export function setup(): void { + registerLoadBalancerType( + TYPE_NAME, + PickFirstLoadBalancer, + PickFirstLoadBalancingConfig + ); + registerDefaultLoadBalancerType(TYPE_NAME); +} diff --git a/node_modules/@grpc/grpc-js/src/load-balancer-round-robin.ts b/node_modules/@grpc/grpc-js/src/load-balancer-round-robin.ts new file mode 100644 index 0000000..7e70c55 --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/load-balancer-round-robin.ts @@ -0,0 +1,242 @@ +/* + * Copyright 2019 gRPC authors. + * + * 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. + * + */ + +import { + LoadBalancer, + ChannelControlHelper, + TypedLoadBalancingConfig, + registerLoadBalancerType, + createChildChannelControlHelper, +} from './load-balancer'; +import { ConnectivityState } from './connectivity-state'; +import { + QueuePicker, + Picker, + PickArgs, + UnavailablePicker, + PickResult, +} from './picker'; +import * as logging from './logging'; +import { LogVerbosity } from './constants'; +import { + Endpoint, + endpointEqual, + endpointToString, +} from './subchannel-address'; +import { LeafLoadBalancer } from './load-balancer-pick-first'; +import { ChannelOptions } from './channel-options'; + +const TRACER_NAME = 'round_robin'; + +function trace(text: string): void { + logging.trace(LogVerbosity.DEBUG, TRACER_NAME, text); +} + +const TYPE_NAME = 'round_robin'; + +class RoundRobinLoadBalancingConfig implements TypedLoadBalancingConfig { + getLoadBalancerName(): string { + return TYPE_NAME; + } + + constructor() {} + + toJsonObject(): object { + return { + [TYPE_NAME]: {}, + }; + } + + // eslint-disable-next-line @typescript-eslint/no-explicit-any + static createFromJson(obj: any) { + return new RoundRobinLoadBalancingConfig(); + } +} + +class RoundRobinPicker implements Picker { + constructor( + private readonly children: { endpoint: Endpoint; picker: Picker }[], + private nextIndex = 0 + ) {} + + pick(pickArgs: PickArgs): PickResult { + const childPicker = this.children[this.nextIndex].picker; + this.nextIndex = (this.nextIndex + 1) % this.children.length; + return childPicker.pick(pickArgs); + } + + /** + * Check what the next subchannel returned would be. Used by the load + * balancer implementation to preserve this part of the picker state if + * possible when a subchannel connects or disconnects. + */ + peekNextEndpoint(): Endpoint { + return this.children[this.nextIndex].endpoint; + } +} + +export class RoundRobinLoadBalancer implements LoadBalancer { + private children: LeafLoadBalancer[] = []; + + private currentState: ConnectivityState = ConnectivityState.IDLE; + + private currentReadyPicker: RoundRobinPicker | null = null; + + private updatesPaused = false; + + private childChannelControlHelper: ChannelControlHelper; + + private lastError: string | null = null; + + constructor( + private readonly channelControlHelper: ChannelControlHelper, + private readonly options: ChannelOptions + ) { + this.childChannelControlHelper = createChildChannelControlHelper( + channelControlHelper, + { + updateState: (connectivityState, picker) => { + this.calculateAndUpdateState(); + }, + } + ); + } + + private countChildrenWithState(state: ConnectivityState) { + return this.children.filter(child => child.getConnectivityState() === state) + .length; + } + + private calculateAndUpdateState() { + if (this.updatesPaused) { + return; + } + if (this.countChildrenWithState(ConnectivityState.READY) > 0) { + const readyChildren = this.children.filter( + child => child.getConnectivityState() === ConnectivityState.READY + ); + let index = 0; + if (this.currentReadyPicker !== null) { + const nextPickedEndpoint = this.currentReadyPicker.peekNextEndpoint(); + index = readyChildren.findIndex(child => + endpointEqual(child.getEndpoint(), nextPickedEndpoint) + ); + if (index < 0) { + index = 0; + } + } + this.updateState( + ConnectivityState.READY, + new RoundRobinPicker( + readyChildren.map(child => ({ + endpoint: child.getEndpoint(), + picker: child.getPicker(), + })), + index + ) + ); + } else if (this.countChildrenWithState(ConnectivityState.CONNECTING) > 0) { + this.updateState(ConnectivityState.CONNECTING, new QueuePicker(this)); + } else if ( + this.countChildrenWithState(ConnectivityState.TRANSIENT_FAILURE) > 0 + ) { + this.updateState( + ConnectivityState.TRANSIENT_FAILURE, + new UnavailablePicker({ + details: `No connection established. Last error: ${this.lastError}`, + }) + ); + } else { + this.updateState(ConnectivityState.IDLE, new QueuePicker(this)); + } + /* round_robin should keep all children connected, this is how we do that. + * We can't do this more efficiently in the individual child's updateState + * callback because that doesn't have a reference to which child the state + * change is associated with. */ + for (const child of this.children) { + if (child.getConnectivityState() === ConnectivityState.IDLE) { + child.exitIdle(); + } + } + } + + private updateState(newState: ConnectivityState, picker: Picker) { + trace( + ConnectivityState[this.currentState] + + ' -> ' + + ConnectivityState[newState] + ); + if (newState === ConnectivityState.READY) { + this.currentReadyPicker = picker as RoundRobinPicker; + } else { + this.currentReadyPicker = null; + } + this.currentState = newState; + this.channelControlHelper.updateState(newState, picker); + } + + private resetSubchannelList() { + for (const child of this.children) { + child.destroy(); + } + } + + updateAddressList( + endpointList: Endpoint[], + lbConfig: TypedLoadBalancingConfig + ): void { + this.resetSubchannelList(); + trace('Connect to endpoint list ' + endpointList.map(endpointToString)); + this.updatesPaused = true; + this.children = endpointList.map( + endpoint => + new LeafLoadBalancer( + endpoint, + this.childChannelControlHelper, + this.options + ) + ); + for (const child of this.children) { + child.startConnecting(); + } + this.updatesPaused = false; + this.calculateAndUpdateState(); + } + + exitIdle(): void { + /* The round_robin LB policy is only in the IDLE state if it has no + * addresses to try to connect to and it has no picked subchannel. + * In that case, there is no meaningful action that can be taken here. */ + } + resetBackoff(): void { + // This LB policy has no backoff to reset + } + destroy(): void { + this.resetSubchannelList(); + } + getTypeName(): string { + return TYPE_NAME; + } +} + +export function setup() { + registerLoadBalancerType( + TYPE_NAME, + RoundRobinLoadBalancer, + RoundRobinLoadBalancingConfig + ); +} diff --git a/node_modules/@grpc/grpc-js/src/load-balancer.ts b/node_modules/@grpc/grpc-js/src/load-balancer.ts new file mode 100644 index 0000000..fb353a5 --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/load-balancer.ts @@ -0,0 +1,252 @@ +/* + * Copyright 2019 gRPC authors. + * + * 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. + * + */ + +import { ChannelOptions } from './channel-options'; +import { Endpoint, SubchannelAddress } from './subchannel-address'; +import { ConnectivityState } from './connectivity-state'; +import { Picker } from './picker'; +import type { ChannelRef, SubchannelRef } from './channelz'; +import { SubchannelInterface } from './subchannel-interface'; +import { LoadBalancingConfig } from './service-config'; +import { log } from './logging'; +import { LogVerbosity } from './constants'; + +/** + * A collection of functions associated with a channel that a load balancer + * can call as necessary. + */ +export interface ChannelControlHelper { + /** + * Returns a subchannel connected to the specified address. + * @param subchannelAddress The address to connect to + * @param subchannelArgs Extra channel arguments specified by the load balancer + */ + createSubchannel( + subchannelAddress: SubchannelAddress, + subchannelArgs: ChannelOptions + ): SubchannelInterface; + /** + * Passes a new subchannel picker up to the channel. This is called if either + * the connectivity state changes or if a different picker is needed for any + * other reason. + * @param connectivityState New connectivity state + * @param picker New picker + */ + updateState(connectivityState: ConnectivityState, picker: Picker): void; + /** + * Request new data from the resolver. + */ + requestReresolution(): void; + addChannelzChild(child: ChannelRef | SubchannelRef): void; + removeChannelzChild(child: ChannelRef | SubchannelRef): void; +} + +/** + * Create a child ChannelControlHelper that overrides some methods of the + * parent while letting others pass through to the parent unmodified. This + * allows other code to create these children without needing to know about + * all of the methods to be passed through. + * @param parent + * @param overrides + */ +export function createChildChannelControlHelper( + parent: ChannelControlHelper, + overrides: Partial +): ChannelControlHelper { + return { + createSubchannel: + overrides.createSubchannel?.bind(overrides) ?? + parent.createSubchannel.bind(parent), + updateState: + overrides.updateState?.bind(overrides) ?? parent.updateState.bind(parent), + requestReresolution: + overrides.requestReresolution?.bind(overrides) ?? + parent.requestReresolution.bind(parent), + addChannelzChild: + overrides.addChannelzChild?.bind(overrides) ?? + parent.addChannelzChild.bind(parent), + removeChannelzChild: + overrides.removeChannelzChild?.bind(overrides) ?? + parent.removeChannelzChild.bind(parent), + }; +} + +/** + * Tracks one or more connected subchannels and determines which subchannel + * each request should use. + */ +export interface LoadBalancer { + /** + * Gives the load balancer a new list of addresses to start connecting to. + * The load balancer will start establishing connections with the new list, + * but will continue using any existing connections until the new connections + * are established + * @param endpointList The new list of addresses to connect to + * @param lbConfig The load balancing config object from the service config, + * if one was provided + */ + updateAddressList( + endpointList: Endpoint[], + lbConfig: TypedLoadBalancingConfig, + attributes: { [key: string]: unknown } + ): void; + /** + * If the load balancer is currently in the IDLE state, start connecting. + */ + exitIdle(): void; + /** + * If the load balancer is currently in the CONNECTING or TRANSIENT_FAILURE + * state, reset the current connection backoff timeout to its base value and + * transition to CONNECTING if in TRANSIENT_FAILURE. + */ + resetBackoff(): void; + /** + * The load balancer unrefs all of its subchannels and stops calling methods + * of its channel control helper. + */ + destroy(): void; + /** + * Get the type name for this load balancer type. Must be constant across an + * entire load balancer implementation class and must match the name that the + * balancer implementation class was registered with. + */ + getTypeName(): string; +} + +export interface LoadBalancerConstructor { + new ( + channelControlHelper: ChannelControlHelper, + options: ChannelOptions + ): LoadBalancer; +} + +export interface TypedLoadBalancingConfig { + getLoadBalancerName(): string; + toJsonObject(): object; +} + +export interface TypedLoadBalancingConfigConstructor { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + new (...args: any): TypedLoadBalancingConfig; + // eslint-disable-next-line @typescript-eslint/no-explicit-any + createFromJson(obj: any): TypedLoadBalancingConfig; +} + +const registeredLoadBalancerTypes: { + [name: string]: { + LoadBalancer: LoadBalancerConstructor; + LoadBalancingConfig: TypedLoadBalancingConfigConstructor; + }; +} = {}; + +let defaultLoadBalancerType: string | null = null; + +export function registerLoadBalancerType( + typeName: string, + loadBalancerType: LoadBalancerConstructor, + loadBalancingConfigType: TypedLoadBalancingConfigConstructor +) { + registeredLoadBalancerTypes[typeName] = { + LoadBalancer: loadBalancerType, + LoadBalancingConfig: loadBalancingConfigType, + }; +} + +export function registerDefaultLoadBalancerType(typeName: string) { + defaultLoadBalancerType = typeName; +} + +export function createLoadBalancer( + config: TypedLoadBalancingConfig, + channelControlHelper: ChannelControlHelper, + options: ChannelOptions +): LoadBalancer | null { + const typeName = config.getLoadBalancerName(); + if (typeName in registeredLoadBalancerTypes) { + return new registeredLoadBalancerTypes[typeName].LoadBalancer( + channelControlHelper, + options + ); + } else { + return null; + } +} + +export function isLoadBalancerNameRegistered(typeName: string): boolean { + return typeName in registeredLoadBalancerTypes; +} + +export function parseLoadBalancingConfig( + rawConfig: LoadBalancingConfig +): TypedLoadBalancingConfig { + const keys = Object.keys(rawConfig); + if (keys.length !== 1) { + throw new Error( + 'Provided load balancing config has multiple conflicting entries' + ); + } + const typeName = keys[0]; + if (typeName in registeredLoadBalancerTypes) { + try { + return registeredLoadBalancerTypes[ + typeName + ].LoadBalancingConfig.createFromJson(rawConfig[typeName]); + } catch (e) { + throw new Error(`${typeName}: ${(e as Error).message}`); + } + } else { + throw new Error(`Unrecognized load balancing config name ${typeName}`); + } +} + +export function getDefaultConfig() { + if (!defaultLoadBalancerType) { + throw new Error('No default load balancer type registered'); + } + return new registeredLoadBalancerTypes[ + defaultLoadBalancerType + ]!.LoadBalancingConfig(); +} + +export function selectLbConfigFromList( + configs: LoadBalancingConfig[], + fallbackTodefault = false +): TypedLoadBalancingConfig | null { + for (const config of configs) { + try { + return parseLoadBalancingConfig(config); + } catch (e) { + log( + LogVerbosity.DEBUG, + 'Config parsing failed with error', + (e as Error).message + ); + continue; + } + } + if (fallbackTodefault) { + if (defaultLoadBalancerType) { + return new registeredLoadBalancerTypes[ + defaultLoadBalancerType + ]!.LoadBalancingConfig(); + } else { + return null; + } + } else { + return null; + } +} diff --git a/node_modules/@grpc/grpc-js/src/load-balancing-call.ts b/node_modules/@grpc/grpc-js/src/load-balancing-call.ts new file mode 100644 index 0000000..7647697 --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/load-balancing-call.ts @@ -0,0 +1,378 @@ +/* + * Copyright 2022 gRPC authors. + * + * 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. + * + */ + +import { CallCredentials } from './call-credentials'; +import { + Call, + DeadlineInfoProvider, + InterceptingListener, + MessageContext, + StatusObject, +} from './call-interface'; +import { SubchannelCall } from './subchannel-call'; +import { ConnectivityState } from './connectivity-state'; +import { LogVerbosity, Status } from './constants'; +import { Deadline, formatDateDifference, getDeadlineTimeoutString } from './deadline'; +import { InternalChannel } from './internal-channel'; +import { Metadata } from './metadata'; +import { PickResultType } from './picker'; +import { CallConfig } from './resolver'; +import { splitHostPort } from './uri-parser'; +import * as logging from './logging'; +import { restrictControlPlaneStatusCode } from './control-plane-status'; +import * as http2 from 'http2'; + +const TRACER_NAME = 'load_balancing_call'; + +export type RpcProgress = 'NOT_STARTED' | 'DROP' | 'REFUSED' | 'PROCESSED'; + +export interface StatusObjectWithProgress extends StatusObject { + progress: RpcProgress; +} + +export interface LoadBalancingCallInterceptingListener + extends InterceptingListener { + onReceiveStatus(status: StatusObjectWithProgress): void; +} + +export class LoadBalancingCall implements Call, DeadlineInfoProvider { + private child: SubchannelCall | null = null; + private readPending = false; + private pendingMessage: { context: MessageContext; message: Buffer } | null = + null; + private pendingHalfClose = false; + private ended = false; + private serviceUrl: string; + private metadata: Metadata | null = null; + private listener: InterceptingListener | null = null; + private onCallEnded: ((statusCode: Status) => void) | null = null; + private startTime: Date; + private childStartTime: Date | null = null; + constructor( + private readonly channel: InternalChannel, + private readonly callConfig: CallConfig, + private readonly methodName: string, + private readonly host: string, + private readonly credentials: CallCredentials, + private readonly deadline: Deadline, + private readonly callNumber: number + ) { + const splitPath: string[] = this.methodName.split('/'); + let serviceName = ''; + /* The standard path format is "/{serviceName}/{methodName}", so if we split + * by '/', the first item should be empty and the second should be the + * service name */ + if (splitPath.length >= 2) { + serviceName = splitPath[1]; + } + const hostname = splitHostPort(this.host)?.host ?? 'localhost'; + /* Currently, call credentials are only allowed on HTTPS connections, so we + * can assume that the scheme is "https" */ + this.serviceUrl = `https://${hostname}/${serviceName}`; + this.startTime = new Date(); + } + getDeadlineInfo(): string[] { + const deadlineInfo: string[] = []; + if (this.childStartTime) { + if (this.childStartTime > this.startTime) { + if (this.metadata?.getOptions().waitForReady) { + deadlineInfo.push('wait_for_ready'); + } + deadlineInfo.push(`LB pick: ${formatDateDifference(this.startTime, this.childStartTime)}`); + } + deadlineInfo.push(...this.child!.getDeadlineInfo()); + return deadlineInfo; + } else { + if (this.metadata?.getOptions().waitForReady) { + deadlineInfo.push('wait_for_ready'); + } + deadlineInfo.push('Waiting for LB pick'); + } + return deadlineInfo; + } + + private trace(text: string): void { + logging.trace( + LogVerbosity.DEBUG, + TRACER_NAME, + '[' + this.callNumber + '] ' + text + ); + } + + private outputStatus(status: StatusObject, progress: RpcProgress) { + if (!this.ended) { + this.ended = true; + this.trace( + 'ended with status: code=' + + status.code + + ' details="' + + status.details + + '" start time=' + + this.startTime.toISOString() + ); + const finalStatus = { ...status, progress }; + this.listener?.onReceiveStatus(finalStatus); + this.onCallEnded?.(finalStatus.code); + } + } + + doPick() { + if (this.ended) { + return; + } + if (!this.metadata) { + throw new Error('doPick called before start'); + } + this.trace('Pick called'); + const finalMetadata = this.metadata.clone(); + const pickResult = this.channel.doPick( + finalMetadata, + this.callConfig.pickInformation + ); + const subchannelString = pickResult.subchannel + ? '(' + + pickResult.subchannel.getChannelzRef().id + + ') ' + + pickResult.subchannel.getAddress() + : '' + pickResult.subchannel; + this.trace( + 'Pick result: ' + + PickResultType[pickResult.pickResultType] + + ' subchannel: ' + + subchannelString + + ' status: ' + + pickResult.status?.code + + ' ' + + pickResult.status?.details + ); + switch (pickResult.pickResultType) { + case PickResultType.COMPLETE: + this.credentials + .generateMetadata({ service_url: this.serviceUrl }) + .then( + credsMetadata => { + /* If this call was cancelled (e.g. by the deadline) before + * metadata generation finished, we shouldn't do anything with + * it. */ + if (this.ended) { + this.trace( + 'Credentials metadata generation finished after call ended' + ); + return; + } + finalMetadata.merge(credsMetadata); + if (finalMetadata.get('authorization').length > 1) { + this.outputStatus( + { + code: Status.INTERNAL, + details: + '"authorization" metadata cannot have multiple values', + metadata: new Metadata(), + }, + 'PROCESSED' + ); + } + if ( + pickResult.subchannel!.getConnectivityState() !== + ConnectivityState.READY + ) { + this.trace( + 'Picked subchannel ' + + subchannelString + + ' has state ' + + ConnectivityState[ + pickResult.subchannel!.getConnectivityState() + ] + + ' after getting credentials metadata. Retrying pick' + ); + this.doPick(); + return; + } + + if (this.deadline !== Infinity) { + finalMetadata.set( + 'grpc-timeout', + getDeadlineTimeoutString(this.deadline) + ); + } + try { + this.child = pickResult + .subchannel!.getRealSubchannel() + .createCall(finalMetadata, this.host, this.methodName, { + onReceiveMetadata: metadata => { + this.trace('Received metadata'); + this.listener!.onReceiveMetadata(metadata); + }, + onReceiveMessage: message => { + this.trace('Received message'); + this.listener!.onReceiveMessage(message); + }, + onReceiveStatus: status => { + this.trace('Received status'); + if ( + status.rstCode === + http2.constants.NGHTTP2_REFUSED_STREAM + ) { + this.outputStatus(status, 'REFUSED'); + } else { + this.outputStatus(status, 'PROCESSED'); + } + }, + }); + this.childStartTime = new Date(); + } catch (error) { + this.trace( + 'Failed to start call on picked subchannel ' + + subchannelString + + ' with error ' + + (error as Error).message + ); + this.outputStatus( + { + code: Status.INTERNAL, + details: + 'Failed to start HTTP/2 stream with error ' + + (error as Error).message, + metadata: new Metadata(), + }, + 'NOT_STARTED' + ); + return; + } + this.callConfig.onCommitted?.(); + pickResult.onCallStarted?.(); + this.onCallEnded = pickResult.onCallEnded; + this.trace( + 'Created child call [' + this.child.getCallNumber() + ']' + ); + if (this.readPending) { + this.child.startRead(); + } + if (this.pendingMessage) { + this.child.sendMessageWithContext( + this.pendingMessage.context, + this.pendingMessage.message + ); + } + if (this.pendingHalfClose) { + this.child.halfClose(); + } + }, + (error: Error & { code: number }) => { + // We assume the error code isn't 0 (Status.OK) + const { code, details } = restrictControlPlaneStatusCode( + typeof error.code === 'number' ? error.code : Status.UNKNOWN, + `Getting metadata from plugin failed with error: ${error.message}` + ); + this.outputStatus( + { + code: code, + details: details, + metadata: new Metadata(), + }, + 'PROCESSED' + ); + } + ); + break; + case PickResultType.DROP: + const { code, details } = restrictControlPlaneStatusCode( + pickResult.status!.code, + pickResult.status!.details + ); + setImmediate(() => { + this.outputStatus( + { code, details, metadata: pickResult.status!.metadata }, + 'DROP' + ); + }); + break; + case PickResultType.TRANSIENT_FAILURE: + if (this.metadata.getOptions().waitForReady) { + this.channel.queueCallForPick(this); + } else { + const { code, details } = restrictControlPlaneStatusCode( + pickResult.status!.code, + pickResult.status!.details + ); + setImmediate(() => { + this.outputStatus( + { code, details, metadata: pickResult.status!.metadata }, + 'PROCESSED' + ); + }); + } + break; + case PickResultType.QUEUE: + this.channel.queueCallForPick(this); + } + } + + cancelWithStatus(status: Status, details: string): void { + this.trace( + 'cancelWithStatus code: ' + status + ' details: "' + details + '"' + ); + this.child?.cancelWithStatus(status, details); + this.outputStatus( + { code: status, details: details, metadata: new Metadata() }, + 'PROCESSED' + ); + } + getPeer(): string { + return this.child?.getPeer() ?? this.channel.getTarget(); + } + start( + metadata: Metadata, + listener: LoadBalancingCallInterceptingListener + ): void { + this.trace('start called'); + this.listener = listener; + this.metadata = metadata; + this.doPick(); + } + sendMessageWithContext(context: MessageContext, message: Buffer): void { + this.trace('write() called with message of length ' + message.length); + if (this.child) { + this.child.sendMessageWithContext(context, message); + } else { + this.pendingMessage = { context, message }; + } + } + startRead(): void { + this.trace('startRead called'); + if (this.child) { + this.child.startRead(); + } else { + this.readPending = true; + } + } + halfClose(): void { + this.trace('halfClose called'); + if (this.child) { + this.child.halfClose(); + } else { + this.pendingHalfClose = true; + } + } + setCredentials(credentials: CallCredentials): void { + throw new Error('Method not implemented.'); + } + + getCallNumber(): number { + return this.callNumber; + } +} diff --git a/node_modules/@grpc/grpc-js/src/logging.ts b/node_modules/@grpc/grpc-js/src/logging.ts new file mode 100644 index 0000000..2279d3b --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/logging.ts @@ -0,0 +1,134 @@ +/* + * Copyright 2019 gRPC authors. + * + * 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. + * + */ + +import { LogVerbosity } from './constants'; +import { pid } from 'process'; + +const clientVersion = require('../../package.json').version; + +const DEFAULT_LOGGER: Partial = { + error: (message?: any, ...optionalParams: any[]) => { + console.error('E ' + message, ...optionalParams); + }, + info: (message?: any, ...optionalParams: any[]) => { + console.error('I ' + message, ...optionalParams); + }, + debug: (message?: any, ...optionalParams: any[]) => { + console.error('D ' + message, ...optionalParams); + }, +}; + +let _logger: Partial = DEFAULT_LOGGER; +let _logVerbosity: LogVerbosity = LogVerbosity.ERROR; + +const verbosityString = + process.env.GRPC_NODE_VERBOSITY ?? process.env.GRPC_VERBOSITY ?? ''; + +switch (verbosityString.toUpperCase()) { + case 'DEBUG': + _logVerbosity = LogVerbosity.DEBUG; + break; + case 'INFO': + _logVerbosity = LogVerbosity.INFO; + break; + case 'ERROR': + _logVerbosity = LogVerbosity.ERROR; + break; + case 'NONE': + _logVerbosity = LogVerbosity.NONE; + break; + default: + // Ignore any other values +} + +export const getLogger = (): Partial => { + return _logger; +}; + +export const setLogger = (logger: Partial): void => { + _logger = logger; +}; + +export const setLoggerVerbosity = (verbosity: LogVerbosity): void => { + _logVerbosity = verbosity; +}; + +// eslint-disable-next-line @typescript-eslint/no-explicit-any +export const log = (severity: LogVerbosity, ...args: any[]): void => { + let logFunction: typeof DEFAULT_LOGGER.error; + if (severity >= _logVerbosity) { + switch (severity) { + case LogVerbosity.DEBUG: + logFunction = _logger.debug; + break; + case LogVerbosity.INFO: + logFunction = _logger.info; + break; + case LogVerbosity.ERROR: + logFunction = _logger.error; + break; + } + /* Fall back to _logger.error when other methods are not available for + * compatiblity with older behavior that always logged to _logger.error */ + if (!logFunction) { + logFunction = _logger.error; + } + if (logFunction) { + logFunction.bind(_logger)(...args); + } + } +}; + +const tracersString = + process.env.GRPC_NODE_TRACE ?? process.env.GRPC_TRACE ?? ''; +const enabledTracers = new Set(); +const disabledTracers = new Set(); +for (const tracerName of tracersString.split(',')) { + if (tracerName.startsWith('-')) { + disabledTracers.add(tracerName.substring(1)); + } else { + enabledTracers.add(tracerName); + } +} +const allEnabled = enabledTracers.has('all'); + +export function trace( + severity: LogVerbosity, + tracer: string, + text: string +): void { + if (isTracerEnabled(tracer)) { + log( + severity, + new Date().toISOString() + + ' | v' + + clientVersion + + ' ' + + pid + + ' | ' + + tracer + + ' | ' + + text + ); + } +} + +export function isTracerEnabled(tracer: string): boolean { + return ( + !disabledTracers.has(tracer) && (allEnabled || enabledTracers.has(tracer)) + ); +} diff --git a/node_modules/@grpc/grpc-js/src/make-client.ts b/node_modules/@grpc/grpc-js/src/make-client.ts new file mode 100644 index 0000000..10d1e95 --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/make-client.ts @@ -0,0 +1,238 @@ +/* + * Copyright 2019 gRPC authors. + * + * 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. + * + */ + +import { ChannelCredentials } from './channel-credentials'; +import { ChannelOptions } from './channel-options'; +import { Client } from './client'; +import { UntypedServiceImplementation } from './server'; + +export interface Serialize { + (value: T): Buffer; +} + +export interface Deserialize { + (bytes: Buffer): T; +} + +export interface ClientMethodDefinition { + path: string; + requestStream: boolean; + responseStream: boolean; + requestSerialize: Serialize; + responseDeserialize: Deserialize; + originalName?: string; +} + +export interface ServerMethodDefinition { + path: string; + requestStream: boolean; + responseStream: boolean; + responseSerialize: Serialize; + requestDeserialize: Deserialize; + originalName?: string; +} + +export interface MethodDefinition + extends ClientMethodDefinition, + ServerMethodDefinition {} + +/* eslint-disable @typescript-eslint/no-explicit-any */ +export type ServiceDefinition< + ImplementationType = UntypedServiceImplementation +> = { + readonly [index in keyof ImplementationType]: MethodDefinition; +}; +/* eslint-enable @typescript-eslint/no-explicit-any */ + +export interface ProtobufTypeDefinition { + format: string; + type: object; + fileDescriptorProtos: Buffer[]; +} + +export interface PackageDefinition { + [index: string]: ServiceDefinition | ProtobufTypeDefinition; +} + +/** + * Map with short names for each of the requester maker functions. Used in + * makeClientConstructor + * @private + */ +const requesterFuncs = { + unary: Client.prototype.makeUnaryRequest, + server_stream: Client.prototype.makeServerStreamRequest, + client_stream: Client.prototype.makeClientStreamRequest, + bidi: Client.prototype.makeBidiStreamRequest, +}; + +export interface ServiceClient extends Client { + [methodName: string]: Function; +} + +export interface ServiceClientConstructor { + new ( + address: string, + credentials: ChannelCredentials, + options?: Partial + ): ServiceClient; + service: ServiceDefinition; + serviceName: string; +} + +/** + * Returns true, if given key is included in the blacklisted + * keys. + * @param key key for check, string. + */ +function isPrototypePolluted(key: string): boolean { + return ['__proto__', 'prototype', 'constructor'].includes(key); +} + +/** + * Creates a constructor for a client with the given methods, as specified in + * the methods argument. The resulting class will have an instance method for + * each method in the service, which is a partial application of one of the + * [Client]{@link grpc.Client} request methods, depending on `requestSerialize` + * and `responseSerialize`, with the `method`, `serialize`, and `deserialize` + * arguments predefined. + * @param methods An object mapping method names to + * method attributes + * @param serviceName The fully qualified name of the service + * @param classOptions An options object. + * @return New client constructor, which is a subclass of + * {@link grpc.Client}, and has the same arguments as that constructor. + */ +export function makeClientConstructor( + methods: ServiceDefinition, + serviceName: string, + classOptions?: {} +): ServiceClientConstructor { + if (!classOptions) { + classOptions = {}; + } + + class ServiceClientImpl extends Client implements ServiceClient { + static service: ServiceDefinition; + static serviceName: string; + [methodName: string]: Function; + } + + Object.keys(methods).forEach(name => { + if (isPrototypePolluted(name)) { + return; + } + const attrs = methods[name]; + let methodType: keyof typeof requesterFuncs; + // TODO(murgatroid99): Verify that we don't need this anymore + if (typeof name === 'string' && name.charAt(0) === '$') { + throw new Error('Method names cannot start with $'); + } + if (attrs.requestStream) { + if (attrs.responseStream) { + methodType = 'bidi'; + } else { + methodType = 'client_stream'; + } + } else { + if (attrs.responseStream) { + methodType = 'server_stream'; + } else { + methodType = 'unary'; + } + } + const serialize = attrs.requestSerialize; + const deserialize = attrs.responseDeserialize; + const methodFunc = partial( + requesterFuncs[methodType], + attrs.path, + serialize, + deserialize + ); + ServiceClientImpl.prototype[name] = methodFunc; + // Associate all provided attributes with the method + Object.assign(ServiceClientImpl.prototype[name], attrs); + if (attrs.originalName && !isPrototypePolluted(attrs.originalName)) { + ServiceClientImpl.prototype[attrs.originalName] = + ServiceClientImpl.prototype[name]; + } + }); + + ServiceClientImpl.service = methods; + ServiceClientImpl.serviceName = serviceName; + + return ServiceClientImpl; +} + +function partial( + fn: Function, + path: string, + serialize: Function, + deserialize: Function +): Function { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + return function (this: any, ...args: any[]) { + return fn.call(this, path, serialize, deserialize, ...args); + }; +} + +export interface GrpcObject { + [index: string]: + | GrpcObject + | ServiceClientConstructor + | ProtobufTypeDefinition; +} + +function isProtobufTypeDefinition( + obj: ServiceDefinition | ProtobufTypeDefinition +): obj is ProtobufTypeDefinition { + return 'format' in obj; +} + +/** + * Load a gRPC package definition as a gRPC object hierarchy. + * @param packageDef The package definition object. + * @return The resulting gRPC object. + */ +export function loadPackageDefinition( + packageDef: PackageDefinition +): GrpcObject { + const result: GrpcObject = {}; + for (const serviceFqn in packageDef) { + if (Object.prototype.hasOwnProperty.call(packageDef, serviceFqn)) { + const service = packageDef[serviceFqn]; + const nameComponents = serviceFqn.split('.'); + if (nameComponents.some((comp: string) => isPrototypePolluted(comp))) { + continue; + } + const serviceName = nameComponents[nameComponents.length - 1]; + let current = result; + for (const packageName of nameComponents.slice(0, -1)) { + if (!current[packageName]) { + current[packageName] = {}; + } + current = current[packageName] as GrpcObject; + } + if (isProtobufTypeDefinition(service)) { + current[serviceName] = service; + } else { + current[serviceName] = makeClientConstructor(service, serviceName, {}); + } + } + } + return result; +} diff --git a/node_modules/@grpc/grpc-js/src/max-message-size-filter.ts b/node_modules/@grpc/grpc-js/src/max-message-size-filter.ts new file mode 100644 index 0000000..b6df374 --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/max-message-size-filter.ts @@ -0,0 +1,88 @@ +/* + * Copyright 2020 gRPC authors. + * + * 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. + * + */ + +import { BaseFilter, Filter, FilterFactory } from './filter'; +import { WriteObject } from './call-interface'; +import { + Status, + DEFAULT_MAX_SEND_MESSAGE_LENGTH, + DEFAULT_MAX_RECEIVE_MESSAGE_LENGTH, +} from './constants'; +import { ChannelOptions } from './channel-options'; +import { Metadata } from './metadata'; + +export class MaxMessageSizeFilter extends BaseFilter implements Filter { + private maxSendMessageSize: number = DEFAULT_MAX_SEND_MESSAGE_LENGTH; + private maxReceiveMessageSize: number = DEFAULT_MAX_RECEIVE_MESSAGE_LENGTH; + constructor(options: ChannelOptions) { + super(); + if ('grpc.max_send_message_length' in options) { + this.maxSendMessageSize = options['grpc.max_send_message_length']!; + } + if ('grpc.max_receive_message_length' in options) { + this.maxReceiveMessageSize = options['grpc.max_receive_message_length']!; + } + } + + async sendMessage(message: Promise): Promise { + /* A configured size of -1 means that there is no limit, so skip the check + * entirely */ + if (this.maxSendMessageSize === -1) { + return message; + } else { + const concreteMessage = await message; + if (concreteMessage.message.length > this.maxSendMessageSize) { + throw { + code: Status.RESOURCE_EXHAUSTED, + details: `Sent message larger than max (${concreteMessage.message.length} vs. ${this.maxSendMessageSize})`, + metadata: new Metadata(), + }; + } else { + return concreteMessage; + } + } + } + + async receiveMessage(message: Promise): Promise { + /* A configured size of -1 means that there is no limit, so skip the check + * entirely */ + if (this.maxReceiveMessageSize === -1) { + return message; + } else { + const concreteMessage = await message; + if (concreteMessage.length > this.maxReceiveMessageSize) { + throw { + code: Status.RESOURCE_EXHAUSTED, + details: `Received message larger than max (${concreteMessage.length} vs. ${this.maxReceiveMessageSize})`, + metadata: new Metadata(), + }; + } else { + return concreteMessage; + } + } + } +} + +export class MaxMessageSizeFilterFactory + implements FilterFactory +{ + constructor(private readonly options: ChannelOptions) {} + + createFilter(): MaxMessageSizeFilter { + return new MaxMessageSizeFilter(this.options); + } +} diff --git a/node_modules/@grpc/grpc-js/src/metadata.ts b/node_modules/@grpc/grpc-js/src/metadata.ts new file mode 100644 index 0000000..eabd2df --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/metadata.ts @@ -0,0 +1,298 @@ +/* + * Copyright 2019 gRPC authors. + * + * 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. + * + */ + +import * as http2 from 'http2'; +import { log } from './logging'; +import { LogVerbosity } from './constants'; +import { getErrorMessage } from './error'; +const LEGAL_KEY_REGEX = /^[0-9a-z_.-]+$/; +const LEGAL_NON_BINARY_VALUE_REGEX = /^[ -~]*$/; + +export type MetadataValue = string | Buffer; +export type MetadataObject = Map; + +function isLegalKey(key: string): boolean { + return LEGAL_KEY_REGEX.test(key); +} + +function isLegalNonBinaryValue(value: string): boolean { + return LEGAL_NON_BINARY_VALUE_REGEX.test(value); +} + +function isBinaryKey(key: string): boolean { + return key.endsWith('-bin'); +} + +function isCustomMetadata(key: string): boolean { + return !key.startsWith('grpc-'); +} + +function normalizeKey(key: string): string { + return key.toLowerCase(); +} + +function validate(key: string, value?: MetadataValue): void { + if (!isLegalKey(key)) { + throw new Error('Metadata key "' + key + '" contains illegal characters'); + } + + if (value !== null && value !== undefined) { + if (isBinaryKey(key)) { + if (!Buffer.isBuffer(value)) { + throw new Error("keys that end with '-bin' must have Buffer values"); + } + } else { + if (Buffer.isBuffer(value)) { + throw new Error( + "keys that don't end with '-bin' must have String values" + ); + } + if (!isLegalNonBinaryValue(value)) { + throw new Error( + 'Metadata string value "' + value + '" contains illegal characters' + ); + } + } + } +} + +export interface MetadataOptions { + /* Signal that the request is idempotent. Defaults to false */ + idempotentRequest?: boolean; + /* Signal that the call should not return UNAVAILABLE before it has + * started. Defaults to false. */ + waitForReady?: boolean; + /* Signal that the call is cacheable. GRPC is free to use GET verb. + * Defaults to false */ + cacheableRequest?: boolean; + /* Signal that the initial metadata should be corked. Defaults to false. */ + corked?: boolean; +} + +/** + * A class for storing metadata. Keys are normalized to lowercase ASCII. + */ +export class Metadata { + protected internalRepr: MetadataObject = new Map(); + private options: MetadataOptions; + + constructor(options: MetadataOptions = {}) { + this.options = options; + } + + /** + * Sets the given value for the given key by replacing any other values + * associated with that key. Normalizes the key. + * @param key The key to whose value should be set. + * @param value The value to set. Must be a buffer if and only + * if the normalized key ends with '-bin'. + */ + set(key: string, value: MetadataValue): void { + key = normalizeKey(key); + validate(key, value); + this.internalRepr.set(key, [value]); + } + + /** + * Adds the given value for the given key by appending to a list of previous + * values associated with that key. Normalizes the key. + * @param key The key for which a new value should be appended. + * @param value The value to add. Must be a buffer if and only + * if the normalized key ends with '-bin'. + */ + add(key: string, value: MetadataValue): void { + key = normalizeKey(key); + validate(key, value); + + const existingValue: MetadataValue[] | undefined = + this.internalRepr.get(key); + + if (existingValue === undefined) { + this.internalRepr.set(key, [value]); + } else { + existingValue.push(value); + } + } + + /** + * Removes the given key and any associated values. Normalizes the key. + * @param key The key whose values should be removed. + */ + remove(key: string): void { + key = normalizeKey(key); + // validate(key); + this.internalRepr.delete(key); + } + + /** + * Gets a list of all values associated with the key. Normalizes the key. + * @param key The key whose value should be retrieved. + * @return A list of values associated with the given key. + */ + get(key: string): MetadataValue[] { + key = normalizeKey(key); + // validate(key); + return this.internalRepr.get(key) || []; + } + + /** + * Gets a plain object mapping each key to the first value associated with it. + * This reflects the most common way that people will want to see metadata. + * @return A key/value mapping of the metadata. + */ + getMap(): { [key: string]: MetadataValue } { + const result: { [key: string]: MetadataValue } = {}; + + for (const [key, values] of this.internalRepr) { + if (values.length > 0) { + const v = values[0]; + result[key] = Buffer.isBuffer(v) ? Buffer.from(v) : v; + } + } + return result; + } + + /** + * Clones the metadata object. + * @return The newly cloned object. + */ + clone(): Metadata { + const newMetadata = new Metadata(this.options); + const newInternalRepr = newMetadata.internalRepr; + + for (const [key, value] of this.internalRepr) { + const clonedValue: MetadataValue[] = value.map(v => { + if (Buffer.isBuffer(v)) { + return Buffer.from(v); + } else { + return v; + } + }); + + newInternalRepr.set(key, clonedValue); + } + + return newMetadata; + } + + /** + * Merges all key-value pairs from a given Metadata object into this one. + * If both this object and the given object have values in the same key, + * values from the other Metadata object will be appended to this object's + * values. + * @param other A Metadata object. + */ + merge(other: Metadata): void { + for (const [key, values] of other.internalRepr) { + const mergedValue: MetadataValue[] = ( + this.internalRepr.get(key) || [] + ).concat(values); + + this.internalRepr.set(key, mergedValue); + } + } + + setOptions(options: MetadataOptions) { + this.options = options; + } + + getOptions(): MetadataOptions { + return this.options; + } + + /** + * Creates an OutgoingHttpHeaders object that can be used with the http2 API. + */ + toHttp2Headers(): http2.OutgoingHttpHeaders { + // NOTE: Node <8.9 formats http2 headers incorrectly. + const result: http2.OutgoingHttpHeaders = {}; + + for (const [key, values] of this.internalRepr) { + // We assume that the user's interaction with this object is limited to + // through its public API (i.e. keys and values are already validated). + result[key] = values.map(bufToString); + } + + return result; + } + + /** + * This modifies the behavior of JSON.stringify to show an object + * representation of the metadata map. + */ + toJSON() { + const result: { [key: string]: MetadataValue[] } = {}; + for (const [key, values] of this.internalRepr) { + result[key] = values; + } + return result; + } + + /** + * Returns a new Metadata object based fields in a given IncomingHttpHeaders + * object. + * @param headers An IncomingHttpHeaders object. + */ + static fromHttp2Headers(headers: http2.IncomingHttpHeaders): Metadata { + const result = new Metadata(); + for (const key of Object.keys(headers)) { + // Reserved headers (beginning with `:`) are not valid keys. + if (key.charAt(0) === ':') { + continue; + } + + const values = headers[key]; + + try { + if (isBinaryKey(key)) { + if (Array.isArray(values)) { + values.forEach(value => { + result.add(key, Buffer.from(value, 'base64')); + }); + } else if (values !== undefined) { + if (isCustomMetadata(key)) { + values.split(',').forEach(v => { + result.add(key, Buffer.from(v.trim(), 'base64')); + }); + } else { + result.add(key, Buffer.from(values, 'base64')); + } + } + } else { + if (Array.isArray(values)) { + values.forEach(value => { + result.add(key, value); + }); + } else if (values !== undefined) { + result.add(key, values); + } + } + } catch (error) { + const message = `Failed to add metadata entry ${key}: ${values}. ${getErrorMessage( + error + )}. For more information see https://github.com/grpc/grpc-node/issues/1173`; + log(LogVerbosity.ERROR, message); + } + } + + return result; + } +} + +const bufToString = (val: string | Buffer): string => { + return Buffer.isBuffer(val) ? val.toString('base64') : val; +}; diff --git a/node_modules/@grpc/grpc-js/src/object-stream.ts b/node_modules/@grpc/grpc-js/src/object-stream.ts new file mode 100644 index 0000000..49ef1f3 --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/object-stream.ts @@ -0,0 +1,66 @@ +/* + * Copyright 2019 gRPC authors. + * + * 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. + * + */ + +import { Readable, Writable } from 'stream'; +import { EmitterAugmentation1 } from './events'; + +/* eslint-disable @typescript-eslint/no-explicit-any */ + +export type WriteCallback = (error: Error | null | undefined) => void; + +export interface IntermediateObjectReadable extends Readable { + read(size?: number): any & T; +} + +export type ObjectReadable = { + read(size?: number): T; +} & EmitterAugmentation1<'data', T> & + IntermediateObjectReadable; + +export interface IntermediateObjectWritable extends Writable { + _write(chunk: any & T, encoding: string, callback: Function): void; + write(chunk: any & T, cb?: WriteCallback): boolean; + write(chunk: any & T, encoding?: any, cb?: WriteCallback): boolean; + setDefaultEncoding(encoding: string): this; + end(): ReturnType extends Writable ? this : void; + end( + chunk: any & T, + cb?: Function + ): ReturnType extends Writable ? this : void; + end( + chunk: any & T, + encoding?: any, + cb?: Function + ): ReturnType extends Writable ? this : void; +} + +export interface ObjectWritable extends IntermediateObjectWritable { + _write(chunk: T, encoding: string, callback: Function): void; + write(chunk: T, cb?: Function): boolean; + write(chunk: T, encoding?: any, cb?: Function): boolean; + setDefaultEncoding(encoding: string): this; + end(): ReturnType extends Writable ? this : void; + end( + chunk: T, + cb?: Function + ): ReturnType extends Writable ? this : void; + end( + chunk: T, + encoding?: any, + cb?: Function + ): ReturnType extends Writable ? this : void; +} diff --git a/node_modules/@grpc/grpc-js/src/picker.ts b/node_modules/@grpc/grpc-js/src/picker.ts new file mode 100644 index 0000000..ac79c9f --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/picker.ts @@ -0,0 +1,155 @@ +/* + * Copyright 2019 gRPC authors. + * + * 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. + * + */ + +import { StatusObject } from './call-interface'; +import { Metadata } from './metadata'; +import { Status } from './constants'; +import { LoadBalancer } from './load-balancer'; +import { SubchannelInterface } from './subchannel-interface'; + +export enum PickResultType { + COMPLETE, + QUEUE, + TRANSIENT_FAILURE, + DROP, +} + +export interface PickResult { + pickResultType: PickResultType; + /** + * The subchannel to use as the transport for the call. Only meaningful if + * `pickResultType` is COMPLETE. If null, indicates that the call should be + * dropped. + */ + subchannel: SubchannelInterface | null; + /** + * The status object to end the call with. Populated if and only if + * `pickResultType` is TRANSIENT_FAILURE. + */ + status: StatusObject | null; + onCallStarted: (() => void) | null; + onCallEnded: ((statusCode: Status) => void) | null; +} + +export interface CompletePickResult extends PickResult { + pickResultType: PickResultType.COMPLETE; + subchannel: SubchannelInterface | null; + status: null; + onCallStarted: (() => void) | null; + onCallEnded: ((statusCode: Status) => void) | null; +} + +export interface QueuePickResult extends PickResult { + pickResultType: PickResultType.QUEUE; + subchannel: null; + status: null; + onCallStarted: null; + onCallEnded: null; +} + +export interface TransientFailurePickResult extends PickResult { + pickResultType: PickResultType.TRANSIENT_FAILURE; + subchannel: null; + status: StatusObject; + onCallStarted: null; + onCallEnded: null; +} + +export interface DropCallPickResult extends PickResult { + pickResultType: PickResultType.DROP; + subchannel: null; + status: StatusObject; + onCallStarted: null; + onCallEnded: null; +} + +export interface PickArgs { + metadata: Metadata; + extraPickInfo: { [key: string]: string }; +} + +/** + * A proxy object representing the momentary state of a load balancer. Picks + * subchannels or returns other information based on that state. Should be + * replaced every time the load balancer changes state. + */ +export interface Picker { + pick(pickArgs: PickArgs): PickResult; +} + +/** + * A standard picker representing a load balancer in the TRANSIENT_FAILURE + * state. Always responds to every pick request with an UNAVAILABLE status. + */ +export class UnavailablePicker implements Picker { + private status: StatusObject; + constructor(status?: Partial) { + this.status = { + code: Status.UNAVAILABLE, + details: 'No connection established', + metadata: new Metadata(), + ...status, + }; + } + pick(pickArgs: PickArgs): TransientFailurePickResult { + return { + pickResultType: PickResultType.TRANSIENT_FAILURE, + subchannel: null, + status: this.status, + onCallStarted: null, + onCallEnded: null, + }; + } +} + +/** + * A standard picker representing a load balancer in the IDLE or CONNECTING + * state. Always responds to every pick request with a QUEUE pick result + * indicating that the pick should be tried again with the next `Picker`. Also + * reports back to the load balancer that a connection should be established + * once any pick is attempted. + * If the childPicker is provided, delegate to it instead of returning the + * hardcoded QUEUE pick result, but still calls exitIdle. + */ +export class QueuePicker { + private calledExitIdle = false; + // Constructed with a load balancer. Calls exitIdle on it the first time pick is called + constructor( + private loadBalancer: LoadBalancer, + private childPicker?: Picker + ) {} + + pick(pickArgs: PickArgs): PickResult { + if (!this.calledExitIdle) { + process.nextTick(() => { + this.loadBalancer.exitIdle(); + }); + this.calledExitIdle = true; + } + if (this.childPicker) { + return this.childPicker.pick(pickArgs); + } else { + return { + pickResultType: PickResultType.QUEUE, + subchannel: null, + status: null, + onCallStarted: null, + onCallEnded: null, + }; + } + } +} diff --git a/node_modules/@grpc/grpc-js/src/resolver-dns.ts b/node_modules/@grpc/grpc-js/src/resolver-dns.ts new file mode 100644 index 0000000..6463c26 --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/resolver-dns.ts @@ -0,0 +1,395 @@ +/* + * Copyright 2019 gRPC authors. + * + * 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. + */ + +import { + Resolver, + ResolverListener, + registerResolver, + registerDefaultScheme, +} from './resolver'; +import * as dns from 'dns'; +import * as util from 'util'; +import { extractAndSelectServiceConfig, ServiceConfig } from './service-config'; +import { Status } from './constants'; +import { StatusObject } from './call-interface'; +import { Metadata } from './metadata'; +import * as logging from './logging'; +import { LogVerbosity } from './constants'; +import { Endpoint, TcpSubchannelAddress } from './subchannel-address'; +import { GrpcUri, uriToString, splitHostPort } from './uri-parser'; +import { isIPv6, isIPv4 } from 'net'; +import { ChannelOptions } from './channel-options'; +import { BackoffOptions, BackoffTimeout } from './backoff-timeout'; + +const TRACER_NAME = 'dns_resolver'; + +function trace(text: string): void { + logging.trace(LogVerbosity.DEBUG, TRACER_NAME, text); +} + +/** + * The default TCP port to connect to if not explicitly specified in the target. + */ +export const DEFAULT_PORT = 443; + +const DEFAULT_MIN_TIME_BETWEEN_RESOLUTIONS_MS = 30_000; + +const resolveTxtPromise = util.promisify(dns.resolveTxt); +const dnsLookupPromise = util.promisify(dns.lookup); + +/** + * Resolver implementation that handles DNS names and IP addresses. + */ +class DnsResolver implements Resolver { + private readonly ipResult: Endpoint[] | null; + private readonly dnsHostname: string | null; + private readonly port: number | null; + /** + * Minimum time between resolutions, measured as the time between starting + * successive resolution requests. Only applies to successful resolutions. + * Failures are handled by the backoff timer. + */ + private readonly minTimeBetweenResolutionsMs: number; + private pendingLookupPromise: Promise | null = null; + private pendingTxtPromise: Promise | null = null; + private latestLookupResult: Endpoint[] | null = null; + private latestServiceConfig: ServiceConfig | null = null; + private latestServiceConfigError: StatusObject | null = null; + private percentage: number; + private defaultResolutionError: StatusObject; + private backoff: BackoffTimeout; + private continueResolving = false; + private nextResolutionTimer: NodeJS.Timeout; + private isNextResolutionTimerRunning = false; + private isServiceConfigEnabled = true; + private returnedIpResult = false; + constructor( + private target: GrpcUri, + private listener: ResolverListener, + channelOptions: ChannelOptions + ) { + trace('Resolver constructed for target ' + uriToString(target)); + const hostPort = splitHostPort(target.path); + if (hostPort === null) { + this.ipResult = null; + this.dnsHostname = null; + this.port = null; + } else { + if (isIPv4(hostPort.host) || isIPv6(hostPort.host)) { + this.ipResult = [ + { + addresses: [ + { + host: hostPort.host, + port: hostPort.port ?? DEFAULT_PORT, + }, + ], + }, + ]; + this.dnsHostname = null; + this.port = null; + } else { + this.ipResult = null; + this.dnsHostname = hostPort.host; + this.port = hostPort.port ?? DEFAULT_PORT; + } + } + this.percentage = Math.random() * 100; + + if (channelOptions['grpc.service_config_disable_resolution'] === 1) { + this.isServiceConfigEnabled = false; + } + + this.defaultResolutionError = { + code: Status.UNAVAILABLE, + details: `Name resolution failed for target ${uriToString(this.target)}`, + metadata: new Metadata(), + }; + + const backoffOptions: BackoffOptions = { + initialDelay: channelOptions['grpc.initial_reconnect_backoff_ms'], + maxDelay: channelOptions['grpc.max_reconnect_backoff_ms'], + }; + + this.backoff = new BackoffTimeout(() => { + if (this.continueResolving) { + this.startResolutionWithBackoff(); + } + }, backoffOptions); + this.backoff.unref(); + + this.minTimeBetweenResolutionsMs = + channelOptions['grpc.dns_min_time_between_resolutions_ms'] ?? + DEFAULT_MIN_TIME_BETWEEN_RESOLUTIONS_MS; + this.nextResolutionTimer = setTimeout(() => {}, 0); + clearTimeout(this.nextResolutionTimer); + } + + /** + * If the target is an IP address, just provide that address as a result. + * Otherwise, initiate A, AAAA, and TXT lookups + */ + private startResolution() { + if (this.ipResult !== null) { + if (!this.returnedIpResult) { + trace('Returning IP address for target ' + uriToString(this.target)); + setImmediate(() => { + this.listener.onSuccessfulResolution( + this.ipResult!, + null, + null, + null, + {} + ); + }); + this.returnedIpResult = true; + } + this.backoff.stop(); + this.backoff.reset(); + this.stopNextResolutionTimer(); + return; + } + if (this.dnsHostname === null) { + trace('Failed to parse DNS address ' + uriToString(this.target)); + setImmediate(() => { + this.listener.onError({ + code: Status.UNAVAILABLE, + details: `Failed to parse DNS address ${uriToString(this.target)}`, + metadata: new Metadata(), + }); + }); + this.stopNextResolutionTimer(); + } else { + if (this.pendingLookupPromise !== null) { + return; + } + trace('Looking up DNS hostname ' + this.dnsHostname); + /* We clear out latestLookupResult here to ensure that it contains the + * latest result since the last time we started resolving. That way, the + * TXT resolution handler can use it, but only if it finishes second. We + * don't clear out any previous service config results because it's + * better to use a service config that's slightly out of date than to + * revert to an effectively blank one. */ + this.latestLookupResult = null; + const hostname: string = this.dnsHostname; + /* We lookup both address families here and then split them up later + * because when looking up a single family, dns.lookup outputs an error + * if the name exists but there are no records for that family, and that + * error is indistinguishable from other kinds of errors */ + this.pendingLookupPromise = dnsLookupPromise(hostname, { all: true }); + this.pendingLookupPromise.then( + addressList => { + if (this.pendingLookupPromise === null) { + return; + } + this.pendingLookupPromise = null; + this.backoff.reset(); + this.backoff.stop(); + const subchannelAddresses: TcpSubchannelAddress[] = addressList.map( + addr => ({ host: addr.address, port: +this.port! }) + ); + this.latestLookupResult = subchannelAddresses.map(address => ({ + addresses: [address], + })); + const allAddressesString: string = + '[' + + subchannelAddresses + .map(addr => addr.host + ':' + addr.port) + .join(',') + + ']'; + trace( + 'Resolved addresses for target ' + + uriToString(this.target) + + ': ' + + allAddressesString + ); + if (this.latestLookupResult.length === 0) { + this.listener.onError(this.defaultResolutionError); + return; + } + /* If the TXT lookup has not yet finished, both of the last two + * arguments will be null, which is the equivalent of getting an + * empty TXT response. When the TXT lookup does finish, its handler + * can update the service config by using the same address list */ + this.listener.onSuccessfulResolution( + this.latestLookupResult, + this.latestServiceConfig, + this.latestServiceConfigError, + null, + {} + ); + }, + err => { + if (this.pendingLookupPromise === null) { + return; + } + trace( + 'Resolution error for target ' + + uriToString(this.target) + + ': ' + + (err as Error).message + ); + this.pendingLookupPromise = null; + this.stopNextResolutionTimer(); + this.listener.onError(this.defaultResolutionError); + } + ); + /* If there already is a still-pending TXT resolution, we can just use + * that result when it comes in */ + if (this.isServiceConfigEnabled && this.pendingTxtPromise === null) { + /* We handle the TXT query promise differently than the others because + * the name resolution attempt as a whole is a success even if the TXT + * lookup fails */ + this.pendingTxtPromise = resolveTxtPromise(hostname); + this.pendingTxtPromise.then( + txtRecord => { + if (this.pendingTxtPromise === null) { + return; + } + this.pendingTxtPromise = null; + try { + this.latestServiceConfig = extractAndSelectServiceConfig( + txtRecord, + this.percentage + ); + } catch (err) { + this.latestServiceConfigError = { + code: Status.UNAVAILABLE, + details: `Parsing service config failed with error ${ + (err as Error).message + }`, + metadata: new Metadata(), + }; + } + if (this.latestLookupResult !== null) { + /* We rely here on the assumption that calling this function with + * identical parameters will be essentialy idempotent, and calling + * it with the same address list and a different service config + * should result in a fast and seamless switchover. */ + this.listener.onSuccessfulResolution( + this.latestLookupResult, + this.latestServiceConfig, + this.latestServiceConfigError, + null, + {} + ); + } + }, + err => { + /* If TXT lookup fails we should do nothing, which means that we + * continue to use the result of the most recent successful lookup, + * or the default null config object if there has never been a + * successful lookup. We do not set the latestServiceConfigError + * here because that is specifically used for response validation + * errors. We still need to handle this error so that it does not + * bubble up as an unhandled promise rejection. */ + } + ); + } + } + } + + private startNextResolutionTimer() { + clearTimeout(this.nextResolutionTimer); + this.nextResolutionTimer = setTimeout(() => { + this.stopNextResolutionTimer(); + if (this.continueResolving) { + this.startResolutionWithBackoff(); + } + }, this.minTimeBetweenResolutionsMs); + this.nextResolutionTimer.unref?.(); + this.isNextResolutionTimerRunning = true; + } + + private stopNextResolutionTimer() { + clearTimeout(this.nextResolutionTimer); + this.isNextResolutionTimerRunning = false; + } + + private startResolutionWithBackoff() { + if (this.pendingLookupPromise === null) { + this.continueResolving = false; + this.backoff.runOnce(); + this.startNextResolutionTimer(); + this.startResolution(); + } + } + + updateResolution() { + /* If there is a pending lookup, just let it finish. Otherwise, if the + * nextResolutionTimer or backoff timer is running, set the + * continueResolving flag to resolve when whichever of those timers + * fires. Otherwise, start resolving immediately. */ + if (this.pendingLookupPromise === null) { + if (this.isNextResolutionTimerRunning || this.backoff.isRunning()) { + if (this.isNextResolutionTimerRunning) { + trace( + 'resolution update delayed by "min time between resolutions" rate limit' + ); + } else { + trace( + 'resolution update delayed by backoff timer until ' + + this.backoff.getEndTime().toISOString() + ); + } + this.continueResolving = true; + } else { + this.startResolutionWithBackoff(); + } + } + } + + /** + * Reset the resolver to the same state it had when it was created. In-flight + * DNS requests cannot be cancelled, but they are discarded and their results + * will be ignored. + */ + destroy() { + this.continueResolving = false; + this.backoff.reset(); + this.backoff.stop(); + this.stopNextResolutionTimer(); + this.pendingLookupPromise = null; + this.pendingTxtPromise = null; + this.latestLookupResult = null; + this.latestServiceConfig = null; + this.latestServiceConfigError = null; + this.returnedIpResult = false; + } + + /** + * Get the default authority for the given target. For IP targets, that is + * the IP address. For DNS targets, it is the hostname. + * @param target + */ + static getDefaultAuthority(target: GrpcUri): string { + return target.path; + } +} + +/** + * Set up the DNS resolver class by registering it as the handler for the + * "dns:" prefix and as the default resolver. + */ +export function setup(): void { + registerResolver('dns', DnsResolver); + registerDefaultScheme('dns'); +} + +export interface DnsUrl { + host: string; + port?: string; +} diff --git a/node_modules/@grpc/grpc-js/src/resolver-ip.ts b/node_modules/@grpc/grpc-js/src/resolver-ip.ts new file mode 100644 index 0000000..8fed35b --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/resolver-ip.ts @@ -0,0 +1,120 @@ +/* + * Copyright 2021 gRPC authors. + * + * 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. + */ + +import { isIPv4, isIPv6 } from 'net'; +import { StatusObject } from './call-interface'; +import { ChannelOptions } from './channel-options'; +import { LogVerbosity, Status } from './constants'; +import { Metadata } from './metadata'; +import { registerResolver, Resolver, ResolverListener } from './resolver'; +import { Endpoint, SubchannelAddress } from './subchannel-address'; +import { GrpcUri, splitHostPort, uriToString } from './uri-parser'; +import * as logging from './logging'; + +const TRACER_NAME = 'ip_resolver'; + +function trace(text: string): void { + logging.trace(LogVerbosity.DEBUG, TRACER_NAME, text); +} + +const IPV4_SCHEME = 'ipv4'; +const IPV6_SCHEME = 'ipv6'; + +/** + * The default TCP port to connect to if not explicitly specified in the target. + */ +const DEFAULT_PORT = 443; + +class IpResolver implements Resolver { + private endpoints: Endpoint[] = []; + private error: StatusObject | null = null; + private hasReturnedResult = false; + constructor( + target: GrpcUri, + private listener: ResolverListener, + channelOptions: ChannelOptions + ) { + trace('Resolver constructed for target ' + uriToString(target)); + const addresses: SubchannelAddress[] = []; + if (!(target.scheme === IPV4_SCHEME || target.scheme === IPV6_SCHEME)) { + this.error = { + code: Status.UNAVAILABLE, + details: `Unrecognized scheme ${target.scheme} in IP resolver`, + metadata: new Metadata(), + }; + return; + } + const pathList = target.path.split(','); + for (const path of pathList) { + const hostPort = splitHostPort(path); + if (hostPort === null) { + this.error = { + code: Status.UNAVAILABLE, + details: `Failed to parse ${target.scheme} address ${path}`, + metadata: new Metadata(), + }; + return; + } + if ( + (target.scheme === IPV4_SCHEME && !isIPv4(hostPort.host)) || + (target.scheme === IPV6_SCHEME && !isIPv6(hostPort.host)) + ) { + this.error = { + code: Status.UNAVAILABLE, + details: `Failed to parse ${target.scheme} address ${path}`, + metadata: new Metadata(), + }; + return; + } + addresses.push({ + host: hostPort.host, + port: hostPort.port ?? DEFAULT_PORT, + }); + } + this.endpoints = addresses.map(address => ({ addresses: [address] })); + trace('Parsed ' + target.scheme + ' address list ' + addresses); + } + updateResolution(): void { + if (!this.hasReturnedResult) { + this.hasReturnedResult = true; + process.nextTick(() => { + if (this.error) { + this.listener.onError(this.error); + } else { + this.listener.onSuccessfulResolution( + this.endpoints, + null, + null, + null, + {} + ); + } + }); + } + } + destroy(): void { + this.hasReturnedResult = false; + } + + static getDefaultAuthority(target: GrpcUri): string { + return target.path.split(',')[0]; + } +} + +export function setup() { + registerResolver(IPV4_SCHEME, IpResolver); + registerResolver(IPV6_SCHEME, IpResolver); +} diff --git a/node_modules/@grpc/grpc-js/src/resolver-uds.ts b/node_modules/@grpc/grpc-js/src/resolver-uds.ts new file mode 100644 index 0000000..4d84de9 --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/resolver-uds.ts @@ -0,0 +1,63 @@ +/* + * Copyright 2019 gRPC authors. + * + * 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. + */ + +import { Resolver, ResolverListener, registerResolver } from './resolver'; +import { Endpoint } from './subchannel-address'; +import { GrpcUri } from './uri-parser'; +import { ChannelOptions } from './channel-options'; + +class UdsResolver implements Resolver { + private hasReturnedResult = false; + private endpoints: Endpoint[] = []; + constructor( + target: GrpcUri, + private listener: ResolverListener, + channelOptions: ChannelOptions + ) { + let path: string; + if (target.authority === '') { + path = '/' + target.path; + } else { + path = target.path; + } + this.endpoints = [{ addresses: [{ path }] }]; + } + updateResolution(): void { + if (!this.hasReturnedResult) { + this.hasReturnedResult = true; + process.nextTick( + this.listener.onSuccessfulResolution, + this.endpoints, + null, + null, + null, + {} + ); + } + } + + destroy() { + this.hasReturnedResult = false; + } + + static getDefaultAuthority(target: GrpcUri): string { + return 'localhost'; + } +} + +export function setup() { + registerResolver('unix', UdsResolver); +} diff --git a/node_modules/@grpc/grpc-js/src/resolver.ts b/node_modules/@grpc/grpc-js/src/resolver.ts new file mode 100644 index 0000000..1c84c04 --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/resolver.ts @@ -0,0 +1,180 @@ +/* + * Copyright 2019 gRPC authors. + * + * 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. + * + */ + +import { MethodConfig, ServiceConfig } from './service-config'; +import { StatusObject } from './call-interface'; +import { Endpoint } from './subchannel-address'; +import { GrpcUri, uriToString } from './uri-parser'; +import { ChannelOptions } from './channel-options'; +import { Metadata } from './metadata'; +import { Status } from './constants'; +import { Filter, FilterFactory } from './filter'; + +export interface CallConfig { + methodConfig: MethodConfig; + onCommitted?: () => void; + pickInformation: { [key: string]: string }; + status: Status; + dynamicFilterFactories: FilterFactory[]; +} + +/** + * Selects a configuration for a method given the name and metadata. Defined in + * https://github.com/grpc/proposal/blob/master/A31-xds-timeout-support-and-config-selector.md#new-functionality-in-grpc + */ +export interface ConfigSelector { + (methodName: string, metadata: Metadata, channelId: number): CallConfig; +} + +/** + * A listener object passed to the resolver's constructor that provides name + * resolution updates back to the resolver's owner. + */ +export interface ResolverListener { + /** + * Called whenever the resolver has new name resolution results to report + * @param addressList The new list of backend addresses + * @param serviceConfig The new service configuration corresponding to the + * `addressList`. Will be `null` if no service configuration was + * retrieved or if the service configuration was invalid + * @param serviceConfigError If non-`null`, indicates that the retrieved + * service configuration was invalid + */ + onSuccessfulResolution( + addressList: Endpoint[], + serviceConfig: ServiceConfig | null, + serviceConfigError: StatusObject | null, + configSelector: ConfigSelector | null, + attributes: { [key: string]: unknown } + ): void; + /** + * Called whenever a name resolution attempt fails. + * @param error Describes how resolution failed + */ + onError(error: StatusObject): void; +} + +/** + * A resolver class that handles one or more of the name syntax schemes defined + * in the [gRPC Name Resolution document](https://github.com/grpc/grpc/blob/master/doc/naming.md) + */ +export interface Resolver { + /** + * Indicates that the caller wants new name resolution data. Calling this + * function may eventually result in calling one of the `ResolverListener` + * functions, but that is not guaranteed. Those functions will never be + * called synchronously with the constructor or updateResolution. + */ + updateResolution(): void; + + /** + * Discard all resources owned by the resolver. A later call to + * `updateResolution` should reinitialize those resources. No + * `ResolverListener` callbacks should be called after `destroy` is called + * until `updateResolution` is called again. + */ + destroy(): void; +} + +export interface ResolverConstructor { + new ( + target: GrpcUri, + listener: ResolverListener, + channelOptions: ChannelOptions + ): Resolver; + /** + * Get the default authority for a target. This loosely corresponds to that + * target's hostname. Throws an error if this resolver class cannot parse the + * `target`. + * @param target + */ + getDefaultAuthority(target: GrpcUri): string; +} + +const registeredResolvers: { [scheme: string]: ResolverConstructor } = {}; +let defaultScheme: string | null = null; + +/** + * Register a resolver class to handle target names prefixed with the `prefix` + * string. This prefix should correspond to a URI scheme name listed in the + * [gRPC Name Resolution document](https://github.com/grpc/grpc/blob/master/doc/naming.md) + * @param prefix + * @param resolverClass + */ +export function registerResolver( + scheme: string, + resolverClass: ResolverConstructor +) { + registeredResolvers[scheme] = resolverClass; +} + +/** + * Register a default resolver to handle target names that do not start with + * any registered prefix. + * @param resolverClass + */ +export function registerDefaultScheme(scheme: string) { + defaultScheme = scheme; +} + +/** + * Create a name resolver for the specified target, if possible. Throws an + * error if no such name resolver can be created. + * @param target + * @param listener + */ +export function createResolver( + target: GrpcUri, + listener: ResolverListener, + options: ChannelOptions +): Resolver { + if (target.scheme !== undefined && target.scheme in registeredResolvers) { + return new registeredResolvers[target.scheme](target, listener, options); + } else { + throw new Error( + `No resolver could be created for target ${uriToString(target)}` + ); + } +} + +/** + * Get the default authority for the specified target, if possible. Throws an + * error if no registered name resolver can parse that target string. + * @param target + */ +export function getDefaultAuthority(target: GrpcUri): string { + if (target.scheme !== undefined && target.scheme in registeredResolvers) { + return registeredResolvers[target.scheme].getDefaultAuthority(target); + } else { + throw new Error(`Invalid target ${uriToString(target)}`); + } +} + +export function mapUriDefaultScheme(target: GrpcUri): GrpcUri | null { + if (target.scheme === undefined || !(target.scheme in registeredResolvers)) { + if (defaultScheme !== null) { + return { + scheme: defaultScheme, + authority: undefined, + path: uriToString(target), + }; + } else { + return null; + } + } + return target; +} diff --git a/node_modules/@grpc/grpc-js/src/resolving-call.ts b/node_modules/@grpc/grpc-js/src/resolving-call.ts new file mode 100644 index 0000000..2c81e78 --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/resolving-call.ts @@ -0,0 +1,364 @@ +/* + * Copyright 2022 gRPC authors. + * + * 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. + * + */ + +import { CallCredentials } from './call-credentials'; +import { + Call, + CallStreamOptions, + DeadlineInfoProvider, + InterceptingListener, + MessageContext, + StatusObject, +} from './call-interface'; +import { LogVerbosity, Propagate, Status } from './constants'; +import { + Deadline, + deadlineToString, + formatDateDifference, + getRelativeTimeout, + minDeadline, +} from './deadline'; +import { FilterStack, FilterStackFactory } from './filter-stack'; +import { InternalChannel } from './internal-channel'; +import { Metadata } from './metadata'; +import * as logging from './logging'; +import { restrictControlPlaneStatusCode } from './control-plane-status'; + +const TRACER_NAME = 'resolving_call'; + +export class ResolvingCall implements Call { + private child: (Call & DeadlineInfoProvider) | null = null; + private readPending = false; + private pendingMessage: { context: MessageContext; message: Buffer } | null = + null; + private pendingHalfClose = false; + private ended = false; + private readFilterPending = false; + private writeFilterPending = false; + private pendingChildStatus: StatusObject | null = null; + private metadata: Metadata | null = null; + private listener: InterceptingListener | null = null; + private deadline: Deadline; + private host: string; + private statusWatchers: ((status: StatusObject) => void)[] = []; + private deadlineTimer: NodeJS.Timeout = setTimeout(() => {}, 0); + private filterStack: FilterStack | null = null; + + private deadlineStartTime: Date | null = null; + private configReceivedTime: Date | null = null; + private childStartTime: Date | null = null; + + constructor( + private readonly channel: InternalChannel, + private readonly method: string, + options: CallStreamOptions, + private readonly filterStackFactory: FilterStackFactory, + private credentials: CallCredentials, + private callNumber: number + ) { + this.deadline = options.deadline; + this.host = options.host; + if (options.parentCall) { + if (options.flags & Propagate.CANCELLATION) { + options.parentCall.on('cancelled', () => { + this.cancelWithStatus(Status.CANCELLED, 'Cancelled by parent call'); + }); + } + if (options.flags & Propagate.DEADLINE) { + this.trace( + 'Propagating deadline from parent: ' + + options.parentCall.getDeadline() + ); + this.deadline = minDeadline( + this.deadline, + options.parentCall.getDeadline() + ); + } + } + this.trace('Created'); + this.runDeadlineTimer(); + } + + private trace(text: string): void { + logging.trace( + LogVerbosity.DEBUG, + TRACER_NAME, + '[' + this.callNumber + '] ' + text + ); + } + + private runDeadlineTimer() { + clearTimeout(this.deadlineTimer); + this.deadlineStartTime = new Date(); + this.trace('Deadline: ' + deadlineToString(this.deadline)); + const timeout = getRelativeTimeout(this.deadline); + if (timeout !== Infinity) { + this.trace('Deadline will be reached in ' + timeout + 'ms'); + const handleDeadline = () => { + if (!this.deadlineStartTime) { + this.cancelWithStatus(Status.DEADLINE_EXCEEDED, 'Deadline exceeded'); + return; + } + const deadlineInfo: string[] = []; + const deadlineEndTime = new Date(); + deadlineInfo.push(`Deadline exceeded after ${formatDateDifference(this.deadlineStartTime, deadlineEndTime)}`); + if (this.configReceivedTime) { + if (this.configReceivedTime > this.deadlineStartTime) { + deadlineInfo.push(`name resolution: ${formatDateDifference(this.deadlineStartTime, this.configReceivedTime)}`); + } + if (this.childStartTime) { + if (this.childStartTime > this.configReceivedTime) { + deadlineInfo.push(`metadata filters: ${formatDateDifference(this.configReceivedTime, this.childStartTime)}`); + } + } else { + deadlineInfo.push('waiting for metadata filters'); + } + } else { + deadlineInfo.push('waiting for name resolution'); + } + if (this.child) { + deadlineInfo.push(...this.child.getDeadlineInfo()); + } + this.cancelWithStatus(Status.DEADLINE_EXCEEDED, deadlineInfo.join(',')); + }; + if (timeout <= 0) { + process.nextTick(handleDeadline); + } else { + this.deadlineTimer = setTimeout(handleDeadline, timeout); + } + } + } + + private outputStatus(status: StatusObject) { + if (!this.ended) { + this.ended = true; + if (!this.filterStack) { + this.filterStack = this.filterStackFactory.createFilter(); + } + clearTimeout(this.deadlineTimer); + const filteredStatus = this.filterStack.receiveTrailers(status); + this.trace( + 'ended with status: code=' + + filteredStatus.code + + ' details="' + + filteredStatus.details + + '"' + ); + this.statusWatchers.forEach(watcher => watcher(filteredStatus)); + process.nextTick(() => { + this.listener?.onReceiveStatus(filteredStatus); + }); + } + } + + private sendMessageOnChild(context: MessageContext, message: Buffer): void { + if (!this.child) { + throw new Error('sendMessageonChild called with child not populated'); + } + const child = this.child; + this.writeFilterPending = true; + this.filterStack!.sendMessage( + Promise.resolve({ message: message, flags: context.flags }) + ).then( + filteredMessage => { + this.writeFilterPending = false; + child.sendMessageWithContext(context, filteredMessage.message); + if (this.pendingHalfClose) { + child.halfClose(); + } + }, + (status: StatusObject) => { + this.cancelWithStatus(status.code, status.details); + } + ); + } + + getConfig(): void { + if (this.ended) { + return; + } + if (!this.metadata || !this.listener) { + throw new Error('getConfig called before start'); + } + const configResult = this.channel.getConfig(this.method, this.metadata); + if (configResult.type === 'NONE') { + this.channel.queueCallForConfig(this); + return; + } else if (configResult.type === 'ERROR') { + if (this.metadata.getOptions().waitForReady) { + this.channel.queueCallForConfig(this); + } else { + this.outputStatus(configResult.error); + } + return; + } + // configResult.type === 'SUCCESS' + this.configReceivedTime = new Date(); + const config = configResult.config; + if (config.status !== Status.OK) { + const { code, details } = restrictControlPlaneStatusCode( + config.status, + 'Failed to route call to method ' + this.method + ); + this.outputStatus({ + code: code, + details: details, + metadata: new Metadata(), + }); + return; + } + + if (config.methodConfig.timeout) { + const configDeadline = new Date(); + configDeadline.setSeconds( + configDeadline.getSeconds() + config.methodConfig.timeout.seconds + ); + configDeadline.setMilliseconds( + configDeadline.getMilliseconds() + + config.methodConfig.timeout.nanos / 1_000_000 + ); + this.deadline = minDeadline(this.deadline, configDeadline); + this.runDeadlineTimer(); + } + + this.filterStackFactory.push(config.dynamicFilterFactories); + this.filterStack = this.filterStackFactory.createFilter(); + this.filterStack.sendMetadata(Promise.resolve(this.metadata)).then( + filteredMetadata => { + this.child = this.channel.createInnerCall( + config, + this.method, + this.host, + this.credentials, + this.deadline + ); + this.trace('Created child [' + this.child.getCallNumber() + ']'); + this.childStartTime = new Date(); + this.child.start(filteredMetadata, { + onReceiveMetadata: metadata => { + this.trace('Received metadata'); + this.listener!.onReceiveMetadata( + this.filterStack!.receiveMetadata(metadata) + ); + }, + onReceiveMessage: message => { + this.trace('Received message'); + this.readFilterPending = true; + this.filterStack!.receiveMessage(message).then( + filteredMesssage => { + this.trace('Finished filtering received message'); + this.readFilterPending = false; + this.listener!.onReceiveMessage(filteredMesssage); + if (this.pendingChildStatus) { + this.outputStatus(this.pendingChildStatus); + } + }, + (status: StatusObject) => { + this.cancelWithStatus(status.code, status.details); + } + ); + }, + onReceiveStatus: status => { + this.trace('Received status'); + if (this.readFilterPending) { + this.pendingChildStatus = status; + } else { + this.outputStatus(status); + } + }, + }); + if (this.readPending) { + this.child.startRead(); + } + if (this.pendingMessage) { + this.sendMessageOnChild( + this.pendingMessage.context, + this.pendingMessage.message + ); + } else if (this.pendingHalfClose) { + this.child.halfClose(); + } + }, + (status: StatusObject) => { + this.outputStatus(status); + } + ); + } + + reportResolverError(status: StatusObject) { + if (this.metadata?.getOptions().waitForReady) { + this.channel.queueCallForConfig(this); + } else { + this.outputStatus(status); + } + } + cancelWithStatus(status: Status, details: string): void { + this.trace( + 'cancelWithStatus code: ' + status + ' details: "' + details + '"' + ); + this.child?.cancelWithStatus(status, details); + this.outputStatus({ + code: status, + details: details, + metadata: new Metadata(), + }); + } + getPeer(): string { + return this.child?.getPeer() ?? this.channel.getTarget(); + } + start(metadata: Metadata, listener: InterceptingListener): void { + this.trace('start called'); + this.metadata = metadata.clone(); + this.listener = listener; + this.getConfig(); + } + sendMessageWithContext(context: MessageContext, message: Buffer): void { + this.trace('write() called with message of length ' + message.length); + if (this.child) { + this.sendMessageOnChild(context, message); + } else { + this.pendingMessage = { context, message }; + } + } + startRead(): void { + this.trace('startRead called'); + if (this.child) { + this.child.startRead(); + } else { + this.readPending = true; + } + } + halfClose(): void { + this.trace('halfClose called'); + if (this.child && !this.writeFilterPending) { + this.child.halfClose(); + } else { + this.pendingHalfClose = true; + } + } + setCredentials(credentials: CallCredentials): void { + this.credentials = this.credentials.compose(credentials); + } + + addStatusWatcher(watcher: (status: StatusObject) => void) { + this.statusWatchers.push(watcher); + } + + getCallNumber(): number { + return this.callNumber; + } +} diff --git a/node_modules/@grpc/grpc-js/src/resolving-load-balancer.ts b/node_modules/@grpc/grpc-js/src/resolving-load-balancer.ts new file mode 100644 index 0000000..72aef0d --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/resolving-load-balancer.ts @@ -0,0 +1,414 @@ +/* + * Copyright 2019 gRPC authors. + * + * 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. + * + */ + +import { + ChannelControlHelper, + LoadBalancer, + TypedLoadBalancingConfig, + selectLbConfigFromList, +} from './load-balancer'; +import { + MethodConfig, + ServiceConfig, + validateServiceConfig, +} from './service-config'; +import { ConnectivityState } from './connectivity-state'; +import { ConfigSelector, createResolver, Resolver } from './resolver'; +import { ServiceError } from './call'; +import { Picker, UnavailablePicker, QueuePicker } from './picker'; +import { BackoffOptions, BackoffTimeout } from './backoff-timeout'; +import { Status } from './constants'; +import { StatusObject } from './call-interface'; +import { Metadata } from './metadata'; +import * as logging from './logging'; +import { LogVerbosity } from './constants'; +import { Endpoint } from './subchannel-address'; +import { GrpcUri, uriToString } from './uri-parser'; +import { ChildLoadBalancerHandler } from './load-balancer-child-handler'; +import { ChannelOptions } from './channel-options'; + +const TRACER_NAME = 'resolving_load_balancer'; + +function trace(text: string): void { + logging.trace(LogVerbosity.DEBUG, TRACER_NAME, text); +} + +type NameMatchLevel = 'EMPTY' | 'SERVICE' | 'SERVICE_AND_METHOD'; + +/** + * Name match levels in order from most to least specific. This is the order in + * which searches will be performed. + */ +const NAME_MATCH_LEVEL_ORDER: NameMatchLevel[] = [ + 'SERVICE_AND_METHOD', + 'SERVICE', + 'EMPTY', +]; + +function hasMatchingName( + service: string, + method: string, + methodConfig: MethodConfig, + matchLevel: NameMatchLevel +): boolean { + for (const name of methodConfig.name) { + switch (matchLevel) { + case 'EMPTY': + if (!name.service && !name.method) { + return true; + } + break; + case 'SERVICE': + if (name.service === service && !name.method) { + return true; + } + break; + case 'SERVICE_AND_METHOD': + if (name.service === service && name.method === method) { + return true; + } + } + } + return false; +} + +function findMatchingConfig( + service: string, + method: string, + methodConfigs: MethodConfig[], + matchLevel: NameMatchLevel +): MethodConfig | null { + for (const config of methodConfigs) { + if (hasMatchingName(service, method, config, matchLevel)) { + return config; + } + } + return null; +} + +function getDefaultConfigSelector( + serviceConfig: ServiceConfig | null +): ConfigSelector { + return function defaultConfigSelector( + methodName: string, + metadata: Metadata + ) { + const splitName = methodName.split('/').filter(x => x.length > 0); + const service = splitName[0] ?? ''; + const method = splitName[1] ?? ''; + if (serviceConfig && serviceConfig.methodConfig) { + /* Check for the following in order, and return the first method + * config that matches: + * 1. A name that exactly matches the service and method + * 2. A name with no method set that matches the service + * 3. An empty name + */ + for (const matchLevel of NAME_MATCH_LEVEL_ORDER) { + const matchingConfig = findMatchingConfig( + service, + method, + serviceConfig.methodConfig, + matchLevel + ); + if (matchingConfig) { + return { + methodConfig: matchingConfig, + pickInformation: {}, + status: Status.OK, + dynamicFilterFactories: [], + }; + } + } + } + return { + methodConfig: { name: [] }, + pickInformation: {}, + status: Status.OK, + dynamicFilterFactories: [], + }; + }; +} + +export interface ResolutionCallback { + (serviceConfig: ServiceConfig, configSelector: ConfigSelector): void; +} + +export interface ResolutionFailureCallback { + (status: StatusObject): void; +} + +export class ResolvingLoadBalancer implements LoadBalancer { + /** + * The resolver class constructed for the target address. + */ + private readonly innerResolver: Resolver; + + private readonly childLoadBalancer: ChildLoadBalancerHandler; + private latestChildState: ConnectivityState = ConnectivityState.IDLE; + private latestChildPicker: Picker = new QueuePicker(this); + /** + * This resolving load balancer's current connectivity state. + */ + private currentState: ConnectivityState = ConnectivityState.IDLE; + private readonly defaultServiceConfig: ServiceConfig; + /** + * The service config object from the last successful resolution, if + * available. A value of null indicates that we have not yet received a valid + * service config from the resolver. + */ + private previousServiceConfig: ServiceConfig | null = null; + + /** + * The backoff timer for handling name resolution failures. + */ + private readonly backoffTimeout: BackoffTimeout; + + /** + * Indicates whether we should attempt to resolve again after the backoff + * timer runs out. + */ + private continueResolving = false; + + /** + * Wrapper class that behaves like a `LoadBalancer` and also handles name + * resolution internally. + * @param target The address of the backend to connect to. + * @param channelControlHelper `ChannelControlHelper` instance provided by + * this load balancer's owner. + * @param defaultServiceConfig The default service configuration to be used + * if none is provided by the name resolver. A `null` value indicates + * that the default behavior should be the default unconfigured behavior. + * In practice, that means using the "pick first" load balancer + * implmentation + */ + constructor( + private readonly target: GrpcUri, + private readonly channelControlHelper: ChannelControlHelper, + channelOptions: ChannelOptions, + private readonly onSuccessfulResolution: ResolutionCallback, + private readonly onFailedResolution: ResolutionFailureCallback + ) { + if (channelOptions['grpc.service_config']) { + this.defaultServiceConfig = validateServiceConfig( + JSON.parse(channelOptions['grpc.service_config']!) + ); + } else { + this.defaultServiceConfig = { + loadBalancingConfig: [], + methodConfig: [], + }; + } + + this.updateState(ConnectivityState.IDLE, new QueuePicker(this)); + this.childLoadBalancer = new ChildLoadBalancerHandler( + { + createSubchannel: + channelControlHelper.createSubchannel.bind(channelControlHelper), + requestReresolution: () => { + /* If the backoffTimeout is running, we're still backing off from + * making resolve requests, so we shouldn't make another one here. + * In that case, the backoff timer callback will call + * updateResolution */ + if (this.backoffTimeout.isRunning()) { + trace( + 'requestReresolution delayed by backoff timer until ' + + this.backoffTimeout.getEndTime().toISOString() + ); + this.continueResolving = true; + } else { + this.updateResolution(); + } + }, + updateState: (newState: ConnectivityState, picker: Picker) => { + this.latestChildState = newState; + this.latestChildPicker = picker; + this.updateState(newState, picker); + }, + addChannelzChild: + channelControlHelper.addChannelzChild.bind(channelControlHelper), + removeChannelzChild: + channelControlHelper.removeChannelzChild.bind(channelControlHelper), + }, + channelOptions + ); + this.innerResolver = createResolver( + target, + { + onSuccessfulResolution: ( + endpointList: Endpoint[], + serviceConfig: ServiceConfig | null, + serviceConfigError: ServiceError | null, + configSelector: ConfigSelector | null, + attributes: { [key: string]: unknown } + ) => { + this.backoffTimeout.stop(); + this.backoffTimeout.reset(); + let workingServiceConfig: ServiceConfig | null = null; + /* This first group of conditionals implements the algorithm described + * in https://github.com/grpc/proposal/blob/master/A21-service-config-error-handling.md + * in the section called "Behavior on receiving a new gRPC Config". + */ + if (serviceConfig === null) { + // Step 4 and 5 + if (serviceConfigError === null) { + // Step 5 + this.previousServiceConfig = null; + workingServiceConfig = this.defaultServiceConfig; + } else { + // Step 4 + if (this.previousServiceConfig === null) { + // Step 4.ii + this.handleResolutionFailure(serviceConfigError); + } else { + // Step 4.i + workingServiceConfig = this.previousServiceConfig; + } + } + } else { + // Step 3 + workingServiceConfig = serviceConfig; + this.previousServiceConfig = serviceConfig; + } + const workingConfigList = + workingServiceConfig?.loadBalancingConfig ?? []; + const loadBalancingConfig = selectLbConfigFromList( + workingConfigList, + true + ); + if (loadBalancingConfig === null) { + // There were load balancing configs but none are supported. This counts as a resolution failure + this.handleResolutionFailure({ + code: Status.UNAVAILABLE, + details: + 'All load balancer options in service config are not compatible', + metadata: new Metadata(), + }); + return; + } + this.childLoadBalancer.updateAddressList( + endpointList, + loadBalancingConfig, + attributes + ); + const finalServiceConfig = + workingServiceConfig ?? this.defaultServiceConfig; + this.onSuccessfulResolution( + finalServiceConfig, + configSelector ?? getDefaultConfigSelector(finalServiceConfig) + ); + }, + onError: (error: StatusObject) => { + this.handleResolutionFailure(error); + }, + }, + channelOptions + ); + const backoffOptions: BackoffOptions = { + initialDelay: channelOptions['grpc.initial_reconnect_backoff_ms'], + maxDelay: channelOptions['grpc.max_reconnect_backoff_ms'], + }; + this.backoffTimeout = new BackoffTimeout(() => { + if (this.continueResolving) { + this.updateResolution(); + this.continueResolving = false; + } else { + this.updateState(this.latestChildState, this.latestChildPicker); + } + }, backoffOptions); + this.backoffTimeout.unref(); + } + + private updateResolution() { + this.innerResolver.updateResolution(); + if (this.currentState === ConnectivityState.IDLE) { + /* this.latestChildPicker is initialized as new QueuePicker(this), which + * is an appropriate value here if the child LB policy is unset. + * Otherwise, we want to delegate to the child here, in case that + * triggers something. */ + this.updateState(ConnectivityState.CONNECTING, this.latestChildPicker); + } + this.backoffTimeout.runOnce(); + } + + private updateState(connectivityState: ConnectivityState, picker: Picker) { + trace( + uriToString(this.target) + + ' ' + + ConnectivityState[this.currentState] + + ' -> ' + + ConnectivityState[connectivityState] + ); + // Ensure that this.exitIdle() is called by the picker + if (connectivityState === ConnectivityState.IDLE) { + picker = new QueuePicker(this, picker); + } + this.currentState = connectivityState; + this.channelControlHelper.updateState(connectivityState, picker); + } + + private handleResolutionFailure(error: StatusObject) { + if (this.latestChildState === ConnectivityState.IDLE) { + this.updateState( + ConnectivityState.TRANSIENT_FAILURE, + new UnavailablePicker(error) + ); + this.onFailedResolution(error); + } + } + + exitIdle() { + if ( + this.currentState === ConnectivityState.IDLE || + this.currentState === ConnectivityState.TRANSIENT_FAILURE + ) { + if (this.backoffTimeout.isRunning()) { + this.continueResolving = true; + } else { + this.updateResolution(); + } + } + this.childLoadBalancer.exitIdle(); + } + + updateAddressList( + endpointList: Endpoint[], + lbConfig: TypedLoadBalancingConfig | null + ): never { + throw new Error('updateAddressList not supported on ResolvingLoadBalancer'); + } + + resetBackoff() { + this.backoffTimeout.reset(); + this.childLoadBalancer.resetBackoff(); + } + + destroy() { + this.childLoadBalancer.destroy(); + this.innerResolver.destroy(); + this.backoffTimeout.reset(); + this.backoffTimeout.stop(); + this.latestChildState = ConnectivityState.IDLE; + this.latestChildPicker = new QueuePicker(this); + this.currentState = ConnectivityState.IDLE; + this.previousServiceConfig = null; + this.continueResolving = false; + } + + getTypeName() { + return 'resolving_load_balancer'; + } +} diff --git a/node_modules/@grpc/grpc-js/src/retrying-call.ts b/node_modules/@grpc/grpc-js/src/retrying-call.ts new file mode 100644 index 0000000..1c5ffaa --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/retrying-call.ts @@ -0,0 +1,842 @@ +/* + * Copyright 2022 gRPC authors. + * + * 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. + * + */ + +import { CallCredentials } from './call-credentials'; +import { LogVerbosity, Status } from './constants'; +import { Deadline, formatDateDifference } from './deadline'; +import { Metadata } from './metadata'; +import { CallConfig } from './resolver'; +import * as logging from './logging'; +import { + Call, + DeadlineInfoProvider, + InterceptingListener, + MessageContext, + StatusObject, + WriteCallback, + WriteObject, +} from './call-interface'; +import { + LoadBalancingCall, + StatusObjectWithProgress, +} from './load-balancing-call'; +import { InternalChannel } from './internal-channel'; + +const TRACER_NAME = 'retrying_call'; + +export class RetryThrottler { + private tokens: number; + constructor( + private readonly maxTokens: number, + private readonly tokenRatio: number, + previousRetryThrottler?: RetryThrottler + ) { + if (previousRetryThrottler) { + /* When carrying over tokens from a previous config, rescale them to the + * new max value */ + this.tokens = + previousRetryThrottler.tokens * + (maxTokens / previousRetryThrottler.maxTokens); + } else { + this.tokens = maxTokens; + } + } + + addCallSucceeded() { + this.tokens = Math.max(this.tokens + this.tokenRatio, this.maxTokens); + } + + addCallFailed() { + this.tokens = Math.min(this.tokens - 1, 0); + } + + canRetryCall() { + return this.tokens > this.maxTokens / 2; + } +} + +export class MessageBufferTracker { + private totalAllocated = 0; + private allocatedPerCall: Map = new Map(); + + constructor(private totalLimit: number, private limitPerCall: number) {} + + allocate(size: number, callId: number): boolean { + const currentPerCall = this.allocatedPerCall.get(callId) ?? 0; + if ( + this.limitPerCall - currentPerCall < size || + this.totalLimit - this.totalAllocated < size + ) { + return false; + } + this.allocatedPerCall.set(callId, currentPerCall + size); + this.totalAllocated += size; + return true; + } + + free(size: number, callId: number) { + if (this.totalAllocated < size) { + throw new Error( + `Invalid buffer allocation state: call ${callId} freed ${size} > total allocated ${this.totalAllocated}` + ); + } + this.totalAllocated -= size; + const currentPerCall = this.allocatedPerCall.get(callId) ?? 0; + if (currentPerCall < size) { + throw new Error( + `Invalid buffer allocation state: call ${callId} freed ${size} > allocated for call ${currentPerCall}` + ); + } + this.allocatedPerCall.set(callId, currentPerCall - size); + } + + freeAll(callId: number) { + const currentPerCall = this.allocatedPerCall.get(callId) ?? 0; + if (this.totalAllocated < currentPerCall) { + throw new Error( + `Invalid buffer allocation state: call ${callId} allocated ${currentPerCall} > total allocated ${this.totalAllocated}` + ); + } + this.totalAllocated -= currentPerCall; + this.allocatedPerCall.delete(callId); + } +} + +type UnderlyingCallState = 'ACTIVE' | 'COMPLETED'; + +interface UnderlyingCall { + state: UnderlyingCallState; + call: LoadBalancingCall; + nextMessageToSend: number; + startTime: Date; +} + +/** + * A retrying call can be in one of these states: + * RETRY: Retries are configured and new attempts may be sent + * HEDGING: Hedging is configured and new attempts may be sent + * TRANSPARENT_ONLY: Neither retries nor hedging are configured, and + * transparent retry attempts may still be sent + * COMMITTED: One attempt is committed, and no new attempts will be + * sent + */ +type RetryingCallState = 'RETRY' | 'HEDGING' | 'TRANSPARENT_ONLY' | 'COMMITTED'; + +/** + * The different types of objects that can be stored in the write buffer, with + * the following meanings: + * MESSAGE: This is a message to be sent. + * HALF_CLOSE: When this entry is reached, the calls should send a half-close. + * FREED: This slot previously contained a message that has been sent on all + * child calls and is no longer needed. + */ +type WriteBufferEntryType = 'MESSAGE' | 'HALF_CLOSE' | 'FREED'; + +/** + * Entry in the buffer of messages to send to the remote end. + */ +interface WriteBufferEntry { + entryType: WriteBufferEntryType; + /** + * Message to send. + * Only populated if entryType is MESSAGE. + */ + message?: WriteObject; + /** + * Callback to call after sending the message. + * Only populated if entryType is MESSAGE and the call is in the COMMITTED + * state. + */ + callback?: WriteCallback; + /** + * Indicates whether the message is allocated in the buffer tracker. Ignored + * if entryType is not MESSAGE. Should be the return value of + * bufferTracker.allocate. + */ + allocated: boolean; +} + +const PREVIONS_RPC_ATTEMPTS_METADATA_KEY = 'grpc-previous-rpc-attempts'; + +export class RetryingCall implements Call, DeadlineInfoProvider { + private state: RetryingCallState; + private listener: InterceptingListener | null = null; + private initialMetadata: Metadata | null = null; + private underlyingCalls: UnderlyingCall[] = []; + private writeBuffer: WriteBufferEntry[] = []; + /** + * The offset of message indices in the writeBuffer. For example, if + * writeBufferOffset is 10, message 10 is in writeBuffer[0] and message 15 + * is in writeBuffer[5]. + */ + private writeBufferOffset = 0; + /** + * Tracks whether a read has been started, so that we know whether to start + * reads on new child calls. This only matters for the first read, because + * once a message comes in the child call becomes committed and there will + * be no new child calls. + */ + private readStarted = false; + private transparentRetryUsed = false; + /** + * Number of attempts so far + */ + private attempts = 0; + private hedgingTimer: NodeJS.Timeout | null = null; + private committedCallIndex: number | null = null; + private initialRetryBackoffSec = 0; + private nextRetryBackoffSec = 0; + private startTime: Date; + constructor( + private readonly channel: InternalChannel, + private readonly callConfig: CallConfig, + private readonly methodName: string, + private readonly host: string, + private readonly credentials: CallCredentials, + private readonly deadline: Deadline, + private readonly callNumber: number, + private readonly bufferTracker: MessageBufferTracker, + private readonly retryThrottler?: RetryThrottler + ) { + if (callConfig.methodConfig.retryPolicy) { + this.state = 'RETRY'; + const retryPolicy = callConfig.methodConfig.retryPolicy; + this.nextRetryBackoffSec = this.initialRetryBackoffSec = Number( + retryPolicy.initialBackoff.substring( + 0, + retryPolicy.initialBackoff.length - 1 + ) + ); + } else if (callConfig.methodConfig.hedgingPolicy) { + this.state = 'HEDGING'; + } else { + this.state = 'TRANSPARENT_ONLY'; + } + this.startTime = new Date(); + } + getDeadlineInfo(): string[] { + if (this.underlyingCalls.length === 0) { + return []; + } + const deadlineInfo: string[] = []; + const latestCall = this.underlyingCalls[this.underlyingCalls.length - 1]; + if (this.underlyingCalls.length > 1) { + deadlineInfo.push(`previous attempts: ${this.underlyingCalls.length - 1}`); + } + if (latestCall.startTime > this.startTime) { + deadlineInfo.push(`time to current attempt start: ${formatDateDifference(this.startTime, latestCall.startTime)}`); + } + deadlineInfo.push(...latestCall.call.getDeadlineInfo()); + return deadlineInfo; + } + getCallNumber(): number { + return this.callNumber; + } + + private trace(text: string): void { + logging.trace( + LogVerbosity.DEBUG, + TRACER_NAME, + '[' + this.callNumber + '] ' + text + ); + } + + private reportStatus(statusObject: StatusObject) { + this.trace( + 'ended with status: code=' + + statusObject.code + + ' details="' + + statusObject.details + + '" start time=' + + this.startTime.toISOString() + ); + this.bufferTracker.freeAll(this.callNumber); + this.writeBufferOffset = this.writeBufferOffset + this.writeBuffer.length; + this.writeBuffer = []; + process.nextTick(() => { + // Explicitly construct status object to remove progress field + this.listener?.onReceiveStatus({ + code: statusObject.code, + details: statusObject.details, + metadata: statusObject.metadata, + }); + }); + } + + cancelWithStatus(status: Status, details: string): void { + this.trace( + 'cancelWithStatus code: ' + status + ' details: "' + details + '"' + ); + this.reportStatus({ code: status, details, metadata: new Metadata() }); + for (const { call } of this.underlyingCalls) { + call.cancelWithStatus(status, details); + } + } + getPeer(): string { + if (this.committedCallIndex !== null) { + return this.underlyingCalls[this.committedCallIndex].call.getPeer(); + } else { + return 'unknown'; + } + } + + private getBufferEntry(messageIndex: number): WriteBufferEntry { + return ( + this.writeBuffer[messageIndex - this.writeBufferOffset] ?? { + entryType: 'FREED', + allocated: false, + } + ); + } + + private getNextBufferIndex() { + return this.writeBufferOffset + this.writeBuffer.length; + } + + private clearSentMessages() { + if (this.state !== 'COMMITTED') { + return; + } + const earliestNeededMessageIndex = + this.underlyingCalls[this.committedCallIndex!].nextMessageToSend; + for ( + let messageIndex = this.writeBufferOffset; + messageIndex < earliestNeededMessageIndex; + messageIndex++ + ) { + const bufferEntry = this.getBufferEntry(messageIndex); + if (bufferEntry.allocated) { + this.bufferTracker.free( + bufferEntry.message!.message.length, + this.callNumber + ); + } + } + this.writeBuffer = this.writeBuffer.slice( + earliestNeededMessageIndex - this.writeBufferOffset + ); + this.writeBufferOffset = earliestNeededMessageIndex; + } + + private commitCall(index: number) { + if (this.state === 'COMMITTED') { + return; + } + if (this.underlyingCalls[index].state === 'COMPLETED') { + return; + } + this.trace( + 'Committing call [' + + this.underlyingCalls[index].call.getCallNumber() + + '] at index ' + + index + ); + this.state = 'COMMITTED'; + this.committedCallIndex = index; + for (let i = 0; i < this.underlyingCalls.length; i++) { + if (i === index) { + continue; + } + if (this.underlyingCalls[i].state === 'COMPLETED') { + continue; + } + this.underlyingCalls[i].state = 'COMPLETED'; + this.underlyingCalls[i].call.cancelWithStatus( + Status.CANCELLED, + 'Discarded in favor of other hedged attempt' + ); + } + this.clearSentMessages(); + } + + private commitCallWithMostMessages() { + if (this.state === 'COMMITTED') { + return; + } + let mostMessages = -1; + let callWithMostMessages = -1; + for (const [index, childCall] of this.underlyingCalls.entries()) { + if ( + childCall.state === 'ACTIVE' && + childCall.nextMessageToSend > mostMessages + ) { + mostMessages = childCall.nextMessageToSend; + callWithMostMessages = index; + } + } + if (callWithMostMessages === -1) { + /* There are no active calls, disable retries to force the next call that + * is started to be committed. */ + this.state = 'TRANSPARENT_ONLY'; + } else { + this.commitCall(callWithMostMessages); + } + } + + private isStatusCodeInList(list: (Status | string)[], code: Status) { + return list.some( + value => + value === code || + value.toString().toLowerCase() === Status[code].toLowerCase() + ); + } + + private getNextRetryBackoffMs() { + const retryPolicy = this.callConfig?.methodConfig.retryPolicy; + if (!retryPolicy) { + return 0; + } + const nextBackoffMs = Math.random() * this.nextRetryBackoffSec * 1000; + const maxBackoffSec = Number( + retryPolicy.maxBackoff.substring(0, retryPolicy.maxBackoff.length - 1) + ); + this.nextRetryBackoffSec = Math.min( + this.nextRetryBackoffSec * retryPolicy.backoffMultiplier, + maxBackoffSec + ); + return nextBackoffMs; + } + + private maybeRetryCall( + pushback: number | null, + callback: (retried: boolean) => void + ) { + if (this.state !== 'RETRY') { + callback(false); + return; + } + const retryPolicy = this.callConfig!.methodConfig.retryPolicy!; + if (this.attempts >= Math.min(retryPolicy.maxAttempts, 5)) { + callback(false); + return; + } + let retryDelayMs: number; + if (pushback === null) { + retryDelayMs = this.getNextRetryBackoffMs(); + } else if (pushback < 0) { + this.state = 'TRANSPARENT_ONLY'; + callback(false); + return; + } else { + retryDelayMs = pushback; + this.nextRetryBackoffSec = this.initialRetryBackoffSec; + } + setTimeout(() => { + if (this.state !== 'RETRY') { + callback(false); + return; + } + if (this.retryThrottler?.canRetryCall() ?? true) { + callback(true); + this.attempts += 1; + this.startNewAttempt(); + } + }, retryDelayMs); + } + + private countActiveCalls(): number { + let count = 0; + for (const call of this.underlyingCalls) { + if (call?.state === 'ACTIVE') { + count += 1; + } + } + return count; + } + + private handleProcessedStatus( + status: StatusObject, + callIndex: number, + pushback: number | null + ) { + switch (this.state) { + case 'COMMITTED': + case 'TRANSPARENT_ONLY': + this.commitCall(callIndex); + this.reportStatus(status); + break; + case 'HEDGING': + if ( + this.isStatusCodeInList( + this.callConfig!.methodConfig.hedgingPolicy!.nonFatalStatusCodes ?? + [], + status.code + ) + ) { + this.retryThrottler?.addCallFailed(); + let delayMs: number; + if (pushback === null) { + delayMs = 0; + } else if (pushback < 0) { + this.state = 'TRANSPARENT_ONLY'; + this.commitCall(callIndex); + this.reportStatus(status); + return; + } else { + delayMs = pushback; + } + setTimeout(() => { + this.maybeStartHedgingAttempt(); + // If after trying to start a call there are no active calls, this was the last one + if (this.countActiveCalls() === 0) { + this.commitCall(callIndex); + this.reportStatus(status); + } + }, delayMs); + } else { + this.commitCall(callIndex); + this.reportStatus(status); + } + break; + case 'RETRY': + if ( + this.isStatusCodeInList( + this.callConfig!.methodConfig.retryPolicy!.retryableStatusCodes, + status.code + ) + ) { + this.retryThrottler?.addCallFailed(); + this.maybeRetryCall(pushback, retried => { + if (!retried) { + this.commitCall(callIndex); + this.reportStatus(status); + } + }); + } else { + this.commitCall(callIndex); + this.reportStatus(status); + } + break; + } + } + + private getPushback(metadata: Metadata): number | null { + const mdValue = metadata.get('grpc-retry-pushback-ms'); + if (mdValue.length === 0) { + return null; + } + try { + return parseInt(mdValue[0] as string); + } catch (e) { + return -1; + } + } + + private handleChildStatus( + status: StatusObjectWithProgress, + callIndex: number + ) { + if (this.underlyingCalls[callIndex].state === 'COMPLETED') { + return; + } + this.trace( + 'state=' + + this.state + + ' handling status with progress ' + + status.progress + + ' from child [' + + this.underlyingCalls[callIndex].call.getCallNumber() + + '] in state ' + + this.underlyingCalls[callIndex].state + ); + this.underlyingCalls[callIndex].state = 'COMPLETED'; + if (status.code === Status.OK) { + this.retryThrottler?.addCallSucceeded(); + this.commitCall(callIndex); + this.reportStatus(status); + return; + } + if (this.state === 'COMMITTED') { + this.reportStatus(status); + return; + } + const pushback = this.getPushback(status.metadata); + switch (status.progress) { + case 'NOT_STARTED': + // RPC never leaves the client, always safe to retry + this.startNewAttempt(); + break; + case 'REFUSED': + // RPC reaches the server library, but not the server application logic + if (this.transparentRetryUsed) { + this.handleProcessedStatus(status, callIndex, pushback); + } else { + this.transparentRetryUsed = true; + this.startNewAttempt(); + } + break; + case 'DROP': + this.commitCall(callIndex); + this.reportStatus(status); + break; + case 'PROCESSED': + this.handleProcessedStatus(status, callIndex, pushback); + break; + } + } + + private maybeStartHedgingAttempt() { + if (this.state !== 'HEDGING') { + return; + } + if (!this.callConfig.methodConfig.hedgingPolicy) { + return; + } + const hedgingPolicy = this.callConfig.methodConfig.hedgingPolicy; + if (this.attempts >= Math.min(hedgingPolicy.maxAttempts, 5)) { + return; + } + this.attempts += 1; + this.startNewAttempt(); + this.maybeStartHedgingTimer(); + } + + private maybeStartHedgingTimer() { + if (this.hedgingTimer) { + clearTimeout(this.hedgingTimer); + } + if (this.state !== 'HEDGING') { + return; + } + if (!this.callConfig.methodConfig.hedgingPolicy) { + return; + } + const hedgingPolicy = this.callConfig.methodConfig.hedgingPolicy; + if (this.attempts >= Math.min(hedgingPolicy.maxAttempts, 5)) { + return; + } + const hedgingDelayString = hedgingPolicy.hedgingDelay ?? '0s'; + const hedgingDelaySec = Number( + hedgingDelayString.substring(0, hedgingDelayString.length - 1) + ); + this.hedgingTimer = setTimeout(() => { + this.maybeStartHedgingAttempt(); + }, hedgingDelaySec * 1000); + this.hedgingTimer.unref?.(); + } + + private startNewAttempt() { + const child = this.channel.createLoadBalancingCall( + this.callConfig, + this.methodName, + this.host, + this.credentials, + this.deadline + ); + this.trace( + 'Created child call [' + + child.getCallNumber() + + '] for attempt ' + + this.attempts + ); + const index = this.underlyingCalls.length; + this.underlyingCalls.push({ + state: 'ACTIVE', + call: child, + nextMessageToSend: 0, + startTime: new Date() + }); + const previousAttempts = this.attempts - 1; + const initialMetadata = this.initialMetadata!.clone(); + if (previousAttempts > 0) { + initialMetadata.set( + PREVIONS_RPC_ATTEMPTS_METADATA_KEY, + `${previousAttempts}` + ); + } + let receivedMetadata = false; + child.start(initialMetadata, { + onReceiveMetadata: metadata => { + this.trace( + 'Received metadata from child [' + child.getCallNumber() + ']' + ); + this.commitCall(index); + receivedMetadata = true; + if (previousAttempts > 0) { + metadata.set( + PREVIONS_RPC_ATTEMPTS_METADATA_KEY, + `${previousAttempts}` + ); + } + if (this.underlyingCalls[index].state === 'ACTIVE') { + this.listener!.onReceiveMetadata(metadata); + } + }, + onReceiveMessage: message => { + this.trace( + 'Received message from child [' + child.getCallNumber() + ']' + ); + this.commitCall(index); + if (this.underlyingCalls[index].state === 'ACTIVE') { + this.listener!.onReceiveMessage(message); + } + }, + onReceiveStatus: status => { + this.trace( + 'Received status from child [' + child.getCallNumber() + ']' + ); + if (!receivedMetadata && previousAttempts > 0) { + status.metadata.set( + PREVIONS_RPC_ATTEMPTS_METADATA_KEY, + `${previousAttempts}` + ); + } + this.handleChildStatus(status, index); + }, + }); + this.sendNextChildMessage(index); + if (this.readStarted) { + child.startRead(); + } + } + + start(metadata: Metadata, listener: InterceptingListener): void { + this.trace('start called'); + this.listener = listener; + this.initialMetadata = metadata; + this.attempts += 1; + this.startNewAttempt(); + this.maybeStartHedgingTimer(); + } + + private handleChildWriteCompleted(childIndex: number) { + const childCall = this.underlyingCalls[childIndex]; + const messageIndex = childCall.nextMessageToSend; + this.getBufferEntry(messageIndex).callback?.(); + this.clearSentMessages(); + childCall.nextMessageToSend += 1; + this.sendNextChildMessage(childIndex); + } + + private sendNextChildMessage(childIndex: number) { + const childCall = this.underlyingCalls[childIndex]; + if (childCall.state === 'COMPLETED') { + return; + } + if (this.getBufferEntry(childCall.nextMessageToSend)) { + const bufferEntry = this.getBufferEntry(childCall.nextMessageToSend); + switch (bufferEntry.entryType) { + case 'MESSAGE': + childCall.call.sendMessageWithContext( + { + callback: error => { + // Ignore error + this.handleChildWriteCompleted(childIndex); + }, + }, + bufferEntry.message!.message + ); + break; + case 'HALF_CLOSE': + childCall.nextMessageToSend += 1; + childCall.call.halfClose(); + break; + case 'FREED': + // Should not be possible + break; + } + } + } + + sendMessageWithContext(context: MessageContext, message: Buffer): void { + this.trace('write() called with message of length ' + message.length); + const writeObj: WriteObject = { + message, + flags: context.flags, + }; + const messageIndex = this.getNextBufferIndex(); + const bufferEntry: WriteBufferEntry = { + entryType: 'MESSAGE', + message: writeObj, + allocated: this.bufferTracker.allocate(message.length, this.callNumber), + }; + this.writeBuffer.push(bufferEntry); + if (bufferEntry.allocated) { + context.callback?.(); + for (const [callIndex, call] of this.underlyingCalls.entries()) { + if ( + call.state === 'ACTIVE' && + call.nextMessageToSend === messageIndex + ) { + call.call.sendMessageWithContext( + { + callback: error => { + // Ignore error + this.handleChildWriteCompleted(callIndex); + }, + }, + message + ); + } + } + } else { + this.commitCallWithMostMessages(); + // commitCallWithMostMessages can fail if we are between ping attempts + if (this.committedCallIndex === null) { + return; + } + const call = this.underlyingCalls[this.committedCallIndex]; + bufferEntry.callback = context.callback; + if (call.state === 'ACTIVE' && call.nextMessageToSend === messageIndex) { + call.call.sendMessageWithContext( + { + callback: error => { + // Ignore error + this.handleChildWriteCompleted(this.committedCallIndex!); + }, + }, + message + ); + } + } + } + startRead(): void { + this.trace('startRead called'); + this.readStarted = true; + for (const underlyingCall of this.underlyingCalls) { + if (underlyingCall?.state === 'ACTIVE') { + underlyingCall.call.startRead(); + } + } + } + halfClose(): void { + this.trace('halfClose called'); + const halfCloseIndex = this.getNextBufferIndex(); + this.writeBuffer.push({ + entryType: 'HALF_CLOSE', + allocated: false, + }); + for (const call of this.underlyingCalls) { + if ( + call?.state === 'ACTIVE' && + call.nextMessageToSend === halfCloseIndex + ) { + call.nextMessageToSend += 1; + call.call.halfClose(); + } + } + } + setCredentials(newCredentials: CallCredentials): void { + throw new Error('Method not implemented.'); + } + getMethod(): string { + return this.methodName; + } + getHost(): string { + return this.host; + } +} diff --git a/node_modules/@grpc/grpc-js/src/server-call.ts b/node_modules/@grpc/grpc-js/src/server-call.ts new file mode 100644 index 0000000..ccc80a1 --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/server-call.ts @@ -0,0 +1,367 @@ +/* + * Copyright 2019 gRPC authors. + * + * 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. + * + */ + +import { EventEmitter } from 'events'; +import { Duplex, Readable, Writable } from 'stream'; + +import { Status } from './constants'; +import type { Deserialize, Serialize } from './make-client'; +import { Metadata } from './metadata'; +import type { ObjectReadable, ObjectWritable } from './object-stream'; +import type { StatusObject, PartialStatusObject } from './call-interface'; +import type { Deadline } from './deadline'; +import type { ServerInterceptingCallInterface } from './server-interceptors'; + +export type ServerStatusResponse = Partial; + +export type ServerErrorResponse = ServerStatusResponse & Error; + +export type ServerSurfaceCall = { + cancelled: boolean; + readonly metadata: Metadata; + getPeer(): string; + sendMetadata(responseMetadata: Metadata): void; + getDeadline(): Deadline; + getPath(): string; +} & EventEmitter; + +export type ServerUnaryCall = ServerSurfaceCall & { + request: RequestType; +}; +export type ServerReadableStream = + ServerSurfaceCall & ObjectReadable; +export type ServerWritableStream = + ServerSurfaceCall & + ObjectWritable & { + request: RequestType; + end: (metadata?: Metadata) => void; + }; +export type ServerDuplexStream = ServerSurfaceCall & + ObjectReadable & + ObjectWritable & { end: (metadata?: Metadata) => void }; + +export function serverErrorToStatus( + error: ServerErrorResponse | ServerStatusResponse, + overrideTrailers?: Metadata | undefined +): PartialStatusObject { + const status: PartialStatusObject = { + code: Status.UNKNOWN, + details: 'message' in error ? error.message : 'Unknown Error', + metadata: overrideTrailers ?? error.metadata ?? null, + }; + + if ( + 'code' in error && + typeof error.code === 'number' && + Number.isInteger(error.code) + ) { + status.code = error.code; + + if ('details' in error && typeof error.details === 'string') { + status.details = error.details!; + } + } + return status; +} + +export class ServerUnaryCallImpl + extends EventEmitter + implements ServerUnaryCall +{ + cancelled: boolean; + + constructor( + private path: string, + private call: ServerInterceptingCallInterface, + public metadata: Metadata, + public request: RequestType + ) { + super(); + this.cancelled = false; + } + + getPeer(): string { + return this.call.getPeer(); + } + + sendMetadata(responseMetadata: Metadata): void { + this.call.sendMetadata(responseMetadata); + } + + getDeadline(): Deadline { + return this.call.getDeadline(); + } + + getPath(): string { + return this.path; + } +} + +export class ServerReadableStreamImpl + extends Readable + implements ServerReadableStream +{ + cancelled: boolean; + + constructor( + private path: string, + private call: ServerInterceptingCallInterface, + public metadata: Metadata + ) { + super({ objectMode: true }); + this.cancelled = false; + } + + _read(size: number) { + this.call.startRead(); + } + + getPeer(): string { + return this.call.getPeer(); + } + + sendMetadata(responseMetadata: Metadata): void { + this.call.sendMetadata(responseMetadata); + } + + getDeadline(): Deadline { + return this.call.getDeadline(); + } + + getPath(): string { + return this.path; + } +} + +export class ServerWritableStreamImpl + extends Writable + implements ServerWritableStream +{ + cancelled: boolean; + private trailingMetadata: Metadata; + private pendingStatus: PartialStatusObject = { + code: Status.OK, + details: 'OK', + }; + + constructor( + private path: string, + private call: ServerInterceptingCallInterface, + public metadata: Metadata, + public request: RequestType + ) { + super({ objectMode: true }); + this.cancelled = false; + this.trailingMetadata = new Metadata(); + + this.on('error', err => { + this.pendingStatus = serverErrorToStatus(err); + this.end(); + }); + } + + getPeer(): string { + return this.call.getPeer(); + } + + sendMetadata(responseMetadata: Metadata): void { + this.call.sendMetadata(responseMetadata); + } + + getDeadline(): Deadline { + return this.call.getDeadline(); + } + + getPath(): string { + return this.path; + } + + _write( + chunk: ResponseType, + encoding: string, + // eslint-disable-next-line @typescript-eslint/no-explicit-any + callback: (...args: any[]) => void + ) { + this.call.sendMessage(chunk, callback); + } + + _final(callback: Function): void { + callback(null); + this.call.sendStatus({ + ...this.pendingStatus, + metadata: this.pendingStatus.metadata ?? this.trailingMetadata, + }); + } + + // eslint-disable-next-line @typescript-eslint/no-explicit-any + end(metadata?: any) { + if (metadata) { + this.trailingMetadata = metadata; + } + + return super.end(); + } +} + +export class ServerDuplexStreamImpl + extends Duplex + implements ServerDuplexStream +{ + cancelled: boolean; + private trailingMetadata: Metadata; + private pendingStatus: PartialStatusObject = { + code: Status.OK, + details: 'OK', + }; + + constructor( + private path: string, + private call: ServerInterceptingCallInterface, + public metadata: Metadata + ) { + super({ objectMode: true }); + this.cancelled = false; + this.trailingMetadata = new Metadata(); + + this.on('error', err => { + this.pendingStatus = serverErrorToStatus(err); + this.end(); + }); + } + + getPeer(): string { + return this.call.getPeer(); + } + + sendMetadata(responseMetadata: Metadata): void { + this.call.sendMetadata(responseMetadata); + } + + getDeadline(): Deadline { + return this.call.getDeadline(); + } + + getPath(): string { + return this.path; + } + + _read(size: number) { + this.call.startRead(); + } + + _write( + chunk: ResponseType, + encoding: string, + // eslint-disable-next-line @typescript-eslint/no-explicit-any + callback: (...args: any[]) => void + ) { + this.call.sendMessage(chunk, callback); + } + + _final(callback: Function): void { + callback(null); + this.call.sendStatus({ + ...this.pendingStatus, + metadata: this.pendingStatus.metadata ?? this.trailingMetadata, + }); + } + + // eslint-disable-next-line @typescript-eslint/no-explicit-any + end(metadata?: any) { + if (metadata) { + this.trailingMetadata = metadata; + } + + return super.end(); + } +} + +// Unary response callback signature. +export type sendUnaryData = ( + error: ServerErrorResponse | ServerStatusResponse | null, + value?: ResponseType | null, + trailer?: Metadata, + flags?: number +) => void; + +// User provided handler for unary calls. +export type handleUnaryCall = ( + call: ServerUnaryCall, + callback: sendUnaryData +) => void; + +// User provided handler for client streaming calls. +export type handleClientStreamingCall = ( + call: ServerReadableStream, + callback: sendUnaryData +) => void; + +// User provided handler for server streaming calls. +export type handleServerStreamingCall = ( + call: ServerWritableStream +) => void; + +// User provided handler for bidirectional streaming calls. +export type handleBidiStreamingCall = ( + call: ServerDuplexStream +) => void; + +export type HandleCall = + | handleUnaryCall + | handleClientStreamingCall + | handleServerStreamingCall + | handleBidiStreamingCall; + +export interface UnaryHandler { + func: handleUnaryCall; + serialize: Serialize; + deserialize: Deserialize; + type: 'unary'; + path: string; +} + +export interface ClientStreamingHandler { + func: handleClientStreamingCall; + serialize: Serialize; + deserialize: Deserialize; + type: 'clientStream'; + path: string; +} + +export interface ServerStreamingHandler { + func: handleServerStreamingCall; + serialize: Serialize; + deserialize: Deserialize; + type: 'serverStream'; + path: string; +} + +export interface BidiStreamingHandler { + func: handleBidiStreamingCall; + serialize: Serialize; + deserialize: Deserialize; + type: 'bidi'; + path: string; +} + +export type Handler = + | UnaryHandler + | ClientStreamingHandler + | ServerStreamingHandler + | BidiStreamingHandler; + +export type HandlerType = 'bidi' | 'clientStream' | 'serverStream' | 'unary'; diff --git a/node_modules/@grpc/grpc-js/src/server-credentials.ts b/node_modules/@grpc/grpc-js/src/server-credentials.ts new file mode 100644 index 0000000..0dd5f8c --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/server-credentials.ts @@ -0,0 +1,191 @@ +/* + * Copyright 2019 gRPC authors. + * + * 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. + * + */ + +import { SecureServerOptions } from 'http2'; +import { CIPHER_SUITES, getDefaultRootsData } from './tls-helpers'; + +export interface KeyCertPair { + private_key: Buffer; + cert_chain: Buffer; +} + +export abstract class ServerCredentials { + abstract _isSecure(): boolean; + abstract _getSettings(): SecureServerOptions | null; + abstract _equals(other: ServerCredentials): boolean; + + static createInsecure(): ServerCredentials { + return new InsecureServerCredentials(); + } + + static createSsl( + rootCerts: Buffer | null, + keyCertPairs: KeyCertPair[], + checkClientCertificate = false + ): ServerCredentials { + if (rootCerts !== null && !Buffer.isBuffer(rootCerts)) { + throw new TypeError('rootCerts must be null or a Buffer'); + } + + if (!Array.isArray(keyCertPairs)) { + throw new TypeError('keyCertPairs must be an array'); + } + + if (typeof checkClientCertificate !== 'boolean') { + throw new TypeError('checkClientCertificate must be a boolean'); + } + + const cert: Buffer[] = []; + const key: Buffer[] = []; + + for (let i = 0; i < keyCertPairs.length; i++) { + const pair = keyCertPairs[i]; + + if (pair === null || typeof pair !== 'object') { + throw new TypeError(`keyCertPair[${i}] must be an object`); + } + + if (!Buffer.isBuffer(pair.private_key)) { + throw new TypeError(`keyCertPair[${i}].private_key must be a Buffer`); + } + + if (!Buffer.isBuffer(pair.cert_chain)) { + throw new TypeError(`keyCertPair[${i}].cert_chain must be a Buffer`); + } + + cert.push(pair.cert_chain); + key.push(pair.private_key); + } + + return new SecureServerCredentials({ + ca: rootCerts ?? getDefaultRootsData() ?? undefined, + cert, + key, + requestCert: checkClientCertificate, + ciphers: CIPHER_SUITES, + }); + } +} + +class InsecureServerCredentials extends ServerCredentials { + _isSecure(): boolean { + return false; + } + + _getSettings(): null { + return null; + } + + _equals(other: ServerCredentials): boolean { + return other instanceof InsecureServerCredentials; + } +} + +class SecureServerCredentials extends ServerCredentials { + private options: SecureServerOptions; + + constructor(options: SecureServerOptions) { + super(); + this.options = options; + } + + _isSecure(): boolean { + return true; + } + + _getSettings(): SecureServerOptions { + return this.options; + } + + /** + * Checks equality by checking the options that are actually set by + * createSsl. + * @param other + * @returns + */ + _equals(other: ServerCredentials): boolean { + if (this === other) { + return true; + } + if (!(other instanceof SecureServerCredentials)) { + return false; + } + // options.ca equality check + if (Buffer.isBuffer(this.options.ca) && Buffer.isBuffer(other.options.ca)) { + if (!this.options.ca.equals(other.options.ca)) { + return false; + } + } else { + if (this.options.ca !== other.options.ca) { + return false; + } + } + // options.cert equality check + if (Array.isArray(this.options.cert) && Array.isArray(other.options.cert)) { + if (this.options.cert.length !== other.options.cert.length) { + return false; + } + for (let i = 0; i < this.options.cert.length; i++) { + const thisCert = this.options.cert[i]; + const otherCert = other.options.cert[i]; + if (Buffer.isBuffer(thisCert) && Buffer.isBuffer(otherCert)) { + if (!thisCert.equals(otherCert)) { + return false; + } + } else { + if (thisCert !== otherCert) { + return false; + } + } + } + } else { + if (this.options.cert !== other.options.cert) { + return false; + } + } + // options.key equality check + if (Array.isArray(this.options.key) && Array.isArray(other.options.key)) { + if (this.options.key.length !== other.options.key.length) { + return false; + } + for (let i = 0; i < this.options.key.length; i++) { + const thisKey = this.options.key[i]; + const otherKey = other.options.key[i]; + if (Buffer.isBuffer(thisKey) && Buffer.isBuffer(otherKey)) { + if (!thisKey.equals(otherKey)) { + return false; + } + } else { + if (thisKey !== otherKey) { + return false; + } + } + } + } else { + if (this.options.key !== other.options.key) { + return false; + } + } + // options.requestCert equality check + if (this.options.requestCert !== other.options.requestCert) { + return false; + } + /* ciphers is derived from a value that is constant for the process, so no + * equality check is needed. */ + return true; + } +} diff --git a/node_modules/@grpc/grpc-js/src/server-interceptors.ts b/node_modules/@grpc/grpc-js/src/server-interceptors.ts new file mode 100644 index 0000000..b62d551 --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/server-interceptors.ts @@ -0,0 +1,967 @@ +/* + * Copyright 2024 gRPC authors. + * + * 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. + * + */ + +import { PartialStatusObject } from './call-interface'; +import { ServerMethodDefinition } from './make-client'; +import { Metadata } from './metadata'; +import { ChannelOptions } from './channel-options'; +import { Handler, ServerErrorResponse } from './server-call'; +import { Deadline } from './deadline'; +import { + DEFAULT_MAX_RECEIVE_MESSAGE_LENGTH, + DEFAULT_MAX_SEND_MESSAGE_LENGTH, + LogVerbosity, + Status, +} from './constants'; +import * as http2 from 'http2'; +import { getErrorMessage } from './error'; +import * as zlib from 'zlib'; +import { promisify } from 'util'; +import { StreamDecoder } from './stream-decoder'; +import { CallEventTracker } from './transport'; +import * as logging from './logging'; + +const unzip = promisify(zlib.unzip); +const inflate = promisify(zlib.inflate); + +const TRACER_NAME = 'server_call'; + +function trace(text: string) { + logging.trace(LogVerbosity.DEBUG, TRACER_NAME, text); +} + +export interface ServerMetadataListener { + (metadata: Metadata, next: (metadata: Metadata) => void): void; +} + +export interface ServerMessageListener { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + (message: any, next: (message: any) => void): void; +} + +export interface ServerHalfCloseListener { + (next: () => void): void; +} + +export interface ServerCancelListener { + (): void; +} + +export interface FullServerListener { + onReceiveMetadata: ServerMetadataListener; + onReceiveMessage: ServerMessageListener; + onReceiveHalfClose: ServerHalfCloseListener; + onCancel: ServerCancelListener; +} + +export type ServerListener = Partial; + +export class ServerListenerBuilder { + private metadata: ServerMetadataListener | undefined = undefined; + private message: ServerMessageListener | undefined = undefined; + private halfClose: ServerHalfCloseListener | undefined = undefined; + private cancel: ServerCancelListener | undefined = undefined; + + withOnReceiveMetadata(onReceiveMetadata: ServerMetadataListener): this { + this.metadata = onReceiveMetadata; + return this; + } + + withOnReceiveMessage(onReceiveMessage: ServerMessageListener): this { + this.message = onReceiveMessage; + return this; + } + + withOnReceiveHalfClose(onReceiveHalfClose: ServerHalfCloseListener): this { + this.halfClose = onReceiveHalfClose; + return this; + } + + withOnCancel(onCancel: ServerCancelListener): this { + this.cancel = onCancel; + return this; + } + + build(): ServerListener { + return { + onReceiveMetadata: this.metadata, + onReceiveMessage: this.message, + onReceiveHalfClose: this.halfClose, + onCancel: this.cancel, + }; + } +} + +export interface InterceptingServerListener { + onReceiveMetadata(metadata: Metadata): void; + // eslint-disable-next-line @typescript-eslint/no-explicit-any + onReceiveMessage(message: any): void; + onReceiveHalfClose(): void; + onCancel(): void; +} + +export function isInterceptingServerListener( + listener: ServerListener | InterceptingServerListener +): listener is InterceptingServerListener { + return ( + listener.onReceiveMetadata !== undefined && + listener.onReceiveMetadata.length === 1 + ); +} + +class InterceptingServerListenerImpl implements InterceptingServerListener { + /** + * Once the call is cancelled, ignore all other events. + */ + private cancelled = false; + private processingMetadata = false; + private hasPendingMessage = false; + private pendingMessage: any = null; + private processingMessage = false; + private hasPendingHalfClose = false; + + constructor( + private listener: FullServerListener, + private nextListener: InterceptingServerListener + ) {} + + private processPendingMessage() { + if (this.hasPendingMessage) { + this.nextListener.onReceiveMessage(this.pendingMessage); + this.pendingMessage = null; + this.hasPendingMessage = false; + } + } + + private processPendingHalfClose() { + if (this.hasPendingHalfClose) { + this.nextListener.onReceiveHalfClose(); + this.hasPendingHalfClose = false; + } + } + + onReceiveMetadata(metadata: Metadata): void { + if (this.cancelled) { + return; + } + this.processingMetadata = true; + this.listener.onReceiveMetadata(metadata, interceptedMetadata => { + this.processingMetadata = false; + if (this.cancelled) { + return; + } + this.nextListener.onReceiveMetadata(interceptedMetadata); + this.processPendingMessage(); + this.processPendingHalfClose(); + }); + } + onReceiveMessage(message: any): void { + if (this.cancelled) { + return; + } + this.processingMessage = true; + this.listener.onReceiveMessage(message, msg => { + this.processingMessage = false; + if (this.cancelled) { + return; + } + if (this.processingMetadata) { + this.pendingMessage = msg; + this.hasPendingMessage = true; + } else { + this.nextListener.onReceiveMessage(msg); + this.processPendingHalfClose(); + } + }); + } + onReceiveHalfClose(): void { + if (this.cancelled) { + return; + } + this.listener.onReceiveHalfClose(() => { + if (this.cancelled) { + return; + } + if (this.processingMetadata || this.processingMessage) { + this.hasPendingHalfClose = true; + } else { + this.nextListener.onReceiveHalfClose(); + } + }); + } + onCancel(): void { + this.cancelled = true; + this.listener.onCancel(); + this.nextListener.onCancel(); + } +} + +export interface StartResponder { + (next: (listener?: ServerListener) => void): void; +} + +export interface MetadataResponder { + (metadata: Metadata, next: (metadata: Metadata) => void): void; +} + +export interface MessageResponder { + // eslint-disable-next-line @typescript-eslint/no-explicit-any + (message: any, next: (message: any) => void): void; +} + +export interface StatusResponder { + ( + status: PartialStatusObject, + next: (status: PartialStatusObject) => void + ): void; +} + +export interface FullResponder { + start: StartResponder; + sendMetadata: MetadataResponder; + sendMessage: MessageResponder; + sendStatus: StatusResponder; +} + +export type Responder = Partial; + +export class ResponderBuilder { + private start: StartResponder | undefined = undefined; + private metadata: MetadataResponder | undefined = undefined; + private message: MessageResponder | undefined = undefined; + private status: StatusResponder | undefined = undefined; + + withStart(start: StartResponder): this { + this.start = start; + return this; + } + + withSendMetadata(sendMetadata: MetadataResponder): this { + this.metadata = sendMetadata; + return this; + } + + withSendMessage(sendMessage: MessageResponder): this { + this.message = sendMessage; + return this; + } + + withSendStatus(sendStatus: StatusResponder): this { + this.status = sendStatus; + return this; + } + + build(): Responder { + return { + start: this.start, + sendMetadata: this.metadata, + sendMessage: this.message, + sendStatus: this.status, + }; + } +} + +const defaultServerListener: FullServerListener = { + onReceiveMetadata: (metadata, next) => { + next(metadata); + }, + onReceiveMessage: (message, next) => { + next(message); + }, + onReceiveHalfClose: next => { + next(); + }, + onCancel: () => {}, +}; + +const defaultResponder: FullResponder = { + start: next => { + next(); + }, + sendMetadata: (metadata, next) => { + next(metadata); + }, + sendMessage: (message, next) => { + next(message); + }, + sendStatus: (status, next) => { + next(status); + }, +}; + +export interface ServerInterceptingCallInterface { + /** + * Register the listener to handle inbound events. + */ + start(listener: InterceptingServerListener): void; + /** + * Send response metadata. + */ + sendMetadata(metadata: Metadata): void; + /** + * Send a response message. + */ + sendMessage(message: any, callback: () => void): void; + /** + * End the call by sending this status. + */ + sendStatus(status: PartialStatusObject): void; + /** + * Start a single read, eventually triggering either listener.onReceiveMessage or listener.onReceiveHalfClose. + */ + startRead(): void; + /** + * Return the peer address of the client making the request, if known, or "unknown" otherwise + */ + getPeer(): string; + /** + * Return the call deadline set by the client. The value is Infinity if there is no deadline. + */ + getDeadline(): Deadline; +} + +export class ServerInterceptingCall implements ServerInterceptingCallInterface { + private responder: FullResponder; + private processingMetadata = false; + private processingMessage = false; + private pendingMessage: any = null; + private pendingMessageCallback: (() => void) | null = null; + private pendingStatus: PartialStatusObject | null = null; + constructor( + private nextCall: ServerInterceptingCallInterface, + responder?: Responder + ) { + this.responder = { + start: responder?.start ?? defaultResponder.start, + sendMetadata: responder?.sendMetadata ?? defaultResponder.sendMetadata, + sendMessage: responder?.sendMessage ?? defaultResponder.sendMessage, + sendStatus: responder?.sendStatus ?? defaultResponder.sendStatus, + }; + } + + private processPendingMessage() { + if (this.pendingMessageCallback) { + this.nextCall.sendMessage( + this.pendingMessage, + this.pendingMessageCallback + ); + this.pendingMessage = null; + this.pendingMessageCallback = null; + } + } + + private processPendingStatus() { + if (this.pendingStatus) { + this.nextCall.sendStatus(this.pendingStatus); + this.pendingStatus = null; + } + } + + start(listener: InterceptingServerListener): void { + this.responder.start(interceptedListener => { + const fullInterceptedListener: FullServerListener = { + onReceiveMetadata: + interceptedListener?.onReceiveMetadata ?? + defaultServerListener.onReceiveMetadata, + onReceiveMessage: + interceptedListener?.onReceiveMessage ?? + defaultServerListener.onReceiveMessage, + onReceiveHalfClose: + interceptedListener?.onReceiveHalfClose ?? + defaultServerListener.onReceiveHalfClose, + onCancel: + interceptedListener?.onCancel ?? defaultServerListener.onCancel, + }; + const finalInterceptingListener = new InterceptingServerListenerImpl( + fullInterceptedListener, + listener + ); + this.nextCall.start(finalInterceptingListener); + }); + } + sendMetadata(metadata: Metadata): void { + this.processingMetadata = true; + this.responder.sendMetadata(metadata, interceptedMetadata => { + this.processingMetadata = false; + this.nextCall.sendMetadata(interceptedMetadata); + this.processPendingMessage(); + this.processPendingStatus(); + }); + } + sendMessage(message: any, callback: () => void): void { + this.processingMessage = true; + this.responder.sendMessage(message, interceptedMessage => { + this.processingMessage = false; + if (this.processingMetadata) { + this.pendingMessage = interceptedMessage; + this.pendingMessageCallback = callback; + } else { + this.nextCall.sendMessage(interceptedMessage, callback); + } + }); + } + sendStatus(status: PartialStatusObject): void { + this.responder.sendStatus(status, interceptedStatus => { + if (this.processingMetadata || this.processingMessage) { + this.pendingStatus = interceptedStatus; + } else { + this.nextCall.sendStatus(interceptedStatus); + } + }); + } + startRead(): void { + this.nextCall.startRead(); + } + getPeer(): string { + return this.nextCall.getPeer(); + } + getDeadline(): Deadline { + return this.nextCall.getDeadline(); + } +} + +export interface ServerInterceptor { + ( + methodDescriptor: ServerMethodDefinition, + call: ServerInterceptingCallInterface + ): ServerInterceptingCall; +} + +interface DeadlineUnitIndexSignature { + [name: string]: number; +} + +const GRPC_ACCEPT_ENCODING_HEADER = 'grpc-accept-encoding'; +const GRPC_ENCODING_HEADER = 'grpc-encoding'; +const GRPC_MESSAGE_HEADER = 'grpc-message'; +const GRPC_STATUS_HEADER = 'grpc-status'; +const GRPC_TIMEOUT_HEADER = 'grpc-timeout'; +const DEADLINE_REGEX = /(\d{1,8})\s*([HMSmun])/; +const deadlineUnitsToMs: DeadlineUnitIndexSignature = { + H: 3600000, + M: 60000, + S: 1000, + m: 1, + u: 0.001, + n: 0.000001, +}; + +const defaultCompressionHeaders = { + // TODO(cjihrig): Remove these encoding headers from the default response + // once compression is integrated. + [GRPC_ACCEPT_ENCODING_HEADER]: 'identity,deflate,gzip', + [GRPC_ENCODING_HEADER]: 'identity', +}; +const defaultResponseHeaders = { + [http2.constants.HTTP2_HEADER_STATUS]: http2.constants.HTTP_STATUS_OK, + [http2.constants.HTTP2_HEADER_CONTENT_TYPE]: 'application/grpc+proto', +}; +const defaultResponseOptions = { + waitForTrailers: true, +} as http2.ServerStreamResponseOptions; + +type ReadQueueEntryType = 'COMPRESSED' | 'READABLE' | 'HALF_CLOSE'; + +interface ReadQueueEntry { + type: ReadQueueEntryType; + compressedMessage: Buffer | null; + parsedMessage: any; +} + +export class BaseServerInterceptingCall + implements ServerInterceptingCallInterface +{ + private listener: InterceptingServerListener | null = null; + private metadata: Metadata; + private deadlineTimer: NodeJS.Timeout | null = null; + private deadline: Deadline = Infinity; + private maxSendMessageSize: number = DEFAULT_MAX_SEND_MESSAGE_LENGTH; + private maxReceiveMessageSize: number = DEFAULT_MAX_RECEIVE_MESSAGE_LENGTH; + private cancelled = false; + private metadataSent = false; + private wantTrailers = false; + private cancelNotified = false; + private incomingEncoding = 'identity'; + private decoder = new StreamDecoder(); + private readQueue: ReadQueueEntry[] = []; + private isReadPending = false; + private receivedHalfClose = false; + private streamEnded = false; + + constructor( + private readonly stream: http2.ServerHttp2Stream, + headers: http2.IncomingHttpHeaders, + private readonly callEventTracker: CallEventTracker | null, + private readonly handler: Handler, + options: ChannelOptions + ) { + this.stream.once('error', (err: ServerErrorResponse) => { + /* We need an error handler to avoid uncaught error event exceptions, but + * there is nothing we can reasonably do here. Any error event should + * have a corresponding close event, which handles emitting the cancelled + * event. And the stream is now in a bad state, so we can't reasonably + * expect to be able to send an error over it. */ + }); + + this.stream.once('close', () => { + trace( + 'Request to method ' + + this.handler?.path + + ' stream closed with rstCode ' + + this.stream.rstCode + ); + + if (this.callEventTracker && !this.streamEnded) { + this.streamEnded = true; + this.callEventTracker.onStreamEnd(false); + this.callEventTracker.onCallEnd({ + code: Status.CANCELLED, + details: 'Stream closed before sending status', + metadata: null, + }); + } + + this.notifyOnCancel(); + }); + + this.stream.on('data', (data: Buffer) => { + this.handleDataFrame(data); + }); + this.stream.pause(); + + this.stream.on('end', () => { + this.handleEndEvent(); + }); + + if ('grpc.max_send_message_length' in options) { + this.maxSendMessageSize = options['grpc.max_send_message_length']!; + } + if ('grpc.max_receive_message_length' in options) { + this.maxReceiveMessageSize = options['grpc.max_receive_message_length']!; + } + + const metadata = Metadata.fromHttp2Headers(headers); + + if (logging.isTracerEnabled(TRACER_NAME)) { + trace( + 'Request to ' + + this.handler.path + + ' received headers ' + + JSON.stringify(metadata.toJSON()) + ); + } + + const timeoutHeader = metadata.get(GRPC_TIMEOUT_HEADER); + + if (timeoutHeader.length > 0) { + this.handleTimeoutHeader(timeoutHeader[0] as string); + } + + const encodingHeader = metadata.get(GRPC_ENCODING_HEADER); + + if (encodingHeader.length > 0) { + this.incomingEncoding = encodingHeader[0] as string; + } + + // Remove several headers that should not be propagated to the application + metadata.remove(GRPC_TIMEOUT_HEADER); + metadata.remove(GRPC_ENCODING_HEADER); + metadata.remove(GRPC_ACCEPT_ENCODING_HEADER); + metadata.remove(http2.constants.HTTP2_HEADER_ACCEPT_ENCODING); + metadata.remove(http2.constants.HTTP2_HEADER_TE); + metadata.remove(http2.constants.HTTP2_HEADER_CONTENT_TYPE); + this.metadata = metadata; + } + + private handleTimeoutHeader(timeoutHeader: string) { + const match = timeoutHeader.toString().match(DEADLINE_REGEX); + + if (match === null) { + const status: PartialStatusObject = { + code: Status.INTERNAL, + details: `Invalid ${GRPC_TIMEOUT_HEADER} value "${timeoutHeader}"`, + metadata: null, + }; + // Wait for the constructor to complete before sending the error. + process.nextTick(() => { + this.sendStatus(status); + }); + return; + } + + const timeout = (+match[1] * deadlineUnitsToMs[match[2]]) | 0; + + const now = new Date(); + this.deadline = now.setMilliseconds(now.getMilliseconds() + timeout); + this.deadlineTimer = setTimeout(() => { + const status: PartialStatusObject = { + code: Status.DEADLINE_EXCEEDED, + details: 'Deadline exceeded', + metadata: null, + }; + this.sendStatus(status); + }, timeout); + } + + private checkCancelled(): boolean { + /* In some cases the stream can become destroyed before the close event + * fires. That creates a race condition that this check works around */ + if (!this.cancelled && (this.stream.destroyed || this.stream.closed)) { + this.notifyOnCancel(); + this.cancelled = true; + } + return this.cancelled; + } + private notifyOnCancel() { + if (this.cancelNotified) { + return; + } + this.cancelNotified = true; + this.cancelled = true; + process.nextTick(() => { + this.listener?.onCancel(); + }); + if (this.deadlineTimer) { + clearTimeout(this.deadlineTimer); + } + // Flush incoming data frames + this.stream.resume(); + } + + /** + * A server handler can start sending messages without explicitly sending + * metadata. In that case, we need to send headers before sending any + * messages. This function does that if necessary. + */ + private maybeSendMetadata() { + if (!this.metadataSent) { + this.sendMetadata(new Metadata()); + } + } + + /** + * Serialize a message to a length-delimited byte string. + * @param value + * @returns + */ + private serializeMessage(value: any) { + const messageBuffer = this.handler.serialize(value); + const byteLength = messageBuffer.byteLength; + const output = Buffer.allocUnsafe(byteLength + 5); + /* Note: response compression is currently not supported, so this + * compressed bit is always 0. */ + output.writeUInt8(0, 0); + output.writeUInt32BE(byteLength, 1); + messageBuffer.copy(output, 5); + return output; + } + + private decompressMessage( + message: Buffer, + encoding: string + ): Buffer | Promise { + switch (encoding) { + case 'deflate': + return inflate(message.subarray(5)); + case 'gzip': + return unzip(message.subarray(5)); + case 'identity': + return message.subarray(5); + default: + return Promise.reject({ + code: Status.UNIMPLEMENTED, + details: `Received message compressed with unsupported encoding "${encoding}"`, + }); + } + } + + private async decompressAndMaybePush(queueEntry: ReadQueueEntry) { + if (queueEntry.type !== 'COMPRESSED') { + throw new Error(`Invalid queue entry type: ${queueEntry.type}`); + } + + const compressed = queueEntry.compressedMessage!.readUInt8(0) === 1; + const compressedMessageEncoding = compressed + ? this.incomingEncoding + : 'identity'; + const decompressedMessage = await this.decompressMessage( + queueEntry.compressedMessage!, + compressedMessageEncoding + ); + try { + queueEntry.parsedMessage = this.handler.deserialize(decompressedMessage); + } catch (err) { + this.sendStatus({ + code: Status.INTERNAL, + details: `Error deserializing request: ${(err as Error).message}`, + }); + return; + } + queueEntry.type = 'READABLE'; + this.maybePushNextMessage(); + } + + private maybePushNextMessage() { + if ( + this.listener && + this.isReadPending && + this.readQueue.length > 0 && + this.readQueue[0].type !== 'COMPRESSED' + ) { + this.isReadPending = false; + const nextQueueEntry = this.readQueue.shift()!; + if (nextQueueEntry.type === 'READABLE') { + this.listener.onReceiveMessage(nextQueueEntry.parsedMessage); + } else { + // nextQueueEntry.type === 'HALF_CLOSE' + this.listener.onReceiveHalfClose(); + } + } + } + + private handleDataFrame(data: Buffer) { + if (this.checkCancelled()) { + return; + } + trace( + 'Request to ' + + this.handler.path + + ' received data frame of size ' + + data.length + ); + const rawMessages = this.decoder.write(data); + + for (const messageBytes of rawMessages) { + this.stream.pause(); + if ( + this.maxReceiveMessageSize !== -1 && + messageBytes.length - 5 > this.maxReceiveMessageSize + ) { + this.sendStatus({ + code: Status.RESOURCE_EXHAUSTED, + details: `Received message larger than max (${ + messageBytes.length - 5 + } vs. ${this.maxReceiveMessageSize})`, + metadata: null, + }); + return; + } + const queueEntry: ReadQueueEntry = { + type: 'COMPRESSED', + compressedMessage: messageBytes, + parsedMessage: null, + }; + this.readQueue.push(queueEntry); + this.decompressAndMaybePush(queueEntry); + this.callEventTracker?.addMessageReceived(); + } + } + private handleEndEvent() { + this.readQueue.push({ + type: 'HALF_CLOSE', + compressedMessage: null, + parsedMessage: null, + }); + this.receivedHalfClose = true; + this.maybePushNextMessage(); + } + start(listener: InterceptingServerListener): void { + trace('Request to ' + this.handler.path + ' start called'); + if (this.checkCancelled()) { + return; + } + this.listener = listener; + listener.onReceiveMetadata(this.metadata); + } + sendMetadata(metadata: Metadata): void { + if (this.checkCancelled()) { + return; + } + + if (this.metadataSent) { + return; + } + + this.metadataSent = true; + const custom = metadata ? metadata.toHttp2Headers() : null; + const headers = { + ...defaultResponseHeaders, + ...defaultCompressionHeaders, + ...custom, + }; + this.stream.respond(headers, defaultResponseOptions); + } + sendMessage(message: any, callback: () => void): void { + if (this.checkCancelled()) { + return; + } + let response: Buffer; + try { + response = this.serializeMessage(message); + } catch (e) { + this.sendStatus({ + code: Status.INTERNAL, + details: `Error serializing response: ${getErrorMessage(e)}`, + metadata: null, + }); + return; + } + + if ( + this.maxSendMessageSize !== -1 && + response.length - 5 > this.maxSendMessageSize + ) { + this.sendStatus({ + code: Status.RESOURCE_EXHAUSTED, + details: `Sent message larger than max (${response.length} vs. ${this.maxSendMessageSize})`, + metadata: null, + }); + return; + } + this.maybeSendMetadata(); + trace( + 'Request to ' + + this.handler.path + + ' sent data frame of size ' + + response.length + ); + this.stream.write(response, error => { + if (error) { + this.sendStatus({ + code: Status.INTERNAL, + details: `Error writing message: ${getErrorMessage(error)}`, + metadata: null, + }); + return; + } + this.callEventTracker?.addMessageSent(); + callback(); + }); + } + sendStatus(status: PartialStatusObject): void { + if (this.checkCancelled()) { + return; + } + + trace( + 'Request to method ' + + this.handler?.path + + ' ended with status code: ' + + Status[status.code] + + ' details: ' + + status.details + ); + + if (this.metadataSent) { + if (!this.wantTrailers) { + this.wantTrailers = true; + this.stream.once('wantTrailers', () => { + if (this.callEventTracker && !this.streamEnded) { + this.streamEnded = true; + this.callEventTracker.onStreamEnd(true); + this.callEventTracker.onCallEnd(status); + } + const trailersToSend = { + [GRPC_STATUS_HEADER]: status.code, + [GRPC_MESSAGE_HEADER]: encodeURI(status.details), + ...status.metadata?.toHttp2Headers(), + }; + + this.stream.sendTrailers(trailersToSend); + this.notifyOnCancel(); + }); + this.stream.end(); + } else { + this.notifyOnCancel(); + } + } else { + if (this.callEventTracker && !this.streamEnded) { + this.streamEnded = true; + this.callEventTracker.onStreamEnd(true); + this.callEventTracker.onCallEnd(status); + } + // Trailers-only response + const trailersToSend = { + [GRPC_STATUS_HEADER]: status.code, + [GRPC_MESSAGE_HEADER]: encodeURI(status.details), + ...defaultResponseHeaders, + ...status.metadata?.toHttp2Headers(), + }; + this.stream.respond(trailersToSend, { endStream: true }); + this.notifyOnCancel(); + } + } + startRead(): void { + trace('Request to ' + this.handler.path + ' startRead called'); + if (this.checkCancelled()) { + return; + } + this.isReadPending = true; + if (this.readQueue.length === 0) { + if (!this.receivedHalfClose) { + this.stream.resume(); + } + } else { + this.maybePushNextMessage(); + } + } + getPeer(): string { + const socket = this.stream.session?.socket; + if (socket?.remoteAddress) { + if (socket.remotePort) { + return `${socket.remoteAddress}:${socket.remotePort}`; + } else { + return socket.remoteAddress; + } + } else { + return 'unknown'; + } + } + getDeadline(): Deadline { + return this.deadline; + } +} + +export function getServerInterceptingCall( + interceptors: ServerInterceptor[], + stream: http2.ServerHttp2Stream, + headers: http2.IncomingHttpHeaders, + callEventTracker: CallEventTracker | null, + handler: Handler, + options: ChannelOptions +) { + const methodDefinition: ServerMethodDefinition = { + path: handler.path, + requestStream: handler.type === 'clientStream' || handler.type === 'bidi', + responseStream: handler.type === 'serverStream' || handler.type === 'bidi', + requestDeserialize: handler.deserialize, + responseSerialize: handler.serialize, + }; + const baseCall = new BaseServerInterceptingCall( + stream, + headers, + callEventTracker, + handler, + options + ); + return interceptors.reduce( + (call: ServerInterceptingCallInterface, interceptor: ServerInterceptor) => { + return interceptor(methodDefinition, call); + }, + baseCall + ); +} diff --git a/node_modules/@grpc/grpc-js/src/server.ts b/node_modules/@grpc/grpc-js/src/server.ts new file mode 100644 index 0000000..feb511b --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/server.ts @@ -0,0 +1,1975 @@ +/* + * Copyright 2019 gRPC authors. + * + * 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. + * + */ + +import * as http2 from 'http2'; +import * as util from 'util'; + +import { ServiceError } from './call'; +import { Status, LogVerbosity } from './constants'; +import { Deserialize, Serialize, ServiceDefinition } from './make-client'; +import { Metadata } from './metadata'; +import { + BidiStreamingHandler, + ClientStreamingHandler, + HandleCall, + Handler, + HandlerType, + sendUnaryData, + ServerDuplexStream, + ServerDuplexStreamImpl, + ServerReadableStream, + ServerStreamingHandler, + ServerUnaryCall, + ServerWritableStream, + ServerWritableStreamImpl, + UnaryHandler, + ServerErrorResponse, + ServerStatusResponse, + serverErrorToStatus, +} from './server-call'; +import { ServerCredentials } from './server-credentials'; +import { ChannelOptions } from './channel-options'; +import { + createResolver, + ResolverListener, + mapUriDefaultScheme, +} from './resolver'; +import * as logging from './logging'; +import { + SubchannelAddress, + isTcpSubchannelAddress, + subchannelAddressToString, + stringToSubchannelAddress, +} from './subchannel-address'; +import { + GrpcUri, + combineHostPort, + parseUri, + splitHostPort, + uriToString, +} from './uri-parser'; +import { + ChannelzCallTracker, + ChannelzCallTrackerStub, + ChannelzChildrenTracker, + ChannelzChildrenTrackerStub, + ChannelzTrace, + ChannelzTraceStub, + registerChannelzServer, + registerChannelzSocket, + ServerInfo, + ServerRef, + SocketInfo, + SocketRef, + TlsInfo, + unregisterChannelzRef, +} from './channelz'; +import { CipherNameAndProtocol, TLSSocket } from 'tls'; +import { + ServerInterceptingCallInterface, + ServerInterceptor, + getServerInterceptingCall, +} from './server-interceptors'; +import { PartialStatusObject } from './call-interface'; +import { CallEventTracker } from './transport'; + +const UNLIMITED_CONNECTION_AGE_MS = ~(1 << 31); +const KEEPALIVE_MAX_TIME_MS = ~(1 << 31); +const KEEPALIVE_TIMEOUT_MS = 20000; +const MAX_CONNECTION_IDLE_MS = ~(1 << 31); + +const { HTTP2_HEADER_PATH } = http2.constants; + +const TRACER_NAME = 'server'; +const kMaxAge = Buffer.from('max_age'); + +type AnyHttp2Server = http2.Http2Server | http2.Http2SecureServer; + +interface BindResult { + port: number; + count: number; + errors: string[]; +} + +interface SingleAddressBindResult { + port: number; + error?: string; +} + +function noop(): void {} + +/** + * Decorator to wrap a class method with util.deprecate + * @param message The message to output if the deprecated method is called + * @returns + */ +function deprecate(message: string) { + return function ( + target: (this: This, ...args: Args) => Return, + context: ClassMethodDecoratorContext< + This, + (this: This, ...args: Args) => Return + > + ) { + return util.deprecate(target, message); + }; +} + +function getUnimplementedStatusResponse( + methodName: string +): PartialStatusObject { + return { + code: Status.UNIMPLEMENTED, + details: `The server does not implement the method ${methodName}`, + }; +} + +/* eslint-disable @typescript-eslint/no-explicit-any */ +type UntypedUnaryHandler = UnaryHandler; +type UntypedClientStreamingHandler = ClientStreamingHandler; +type UntypedServerStreamingHandler = ServerStreamingHandler; +type UntypedBidiStreamingHandler = BidiStreamingHandler; +export type UntypedHandleCall = HandleCall; +type UntypedHandler = Handler; +export interface UntypedServiceImplementation { + [name: string]: UntypedHandleCall; +} + +function getDefaultHandler(handlerType: HandlerType, methodName: string) { + const unimplementedStatusResponse = + getUnimplementedStatusResponse(methodName); + switch (handlerType) { + case 'unary': + return ( + call: ServerUnaryCall, + callback: sendUnaryData + ) => { + callback(unimplementedStatusResponse as ServiceError, null); + }; + case 'clientStream': + return ( + call: ServerReadableStream, + callback: sendUnaryData + ) => { + callback(unimplementedStatusResponse as ServiceError, null); + }; + case 'serverStream': + return (call: ServerWritableStream) => { + call.emit('error', unimplementedStatusResponse); + }; + case 'bidi': + return (call: ServerDuplexStream) => { + call.emit('error', unimplementedStatusResponse); + }; + default: + throw new Error(`Invalid handlerType ${handlerType}`); + } +} + +interface ChannelzSessionInfo { + ref: SocketRef; + streamTracker: ChannelzCallTracker | ChannelzCallTrackerStub; + messagesSent: number; + messagesReceived: number; + keepAlivesSent: number; + lastMessageSentTimestamp: Date | null; + lastMessageReceivedTimestamp: Date | null; +} + +/** + * Information related to a single invocation of bindAsync. This should be + * tracked in a map keyed by target string, normalized with a pass through + * parseUri -> mapUriDefaultScheme -> uriToString. If the target has a port + * number and the port number is 0, the target string is modified with the + * concrete bound port. + */ +interface BoundPort { + /** + * The key used to refer to this object in the boundPorts map. + */ + mapKey: string; + /** + * The target string, passed through parseUri -> mapUriDefaultScheme. Used + * to determine the final key when the port number is 0. + */ + originalUri: GrpcUri; + /** + * If there is a pending bindAsync operation, this is a promise that resolves + * with the port number when that operation succeeds. If there is no such + * operation pending, this is null. + */ + completionPromise: Promise | null; + /** + * The port number that was actually bound. Populated only after + * completionPromise resolves. + */ + portNumber: number; + /** + * Set by unbind if called while pending is true. + */ + cancelled: boolean; + /** + * The credentials object passed to the original bindAsync call. + */ + credentials: ServerCredentials; + /** + * The set of servers associated with this listening port. A target string + * that expands to multiple addresses will result in multiple listening + * servers. + */ + listeningServers: Set; +} + +/** + * Should be in a map keyed by AnyHttp2Server. + */ +interface Http2ServerInfo { + channelzRef: SocketRef; + sessions: Set; +} + +interface SessionIdleTimeoutTracker { + activeStreams: number; + lastIdle: number; + timeout: NodeJS.Timeout; + onClose: (session: http2.ServerHttp2Session) => void | null; +} + +export interface ServerOptions extends ChannelOptions { + interceptors?: ServerInterceptor[]; +} + +export class Server { + private boundPorts: Map = new Map(); + private http2Servers: Map = new Map(); + private sessionIdleTimeouts = new Map< + http2.ServerHttp2Session, + SessionIdleTimeoutTracker + >(); + + private handlers: Map = new Map< + string, + UntypedHandler + >(); + private sessions = new Map(); + /** + * This field only exists to ensure that the start method throws an error if + * it is called twice, as it did previously. + */ + private started = false; + private shutdown = false; + private options: ServerOptions; + private serverAddressString = 'null'; + + // Channelz Info + private readonly channelzEnabled: boolean = true; + private channelzRef: ServerRef; + private channelzTrace: ChannelzTrace | ChannelzTraceStub; + private callTracker: ChannelzCallTracker | ChannelzCallTrackerStub; + private listenerChildrenTracker: + | ChannelzChildrenTracker + | ChannelzChildrenTrackerStub; + private sessionChildrenTracker: + | ChannelzChildrenTracker + | ChannelzChildrenTrackerStub; + + private readonly maxConnectionAgeMs: number; + private readonly maxConnectionAgeGraceMs: number; + + private readonly keepaliveTimeMs: number; + private readonly keepaliveTimeoutMs: number; + + private readonly sessionIdleTimeout: number; + + private readonly interceptors: ServerInterceptor[]; + + /** + * Options that will be used to construct all Http2Server instances for this + * Server. + */ + private commonServerOptions: http2.ServerOptions; + + constructor(options?: ServerOptions) { + this.options = options ?? {}; + if (this.options['grpc.enable_channelz'] === 0) { + this.channelzEnabled = false; + this.channelzTrace = new ChannelzTraceStub(); + this.callTracker = new ChannelzCallTrackerStub(); + this.listenerChildrenTracker = new ChannelzChildrenTrackerStub(); + this.sessionChildrenTracker = new ChannelzChildrenTrackerStub(); + } else { + this.channelzTrace = new ChannelzTrace(); + this.callTracker = new ChannelzCallTracker(); + this.listenerChildrenTracker = new ChannelzChildrenTracker(); + this.sessionChildrenTracker = new ChannelzChildrenTracker(); + } + + this.channelzRef = registerChannelzServer( + 'server', + () => this.getChannelzInfo(), + this.channelzEnabled + ); + + this.channelzTrace.addTrace('CT_INFO', 'Server created'); + this.maxConnectionAgeMs = + this.options['grpc.max_connection_age_ms'] ?? UNLIMITED_CONNECTION_AGE_MS; + this.maxConnectionAgeGraceMs = + this.options['grpc.max_connection_age_grace_ms'] ?? + UNLIMITED_CONNECTION_AGE_MS; + this.keepaliveTimeMs = + this.options['grpc.keepalive_time_ms'] ?? KEEPALIVE_MAX_TIME_MS; + this.keepaliveTimeoutMs = + this.options['grpc.keepalive_timeout_ms'] ?? KEEPALIVE_TIMEOUT_MS; + this.sessionIdleTimeout = + this.options['grpc.max_connection_idle_ms'] ?? MAX_CONNECTION_IDLE_MS; + + this.commonServerOptions = { + maxSendHeaderBlockLength: Number.MAX_SAFE_INTEGER, + }; + if ('grpc-node.max_session_memory' in this.options) { + this.commonServerOptions.maxSessionMemory = + this.options['grpc-node.max_session_memory']; + } else { + /* By default, set a very large max session memory limit, to effectively + * disable enforcement of the limit. Some testing indicates that Node's + * behavior degrades badly when this limit is reached, so we solve that + * by disabling the check entirely. */ + this.commonServerOptions.maxSessionMemory = Number.MAX_SAFE_INTEGER; + } + if ('grpc.max_concurrent_streams' in this.options) { + this.commonServerOptions.settings = { + maxConcurrentStreams: this.options['grpc.max_concurrent_streams'], + }; + } + this.interceptors = this.options.interceptors ?? []; + this.trace('Server constructed'); + } + + private getChannelzInfo(): ServerInfo { + return { + trace: this.channelzTrace, + callTracker: this.callTracker, + listenerChildren: this.listenerChildrenTracker.getChildLists(), + sessionChildren: this.sessionChildrenTracker.getChildLists(), + }; + } + + private getChannelzSessionInfo( + session: http2.ServerHttp2Session + ): SocketInfo { + const sessionInfo = this.sessions.get(session)!; + const sessionSocket = session.socket; + const remoteAddress = sessionSocket.remoteAddress + ? stringToSubchannelAddress( + sessionSocket.remoteAddress, + sessionSocket.remotePort + ) + : null; + const localAddress = sessionSocket.localAddress + ? stringToSubchannelAddress( + sessionSocket.localAddress!, + sessionSocket.localPort + ) + : null; + let tlsInfo: TlsInfo | null; + if (session.encrypted) { + const tlsSocket: TLSSocket = sessionSocket as TLSSocket; + const cipherInfo: CipherNameAndProtocol & { standardName?: string } = + tlsSocket.getCipher(); + const certificate = tlsSocket.getCertificate(); + const peerCertificate = tlsSocket.getPeerCertificate(); + tlsInfo = { + cipherSuiteStandardName: cipherInfo.standardName ?? null, + cipherSuiteOtherName: cipherInfo.standardName ? null : cipherInfo.name, + localCertificate: + certificate && 'raw' in certificate ? certificate.raw : null, + remoteCertificate: + peerCertificate && 'raw' in peerCertificate + ? peerCertificate.raw + : null, + }; + } else { + tlsInfo = null; + } + const socketInfo: SocketInfo = { + remoteAddress: remoteAddress, + localAddress: localAddress, + security: tlsInfo, + remoteName: null, + streamsStarted: sessionInfo.streamTracker.callsStarted, + streamsSucceeded: sessionInfo.streamTracker.callsSucceeded, + streamsFailed: sessionInfo.streamTracker.callsFailed, + messagesSent: sessionInfo.messagesSent, + messagesReceived: sessionInfo.messagesReceived, + keepAlivesSent: sessionInfo.keepAlivesSent, + lastLocalStreamCreatedTimestamp: null, + lastRemoteStreamCreatedTimestamp: + sessionInfo.streamTracker.lastCallStartedTimestamp, + lastMessageSentTimestamp: sessionInfo.lastMessageSentTimestamp, + lastMessageReceivedTimestamp: sessionInfo.lastMessageReceivedTimestamp, + localFlowControlWindow: session.state.localWindowSize ?? null, + remoteFlowControlWindow: session.state.remoteWindowSize ?? null, + }; + return socketInfo; + } + + private trace(text: string): void { + logging.trace( + LogVerbosity.DEBUG, + TRACER_NAME, + '(' + this.channelzRef.id + ') ' + text + ); + } + + addProtoService(): never { + throw new Error('Not implemented. Use addService() instead'); + } + + addService( + service: ServiceDefinition, + implementation: UntypedServiceImplementation + ): void { + if ( + service === null || + typeof service !== 'object' || + implementation === null || + typeof implementation !== 'object' + ) { + throw new Error('addService() requires two objects as arguments'); + } + + const serviceKeys = Object.keys(service); + + if (serviceKeys.length === 0) { + throw new Error('Cannot add an empty service to a server'); + } + + serviceKeys.forEach(name => { + const attrs = service[name]; + let methodType: HandlerType; + + if (attrs.requestStream) { + if (attrs.responseStream) { + methodType = 'bidi'; + } else { + methodType = 'clientStream'; + } + } else { + if (attrs.responseStream) { + methodType = 'serverStream'; + } else { + methodType = 'unary'; + } + } + + let implFn = implementation[name]; + let impl; + + if (implFn === undefined && typeof attrs.originalName === 'string') { + implFn = implementation[attrs.originalName]; + } + + if (implFn !== undefined) { + impl = implFn.bind(implementation); + } else { + impl = getDefaultHandler(methodType, name); + } + + const success = this.register( + attrs.path, + impl as UntypedHandleCall, + attrs.responseSerialize, + attrs.requestDeserialize, + methodType + ); + + if (success === false) { + throw new Error(`Method handler for ${attrs.path} already provided.`); + } + }); + } + + removeService(service: ServiceDefinition): void { + if (service === null || typeof service !== 'object') { + throw new Error('removeService() requires object as argument'); + } + + const serviceKeys = Object.keys(service); + serviceKeys.forEach(name => { + const attrs = service[name]; + this.unregister(attrs.path); + }); + } + + bind(port: string, creds: ServerCredentials): never { + throw new Error('Not implemented. Use bindAsync() instead'); + } + + private registerListenerToChannelz(boundAddress: SubchannelAddress) { + return registerChannelzSocket( + subchannelAddressToString(boundAddress), + () => { + return { + localAddress: boundAddress, + remoteAddress: null, + security: null, + remoteName: null, + streamsStarted: 0, + streamsSucceeded: 0, + streamsFailed: 0, + messagesSent: 0, + messagesReceived: 0, + keepAlivesSent: 0, + lastLocalStreamCreatedTimestamp: null, + lastRemoteStreamCreatedTimestamp: null, + lastMessageSentTimestamp: null, + lastMessageReceivedTimestamp: null, + localFlowControlWindow: null, + remoteFlowControlWindow: null, + }; + }, + this.channelzEnabled + ); + } + + private createHttp2Server(credentials: ServerCredentials) { + let http2Server: http2.Http2Server | http2.Http2SecureServer; + if (credentials._isSecure()) { + const secureServerOptions = Object.assign( + this.commonServerOptions, + credentials._getSettings()! + ); + secureServerOptions.enableTrace = + this.options['grpc-node.tls_enable_trace'] === 1; + http2Server = http2.createSecureServer(secureServerOptions); + http2Server.on('secureConnection', (socket: TLSSocket) => { + /* These errors need to be handled by the user of Http2SecureServer, + * according to https://github.com/nodejs/node/issues/35824 */ + socket.on('error', (e: Error) => { + this.trace( + 'An incoming TLS connection closed with error: ' + e.message + ); + }); + }); + } else { + http2Server = http2.createServer(this.commonServerOptions); + } + + http2Server.setTimeout(0, noop); + this._setupHandlers(http2Server); + return http2Server; + } + + private bindOneAddress( + address: SubchannelAddress, + boundPortObject: BoundPort + ): Promise { + this.trace('Attempting to bind ' + subchannelAddressToString(address)); + const http2Server = this.createHttp2Server(boundPortObject.credentials); + return new Promise((resolve, reject) => { + const onError = (err: Error) => { + this.trace( + 'Failed to bind ' + + subchannelAddressToString(address) + + ' with error ' + + err.message + ); + resolve({ + port: 'port' in address ? address.port : 1, + error: err.message, + }); + }; + + http2Server.once('error', onError); + + http2Server.listen(address, () => { + const boundAddress = http2Server.address()!; + let boundSubchannelAddress: SubchannelAddress; + if (typeof boundAddress === 'string') { + boundSubchannelAddress = { + path: boundAddress, + }; + } else { + boundSubchannelAddress = { + host: boundAddress.address, + port: boundAddress.port, + }; + } + + const channelzRef = this.registerListenerToChannelz( + boundSubchannelAddress + ); + this.listenerChildrenTracker.refChild(channelzRef); + + this.http2Servers.set(http2Server, { + channelzRef: channelzRef, + sessions: new Set(), + }); + boundPortObject.listeningServers.add(http2Server); + this.trace( + 'Successfully bound ' + + subchannelAddressToString(boundSubchannelAddress) + ); + resolve({ + port: + 'port' in boundSubchannelAddress ? boundSubchannelAddress.port : 1, + }); + http2Server.removeListener('error', onError); + }); + }); + } + + private async bindManyPorts( + addressList: SubchannelAddress[], + boundPortObject: BoundPort + ): Promise { + if (addressList.length === 0) { + return { + count: 0, + port: 0, + errors: [], + }; + } + if (isTcpSubchannelAddress(addressList[0]) && addressList[0].port === 0) { + /* If binding to port 0, first try to bind the first address, then bind + * the rest of the address list to the specific port that it binds. */ + const firstAddressResult = await this.bindOneAddress( + addressList[0], + boundPortObject + ); + if (firstAddressResult.error) { + /* If the first address fails to bind, try the same operation starting + * from the second item in the list. */ + const restAddressResult = await this.bindManyPorts( + addressList.slice(1), + boundPortObject + ); + return { + ...restAddressResult, + errors: [firstAddressResult.error, ...restAddressResult.errors], + }; + } else { + const restAddresses = addressList + .slice(1) + .map(address => + isTcpSubchannelAddress(address) + ? { host: address.host, port: firstAddressResult.port } + : address + ); + const restAddressResult = await Promise.all( + restAddresses.map(address => + this.bindOneAddress(address, boundPortObject) + ) + ); + const allResults = [firstAddressResult, ...restAddressResult]; + return { + count: allResults.filter(result => result.error === undefined).length, + port: firstAddressResult.port, + errors: allResults + .filter(result => result.error) + .map(result => result.error!), + }; + } + } else { + const allResults = await Promise.all( + addressList.map(address => + this.bindOneAddress(address, boundPortObject) + ) + ); + return { + count: allResults.filter(result => result.error === undefined).length, + port: allResults[0].port, + errors: allResults + .filter(result => result.error) + .map(result => result.error!), + }; + } + } + + private async bindAddressList( + addressList: SubchannelAddress[], + boundPortObject: BoundPort + ): Promise { + const bindResult = await this.bindManyPorts(addressList, boundPortObject); + if (bindResult.count > 0) { + if (bindResult.count < addressList.length) { + logging.log( + LogVerbosity.INFO, + `WARNING Only ${bindResult.count} addresses added out of total ${addressList.length} resolved` + ); + } + return bindResult.port; + } else { + const errorString = `No address added out of total ${addressList.length} resolved`; + logging.log(LogVerbosity.ERROR, errorString); + throw new Error( + `${errorString} errors: [${bindResult.errors.join(',')}]` + ); + } + } + + private resolvePort(port: GrpcUri): Promise { + return new Promise((resolve, reject) => { + const resolverListener: ResolverListener = { + onSuccessfulResolution: ( + endpointList, + serviceConfig, + serviceConfigError + ) => { + // We only want one resolution result. Discard all future results + resolverListener.onSuccessfulResolution = () => {}; + const addressList = ([] as SubchannelAddress[]).concat( + ...endpointList.map(endpoint => endpoint.addresses) + ); + if (addressList.length === 0) { + reject(new Error(`No addresses resolved for port ${port}`)); + return; + } + resolve(addressList); + }, + onError: error => { + reject(new Error(error.details)); + }, + }; + const resolver = createResolver(port, resolverListener, this.options); + resolver.updateResolution(); + }); + } + + private async bindPort( + port: GrpcUri, + boundPortObject: BoundPort + ): Promise { + const addressList = await this.resolvePort(port); + if (boundPortObject.cancelled) { + this.completeUnbind(boundPortObject); + throw new Error('bindAsync operation cancelled by unbind call'); + } + const portNumber = await this.bindAddressList(addressList, boundPortObject); + if (boundPortObject.cancelled) { + this.completeUnbind(boundPortObject); + throw new Error('bindAsync operation cancelled by unbind call'); + } + return portNumber; + } + + private normalizePort(port: string): GrpcUri { + const initialPortUri = parseUri(port); + if (initialPortUri === null) { + throw new Error(`Could not parse port "${port}"`); + } + const portUri = mapUriDefaultScheme(initialPortUri); + if (portUri === null) { + throw new Error(`Could not get a default scheme for port "${port}"`); + } + return portUri; + } + + bindAsync( + port: string, + creds: ServerCredentials, + callback: (error: Error | null, port: number) => void + ): void { + if (this.shutdown) { + throw new Error('bindAsync called after shutdown'); + } + if (typeof port !== 'string') { + throw new TypeError('port must be a string'); + } + + if (creds === null || !(creds instanceof ServerCredentials)) { + throw new TypeError('creds must be a ServerCredentials object'); + } + + if (typeof callback !== 'function') { + throw new TypeError('callback must be a function'); + } + + this.trace('bindAsync port=' + port); + + const portUri = this.normalizePort(port); + + const deferredCallback = (error: Error | null, port: number) => { + process.nextTick(() => callback(error, port)); + }; + + /* First, if this port is already bound or that bind operation is in + * progress, use that result. */ + let boundPortObject = this.boundPorts.get(uriToString(portUri)); + if (boundPortObject) { + if (!creds._equals(boundPortObject.credentials)) { + deferredCallback( + new Error(`${port} already bound with incompatible credentials`), + 0 + ); + return; + } + /* If that operation has previously been cancelled by an unbind call, + * uncancel it. */ + boundPortObject.cancelled = false; + if (boundPortObject.completionPromise) { + boundPortObject.completionPromise.then( + portNum => callback(null, portNum), + error => callback(error as Error, 0) + ); + } else { + deferredCallback(null, boundPortObject.portNumber); + } + return; + } + boundPortObject = { + mapKey: uriToString(portUri), + originalUri: portUri, + completionPromise: null, + cancelled: false, + portNumber: 0, + credentials: creds, + listeningServers: new Set(), + }; + const splitPort = splitHostPort(portUri.path); + const completionPromise = this.bindPort(portUri, boundPortObject); + boundPortObject.completionPromise = completionPromise; + /* If the port number is 0, defer populating the map entry until after the + * bind operation completes and we have a specific port number. Otherwise, + * populate it immediately. */ + if (splitPort?.port === 0) { + completionPromise.then( + portNum => { + const finalUri: GrpcUri = { + scheme: portUri.scheme, + authority: portUri.authority, + path: combineHostPort({ host: splitPort.host, port: portNum }), + }; + boundPortObject!.mapKey = uriToString(finalUri); + boundPortObject!.completionPromise = null; + boundPortObject!.portNumber = portNum; + this.boundPorts.set(boundPortObject!.mapKey, boundPortObject!); + callback(null, portNum); + }, + error => { + callback(error, 0); + } + ); + } else { + this.boundPorts.set(boundPortObject.mapKey, boundPortObject); + completionPromise.then( + portNum => { + boundPortObject!.completionPromise = null; + boundPortObject!.portNumber = portNum; + callback(null, portNum); + }, + error => { + callback(error, 0); + } + ); + } + } + + private closeServer(server: AnyHttp2Server, callback?: () => void) { + this.trace( + 'Closing server with address ' + JSON.stringify(server.address()) + ); + const serverInfo = this.http2Servers.get(server); + server.close(() => { + if (serverInfo) { + this.listenerChildrenTracker.unrefChild(serverInfo.channelzRef); + unregisterChannelzRef(serverInfo.channelzRef); + } + this.http2Servers.delete(server); + callback?.(); + }); + } + + private closeSession( + session: http2.ServerHttp2Session, + callback?: () => void + ) { + this.trace('Closing session initiated by ' + session.socket?.remoteAddress); + const sessionInfo = this.sessions.get(session); + const closeCallback = () => { + if (sessionInfo) { + this.sessionChildrenTracker.unrefChild(sessionInfo.ref); + unregisterChannelzRef(sessionInfo.ref); + } + callback?.(); + }; + if (session.closed) { + queueMicrotask(closeCallback); + } else { + session.close(closeCallback); + } + } + + private completeUnbind(boundPortObject: BoundPort) { + for (const server of boundPortObject.listeningServers) { + const serverInfo = this.http2Servers.get(server); + this.closeServer(server, () => { + boundPortObject.listeningServers.delete(server); + }); + if (serverInfo) { + for (const session of serverInfo.sessions) { + this.closeSession(session); + } + } + } + this.boundPorts.delete(boundPortObject.mapKey); + } + + /** + * Unbind a previously bound port, or cancel an in-progress bindAsync + * operation. If port 0 was bound, only the actual bound port can be + * unbound. For example, if bindAsync was called with "localhost:0" and the + * bound port result was 54321, it can be unbound as "localhost:54321". + * @param port + */ + unbind(port: string): void { + this.trace('unbind port=' + port); + const portUri = this.normalizePort(port); + const splitPort = splitHostPort(portUri.path); + if (splitPort?.port === 0) { + throw new Error('Cannot unbind port 0'); + } + const boundPortObject = this.boundPorts.get(uriToString(portUri)); + if (boundPortObject) { + this.trace( + 'unbinding ' + + boundPortObject.mapKey + + ' originally bound as ' + + uriToString(boundPortObject.originalUri) + ); + /* If the bind operation is pending, the cancelled flag will trigger + * the unbind operation later. */ + if (boundPortObject.completionPromise) { + boundPortObject.cancelled = true; + } else { + this.completeUnbind(boundPortObject); + } + } + } + + /** + * Gracefully close all connections associated with a previously bound port. + * After the grace time, forcefully close all remaining open connections. + * + * If port 0 was bound, only the actual bound port can be + * drained. For example, if bindAsync was called with "localhost:0" and the + * bound port result was 54321, it can be drained as "localhost:54321". + * @param port + * @param graceTimeMs + * @returns + */ + drain(port: string, graceTimeMs: number): void { + this.trace('drain port=' + port + ' graceTimeMs=' + graceTimeMs); + const portUri = this.normalizePort(port); + const splitPort = splitHostPort(portUri.path); + if (splitPort?.port === 0) { + throw new Error('Cannot drain port 0'); + } + const boundPortObject = this.boundPorts.get(uriToString(portUri)); + if (!boundPortObject) { + return; + } + const allSessions: Set = new Set(); + for (const http2Server of boundPortObject.listeningServers) { + const serverEntry = this.http2Servers.get(http2Server); + if (serverEntry) { + for (const session of serverEntry.sessions) { + allSessions.add(session); + this.closeSession(session, () => { + allSessions.delete(session); + }); + } + } + } + /* After the grace time ends, send another goaway to all remaining sessions + * with the CANCEL code. */ + setTimeout(() => { + for (const session of allSessions) { + session.destroy(http2.constants.NGHTTP2_CANCEL as any); + } + }, graceTimeMs).unref?.(); + } + + forceShutdown(): void { + for (const boundPortObject of this.boundPorts.values()) { + boundPortObject.cancelled = true; + } + this.boundPorts.clear(); + // Close the server if it is still running. + for (const server of this.http2Servers.keys()) { + this.closeServer(server); + } + + // Always destroy any available sessions. It's possible that one or more + // tryShutdown() calls are in progress. Don't wait on them to finish. + this.sessions.forEach((channelzInfo, session) => { + this.closeSession(session); + // Cast NGHTTP2_CANCEL to any because TypeScript doesn't seem to + // recognize destroy(code) as a valid signature. + // eslint-disable-next-line @typescript-eslint/no-explicit-any + session.destroy(http2.constants.NGHTTP2_CANCEL as any); + }); + this.sessions.clear(); + unregisterChannelzRef(this.channelzRef); + + this.shutdown = true; + } + + register( + name: string, + handler: HandleCall, + serialize: Serialize, + deserialize: Deserialize, + type: string + ): boolean { + if (this.handlers.has(name)) { + return false; + } + + this.handlers.set(name, { + func: handler, + serialize, + deserialize, + type, + path: name, + } as UntypedHandler); + return true; + } + + unregister(name: string): boolean { + return this.handlers.delete(name); + } + + /** + * @deprecated No longer needed as of version 1.10.x + */ + @deprecate( + 'Calling start() is no longer necessary. It can be safely omitted.' + ) + start(): void { + if ( + this.http2Servers.size === 0 || + [...this.http2Servers.keys()].every(server => !server.listening) + ) { + throw new Error('server must be bound in order to start'); + } + + if (this.started === true) { + throw new Error('server is already started'); + } + this.started = true; + } + + tryShutdown(callback: (error?: Error) => void): void { + const wrappedCallback = (error?: Error) => { + unregisterChannelzRef(this.channelzRef); + callback(error); + }; + let pendingChecks = 0; + + function maybeCallback(): void { + pendingChecks--; + + if (pendingChecks === 0) { + wrappedCallback(); + } + } + this.shutdown = true; + + for (const [serverKey, server] of this.http2Servers.entries()) { + pendingChecks++; + const serverString = server.channelzRef.name; + this.trace('Waiting for server ' + serverString + ' to close'); + this.closeServer(serverKey, () => { + this.trace('Server ' + serverString + ' finished closing'); + maybeCallback(); + }); + + for (const session of server.sessions.keys()) { + pendingChecks++; + const sessionString = session.socket?.remoteAddress; + this.trace('Waiting for session ' + sessionString + ' to close'); + this.closeSession(session, () => { + this.trace('Session ' + sessionString + ' finished closing'); + maybeCallback(); + }); + } + } + + if (pendingChecks === 0) { + wrappedCallback(); + } + } + + addHttp2Port(): never { + throw new Error('Not yet implemented'); + } + + /** + * Get the channelz reference object for this server. The returned value is + * garbage if channelz is disabled for this server. + * @returns + */ + getChannelzRef() { + return this.channelzRef; + } + + private _verifyContentType( + stream: http2.ServerHttp2Stream, + headers: http2.IncomingHttpHeaders + ): boolean { + const contentType = headers[http2.constants.HTTP2_HEADER_CONTENT_TYPE]; + + if ( + typeof contentType !== 'string' || + !contentType.startsWith('application/grpc') + ) { + stream.respond( + { + [http2.constants.HTTP2_HEADER_STATUS]: + http2.constants.HTTP_STATUS_UNSUPPORTED_MEDIA_TYPE, + }, + { endStream: true } + ); + return false; + } + + return true; + } + + private _retrieveHandler(path: string): Handler | null { + this.trace( + 'Received call to method ' + + path + + ' at address ' + + this.serverAddressString + ); + + const handler = this.handlers.get(path); + + if (handler === undefined) { + this.trace( + 'No handler registered for method ' + + path + + '. Sending UNIMPLEMENTED status.' + ); + return null; + } + + return handler; + } + + private _respondWithError( + err: PartialStatusObject, + stream: http2.ServerHttp2Stream, + channelzSessionInfo: ChannelzSessionInfo | null = null + ) { + const trailersToSend = { + 'grpc-status': err.code ?? Status.INTERNAL, + 'grpc-message': err.details, + [http2.constants.HTTP2_HEADER_STATUS]: http2.constants.HTTP_STATUS_OK, + [http2.constants.HTTP2_HEADER_CONTENT_TYPE]: 'application/grpc+proto', + ...err.metadata?.toHttp2Headers(), + }; + stream.respond(trailersToSend, { endStream: true }); + + this.callTracker.addCallFailed(); + channelzSessionInfo?.streamTracker.addCallFailed(); + } + + private _channelzHandler( + stream: http2.ServerHttp2Stream, + headers: http2.IncomingHttpHeaders + ) { + // for handling idle timeout + this.onStreamOpened(stream); + + const channelzSessionInfo = this.sessions.get( + stream.session as http2.ServerHttp2Session + ); + + this.callTracker.addCallStarted(); + channelzSessionInfo?.streamTracker.addCallStarted(); + + if (!this._verifyContentType(stream, headers)) { + this.callTracker.addCallFailed(); + channelzSessionInfo?.streamTracker.addCallFailed(); + return; + } + + const path = headers[HTTP2_HEADER_PATH] as string; + + const handler = this._retrieveHandler(path); + if (!handler) { + this._respondWithError( + getUnimplementedStatusResponse(path), + stream, + channelzSessionInfo + ); + return; + } + + const callEventTracker: CallEventTracker = { + addMessageSent: () => { + if (channelzSessionInfo) { + channelzSessionInfo.messagesSent += 1; + channelzSessionInfo.lastMessageSentTimestamp = new Date(); + } + }, + addMessageReceived: () => { + if (channelzSessionInfo) { + channelzSessionInfo.messagesReceived += 1; + channelzSessionInfo.lastMessageReceivedTimestamp = new Date(); + } + }, + onCallEnd: status => { + if (status.code === Status.OK) { + this.callTracker.addCallSucceeded(); + } else { + this.callTracker.addCallFailed(); + } + }, + onStreamEnd: success => { + if (channelzSessionInfo) { + if (success) { + channelzSessionInfo.streamTracker.addCallSucceeded(); + } else { + channelzSessionInfo.streamTracker.addCallFailed(); + } + } + }, + }; + + const call = getServerInterceptingCall( + this.interceptors, + stream, + headers, + callEventTracker, + handler, + this.options + ); + + if (!this._runHandlerForCall(call, handler)) { + this.callTracker.addCallFailed(); + channelzSessionInfo?.streamTracker.addCallFailed(); + + call.sendStatus({ + code: Status.INTERNAL, + details: `Unknown handler type: ${handler.type}`, + }); + } + } + + private _streamHandler( + stream: http2.ServerHttp2Stream, + headers: http2.IncomingHttpHeaders + ) { + // for handling idle timeout + this.onStreamOpened(stream); + + if (this._verifyContentType(stream, headers) !== true) { + return; + } + + const path = headers[HTTP2_HEADER_PATH] as string; + + const handler = this._retrieveHandler(path); + if (!handler) { + this._respondWithError( + getUnimplementedStatusResponse(path), + stream, + null + ); + return; + } + + const call = getServerInterceptingCall( + this.interceptors, + stream, + headers, + null, + handler, + this.options + ); + + if (!this._runHandlerForCall(call, handler)) { + call.sendStatus({ + code: Status.INTERNAL, + details: `Unknown handler type: ${handler.type}`, + }); + } + } + + private _runHandlerForCall( + call: ServerInterceptingCallInterface, + handler: + | UntypedUnaryHandler + | UntypedClientStreamingHandler + | UntypedServerStreamingHandler + | UntypedBidiStreamingHandler + ): boolean { + const { type } = handler; + if (type === 'unary') { + handleUnary(call, handler); + } else if (type === 'clientStream') { + handleClientStreaming(call, handler); + } else if (type === 'serverStream') { + handleServerStreaming(call, handler); + } else if (type === 'bidi') { + handleBidiStreaming(call, handler); + } else { + return false; + } + + return true; + } + + private _setupHandlers( + http2Server: http2.Http2Server | http2.Http2SecureServer + ): void { + if (http2Server === null) { + return; + } + + const serverAddress = http2Server.address(); + let serverAddressString = 'null'; + if (serverAddress) { + if (typeof serverAddress === 'string') { + serverAddressString = serverAddress; + } else { + serverAddressString = serverAddress.address + ':' + serverAddress.port; + } + } + this.serverAddressString = serverAddressString; + + const handler = this.channelzEnabled + ? this._channelzHandler + : this._streamHandler; + + const sessionHandler = this.channelzEnabled + ? this._channelzSessionHandler(http2Server) + : this._sessionHandler(http2Server); + + http2Server.on('stream', handler.bind(this)); + http2Server.on('session', sessionHandler); + } + + private _sessionHandler( + http2Server: http2.Http2Server | http2.Http2SecureServer + ) { + return (session: http2.ServerHttp2Session) => { + this.http2Servers.get(http2Server)?.sessions.add(session); + + let connectionAgeTimer: NodeJS.Timeout | null = null; + let connectionAgeGraceTimer: NodeJS.Timeout | null = null; + let keeapliveTimeTimer: NodeJS.Timeout | null = null; + let keepaliveTimeoutTimer: NodeJS.Timeout | null = null; + let sessionClosedByServer = false; + + const idleTimeoutObj = this.enableIdleTimeout(session); + + if (this.maxConnectionAgeMs !== UNLIMITED_CONNECTION_AGE_MS) { + // Apply a random jitter within a +/-10% range + const jitterMagnitude = this.maxConnectionAgeMs / 10; + const jitter = Math.random() * jitterMagnitude * 2 - jitterMagnitude; + + connectionAgeTimer = setTimeout(() => { + sessionClosedByServer = true; + + this.trace( + 'Connection dropped by max connection age: ' + + session.socket?.remoteAddress + ); + + try { + session.goaway( + http2.constants.NGHTTP2_NO_ERROR, + ~(1 << 31), + kMaxAge + ); + } catch (e) { + // The goaway can't be sent because the session is already closed + session.destroy(); + return; + } + session.close(); + + /* Allow a grace period after sending the GOAWAY before forcibly + * closing the connection. */ + if (this.maxConnectionAgeGraceMs !== UNLIMITED_CONNECTION_AGE_MS) { + connectionAgeGraceTimer = setTimeout(() => { + session.destroy(); + }, this.maxConnectionAgeGraceMs); + connectionAgeGraceTimer.unref?.(); + } + }, this.maxConnectionAgeMs + jitter); + connectionAgeTimer.unref?.(); + } + + if (this.keepaliveTimeMs < KEEPALIVE_MAX_TIME_MS) { + keeapliveTimeTimer = setInterval(() => { + keepaliveTimeoutTimer = setTimeout(() => { + sessionClosedByServer = true; + session.close(); + }, this.keepaliveTimeoutMs); + keepaliveTimeoutTimer.unref?.(); + + try { + session.ping( + (err: Error | null, duration: number, payload: Buffer) => { + if (keepaliveTimeoutTimer) { + clearTimeout(keepaliveTimeoutTimer); + } + + if (err) { + sessionClosedByServer = true; + this.trace( + 'Connection dropped due to error of a ping frame ' + + err.message + + ' return in ' + + duration + ); + session.close(); + } + } + ); + } catch (e) { + clearTimeout(keepaliveTimeoutTimer); + // The ping can't be sent because the session is already closed + session.destroy(); + } + }, this.keepaliveTimeMs); + keeapliveTimeTimer.unref?.(); + } + + session.on('close', () => { + if (!sessionClosedByServer) { + this.trace( + `Connection dropped by client ${session.socket?.remoteAddress}` + ); + } + + if (connectionAgeTimer) { + clearTimeout(connectionAgeTimer); + } + + if (connectionAgeGraceTimer) { + clearTimeout(connectionAgeGraceTimer); + } + + if (keeapliveTimeTimer) { + clearInterval(keeapliveTimeTimer); + if (keepaliveTimeoutTimer) { + clearTimeout(keepaliveTimeoutTimer); + } + } + + if (idleTimeoutObj !== null) { + clearTimeout(idleTimeoutObj.timeout); + this.sessionIdleTimeouts.delete(session); + } + + this.http2Servers.get(http2Server)?.sessions.delete(session); + }); + }; + } + + private _channelzSessionHandler( + http2Server: http2.Http2Server | http2.Http2SecureServer + ) { + return (session: http2.ServerHttp2Session) => { + const channelzRef = registerChannelzSocket( + session.socket?.remoteAddress ?? 'unknown', + this.getChannelzSessionInfo.bind(this, session), + this.channelzEnabled + ); + + const channelzSessionInfo: ChannelzSessionInfo = { + ref: channelzRef, + streamTracker: new ChannelzCallTracker(), + messagesSent: 0, + messagesReceived: 0, + keepAlivesSent: 0, + lastMessageSentTimestamp: null, + lastMessageReceivedTimestamp: null, + }; + + this.http2Servers.get(http2Server)?.sessions.add(session); + this.sessions.set(session, channelzSessionInfo); + const clientAddress = `${session.socket.remoteAddress}:${session.socket.remotePort}`; + + this.channelzTrace.addTrace( + 'CT_INFO', + 'Connection established by client ' + clientAddress + ); + this.trace('Connection established by client ' + clientAddress); + this.sessionChildrenTracker.refChild(channelzRef); + + let connectionAgeTimer: NodeJS.Timeout | null = null; + let connectionAgeGraceTimer: NodeJS.Timeout | null = null; + let keeapliveTimeTimer: NodeJS.Timeout | null = null; + let keepaliveTimeoutTimer: NodeJS.Timeout | null = null; + let sessionClosedByServer = false; + + const idleTimeoutObj = this.enableIdleTimeout(session); + + if (this.maxConnectionAgeMs !== UNLIMITED_CONNECTION_AGE_MS) { + // Apply a random jitter within a +/-10% range + const jitterMagnitude = this.maxConnectionAgeMs / 10; + const jitter = Math.random() * jitterMagnitude * 2 - jitterMagnitude; + + connectionAgeTimer = setTimeout(() => { + sessionClosedByServer = true; + this.channelzTrace.addTrace( + 'CT_INFO', + 'Connection dropped by max connection age from ' + clientAddress + ); + + try { + session.goaway( + http2.constants.NGHTTP2_NO_ERROR, + ~(1 << 31), + kMaxAge + ); + } catch (e) { + // The goaway can't be sent because the session is already closed + session.destroy(); + return; + } + session.close(); + + /* Allow a grace period after sending the GOAWAY before forcibly + * closing the connection. */ + if (this.maxConnectionAgeGraceMs !== UNLIMITED_CONNECTION_AGE_MS) { + connectionAgeGraceTimer = setTimeout(() => { + session.destroy(); + }, this.maxConnectionAgeGraceMs); + connectionAgeGraceTimer.unref?.(); + } + }, this.maxConnectionAgeMs + jitter); + connectionAgeTimer.unref?.(); + } + + if (this.keepaliveTimeMs < KEEPALIVE_MAX_TIME_MS) { + keeapliveTimeTimer = setInterval(() => { + keepaliveTimeoutTimer = setTimeout(() => { + sessionClosedByServer = true; + this.channelzTrace.addTrace( + 'CT_INFO', + 'Connection dropped by keepalive timeout from ' + clientAddress + ); + + session.close(); + }, this.keepaliveTimeoutMs); + keepaliveTimeoutTimer.unref?.(); + + try { + session.ping( + (err: Error | null, duration: number, payload: Buffer) => { + if (keepaliveTimeoutTimer) { + clearTimeout(keepaliveTimeoutTimer); + } + + if (err) { + sessionClosedByServer = true; + this.channelzTrace.addTrace( + 'CT_INFO', + 'Connection dropped due to error of a ping frame ' + + err.message + + ' return in ' + + duration + ); + + session.close(); + } + } + ); + channelzSessionInfo.keepAlivesSent += 1; + } catch (e) { + clearTimeout(keepaliveTimeoutTimer); + // The ping can't be sent because the session is already closed + session.destroy(); + } + }, this.keepaliveTimeMs); + keeapliveTimeTimer.unref?.(); + } + + session.on('close', () => { + if (!sessionClosedByServer) { + this.channelzTrace.addTrace( + 'CT_INFO', + 'Connection dropped by client ' + clientAddress + ); + } + + this.sessionChildrenTracker.unrefChild(channelzRef); + unregisterChannelzRef(channelzRef); + + if (connectionAgeTimer) { + clearTimeout(connectionAgeTimer); + } + + if (connectionAgeGraceTimer) { + clearTimeout(connectionAgeGraceTimer); + } + + if (keeapliveTimeTimer) { + clearInterval(keeapliveTimeTimer); + if (keepaliveTimeoutTimer) { + clearTimeout(keepaliveTimeoutTimer); + } + } + + if (idleTimeoutObj !== null) { + clearTimeout(idleTimeoutObj.timeout); + this.sessionIdleTimeouts.delete(session); + } + + this.http2Servers.get(http2Server)?.sessions.delete(session); + this.sessions.delete(session); + }); + }; + } + + private enableIdleTimeout( + session: http2.ServerHttp2Session + ): SessionIdleTimeoutTracker | null { + if (this.sessionIdleTimeout >= MAX_CONNECTION_IDLE_MS) { + return null; + } + + const idleTimeoutObj: SessionIdleTimeoutTracker = { + activeStreams: 0, + lastIdle: Date.now(), + onClose: this.onStreamClose.bind(this, session), + timeout: setTimeout( + this.onIdleTimeout, + this.sessionIdleTimeout, + this, + session + ), + }; + idleTimeoutObj.timeout.unref?.(); + this.sessionIdleTimeouts.set(session, idleTimeoutObj); + + const { socket } = session; + this.trace( + 'Enable idle timeout for ' + + socket.remoteAddress + + ':' + + socket.remotePort + ); + + return idleTimeoutObj; + } + + private onIdleTimeout( + this: undefined, + ctx: Server, + session: http2.ServerHttp2Session + ) { + const { socket } = session; + const sessionInfo = ctx.sessionIdleTimeouts.get(session); + + // if it is called while we have activeStreams - timer will not be rescheduled + // until last active stream is closed, then it will call .refresh() on the timer + // important part is to not clearTimeout(timer) or it becomes unusable + // for future refreshes + if ( + sessionInfo !== undefined && + sessionInfo.activeStreams === 0 && + Date.now() - sessionInfo.lastIdle >= ctx.sessionIdleTimeout + ) { + ctx.trace( + 'Session idle timeout triggered for ' + + socket?.remoteAddress + + ':' + + socket?.remotePort + + ' last idle at ' + + sessionInfo.lastIdle + ); + + ctx.closeSession(session); + } + } + + private onStreamOpened(stream: http2.ServerHttp2Stream) { + const session = stream.session as http2.ServerHttp2Session; + + const idleTimeoutObj = this.sessionIdleTimeouts.get(session); + if (idleTimeoutObj) { + idleTimeoutObj.activeStreams += 1; + stream.once('close', idleTimeoutObj.onClose); + } + } + + private onStreamClose(session: http2.ServerHttp2Session) { + const idleTimeoutObj = this.sessionIdleTimeouts.get(session); + + if (idleTimeoutObj) { + idleTimeoutObj.activeStreams -= 1; + if (idleTimeoutObj.activeStreams === 0) { + idleTimeoutObj.lastIdle = Date.now(); + idleTimeoutObj.timeout.refresh(); + + this.trace( + 'Session onStreamClose' + + session.socket?.remoteAddress + + ':' + + session.socket?.remotePort + + ' at ' + + idleTimeoutObj.lastIdle + ); + } + } + } +} + +async function handleUnary( + call: ServerInterceptingCallInterface, + handler: UnaryHandler +): Promise { + let stream: ServerUnaryCall; + + function respond( + err: ServerErrorResponse | ServerStatusResponse | null, + value?: ResponseType | null, + trailer?: Metadata, + flags?: number + ) { + if (err) { + call.sendStatus(serverErrorToStatus(err, trailer)); + return; + } + call.sendMessage(value, () => { + call.sendStatus({ + code: Status.OK, + details: 'OK', + metadata: trailer ?? null, + }); + }); + } + + let requestMetadata: Metadata; + let requestMessage: RequestType | null = null; + call.start({ + onReceiveMetadata(metadata) { + requestMetadata = metadata; + call.startRead(); + }, + onReceiveMessage(message) { + if (requestMessage) { + call.sendStatus({ + code: Status.UNIMPLEMENTED, + details: `Received a second request message for server streaming method ${handler.path}`, + metadata: null, + }); + return; + } + requestMessage = message; + call.startRead(); + }, + onReceiveHalfClose() { + if (!requestMessage) { + call.sendStatus({ + code: Status.UNIMPLEMENTED, + details: `Received no request message for server streaming method ${handler.path}`, + metadata: null, + }); + return; + } + stream = new ServerWritableStreamImpl( + handler.path, + call, + requestMetadata, + requestMessage + ); + try { + handler.func(stream, respond); + } catch (err) { + call.sendStatus({ + code: Status.UNKNOWN, + details: `Server method handler threw error ${ + (err as Error).message + }`, + metadata: null, + }); + } + }, + onCancel() { + if (stream) { + stream.cancelled = true; + stream.emit('cancelled', 'cancelled'); + } + }, + }); +} + +function handleClientStreaming( + call: ServerInterceptingCallInterface, + handler: ClientStreamingHandler +): void { + let stream: ServerReadableStream; + + function respond( + err: ServerErrorResponse | ServerStatusResponse | null, + value?: ResponseType | null, + trailer?: Metadata, + flags?: number + ) { + if (err) { + call.sendStatus(serverErrorToStatus(err, trailer)); + return; + } + call.sendMessage(value, () => { + call.sendStatus({ + code: Status.OK, + details: 'OK', + metadata: trailer ?? null, + }); + }); + } + + call.start({ + onReceiveMetadata(metadata) { + stream = new ServerDuplexStreamImpl(handler.path, call, metadata); + try { + handler.func(stream, respond); + } catch (err) { + call.sendStatus({ + code: Status.UNKNOWN, + details: `Server method handler threw error ${ + (err as Error).message + }`, + metadata: null, + }); + } + }, + onReceiveMessage(message) { + stream.push(message); + }, + onReceiveHalfClose() { + stream.push(null); + }, + onCancel() { + if (stream) { + stream.cancelled = true; + stream.emit('cancelled', 'cancelled'); + stream.destroy(); + } + }, + }); +} + +function handleServerStreaming( + call: ServerInterceptingCallInterface, + handler: ServerStreamingHandler +): void { + let stream: ServerWritableStream; + + let requestMetadata: Metadata; + let requestMessage: RequestType | null = null; + call.start({ + onReceiveMetadata(metadata) { + requestMetadata = metadata; + call.startRead(); + }, + onReceiveMessage(message) { + if (requestMessage) { + call.sendStatus({ + code: Status.UNIMPLEMENTED, + details: `Received a second request message for server streaming method ${handler.path}`, + metadata: null, + }); + return; + } + requestMessage = message; + call.startRead(); + }, + onReceiveHalfClose() { + if (!requestMessage) { + call.sendStatus({ + code: Status.UNIMPLEMENTED, + details: `Received no request message for server streaming method ${handler.path}`, + metadata: null, + }); + return; + } + stream = new ServerWritableStreamImpl( + handler.path, + call, + requestMetadata, + requestMessage + ); + try { + handler.func(stream); + } catch (err) { + call.sendStatus({ + code: Status.UNKNOWN, + details: `Server method handler threw error ${ + (err as Error).message + }`, + metadata: null, + }); + } + }, + onCancel() { + if (stream) { + stream.cancelled = true; + stream.emit('cancelled', 'cancelled'); + stream.destroy(); + } + }, + }); +} + +function handleBidiStreaming( + call: ServerInterceptingCallInterface, + handler: BidiStreamingHandler +): void { + let stream: ServerDuplexStream; + + call.start({ + onReceiveMetadata(metadata) { + stream = new ServerDuplexStreamImpl(handler.path, call, metadata); + try { + handler.func(stream); + } catch (err) { + call.sendStatus({ + code: Status.UNKNOWN, + details: `Server method handler threw error ${ + (err as Error).message + }`, + metadata: null, + }); + } + }, + onReceiveMessage(message) { + stream.push(message); + }, + onReceiveHalfClose() { + stream.push(null); + }, + onCancel() { + if (stream) { + stream.cancelled = true; + stream.emit('cancelled', 'cancelled'); + stream.destroy(); + } + }, + }); +} diff --git a/node_modules/@grpc/grpc-js/src/service-config.ts b/node_modules/@grpc/grpc-js/src/service-config.ts new file mode 100644 index 0000000..b0d0d55 --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/service-config.ts @@ -0,0 +1,564 @@ +/* + * Copyright 2019 gRPC authors. + * + * 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. + * + */ + +/* This file implements gRFC A2 and the service config spec: + * https://github.com/grpc/proposal/blob/master/A2-service-configs-in-dns.md + * https://github.com/grpc/grpc/blob/master/doc/service_config.md. Each + * function here takes an object with unknown structure and returns its + * specific object type if the input has the right structure, and throws an + * error otherwise. */ + +/* The any type is purposely used here. All functions validate their input at + * runtime */ +/* eslint-disable @typescript-eslint/no-explicit-any */ + +import * as os from 'os'; +import { Status } from './constants'; +import { Duration } from './duration'; + +export interface MethodConfigName { + service?: string; + method?: string; +} + +export interface RetryPolicy { + maxAttempts: number; + initialBackoff: string; + maxBackoff: string; + backoffMultiplier: number; + retryableStatusCodes: (Status | string)[]; +} + +export interface HedgingPolicy { + maxAttempts: number; + hedgingDelay?: string; + nonFatalStatusCodes?: (Status | string)[]; +} + +export interface MethodConfig { + name: MethodConfigName[]; + waitForReady?: boolean; + timeout?: Duration; + maxRequestBytes?: number; + maxResponseBytes?: number; + retryPolicy?: RetryPolicy; + hedgingPolicy?: HedgingPolicy; +} + +export interface RetryThrottling { + maxTokens: number; + tokenRatio: number; +} + +export interface LoadBalancingConfig { + [key: string]: object; +} + +export interface ServiceConfig { + loadBalancingPolicy?: string; + loadBalancingConfig: LoadBalancingConfig[]; + methodConfig: MethodConfig[]; + retryThrottling?: RetryThrottling; +} + +export interface ServiceConfigCanaryConfig { + clientLanguage?: string[]; + percentage?: number; + clientHostname?: string[]; + serviceConfig: ServiceConfig; +} + +/** + * Recognizes a number with up to 9 digits after the decimal point, followed by + * an "s", representing a number of seconds. + */ +const DURATION_REGEX = /^\d+(\.\d{1,9})?s$/; + +/** + * Client language name used for determining whether this client matches a + * `ServiceConfigCanaryConfig`'s `clientLanguage` list. + */ +const CLIENT_LANGUAGE_STRING = 'node'; + +function validateName(obj: any): MethodConfigName { + // In this context, and unset field and '' are considered the same + if ('service' in obj && obj.service !== '') { + if (typeof obj.service !== 'string') { + throw new Error( + `Invalid method config name: invalid service: expected type string, got ${typeof obj.service}` + ); + } + if ('method' in obj && obj.method !== '') { + if (typeof obj.method !== 'string') { + throw new Error( + `Invalid method config name: invalid method: expected type string, got ${typeof obj.service}` + ); + } + return { + service: obj.service, + method: obj.method, + }; + } else { + return { + service: obj.service, + }; + } + } else { + if ('method' in obj && obj.method !== undefined) { + throw new Error( + `Invalid method config name: method set with empty or unset service` + ); + } + return {}; + } +} + +function validateRetryPolicy(obj: any): RetryPolicy { + if ( + !('maxAttempts' in obj) || + !Number.isInteger(obj.maxAttempts) || + obj.maxAttempts < 2 + ) { + throw new Error( + 'Invalid method config retry policy: maxAttempts must be an integer at least 2' + ); + } + if ( + !('initialBackoff' in obj) || + typeof obj.initialBackoff !== 'string' || + !DURATION_REGEX.test(obj.initialBackoff) + ) { + throw new Error( + 'Invalid method config retry policy: initialBackoff must be a string consisting of a positive integer followed by s' + ); + } + if ( + !('maxBackoff' in obj) || + typeof obj.maxBackoff !== 'string' || + !DURATION_REGEX.test(obj.maxBackoff) + ) { + throw new Error( + 'Invalid method config retry policy: maxBackoff must be a string consisting of a positive integer followed by s' + ); + } + if ( + !('backoffMultiplier' in obj) || + typeof obj.backoffMultiplier !== 'number' || + obj.backoffMultiplier <= 0 + ) { + throw new Error( + 'Invalid method config retry policy: backoffMultiplier must be a number greater than 0' + ); + } + if ( + !('retryableStatusCodes' in obj && Array.isArray(obj.retryableStatusCodes)) + ) { + throw new Error( + 'Invalid method config retry policy: retryableStatusCodes is required' + ); + } + if (obj.retryableStatusCodes.length === 0) { + throw new Error( + 'Invalid method config retry policy: retryableStatusCodes must be non-empty' + ); + } + for (const value of obj.retryableStatusCodes) { + if (typeof value === 'number') { + if (!Object.values(Status).includes(value)) { + throw new Error( + 'Invalid method config retry policy: retryableStatusCodes value not in status code range' + ); + } + } else if (typeof value === 'string') { + if (!Object.values(Status).includes(value.toUpperCase())) { + throw new Error( + 'Invalid method config retry policy: retryableStatusCodes value not a status code name' + ); + } + } else { + throw new Error( + 'Invalid method config retry policy: retryableStatusCodes value must be a string or number' + ); + } + } + return { + maxAttempts: obj.maxAttempts, + initialBackoff: obj.initialBackoff, + maxBackoff: obj.maxBackoff, + backoffMultiplier: obj.backoffMultiplier, + retryableStatusCodes: obj.retryableStatusCodes, + }; +} + +function validateHedgingPolicy(obj: any): HedgingPolicy { + if ( + !('maxAttempts' in obj) || + !Number.isInteger(obj.maxAttempts) || + obj.maxAttempts < 2 + ) { + throw new Error( + 'Invalid method config hedging policy: maxAttempts must be an integer at least 2' + ); + } + if ( + 'hedgingDelay' in obj && + (typeof obj.hedgingDelay !== 'string' || + !DURATION_REGEX.test(obj.hedgingDelay)) + ) { + throw new Error( + 'Invalid method config hedging policy: hedgingDelay must be a string consisting of a positive integer followed by s' + ); + } + if ('nonFatalStatusCodes' in obj && Array.isArray(obj.nonFatalStatusCodes)) { + for (const value of obj.nonFatalStatusCodes) { + if (typeof value === 'number') { + if (!Object.values(Status).includes(value)) { + throw new Error( + 'Invlid method config hedging policy: nonFatalStatusCodes value not in status code range' + ); + } + } else if (typeof value === 'string') { + if (!Object.values(Status).includes(value.toUpperCase())) { + throw new Error( + 'Invlid method config hedging policy: nonFatalStatusCodes value not a status code name' + ); + } + } else { + throw new Error( + 'Invlid method config hedging policy: nonFatalStatusCodes value must be a string or number' + ); + } + } + } + const result: HedgingPolicy = { + maxAttempts: obj.maxAttempts, + }; + if (obj.hedgingDelay) { + result.hedgingDelay = obj.hedgingDelay; + } + if (obj.nonFatalStatusCodes) { + result.nonFatalStatusCodes = obj.nonFatalStatusCodes; + } + return result; +} + +function validateMethodConfig(obj: any): MethodConfig { + const result: MethodConfig = { + name: [], + }; + if (!('name' in obj) || !Array.isArray(obj.name)) { + throw new Error('Invalid method config: invalid name array'); + } + for (const name of obj.name) { + result.name.push(validateName(name)); + } + if ('waitForReady' in obj) { + if (typeof obj.waitForReady !== 'boolean') { + throw new Error('Invalid method config: invalid waitForReady'); + } + result.waitForReady = obj.waitForReady; + } + if ('timeout' in obj) { + if (typeof obj.timeout === 'object') { + if ( + !('seconds' in obj.timeout) || + !(typeof obj.timeout.seconds === 'number') + ) { + throw new Error('Invalid method config: invalid timeout.seconds'); + } + if ( + !('nanos' in obj.timeout) || + !(typeof obj.timeout.nanos === 'number') + ) { + throw new Error('Invalid method config: invalid timeout.nanos'); + } + result.timeout = obj.timeout; + } else if ( + typeof obj.timeout === 'string' && + DURATION_REGEX.test(obj.timeout) + ) { + const timeoutParts = obj.timeout + .substring(0, obj.timeout.length - 1) + .split('.'); + result.timeout = { + seconds: timeoutParts[0] | 0, + nanos: (timeoutParts[1] ?? 0) | 0, + }; + } else { + throw new Error('Invalid method config: invalid timeout'); + } + } + if ('maxRequestBytes' in obj) { + if (typeof obj.maxRequestBytes !== 'number') { + throw new Error('Invalid method config: invalid maxRequestBytes'); + } + result.maxRequestBytes = obj.maxRequestBytes; + } + if ('maxResponseBytes' in obj) { + if (typeof obj.maxResponseBytes !== 'number') { + throw new Error('Invalid method config: invalid maxRequestBytes'); + } + result.maxResponseBytes = obj.maxResponseBytes; + } + if ('retryPolicy' in obj) { + if ('hedgingPolicy' in obj) { + throw new Error( + 'Invalid method config: retryPolicy and hedgingPolicy cannot both be specified' + ); + } else { + result.retryPolicy = validateRetryPolicy(obj.retryPolicy); + } + } else if ('hedgingPolicy' in obj) { + result.hedgingPolicy = validateHedgingPolicy(obj.hedgingPolicy); + } + return result; +} + +export function validateRetryThrottling(obj: any): RetryThrottling { + if ( + !('maxTokens' in obj) || + typeof obj.maxTokens !== 'number' || + obj.maxTokens <= 0 || + obj.maxTokens > 1000 + ) { + throw new Error( + 'Invalid retryThrottling: maxTokens must be a number in (0, 1000]' + ); + } + if ( + !('tokenRatio' in obj) || + typeof obj.tokenRatio !== 'number' || + obj.tokenRatio <= 0 + ) { + throw new Error( + 'Invalid retryThrottling: tokenRatio must be a number greater than 0' + ); + } + return { + maxTokens: +(obj.maxTokens as number).toFixed(3), + tokenRatio: +(obj.tokenRatio as number).toFixed(3), + }; +} + +function validateLoadBalancingConfig(obj: any): LoadBalancingConfig { + if (!(typeof obj === 'object' && obj !== null)) { + throw new Error( + `Invalid loadBalancingConfig: unexpected type ${typeof obj}` + ); + } + const keys = Object.keys(obj); + if (keys.length > 1) { + throw new Error( + `Invalid loadBalancingConfig: unexpected multiple keys ${keys}` + ); + } + if (keys.length === 0) { + throw new Error( + 'Invalid loadBalancingConfig: load balancing policy name required' + ); + } + return { + [keys[0]]: obj[keys[0]], + }; +} + +export function validateServiceConfig(obj: any): ServiceConfig { + const result: ServiceConfig = { + loadBalancingConfig: [], + methodConfig: [], + }; + if ('loadBalancingPolicy' in obj) { + if (typeof obj.loadBalancingPolicy === 'string') { + result.loadBalancingPolicy = obj.loadBalancingPolicy; + } else { + throw new Error('Invalid service config: invalid loadBalancingPolicy'); + } + } + if ('loadBalancingConfig' in obj) { + if (Array.isArray(obj.loadBalancingConfig)) { + for (const config of obj.loadBalancingConfig) { + result.loadBalancingConfig.push(validateLoadBalancingConfig(config)); + } + } else { + throw new Error('Invalid service config: invalid loadBalancingConfig'); + } + } + if ('methodConfig' in obj) { + if (Array.isArray(obj.methodConfig)) { + for (const methodConfig of obj.methodConfig) { + result.methodConfig.push(validateMethodConfig(methodConfig)); + } + } + } + if ('retryThrottling' in obj) { + result.retryThrottling = validateRetryThrottling(obj.retryThrottling); + } + // Validate method name uniqueness + const seenMethodNames: MethodConfigName[] = []; + for (const methodConfig of result.methodConfig) { + for (const name of methodConfig.name) { + for (const seenName of seenMethodNames) { + if ( + name.service === seenName.service && + name.method === seenName.method + ) { + throw new Error( + `Invalid service config: duplicate name ${name.service}/${name.method}` + ); + } + } + seenMethodNames.push(name); + } + } + return result; +} + +function validateCanaryConfig(obj: any): ServiceConfigCanaryConfig { + if (!('serviceConfig' in obj)) { + throw new Error('Invalid service config choice: missing service config'); + } + const result: ServiceConfigCanaryConfig = { + serviceConfig: validateServiceConfig(obj.serviceConfig), + }; + if ('clientLanguage' in obj) { + if (Array.isArray(obj.clientLanguage)) { + result.clientLanguage = []; + for (const lang of obj.clientLanguage) { + if (typeof lang === 'string') { + result.clientLanguage.push(lang); + } else { + throw new Error( + 'Invalid service config choice: invalid clientLanguage' + ); + } + } + } else { + throw new Error('Invalid service config choice: invalid clientLanguage'); + } + } + if ('clientHostname' in obj) { + if (Array.isArray(obj.clientHostname)) { + result.clientHostname = []; + for (const lang of obj.clientHostname) { + if (typeof lang === 'string') { + result.clientHostname.push(lang); + } else { + throw new Error( + 'Invalid service config choice: invalid clientHostname' + ); + } + } + } else { + throw new Error('Invalid service config choice: invalid clientHostname'); + } + } + if ('percentage' in obj) { + if ( + typeof obj.percentage === 'number' && + 0 <= obj.percentage && + obj.percentage <= 100 + ) { + result.percentage = obj.percentage; + } else { + throw new Error('Invalid service config choice: invalid percentage'); + } + } + // Validate that no unexpected fields are present + const allowedFields = [ + 'clientLanguage', + 'percentage', + 'clientHostname', + 'serviceConfig', + ]; + for (const field in obj) { + if (!allowedFields.includes(field)) { + throw new Error( + `Invalid service config choice: unexpected field ${field}` + ); + } + } + return result; +} + +function validateAndSelectCanaryConfig( + obj: any, + percentage: number +): ServiceConfig { + if (!Array.isArray(obj)) { + throw new Error('Invalid service config list'); + } + for (const config of obj) { + const validatedConfig = validateCanaryConfig(config); + /* For each field, we check if it is present, then only discard the + * config if the field value does not match the current client */ + if ( + typeof validatedConfig.percentage === 'number' && + percentage > validatedConfig.percentage + ) { + continue; + } + if (Array.isArray(validatedConfig.clientHostname)) { + let hostnameMatched = false; + for (const hostname of validatedConfig.clientHostname) { + if (hostname === os.hostname()) { + hostnameMatched = true; + } + } + if (!hostnameMatched) { + continue; + } + } + if (Array.isArray(validatedConfig.clientLanguage)) { + let languageMatched = false; + for (const language of validatedConfig.clientLanguage) { + if (language === CLIENT_LANGUAGE_STRING) { + languageMatched = true; + } + } + if (!languageMatched) { + continue; + } + } + return validatedConfig.serviceConfig; + } + throw new Error('No matching service config found'); +} + +/** + * Find the "grpc_config" record among the TXT records, parse its value as JSON, validate its contents, + * and select a service config with selection fields that all match this client. Most of these steps + * can fail with an error; the caller must handle any errors thrown this way. + * @param txtRecord The TXT record array that is output from a successful call to dns.resolveTxt + * @param percentage A number chosen from the range [0, 100) that is used to select which config to use + * @return The service configuration to use, given the percentage value, or null if the service config + * data has a valid format but none of the options match the current client. + */ +export function extractAndSelectServiceConfig( + txtRecord: string[][], + percentage: number +): ServiceConfig | null { + for (const record of txtRecord) { + if (record.length > 0 && record[0].startsWith('grpc_config=')) { + /* Treat the list of strings in this record as a single string and remove + * "grpc_config=" from the beginning. The rest should be a JSON string */ + const recordString = record.join('').substring('grpc_config='.length); + const recordJson: any = JSON.parse(recordString); + return validateAndSelectCanaryConfig(recordJson, percentage); + } + } + return null; +} diff --git a/node_modules/@grpc/grpc-js/src/status-builder.ts b/node_modules/@grpc/grpc-js/src/status-builder.ts new file mode 100644 index 0000000..78e2ea3 --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/status-builder.ts @@ -0,0 +1,80 @@ +/* + * Copyright 2019 gRPC authors. + * + * 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. + * + */ + +import { StatusObject } from './call-interface'; +import { Status } from './constants'; +import { Metadata } from './metadata'; + +/** + * A builder for gRPC status objects. + */ +export class StatusBuilder { + private code: Status | null; + private details: string | null; + private metadata: Metadata | null; + + constructor() { + this.code = null; + this.details = null; + this.metadata = null; + } + + /** + * Adds a status code to the builder. + */ + withCode(code: Status): this { + this.code = code; + return this; + } + + /** + * Adds details to the builder. + */ + withDetails(details: string): this { + this.details = details; + return this; + } + + /** + * Adds metadata to the builder. + */ + withMetadata(metadata: Metadata): this { + this.metadata = metadata; + return this; + } + + /** + * Builds the status object. + */ + build(): Partial { + const status: Partial = {}; + + if (this.code !== null) { + status.code = this.code; + } + + if (this.details !== null) { + status.details = this.details; + } + + if (this.metadata !== null) { + status.metadata = this.metadata; + } + + return status; + } +} diff --git a/node_modules/@grpc/grpc-js/src/stream-decoder.ts b/node_modules/@grpc/grpc-js/src/stream-decoder.ts new file mode 100644 index 0000000..671ad41 --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/stream-decoder.ts @@ -0,0 +1,105 @@ +/* + * Copyright 2019 gRPC authors. + * + * 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. + * + */ + +enum ReadState { + NO_DATA, + READING_SIZE, + READING_MESSAGE, +} + +export class StreamDecoder { + private readState: ReadState = ReadState.NO_DATA; + private readCompressFlag: Buffer = Buffer.alloc(1); + private readPartialSize: Buffer = Buffer.alloc(4); + private readSizeRemaining = 4; + private readMessageSize = 0; + private readPartialMessage: Buffer[] = []; + private readMessageRemaining = 0; + + write(data: Buffer): Buffer[] { + let readHead = 0; + let toRead: number; + const result: Buffer[] = []; + + while (readHead < data.length) { + switch (this.readState) { + case ReadState.NO_DATA: + this.readCompressFlag = data.slice(readHead, readHead + 1); + readHead += 1; + this.readState = ReadState.READING_SIZE; + this.readPartialSize.fill(0); + this.readSizeRemaining = 4; + this.readMessageSize = 0; + this.readMessageRemaining = 0; + this.readPartialMessage = []; + break; + case ReadState.READING_SIZE: + toRead = Math.min(data.length - readHead, this.readSizeRemaining); + data.copy( + this.readPartialSize, + 4 - this.readSizeRemaining, + readHead, + readHead + toRead + ); + this.readSizeRemaining -= toRead; + readHead += toRead; + // readSizeRemaining >=0 here + if (this.readSizeRemaining === 0) { + this.readMessageSize = this.readPartialSize.readUInt32BE(0); + this.readMessageRemaining = this.readMessageSize; + if (this.readMessageRemaining > 0) { + this.readState = ReadState.READING_MESSAGE; + } else { + const message = Buffer.concat( + [this.readCompressFlag, this.readPartialSize], + 5 + ); + + this.readState = ReadState.NO_DATA; + result.push(message); + } + } + break; + case ReadState.READING_MESSAGE: + toRead = Math.min(data.length - readHead, this.readMessageRemaining); + this.readPartialMessage.push(data.slice(readHead, readHead + toRead)); + this.readMessageRemaining -= toRead; + readHead += toRead; + // readMessageRemaining >=0 here + if (this.readMessageRemaining === 0) { + // At this point, we have read a full message + const framedMessageBuffers = [ + this.readCompressFlag, + this.readPartialSize, + ].concat(this.readPartialMessage); + const framedMessage = Buffer.concat( + framedMessageBuffers, + this.readMessageSize + 5 + ); + + this.readState = ReadState.NO_DATA; + result.push(framedMessage); + } + break; + default: + throw new Error('Unexpected read state'); + } + } + + return result; + } +} diff --git a/node_modules/@grpc/grpc-js/src/subchannel-address.ts b/node_modules/@grpc/grpc-js/src/subchannel-address.ts new file mode 100644 index 0000000..7e4f3e4 --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/subchannel-address.ts @@ -0,0 +1,252 @@ +/* + * Copyright 2021 gRPC authors. + * + * 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. + * + */ + +import { isIP, isIPv6 } from 'net'; + +export interface TcpSubchannelAddress { + port: number; + host: string; +} + +export interface IpcSubchannelAddress { + path: string; +} +/** + * This represents a single backend address to connect to. This interface is a + * subset of net.SocketConnectOpts, i.e. the options described at + * https://nodejs.org/api/net.html#net_socket_connect_options_connectlistener. + * Those are in turn a subset of the options that can be passed to http2.connect. + */ + +export type SubchannelAddress = TcpSubchannelAddress | IpcSubchannelAddress; + +export function isTcpSubchannelAddress( + address: SubchannelAddress +): address is TcpSubchannelAddress { + return 'port' in address; +} + +export function subchannelAddressEqual( + address1?: SubchannelAddress, + address2?: SubchannelAddress +): boolean { + if (!address1 && !address2) { + return true; + } + if (!address1 || !address2) { + return false; + } + if (isTcpSubchannelAddress(address1)) { + return ( + isTcpSubchannelAddress(address2) && + address1.host === address2.host && + address1.port === address2.port + ); + } else { + return !isTcpSubchannelAddress(address2) && address1.path === address2.path; + } +} + +export function subchannelAddressToString(address: SubchannelAddress): string { + if (isTcpSubchannelAddress(address)) { + if (isIPv6(address.host)) { + return '[' + address.host + ']:' + address.port; + } else { + return address.host + ':' + address.port; + } + } else { + return address.path; + } +} + +const DEFAULT_PORT = 443; + +export function stringToSubchannelAddress( + addressString: string, + port?: number +): SubchannelAddress { + if (isIP(addressString)) { + return { + host: addressString, + port: port ?? DEFAULT_PORT, + }; + } else { + return { + path: addressString, + }; + } +} + +export interface Endpoint { + addresses: SubchannelAddress[]; +} + +export function endpointEqual(endpoint1: Endpoint, endpoint2: Endpoint) { + if (endpoint1.addresses.length !== endpoint2.addresses.length) { + return false; + } + for (let i = 0; i < endpoint1.addresses.length; i++) { + if ( + !subchannelAddressEqual(endpoint1.addresses[i], endpoint2.addresses[i]) + ) { + return false; + } + } + return true; +} + +export function endpointToString(endpoint: Endpoint): string { + return ( + '[' + endpoint.addresses.map(subchannelAddressToString).join(', ') + ']' + ); +} + +export function endpointHasAddress( + endpoint: Endpoint, + expectedAddress: SubchannelAddress +): boolean { + for (const address of endpoint.addresses) { + if (subchannelAddressEqual(address, expectedAddress)) { + return true; + } + } + return false; +} + +interface EndpointMapEntry { + key: Endpoint; + value: ValueType; +} + +function endpointEqualUnordered( + endpoint1: Endpoint, + endpoint2: Endpoint +): boolean { + if (endpoint1.addresses.length !== endpoint2.addresses.length) { + return false; + } + for (const address1 of endpoint1.addresses) { + let matchFound = false; + for (const address2 of endpoint2.addresses) { + if (subchannelAddressEqual(address1, address2)) { + matchFound = true; + break; + } + } + if (!matchFound) { + return false; + } + } + return true; +} + +export class EndpointMap { + private map: Set> = new Set(); + + get size() { + return this.map.size; + } + + getForSubchannelAddress(address: SubchannelAddress): ValueType | undefined { + for (const entry of this.map) { + if (endpointHasAddress(entry.key, address)) { + return entry.value; + } + } + return undefined; + } + + /** + * Delete any entries in this map with keys that are not in endpoints + * @param endpoints + */ + deleteMissing(endpoints: Endpoint[]): ValueType[] { + const removedValues: ValueType[] = []; + for (const entry of this.map) { + let foundEntry = false; + for (const endpoint of endpoints) { + if (endpointEqualUnordered(endpoint, entry.key)) { + foundEntry = true; + } + } + if (!foundEntry) { + removedValues.push(entry.value); + this.map.delete(entry); + } + } + return removedValues; + } + + get(endpoint: Endpoint): ValueType | undefined { + for (const entry of this.map) { + if (endpointEqualUnordered(endpoint, entry.key)) { + return entry.value; + } + } + return undefined; + } + + set(endpoint: Endpoint, mapEntry: ValueType) { + for (const entry of this.map) { + if (endpointEqualUnordered(endpoint, entry.key)) { + entry.value = mapEntry; + return; + } + } + this.map.add({ key: endpoint, value: mapEntry }); + } + + delete(endpoint: Endpoint) { + for (const entry of this.map) { + if (endpointEqualUnordered(endpoint, entry.key)) { + this.map.delete(entry); + return; + } + } + } + + has(endpoint: Endpoint): boolean { + for (const entry of this.map) { + if (endpointEqualUnordered(endpoint, entry.key)) { + return true; + } + } + return false; + } + + clear() { + this.map.clear(); + } + + *keys(): IterableIterator { + for (const entry of this.map) { + yield entry.key; + } + } + + *values(): IterableIterator { + for (const entry of this.map) { + yield entry.value; + } + } + + *entries(): IterableIterator<[Endpoint, ValueType]> { + for (const entry of this.map) { + yield [entry.key, entry.value]; + } + } +} diff --git a/node_modules/@grpc/grpc-js/src/subchannel-call.ts b/node_modules/@grpc/grpc-js/src/subchannel-call.ts new file mode 100644 index 0000000..0ce7d72 --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/subchannel-call.ts @@ -0,0 +1,578 @@ +/* + * Copyright 2019 gRPC authors. + * + * 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. + * + */ + +import * as http2 from 'http2'; +import * as os from 'os'; + +import { Status } from './constants'; +import { Metadata } from './metadata'; +import { StreamDecoder } from './stream-decoder'; +import * as logging from './logging'; +import { LogVerbosity } from './constants'; +import { + InterceptingListener, + MessageContext, + StatusObject, + WriteCallback, +} from './call-interface'; +import { CallEventTracker, Transport } from './transport'; + +const TRACER_NAME = 'subchannel_call'; + +/** + * https://nodejs.org/api/errors.html#errors_class_systemerror + */ +interface SystemError extends Error { + address?: string; + code: string; + dest?: string; + errno: number; + info?: object; + message: string; + path?: string; + port?: number; + syscall: string; +} + +/** + * Should do approximately the same thing as util.getSystemErrorName but the + * TypeScript types don't have that function for some reason so I just made my + * own. + * @param errno + */ +function getSystemErrorName(errno: number): string { + for (const [name, num] of Object.entries(os.constants.errno)) { + if (num === errno) { + return name; + } + } + return 'Unknown system error ' + errno; +} + +export interface SubchannelCall { + cancelWithStatus(status: Status, details: string): void; + getPeer(): string; + sendMessageWithContext(context: MessageContext, message: Buffer): void; + startRead(): void; + halfClose(): void; + getCallNumber(): number; + getDeadlineInfo(): string[]; +} + +export interface StatusObjectWithRstCode extends StatusObject { + rstCode?: number; +} + +export interface SubchannelCallInterceptingListener + extends InterceptingListener { + onReceiveStatus(status: StatusObjectWithRstCode): void; +} + +function mapHttpStatusCode(code: number): StatusObject { + const details = `Received HTTP status code ${code}`; + let mappedStatusCode: number; + switch (code) { + // TODO(murgatroid99): handle 100 and 101 + case 400: + mappedStatusCode = Status.INTERNAL; + break; + case 401: + mappedStatusCode = Status.UNAUTHENTICATED; + break; + case 403: + mappedStatusCode = Status.PERMISSION_DENIED; + break; + case 404: + mappedStatusCode = Status.UNIMPLEMENTED; + break; + case 429: + case 502: + case 503: + case 504: + mappedStatusCode = Status.UNAVAILABLE; + break; + default: + mappedStatusCode = Status.UNKNOWN; + } + return { + code: mappedStatusCode, + details: details, + metadata: new Metadata() + }; +} + +export class Http2SubchannelCall implements SubchannelCall { + private decoder = new StreamDecoder(); + + private isReadFilterPending = false; + private isPushPending = false; + private canPush = false; + /** + * Indicates that an 'end' event has come from the http2 stream, so there + * will be no more data events. + */ + private readsClosed = false; + + private statusOutput = false; + + private unpushedReadMessages: Buffer[] = []; + + private httpStatusCode: number | undefined; + + // This is populated (non-null) if and only if the call has ended + private finalStatus: StatusObject | null = null; + + private internalError: SystemError | null = null; + + private serverEndedCall = false; + + constructor( + private readonly http2Stream: http2.ClientHttp2Stream, + private readonly callEventTracker: CallEventTracker, + private readonly listener: SubchannelCallInterceptingListener, + private readonly transport: Transport, + private readonly callId: number + ) { + http2Stream.on('response', (headers, flags) => { + let headersString = ''; + for (const header of Object.keys(headers)) { + headersString += '\t\t' + header + ': ' + headers[header] + '\n'; + } + this.trace('Received server headers:\n' + headersString); + this.httpStatusCode = headers[':status']; + + if (flags & http2.constants.NGHTTP2_FLAG_END_STREAM) { + this.handleTrailers(headers); + } else { + let metadata: Metadata; + try { + metadata = Metadata.fromHttp2Headers(headers); + } catch (error) { + this.endCall({ + code: Status.UNKNOWN, + details: (error as Error).message, + metadata: new Metadata(), + }); + return; + } + this.listener.onReceiveMetadata(metadata); + } + }); + http2Stream.on('trailers', (headers: http2.IncomingHttpHeaders) => { + this.handleTrailers(headers); + }); + http2Stream.on('data', (data: Buffer) => { + /* If the status has already been output, allow the http2 stream to + * drain without processing the data. */ + if (this.statusOutput) { + return; + } + this.trace('receive HTTP/2 data frame of length ' + data.length); + const messages = this.decoder.write(data); + + for (const message of messages) { + this.trace('parsed message of length ' + message.length); + this.callEventTracker!.addMessageReceived(); + this.tryPush(message); + } + }); + http2Stream.on('end', () => { + this.readsClosed = true; + this.maybeOutputStatus(); + }); + http2Stream.on('close', () => { + this.serverEndedCall = true; + /* Use process.next tick to ensure that this code happens after any + * "error" event that may be emitted at about the same time, so that + * we can bubble up the error message from that event. */ + process.nextTick(() => { + this.trace('HTTP/2 stream closed with code ' + http2Stream.rstCode); + /* If we have a final status with an OK status code, that means that + * we have received all of the messages and we have processed the + * trailers and the call completed successfully, so it doesn't matter + * how the stream ends after that */ + if (this.finalStatus?.code === Status.OK) { + return; + } + let code: Status; + let details = ''; + switch (http2Stream.rstCode) { + case http2.constants.NGHTTP2_NO_ERROR: + /* If we get a NO_ERROR code and we already have a status, the + * stream completed properly and we just haven't fully processed + * it yet */ + if (this.finalStatus !== null) { + return; + } + if (this.httpStatusCode && this.httpStatusCode !== 200) { + const mappedStatus = mapHttpStatusCode(this.httpStatusCode); + code = mappedStatus.code; + details = mappedStatus.details; + } else { + code = Status.INTERNAL; + details = `Received RST_STREAM with code ${http2Stream.rstCode} (Call ended without gRPC status)`; + } + break; + case http2.constants.NGHTTP2_REFUSED_STREAM: + code = Status.UNAVAILABLE; + details = 'Stream refused by server'; + break; + case http2.constants.NGHTTP2_CANCEL: + code = Status.CANCELLED; + details = 'Call cancelled'; + break; + case http2.constants.NGHTTP2_ENHANCE_YOUR_CALM: + code = Status.RESOURCE_EXHAUSTED; + details = 'Bandwidth exhausted or memory limit exceeded'; + break; + case http2.constants.NGHTTP2_INADEQUATE_SECURITY: + code = Status.PERMISSION_DENIED; + details = 'Protocol not secure enough'; + break; + case http2.constants.NGHTTP2_INTERNAL_ERROR: + code = Status.INTERNAL; + if (this.internalError === null) { + /* This error code was previously handled in the default case, and + * there are several instances of it online, so I wanted to + * preserve the original error message so that people find existing + * information in searches, but also include the more recognizable + * "Internal server error" message. */ + details = `Received RST_STREAM with code ${http2Stream.rstCode} (Internal server error)`; + } else { + if ( + this.internalError.code === 'ECONNRESET' || + this.internalError.code === 'ETIMEDOUT' + ) { + code = Status.UNAVAILABLE; + details = this.internalError.message; + } else { + /* The "Received RST_STREAM with code ..." error is preserved + * here for continuity with errors reported online, but the + * error message at the end will probably be more relevant in + * most cases. */ + details = `Received RST_STREAM with code ${http2Stream.rstCode} triggered by internal client error: ${this.internalError.message}`; + } + } + break; + default: + code = Status.INTERNAL; + details = `Received RST_STREAM with code ${http2Stream.rstCode}`; + } + // This is a no-op if trailers were received at all. + // This is OK, because status codes emitted here correspond to more + // catastrophic issues that prevent us from receiving trailers in the + // first place. + this.endCall({ + code, + details, + metadata: new Metadata(), + rstCode: http2Stream.rstCode, + }); + }); + }); + http2Stream.on('error', (err: SystemError) => { + /* We need an error handler here to stop "Uncaught Error" exceptions + * from bubbling up. However, errors here should all correspond to + * "close" events, where we will handle the error more granularly */ + /* Specifically looking for stream errors that were *not* constructed + * from a RST_STREAM response here: + * https://github.com/nodejs/node/blob/8b8620d580314050175983402dfddf2674e8e22a/lib/internal/http2/core.js#L2267 + */ + if (err.code !== 'ERR_HTTP2_STREAM_ERROR') { + this.trace( + 'Node error event: message=' + + err.message + + ' code=' + + err.code + + ' errno=' + + getSystemErrorName(err.errno) + + ' syscall=' + + err.syscall + ); + this.internalError = err; + } + this.callEventTracker.onStreamEnd(false); + }); + } + getDeadlineInfo(): string[] { + return [`remote_addr=${this.getPeer()}`]; + } + + public onDisconnect() { + this.endCall({ + code: Status.UNAVAILABLE, + details: 'Connection dropped', + metadata: new Metadata(), + }); + } + + private outputStatus() { + /* Precondition: this.finalStatus !== null */ + if (!this.statusOutput) { + this.statusOutput = true; + this.trace( + 'ended with status: code=' + + this.finalStatus!.code + + ' details="' + + this.finalStatus!.details + + '"' + ); + this.callEventTracker.onCallEnd(this.finalStatus!); + /* We delay the actual action of bubbling up the status to insulate the + * cleanup code in this class from any errors that may be thrown in the + * upper layers as a result of bubbling up the status. In particular, + * if the status is not OK, the "error" event may be emitted + * synchronously at the top level, which will result in a thrown error if + * the user does not handle that event. */ + process.nextTick(() => { + this.listener.onReceiveStatus(this.finalStatus!); + }); + /* Leave the http2 stream in flowing state to drain incoming messages, to + * ensure that the stream closure completes. The call stream already does + * not push more messages after the status is output, so the messages go + * nowhere either way. */ + this.http2Stream.resume(); + } + } + + private trace(text: string): void { + logging.trace( + LogVerbosity.DEBUG, + TRACER_NAME, + '[' + this.callId + '] ' + text + ); + } + + /** + * On first call, emits a 'status' event with the given StatusObject. + * Subsequent calls are no-ops. + * @param status The status of the call. + */ + private endCall(status: StatusObjectWithRstCode): void { + /* If the status is OK and a new status comes in (e.g. from a + * deserialization failure), that new status takes priority */ + if (this.finalStatus === null || this.finalStatus.code === Status.OK) { + this.finalStatus = status; + this.maybeOutputStatus(); + } + this.destroyHttp2Stream(); + } + + private maybeOutputStatus() { + if (this.finalStatus !== null) { + /* The combination check of readsClosed and that the two message buffer + * arrays are empty checks that there all incoming data has been fully + * processed */ + if ( + this.finalStatus.code !== Status.OK || + (this.readsClosed && + this.unpushedReadMessages.length === 0 && + !this.isReadFilterPending && + !this.isPushPending) + ) { + this.outputStatus(); + } + } + } + + private push(message: Buffer): void { + this.trace( + 'pushing to reader message of length ' + + (message instanceof Buffer ? message.length : null) + ); + this.canPush = false; + this.isPushPending = true; + process.nextTick(() => { + this.isPushPending = false; + /* If we have already output the status any later messages should be + * ignored, and can cause out-of-order operation errors higher up in the + * stack. Checking as late as possible here to avoid any race conditions. + */ + if (this.statusOutput) { + return; + } + this.listener.onReceiveMessage(message); + this.maybeOutputStatus(); + }); + } + + private tryPush(messageBytes: Buffer): void { + if (this.canPush) { + this.http2Stream!.pause(); + this.push(messageBytes); + } else { + this.trace( + 'unpushedReadMessages.push message of length ' + messageBytes.length + ); + this.unpushedReadMessages.push(messageBytes); + } + } + + private handleTrailers(headers: http2.IncomingHttpHeaders) { + this.serverEndedCall = true; + this.callEventTracker.onStreamEnd(true); + let headersString = ''; + for (const header of Object.keys(headers)) { + headersString += '\t\t' + header + ': ' + headers[header] + '\n'; + } + this.trace('Received server trailers:\n' + headersString); + let metadata: Metadata; + try { + metadata = Metadata.fromHttp2Headers(headers); + } catch (e) { + metadata = new Metadata(); + } + const metadataMap = metadata.getMap(); + let status: StatusObject; + if (typeof metadataMap['grpc-status'] === 'string') { + const receivedStatus: Status = Number(metadataMap['grpc-status']); + this.trace('received status code ' + receivedStatus + ' from server'); + metadata.remove('grpc-status'); + let details = ''; + if (typeof metadataMap['grpc-message'] === 'string') { + try { + details = decodeURI(metadataMap['grpc-message']); + } catch (e) { + details = metadataMap['grpc-message']; + } + metadata.remove('grpc-message'); + this.trace( + 'received status details string "' + details + '" from server' + ); + } + status = { + code: receivedStatus, + details: details, + metadata: metadata + }; + } else if (this.httpStatusCode) { + status = mapHttpStatusCode(this.httpStatusCode); + status.metadata = metadata; + } else { + status = { + code: Status.UNKNOWN, + details: 'No status information received', + metadata: metadata + }; + } + // This is a no-op if the call was already ended when handling headers. + this.endCall(status); + } + + private destroyHttp2Stream() { + // The http2 stream could already have been destroyed if cancelWithStatus + // is called in response to an internal http2 error. + if (this.http2Stream.destroyed) { + return; + } + /* If the server ended the call, sending an RST_STREAM is redundant, so we + * just half close on the client side instead to finish closing the stream. + */ + if (this.serverEndedCall) { + this.http2Stream.end(); + } else { + /* If the call has ended with an OK status, communicate that when closing + * the stream, partly to avoid a situation in which we detect an error + * RST_STREAM as a result after we have the status */ + let code: number; + if (this.finalStatus?.code === Status.OK) { + code = http2.constants.NGHTTP2_NO_ERROR; + } else { + code = http2.constants.NGHTTP2_CANCEL; + } + this.trace('close http2 stream with code ' + code); + this.http2Stream.close(code); + } + } + + cancelWithStatus(status: Status, details: string): void { + this.trace( + 'cancelWithStatus code: ' + status + ' details: "' + details + '"' + ); + this.endCall({ code: status, details, metadata: new Metadata() }); + } + + getStatus(): StatusObject | null { + return this.finalStatus; + } + + getPeer(): string { + return this.transport.getPeerName(); + } + + getCallNumber(): number { + return this.callId; + } + + startRead() { + /* If the stream has ended with an error, we should not emit any more + * messages and we should communicate that the stream has ended */ + if (this.finalStatus !== null && this.finalStatus.code !== Status.OK) { + this.readsClosed = true; + this.maybeOutputStatus(); + return; + } + this.canPush = true; + if (this.unpushedReadMessages.length > 0) { + const nextMessage: Buffer = this.unpushedReadMessages.shift()!; + this.push(nextMessage); + return; + } + /* Only resume reading from the http2Stream if we don't have any pending + * messages to emit */ + this.http2Stream.resume(); + } + + sendMessageWithContext(context: MessageContext, message: Buffer) { + this.trace('write() called with message of length ' + message.length); + const cb: WriteCallback = (error?: Error | null) => { + /* nextTick here ensures that no stream action can be taken in the call + * stack of the write callback, in order to hopefully work around + * https://github.com/nodejs/node/issues/49147 */ + process.nextTick(() => { + let code: Status = Status.UNAVAILABLE; + if ( + (error as NodeJS.ErrnoException)?.code === + 'ERR_STREAM_WRITE_AFTER_END' + ) { + code = Status.INTERNAL; + } + if (error) { + this.cancelWithStatus(code, `Write error: ${error.message}`); + } + context.callback?.(); + }); + }; + this.trace('sending data chunk of length ' + message.length); + this.callEventTracker.addMessageSent(); + try { + this.http2Stream!.write(message, cb); + } catch (error) { + this.endCall({ + code: Status.UNAVAILABLE, + details: `Write failed with error ${(error as Error).message}`, + metadata: new Metadata(), + }); + } + } + + halfClose() { + this.trace('end() called'); + this.trace('calling end() on HTTP/2 stream'); + this.http2Stream.end(); + } +} diff --git a/node_modules/@grpc/grpc-js/src/subchannel-interface.ts b/node_modules/@grpc/grpc-js/src/subchannel-interface.ts new file mode 100644 index 0000000..6c31418 --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/subchannel-interface.ts @@ -0,0 +1,137 @@ +/* + * Copyright 2022 gRPC authors. + * + * 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. + * + */ + +import type { SubchannelRef } from './channelz'; +import { ConnectivityState } from './connectivity-state'; +import { Subchannel } from './subchannel'; + +export type ConnectivityStateListener = ( + subchannel: SubchannelInterface, + previousState: ConnectivityState, + newState: ConnectivityState, + keepaliveTime: number, + errorMessage?: string +) => void; + +export type HealthListener = (healthy: boolean) => void; + +/** + * This is an interface for load balancing policies to use to interact with + * subchannels. This allows load balancing policies to wrap and unwrap + * subchannels. + * + * Any load balancing policy that wraps subchannels must unwrap the subchannel + * in the picker, so that other load balancing policies consistently have + * access to their own wrapper objects. + */ +export interface SubchannelInterface { + getConnectivityState(): ConnectivityState; + addConnectivityStateListener(listener: ConnectivityStateListener): void; + removeConnectivityStateListener(listener: ConnectivityStateListener): void; + startConnecting(): void; + getAddress(): string; + throttleKeepalive(newKeepaliveTime: number): void; + ref(): void; + unref(): void; + getChannelzRef(): SubchannelRef; + isHealthy(): boolean; + addHealthStateWatcher(listener: HealthListener): void; + removeHealthStateWatcher(listener: HealthListener): void; + /** + * If this is a wrapper, return the wrapped subchannel, otherwise return this + */ + getRealSubchannel(): Subchannel; + /** + * Returns true if this and other both proxy the same underlying subchannel. + * Can be used instead of directly accessing getRealSubchannel to allow mocks + * to avoid implementing getRealSubchannel + */ + realSubchannelEquals(other: SubchannelInterface): boolean; +} + +export abstract class BaseSubchannelWrapper implements SubchannelInterface { + private healthy = true; + private healthListeners: Set = new Set(); + constructor(protected child: SubchannelInterface) { + child.addHealthStateWatcher(childHealthy => { + /* A change to the child health state only affects this wrapper's overall + * health state if this wrapper is reporting healthy. */ + if (this.healthy) { + this.updateHealthListeners(); + } + }); + } + + private updateHealthListeners(): void { + for (const listener of this.healthListeners) { + listener(this.isHealthy()); + } + } + + getConnectivityState(): ConnectivityState { + return this.child.getConnectivityState(); + } + addConnectivityStateListener(listener: ConnectivityStateListener): void { + this.child.addConnectivityStateListener(listener); + } + removeConnectivityStateListener(listener: ConnectivityStateListener): void { + this.child.removeConnectivityStateListener(listener); + } + startConnecting(): void { + this.child.startConnecting(); + } + getAddress(): string { + return this.child.getAddress(); + } + throttleKeepalive(newKeepaliveTime: number): void { + this.child.throttleKeepalive(newKeepaliveTime); + } + ref(): void { + this.child.ref(); + } + unref(): void { + this.child.unref(); + } + getChannelzRef(): SubchannelRef { + return this.child.getChannelzRef(); + } + isHealthy(): boolean { + return this.healthy && this.child.isHealthy(); + } + addHealthStateWatcher(listener: HealthListener): void { + this.healthListeners.add(listener); + } + removeHealthStateWatcher(listener: HealthListener): void { + this.healthListeners.delete(listener); + } + protected setHealthy(healthy: boolean): void { + if (healthy !== this.healthy) { + this.healthy = healthy; + /* A change to this wrapper's health state only affects the overall + * reported health state if the child is healthy. */ + if (this.child.isHealthy()) { + this.updateHealthListeners(); + } + } + } + getRealSubchannel(): Subchannel { + return this.child.getRealSubchannel(); + } + realSubchannelEquals(other: SubchannelInterface): boolean { + return this.getRealSubchannel() === other.getRealSubchannel(); + } +} diff --git a/node_modules/@grpc/grpc-js/src/subchannel-pool.ts b/node_modules/@grpc/grpc-js/src/subchannel-pool.ts new file mode 100644 index 0000000..a5dec72 --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/subchannel-pool.ts @@ -0,0 +1,176 @@ +/* + * Copyright 2019 gRPC authors. + * + * 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. + * + */ + +import { ChannelOptions, channelOptionsEqual } from './channel-options'; +import { Subchannel } from './subchannel'; +import { + SubchannelAddress, + subchannelAddressEqual, +} from './subchannel-address'; +import { ChannelCredentials } from './channel-credentials'; +import { GrpcUri, uriToString } from './uri-parser'; +import { Http2SubchannelConnector } from './transport'; + +// 10 seconds in milliseconds. This value is arbitrary. +/** + * The amount of time in between checks for dropping subchannels that have no + * other references + */ +const REF_CHECK_INTERVAL = 10_000; + +export class SubchannelPool { + private pool: { + [channelTarget: string]: Array<{ + subchannelAddress: SubchannelAddress; + channelArguments: ChannelOptions; + channelCredentials: ChannelCredentials; + subchannel: Subchannel; + }>; + } = Object.create(null); + + /** + * A timer of a task performing a periodic subchannel cleanup. + */ + private cleanupTimer: NodeJS.Timeout | null = null; + + /** + * A pool of subchannels use for making connections. Subchannels with the + * exact same parameters will be reused. + */ + constructor() {} + + /** + * Unrefs all unused subchannels and cancels the cleanup task if all + * subchannels have been unrefed. + */ + unrefUnusedSubchannels(): void { + let allSubchannelsUnrefed = true; + + /* These objects are created with Object.create(null), so they do not + * have a prototype, which means that for (... in ...) loops over them + * do not need to be filtered */ + // eslint-disable-disable-next-line:forin + for (const channelTarget in this.pool) { + const subchannelObjArray = this.pool[channelTarget]; + + const refedSubchannels = subchannelObjArray.filter( + value => !value.subchannel.unrefIfOneRef() + ); + + if (refedSubchannels.length > 0) { + allSubchannelsUnrefed = false; + } + + /* For each subchannel in the pool, try to unref it if it has + * exactly one ref (which is the ref from the pool itself). If that + * does happen, remove the subchannel from the pool */ + this.pool[channelTarget] = refedSubchannels; + } + /* Currently we do not delete keys with empty values. If that results + * in significant memory usage we should change it. */ + + // Cancel the cleanup task if all subchannels have been unrefed. + if (allSubchannelsUnrefed && this.cleanupTimer !== null) { + clearInterval(this.cleanupTimer); + this.cleanupTimer = null; + } + } + + /** + * Ensures that the cleanup task is spawned. + */ + ensureCleanupTask(): void { + if (this.cleanupTimer === null) { + this.cleanupTimer = setInterval(() => { + this.unrefUnusedSubchannels(); + }, REF_CHECK_INTERVAL); + + // Unref because this timer should not keep the event loop running. + // Call unref only if it exists to address electron/electron#21162 + this.cleanupTimer.unref?.(); + } + } + + /** + * Get a subchannel if one already exists with exactly matching parameters. + * Otherwise, create and save a subchannel with those parameters. + * @param channelTarget + * @param subchannelTarget + * @param channelArguments + * @param channelCredentials + */ + getOrCreateSubchannel( + channelTargetUri: GrpcUri, + subchannelTarget: SubchannelAddress, + channelArguments: ChannelOptions, + channelCredentials: ChannelCredentials + ): Subchannel { + this.ensureCleanupTask(); + const channelTarget = uriToString(channelTargetUri); + if (channelTarget in this.pool) { + const subchannelObjArray = this.pool[channelTarget]; + for (const subchannelObj of subchannelObjArray) { + if ( + subchannelAddressEqual( + subchannelTarget, + subchannelObj.subchannelAddress + ) && + channelOptionsEqual( + channelArguments, + subchannelObj.channelArguments + ) && + channelCredentials._equals(subchannelObj.channelCredentials) + ) { + return subchannelObj.subchannel; + } + } + } + // If we get here, no matching subchannel was found + const subchannel = new Subchannel( + channelTargetUri, + subchannelTarget, + channelArguments, + channelCredentials, + new Http2SubchannelConnector(channelTargetUri) + ); + if (!(channelTarget in this.pool)) { + this.pool[channelTarget] = []; + } + this.pool[channelTarget].push({ + subchannelAddress: subchannelTarget, + channelArguments, + channelCredentials, + subchannel, + }); + subchannel.ref(); + return subchannel; + } +} + +const globalSubchannelPool = new SubchannelPool(); + +/** + * Get either the global subchannel pool, or a new subchannel pool. + * @param global + */ +export function getSubchannelPool(global: boolean): SubchannelPool { + if (global) { + return globalSubchannelPool; + } else { + return new SubchannelPool(); + } +} diff --git a/node_modules/@grpc/grpc-js/src/subchannel.ts b/node_modules/@grpc/grpc-js/src/subchannel.ts new file mode 100644 index 0000000..95b600c --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/subchannel.ts @@ -0,0 +1,504 @@ +/* + * Copyright 2019 gRPC authors. + * + * 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. + * + */ + +import { ChannelCredentials } from './channel-credentials'; +import { Metadata } from './metadata'; +import { ChannelOptions } from './channel-options'; +import { ConnectivityState } from './connectivity-state'; +import { BackoffTimeout, BackoffOptions } from './backoff-timeout'; +import * as logging from './logging'; +import { LogVerbosity, Status } from './constants'; +import { GrpcUri, uriToString } from './uri-parser'; +import { + SubchannelAddress, + subchannelAddressToString, +} from './subchannel-address'; +import { + SubchannelRef, + ChannelzTrace, + ChannelzChildrenTracker, + ChannelzChildrenTrackerStub, + SubchannelInfo, + registerChannelzSubchannel, + ChannelzCallTracker, + ChannelzCallTrackerStub, + unregisterChannelzRef, + ChannelzTraceStub, +} from './channelz'; +import { + ConnectivityStateListener, + SubchannelInterface, +} from './subchannel-interface'; +import { SubchannelCallInterceptingListener } from './subchannel-call'; +import { SubchannelCall } from './subchannel-call'; +import { CallEventTracker, SubchannelConnector, Transport } from './transport'; + +const TRACER_NAME = 'subchannel'; + +/* setInterval and setTimeout only accept signed 32 bit integers. JS doesn't + * have a constant for the max signed 32 bit integer, so this is a simple way + * to calculate it */ +const KEEPALIVE_MAX_TIME_MS = ~(1 << 31); + +export class Subchannel { + /** + * The subchannel's current connectivity state. Invariant: `session` === `null` + * if and only if `connectivityState` is IDLE or TRANSIENT_FAILURE. + */ + private connectivityState: ConnectivityState = ConnectivityState.IDLE; + /** + * The underlying http2 session used to make requests. + */ + private transport: Transport | null = null; + /** + * Indicates that the subchannel should transition from TRANSIENT_FAILURE to + * CONNECTING instead of IDLE when the backoff timeout ends. + */ + private continueConnecting = false; + /** + * A list of listener functions that will be called whenever the connectivity + * state changes. Will be modified by `addConnectivityStateListener` and + * `removeConnectivityStateListener` + */ + private stateListeners: Set = new Set(); + + private backoffTimeout: BackoffTimeout; + + private keepaliveTime: number; + /** + * Tracks channels and subchannel pools with references to this subchannel + */ + private refcount = 0; + + /** + * A string representation of the subchannel address, for logging/tracing + */ + private subchannelAddressString: string; + + // Channelz info + private readonly channelzEnabled: boolean = true; + private channelzRef: SubchannelRef; + + private channelzTrace: ChannelzTrace | ChannelzTraceStub; + private callTracker: ChannelzCallTracker | ChannelzCallTrackerStub; + private childrenTracker: + | ChannelzChildrenTracker + | ChannelzChildrenTrackerStub; + + // Channelz socket info + private streamTracker: ChannelzCallTracker | ChannelzCallTrackerStub; + + /** + * A class representing a connection to a single backend. + * @param channelTarget The target string for the channel as a whole + * @param subchannelAddress The address for the backend that this subchannel + * will connect to + * @param options The channel options, plus any specific subchannel options + * for this subchannel + * @param credentials The channel credentials used to establish this + * connection + */ + constructor( + private channelTarget: GrpcUri, + private subchannelAddress: SubchannelAddress, + private options: ChannelOptions, + private credentials: ChannelCredentials, + private connector: SubchannelConnector + ) { + const backoffOptions: BackoffOptions = { + initialDelay: options['grpc.initial_reconnect_backoff_ms'], + maxDelay: options['grpc.max_reconnect_backoff_ms'], + }; + this.backoffTimeout = new BackoffTimeout(() => { + this.handleBackoffTimer(); + }, backoffOptions); + this.backoffTimeout.unref(); + this.subchannelAddressString = subchannelAddressToString(subchannelAddress); + + this.keepaliveTime = options['grpc.keepalive_time_ms'] ?? -1; + + if (options['grpc.enable_channelz'] === 0) { + this.channelzEnabled = false; + this.channelzTrace = new ChannelzTraceStub(); + this.callTracker = new ChannelzCallTrackerStub(); + this.childrenTracker = new ChannelzChildrenTrackerStub(); + this.streamTracker = new ChannelzCallTrackerStub(); + } else { + this.channelzTrace = new ChannelzTrace(); + this.callTracker = new ChannelzCallTracker(); + this.childrenTracker = new ChannelzChildrenTracker(); + this.streamTracker = new ChannelzCallTracker(); + } + + this.channelzRef = registerChannelzSubchannel( + this.subchannelAddressString, + () => this.getChannelzInfo(), + this.channelzEnabled + ); + + this.channelzTrace.addTrace('CT_INFO', 'Subchannel created'); + this.trace( + 'Subchannel constructed with options ' + + JSON.stringify(options, undefined, 2) + ); + } + + private getChannelzInfo(): SubchannelInfo { + return { + state: this.connectivityState, + trace: this.channelzTrace, + callTracker: this.callTracker, + children: this.childrenTracker.getChildLists(), + target: this.subchannelAddressString, + }; + } + + private trace(text: string): void { + logging.trace( + LogVerbosity.DEBUG, + TRACER_NAME, + '(' + + this.channelzRef.id + + ') ' + + this.subchannelAddressString + + ' ' + + text + ); + } + + private refTrace(text: string): void { + logging.trace( + LogVerbosity.DEBUG, + 'subchannel_refcount', + '(' + + this.channelzRef.id + + ') ' + + this.subchannelAddressString + + ' ' + + text + ); + } + + private handleBackoffTimer() { + if (this.continueConnecting) { + this.transitionToState( + [ConnectivityState.TRANSIENT_FAILURE], + ConnectivityState.CONNECTING + ); + } else { + this.transitionToState( + [ConnectivityState.TRANSIENT_FAILURE], + ConnectivityState.IDLE + ); + } + } + + /** + * Start a backoff timer with the current nextBackoff timeout + */ + private startBackoff() { + this.backoffTimeout.runOnce(); + } + + private stopBackoff() { + this.backoffTimeout.stop(); + this.backoffTimeout.reset(); + } + + private startConnectingInternal() { + let options = this.options; + if (options['grpc.keepalive_time_ms']) { + const adjustedKeepaliveTime = Math.min( + this.keepaliveTime, + KEEPALIVE_MAX_TIME_MS + ); + options = { ...options, 'grpc.keepalive_time_ms': adjustedKeepaliveTime }; + } + this.connector + .connect(this.subchannelAddress, this.credentials, options) + .then( + transport => { + if ( + this.transitionToState( + [ConnectivityState.CONNECTING], + ConnectivityState.READY + ) + ) { + this.transport = transport; + if (this.channelzEnabled) { + this.childrenTracker.refChild(transport.getChannelzRef()); + } + transport.addDisconnectListener(tooManyPings => { + this.transitionToState( + [ConnectivityState.READY], + ConnectivityState.IDLE + ); + if (tooManyPings && this.keepaliveTime > 0) { + this.keepaliveTime *= 2; + logging.log( + LogVerbosity.ERROR, + `Connection to ${uriToString(this.channelTarget)} at ${ + this.subchannelAddressString + } rejected by server because of excess pings. Increasing ping interval to ${ + this.keepaliveTime + } ms` + ); + } + }); + } else { + /* If we can't transition from CONNECTING to READY here, we will + * not be using this transport, so release its resources. */ + transport.shutdown(); + } + }, + error => { + this.transitionToState( + [ConnectivityState.CONNECTING], + ConnectivityState.TRANSIENT_FAILURE, + `${error}` + ); + } + ); + } + + /** + * Initiate a state transition from any element of oldStates to the new + * state. If the current connectivityState is not in oldStates, do nothing. + * @param oldStates The set of states to transition from + * @param newState The state to transition to + * @returns True if the state changed, false otherwise + */ + private transitionToState( + oldStates: ConnectivityState[], + newState: ConnectivityState, + errorMessage?: string + ): boolean { + if (oldStates.indexOf(this.connectivityState) === -1) { + return false; + } + this.trace( + ConnectivityState[this.connectivityState] + + ' -> ' + + ConnectivityState[newState] + ); + if (this.channelzEnabled) { + this.channelzTrace.addTrace( + 'CT_INFO', + 'Connectivity state change to ' + ConnectivityState[newState] + ); + } + const previousState = this.connectivityState; + this.connectivityState = newState; + switch (newState) { + case ConnectivityState.READY: + this.stopBackoff(); + break; + case ConnectivityState.CONNECTING: + this.startBackoff(); + this.startConnectingInternal(); + this.continueConnecting = false; + break; + case ConnectivityState.TRANSIENT_FAILURE: + if (this.channelzEnabled && this.transport) { + this.childrenTracker.unrefChild(this.transport.getChannelzRef()); + } + this.transport?.shutdown(); + this.transport = null; + /* If the backoff timer has already ended by the time we get to the + * TRANSIENT_FAILURE state, we want to immediately transition out of + * TRANSIENT_FAILURE as though the backoff timer is ending right now */ + if (!this.backoffTimeout.isRunning()) { + process.nextTick(() => { + this.handleBackoffTimer(); + }); + } + break; + case ConnectivityState.IDLE: + if (this.channelzEnabled && this.transport) { + this.childrenTracker.unrefChild(this.transport.getChannelzRef()); + } + this.transport?.shutdown(); + this.transport = null; + break; + default: + throw new Error(`Invalid state: unknown ConnectivityState ${newState}`); + } + for (const listener of this.stateListeners) { + listener(this, previousState, newState, this.keepaliveTime, errorMessage); + } + return true; + } + + ref() { + this.refTrace('refcount ' + this.refcount + ' -> ' + (this.refcount + 1)); + this.refcount += 1; + } + + unref() { + this.refTrace('refcount ' + this.refcount + ' -> ' + (this.refcount - 1)); + this.refcount -= 1; + if (this.refcount === 0) { + this.channelzTrace.addTrace('CT_INFO', 'Shutting down'); + unregisterChannelzRef(this.channelzRef); + process.nextTick(() => { + this.transitionToState( + [ConnectivityState.CONNECTING, ConnectivityState.READY], + ConnectivityState.IDLE + ); + }); + } + } + + unrefIfOneRef(): boolean { + if (this.refcount === 1) { + this.unref(); + return true; + } + return false; + } + + createCall( + metadata: Metadata, + host: string, + method: string, + listener: SubchannelCallInterceptingListener + ): SubchannelCall { + if (!this.transport) { + throw new Error('Cannot create call, subchannel not READY'); + } + let statsTracker: Partial; + if (this.channelzEnabled) { + this.callTracker.addCallStarted(); + this.streamTracker.addCallStarted(); + statsTracker = { + onCallEnd: status => { + if (status.code === Status.OK) { + this.callTracker.addCallSucceeded(); + } else { + this.callTracker.addCallFailed(); + } + }, + }; + } else { + statsTracker = {}; + } + return this.transport.createCall( + metadata, + host, + method, + listener, + statsTracker + ); + } + + /** + * If the subchannel is currently IDLE, start connecting and switch to the + * CONNECTING state. If the subchannel is current in TRANSIENT_FAILURE, + * the next time it would transition to IDLE, start connecting again instead. + * Otherwise, do nothing. + */ + startConnecting() { + process.nextTick(() => { + /* First, try to transition from IDLE to connecting. If that doesn't happen + * because the state is not currently IDLE, check if it is + * TRANSIENT_FAILURE, and if so indicate that it should go back to + * connecting after the backoff timer ends. Otherwise do nothing */ + if ( + !this.transitionToState( + [ConnectivityState.IDLE], + ConnectivityState.CONNECTING + ) + ) { + if (this.connectivityState === ConnectivityState.TRANSIENT_FAILURE) { + this.continueConnecting = true; + } + } + }); + } + + /** + * Get the subchannel's current connectivity state. + */ + getConnectivityState() { + return this.connectivityState; + } + + /** + * Add a listener function to be called whenever the subchannel's + * connectivity state changes. + * @param listener + */ + addConnectivityStateListener(listener: ConnectivityStateListener) { + this.stateListeners.add(listener); + } + + /** + * Remove a listener previously added with `addConnectivityStateListener` + * @param listener A reference to a function previously passed to + * `addConnectivityStateListener` + */ + removeConnectivityStateListener(listener: ConnectivityStateListener) { + this.stateListeners.delete(listener); + } + + /** + * Reset the backoff timeout, and immediately start connecting if in backoff. + */ + resetBackoff() { + process.nextTick(() => { + this.backoffTimeout.reset(); + this.transitionToState( + [ConnectivityState.TRANSIENT_FAILURE], + ConnectivityState.CONNECTING + ); + }); + } + + getAddress(): string { + return this.subchannelAddressString; + } + + getChannelzRef(): SubchannelRef { + return this.channelzRef; + } + + isHealthy(): boolean { + return true; + } + + addHealthStateWatcher(listener: (healthy: boolean) => void): void { + // Do nothing with the listener + } + + removeHealthStateWatcher(listener: (healthy: boolean) => void): void { + // Do nothing with the listener + } + + getRealSubchannel(): this { + return this; + } + + realSubchannelEquals(other: SubchannelInterface): boolean { + return other.getRealSubchannel() === this; + } + + throttleKeepalive(newKeepaliveTime: number) { + if (newKeepaliveTime > this.keepaliveTime) { + this.keepaliveTime = newKeepaliveTime; + } + } +} diff --git a/node_modules/@grpc/grpc-js/src/tls-helpers.ts b/node_modules/@grpc/grpc-js/src/tls-helpers.ts new file mode 100644 index 0000000..3f7a62e --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/tls-helpers.ts @@ -0,0 +1,35 @@ +/* + * Copyright 2019 gRPC authors. + * + * 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. + * + */ + +import * as fs from 'fs'; + +export const CIPHER_SUITES: string | undefined = + process.env.GRPC_SSL_CIPHER_SUITES; + +const DEFAULT_ROOTS_FILE_PATH = process.env.GRPC_DEFAULT_SSL_ROOTS_FILE_PATH; + +let defaultRootsData: Buffer | null = null; + +export function getDefaultRootsData(): Buffer | null { + if (DEFAULT_ROOTS_FILE_PATH) { + if (defaultRootsData === null) { + defaultRootsData = fs.readFileSync(DEFAULT_ROOTS_FILE_PATH); + } + return defaultRootsData; + } + return null; +} diff --git a/node_modules/@grpc/grpc-js/src/transport.ts b/node_modules/@grpc/grpc-js/src/transport.ts new file mode 100644 index 0000000..66a5d45 --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/transport.ts @@ -0,0 +1,848 @@ +/* + * Copyright 2023 gRPC authors. + * + * 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. + * + */ + +import * as http2 from 'http2'; +import { + checkServerIdentity, + CipherNameAndProtocol, + ConnectionOptions, + PeerCertificate, + TLSSocket, +} from 'tls'; +import { PartialStatusObject } from './call-interface'; +import { ChannelCredentials } from './channel-credentials'; +import { ChannelOptions } from './channel-options'; +import { + ChannelzCallTracker, + ChannelzCallTrackerStub, + registerChannelzSocket, + SocketInfo, + SocketRef, + TlsInfo, + unregisterChannelzRef, +} from './channelz'; +import { LogVerbosity } from './constants'; +import { getProxiedConnection, ProxyConnectionResult } from './http_proxy'; +import * as logging from './logging'; +import { getDefaultAuthority } from './resolver'; +import { + stringToSubchannelAddress, + SubchannelAddress, + subchannelAddressToString, +} from './subchannel-address'; +import { GrpcUri, parseUri, splitHostPort, uriToString } from './uri-parser'; +import * as net from 'net'; +import { + Http2SubchannelCall, + SubchannelCall, + SubchannelCallInterceptingListener, +} from './subchannel-call'; +import { Metadata } from './metadata'; +import { getNextCallNumber } from './call-number'; + +const TRACER_NAME = 'transport'; +const FLOW_CONTROL_TRACER_NAME = 'transport_flowctrl'; + +const clientVersion = require('../../package.json').version; + +const { + HTTP2_HEADER_AUTHORITY, + HTTP2_HEADER_CONTENT_TYPE, + HTTP2_HEADER_METHOD, + HTTP2_HEADER_PATH, + HTTP2_HEADER_TE, + HTTP2_HEADER_USER_AGENT, +} = http2.constants; + +const KEEPALIVE_TIMEOUT_MS = 20000; + +export interface CallEventTracker { + addMessageSent(): void; + addMessageReceived(): void; + onCallEnd(status: PartialStatusObject): void; + onStreamEnd(success: boolean): void; +} + +export interface TransportDisconnectListener { + (tooManyPings: boolean): void; +} + +export interface Transport { + getChannelzRef(): SocketRef; + getPeerName(): string; + createCall( + metadata: Metadata, + host: string, + method: string, + listener: SubchannelCallInterceptingListener, + subchannelCallStatsTracker: Partial + ): SubchannelCall; + addDisconnectListener(listener: TransportDisconnectListener): void; + shutdown(): void; +} + +const tooManyPingsData: Buffer = Buffer.from('too_many_pings', 'ascii'); + +class Http2Transport implements Transport { + /** + * The amount of time in between sending pings + */ + private keepaliveTimeMs = -1; + /** + * The amount of time to wait for an acknowledgement after sending a ping + */ + private keepaliveTimeoutMs: number = KEEPALIVE_TIMEOUT_MS; + /** + * Timer reference for timeout that indicates when to send the next ping + */ + private keepaliveTimerId: NodeJS.Timeout | null = null; + /** + * Indicates that the keepalive timer ran out while there were no active + * calls, and a ping should be sent the next time a call starts. + */ + private pendingSendKeepalivePing = false; + /** + * Timer reference tracking when the most recent ping will be considered lost + */ + private keepaliveTimeoutId: NodeJS.Timeout | null = null; + /** + * Indicates whether keepalive pings should be sent without any active calls + */ + private keepaliveWithoutCalls = false; + + private userAgent: string; + + private activeCalls: Set = new Set(); + + private subchannelAddressString: string; + + private disconnectListeners: TransportDisconnectListener[] = []; + + private disconnectHandled = false; + + // Channelz info + private channelzRef: SocketRef; + private readonly channelzEnabled: boolean = true; + private streamTracker: ChannelzCallTracker | ChannelzCallTrackerStub; + private keepalivesSent = 0; + private messagesSent = 0; + private messagesReceived = 0; + private lastMessageSentTimestamp: Date | null = null; + private lastMessageReceivedTimestamp: Date | null = null; + + constructor( + private session: http2.ClientHttp2Session, + subchannelAddress: SubchannelAddress, + options: ChannelOptions, + /** + * Name of the remote server, if it is not the same as the subchannel + * address, i.e. if connecting through an HTTP CONNECT proxy. + */ + private remoteName: string | null + ) { + /* Populate subchannelAddressString and channelzRef before doing anything + * else, because they are used in the trace methods. */ + this.subchannelAddressString = subchannelAddressToString(subchannelAddress); + + if (options['grpc.enable_channelz'] === 0) { + this.channelzEnabled = false; + this.streamTracker = new ChannelzCallTrackerStub(); + } else { + this.streamTracker = new ChannelzCallTracker(); + } + + this.channelzRef = registerChannelzSocket( + this.subchannelAddressString, + () => this.getChannelzInfo(), + this.channelzEnabled + ); + + // Build user-agent string. + this.userAgent = [ + options['grpc.primary_user_agent'], + `grpc-node-js/${clientVersion}`, + options['grpc.secondary_user_agent'], + ] + .filter(e => e) + .join(' '); // remove falsey values first + + if ('grpc.keepalive_time_ms' in options) { + this.keepaliveTimeMs = options['grpc.keepalive_time_ms']!; + } + if ('grpc.keepalive_timeout_ms' in options) { + this.keepaliveTimeoutMs = options['grpc.keepalive_timeout_ms']!; + } + if ('grpc.keepalive_permit_without_calls' in options) { + this.keepaliveWithoutCalls = + options['grpc.keepalive_permit_without_calls'] === 1; + } else { + this.keepaliveWithoutCalls = false; + } + + session.once('close', () => { + this.trace('session closed'); + this.stopKeepalivePings(); + this.handleDisconnect(); + }); + + session.once( + 'goaway', + (errorCode: number, lastStreamID: number, opaqueData?: Buffer) => { + let tooManyPings = false; + /* See the last paragraph of + * https://github.com/grpc/proposal/blob/master/A8-client-side-keepalive.md#basic-keepalive */ + if ( + errorCode === http2.constants.NGHTTP2_ENHANCE_YOUR_CALM && + opaqueData && + opaqueData.equals(tooManyPingsData) + ) { + tooManyPings = true; + } + this.trace( + 'connection closed by GOAWAY with code ' + + errorCode + + ' and data ' + + opaqueData?.toString() + ); + this.reportDisconnectToOwner(tooManyPings); + } + ); + + session.once('error', error => { + /* Do nothing here. Any error should also trigger a close event, which is + * where we want to handle that. */ + this.trace('connection closed with error ' + (error as Error).message); + }); + + if (logging.isTracerEnabled(TRACER_NAME)) { + session.on('remoteSettings', (settings: http2.Settings) => { + this.trace( + 'new settings received' + + (this.session !== session ? ' on the old connection' : '') + + ': ' + + JSON.stringify(settings) + ); + }); + session.on('localSettings', (settings: http2.Settings) => { + this.trace( + 'local settings acknowledged by remote' + + (this.session !== session ? ' on the old connection' : '') + + ': ' + + JSON.stringify(settings) + ); + }); + } + + /* Start the keepalive timer last, because this can trigger trace logs, + * which should only happen after everything else is set up. */ + if (this.keepaliveWithoutCalls) { + this.maybeStartKeepalivePingTimer(); + } + } + + private getChannelzInfo(): SocketInfo { + const sessionSocket = this.session.socket; + const remoteAddress = sessionSocket.remoteAddress + ? stringToSubchannelAddress( + sessionSocket.remoteAddress, + sessionSocket.remotePort + ) + : null; + const localAddress = sessionSocket.localAddress + ? stringToSubchannelAddress( + sessionSocket.localAddress, + sessionSocket.localPort + ) + : null; + let tlsInfo: TlsInfo | null; + if (this.session.encrypted) { + const tlsSocket: TLSSocket = sessionSocket as TLSSocket; + const cipherInfo: CipherNameAndProtocol & { standardName?: string } = + tlsSocket.getCipher(); + const certificate = tlsSocket.getCertificate(); + const peerCertificate = tlsSocket.getPeerCertificate(); + tlsInfo = { + cipherSuiteStandardName: cipherInfo.standardName ?? null, + cipherSuiteOtherName: cipherInfo.standardName ? null : cipherInfo.name, + localCertificate: + certificate && 'raw' in certificate ? certificate.raw : null, + remoteCertificate: + peerCertificate && 'raw' in peerCertificate + ? peerCertificate.raw + : null, + }; + } else { + tlsInfo = null; + } + const socketInfo: SocketInfo = { + remoteAddress: remoteAddress, + localAddress: localAddress, + security: tlsInfo, + remoteName: this.remoteName, + streamsStarted: this.streamTracker.callsStarted, + streamsSucceeded: this.streamTracker.callsSucceeded, + streamsFailed: this.streamTracker.callsFailed, + messagesSent: this.messagesSent, + messagesReceived: this.messagesReceived, + keepAlivesSent: this.keepalivesSent, + lastLocalStreamCreatedTimestamp: + this.streamTracker.lastCallStartedTimestamp, + lastRemoteStreamCreatedTimestamp: null, + lastMessageSentTimestamp: this.lastMessageSentTimestamp, + lastMessageReceivedTimestamp: this.lastMessageReceivedTimestamp, + localFlowControlWindow: this.session.state.localWindowSize ?? null, + remoteFlowControlWindow: this.session.state.remoteWindowSize ?? null, + }; + return socketInfo; + } + + private trace(text: string): void { + logging.trace( + LogVerbosity.DEBUG, + TRACER_NAME, + '(' + + this.channelzRef.id + + ') ' + + this.subchannelAddressString + + ' ' + + text + ); + } + + private keepaliveTrace(text: string): void { + logging.trace( + LogVerbosity.DEBUG, + 'keepalive', + '(' + + this.channelzRef.id + + ') ' + + this.subchannelAddressString + + ' ' + + text + ); + } + + private flowControlTrace(text: string): void { + logging.trace( + LogVerbosity.DEBUG, + FLOW_CONTROL_TRACER_NAME, + '(' + + this.channelzRef.id + + ') ' + + this.subchannelAddressString + + ' ' + + text + ); + } + + private internalsTrace(text: string): void { + logging.trace( + LogVerbosity.DEBUG, + 'transport_internals', + '(' + + this.channelzRef.id + + ') ' + + this.subchannelAddressString + + ' ' + + text + ); + } + + /** + * Indicate to the owner of this object that this transport should no longer + * be used. That happens if the connection drops, or if the server sends a + * GOAWAY. + * @param tooManyPings If true, this was triggered by a GOAWAY with data + * indicating that the session was closed becaues the client sent too many + * pings. + * @returns + */ + private reportDisconnectToOwner(tooManyPings: boolean) { + if (this.disconnectHandled) { + return; + } + this.disconnectHandled = true; + this.disconnectListeners.forEach(listener => listener(tooManyPings)); + } + + /** + * Handle connection drops, but not GOAWAYs. + */ + private handleDisconnect() { + this.reportDisconnectToOwner(false); + /* Give calls an event loop cycle to finish naturally before reporting the + * disconnnection to them. */ + setImmediate(() => { + for (const call of this.activeCalls) { + call.onDisconnect(); + } + }); + } + + addDisconnectListener(listener: TransportDisconnectListener): void { + this.disconnectListeners.push(listener); + } + + private clearKeepaliveTimer() { + if (!this.keepaliveTimerId) { + return; + } + clearTimeout(this.keepaliveTimerId); + this.keepaliveTimerId = null; + } + + private clearKeepaliveTimeout() { + if (!this.keepaliveTimeoutId) { + return; + } + clearTimeout(this.keepaliveTimeoutId); + this.keepaliveTimeoutId = null; + } + + private canSendPing() { + return ( + this.keepaliveTimeMs > 0 && + (this.keepaliveWithoutCalls || this.activeCalls.size > 0) + ); + } + + private maybeSendPing() { + this.clearKeepaliveTimer(); + if (!this.canSendPing()) { + this.pendingSendKeepalivePing = true; + return; + } + if (this.channelzEnabled) { + this.keepalivesSent += 1; + } + this.keepaliveTrace( + 'Sending ping with timeout ' + this.keepaliveTimeoutMs + 'ms' + ); + if (!this.keepaliveTimeoutId) { + this.keepaliveTimeoutId = setTimeout(() => { + this.keepaliveTrace('Ping timeout passed without response'); + this.handleDisconnect(); + }, this.keepaliveTimeoutMs); + this.keepaliveTimeoutId.unref?.(); + } + try { + this.session!.ping( + (err: Error | null, duration: number, payload: Buffer) => { + if (err) { + this.keepaliveTrace('Ping failed with error ' + err.message); + this.handleDisconnect(); + } + this.keepaliveTrace('Received ping response'); + this.clearKeepaliveTimeout(); + this.maybeStartKeepalivePingTimer(); + } + ); + } catch (e) { + /* If we fail to send a ping, the connection is no longer functional, so + * we should discard it. */ + this.handleDisconnect(); + } + } + + /** + * Starts the keepalive ping timer if appropriate. If the timer already ran + * out while there were no active requests, instead send a ping immediately. + * If the ping timer is already running or a ping is currently in flight, + * instead do nothing and wait for them to resolve. + */ + private maybeStartKeepalivePingTimer() { + if (!this.canSendPing()) { + return; + } + if (this.pendingSendKeepalivePing) { + this.pendingSendKeepalivePing = false; + this.maybeSendPing(); + } else if (!this.keepaliveTimerId && !this.keepaliveTimeoutId) { + this.keepaliveTrace( + 'Starting keepalive timer for ' + this.keepaliveTimeMs + 'ms' + ); + this.keepaliveTimerId = setTimeout(() => { + this.maybeSendPing(); + }, this.keepaliveTimeMs); + this.keepaliveTimerId.unref?.(); + } + /* Otherwise, there is already either a keepalive timer or a ping pending, + * wait for those to resolve. */ + } + + private stopKeepalivePings() { + if (this.keepaliveTimerId) { + clearTimeout(this.keepaliveTimerId); + this.keepaliveTimerId = null; + } + this.clearKeepaliveTimeout(); + } + + private removeActiveCall(call: Http2SubchannelCall) { + this.activeCalls.delete(call); + if (this.activeCalls.size === 0) { + this.session.unref(); + } + } + + private addActiveCall(call: Http2SubchannelCall) { + this.activeCalls.add(call); + if (this.activeCalls.size === 1) { + this.session.ref(); + if (!this.keepaliveWithoutCalls) { + this.maybeStartKeepalivePingTimer(); + } + } + } + + createCall( + metadata: Metadata, + host: string, + method: string, + listener: SubchannelCallInterceptingListener, + subchannelCallStatsTracker: Partial + ): Http2SubchannelCall { + const headers = metadata.toHttp2Headers(); + headers[HTTP2_HEADER_AUTHORITY] = host; + headers[HTTP2_HEADER_USER_AGENT] = this.userAgent; + headers[HTTP2_HEADER_CONTENT_TYPE] = 'application/grpc'; + headers[HTTP2_HEADER_METHOD] = 'POST'; + headers[HTTP2_HEADER_PATH] = method; + headers[HTTP2_HEADER_TE] = 'trailers'; + let http2Stream: http2.ClientHttp2Stream; + /* In theory, if an error is thrown by session.request because session has + * become unusable (e.g. because it has received a goaway), this subchannel + * should soon see the corresponding close or goaway event anyway and leave + * READY. But we have seen reports that this does not happen + * (https://github.com/googleapis/nodejs-firestore/issues/1023#issuecomment-653204096) + * so for defense in depth, we just discard the session when we see an + * error here. + */ + try { + http2Stream = this.session!.request(headers); + } catch (e) { + this.handleDisconnect(); + throw e; + } + this.flowControlTrace( + 'local window size: ' + + this.session.state.localWindowSize + + ' remote window size: ' + + this.session.state.remoteWindowSize + ); + this.internalsTrace( + 'session.closed=' + + this.session.closed + + ' session.destroyed=' + + this.session.destroyed + + ' session.socket.destroyed=' + + this.session.socket.destroyed + ); + let eventTracker: CallEventTracker; + // eslint-disable-next-line prefer-const + let call: Http2SubchannelCall; + if (this.channelzEnabled) { + this.streamTracker.addCallStarted(); + eventTracker = { + addMessageSent: () => { + this.messagesSent += 1; + this.lastMessageSentTimestamp = new Date(); + subchannelCallStatsTracker.addMessageSent?.(); + }, + addMessageReceived: () => { + this.messagesReceived += 1; + this.lastMessageReceivedTimestamp = new Date(); + subchannelCallStatsTracker.addMessageReceived?.(); + }, + onCallEnd: status => { + subchannelCallStatsTracker.onCallEnd?.(status); + this.removeActiveCall(call); + }, + onStreamEnd: success => { + if (success) { + this.streamTracker.addCallSucceeded(); + } else { + this.streamTracker.addCallFailed(); + } + subchannelCallStatsTracker.onStreamEnd?.(success); + }, + }; + } else { + eventTracker = { + addMessageSent: () => { + subchannelCallStatsTracker.addMessageSent?.(); + }, + addMessageReceived: () => { + subchannelCallStatsTracker.addMessageReceived?.(); + }, + onCallEnd: status => { + subchannelCallStatsTracker.onCallEnd?.(status); + this.removeActiveCall(call); + }, + onStreamEnd: success => { + subchannelCallStatsTracker.onStreamEnd?.(success); + }, + }; + } + call = new Http2SubchannelCall( + http2Stream, + eventTracker, + listener, + this, + getNextCallNumber() + ); + this.addActiveCall(call); + return call; + } + + getChannelzRef(): SocketRef { + return this.channelzRef; + } + + getPeerName() { + return this.subchannelAddressString; + } + + shutdown() { + this.session.close(); + unregisterChannelzRef(this.channelzRef); + } +} + +export interface SubchannelConnector { + connect( + address: SubchannelAddress, + credentials: ChannelCredentials, + options: ChannelOptions + ): Promise; + shutdown(): void; +} + +export class Http2SubchannelConnector implements SubchannelConnector { + private session: http2.ClientHttp2Session | null = null; + private isShutdown = false; + constructor(private channelTarget: GrpcUri) {} + + private trace(text: string) { + logging.trace( + LogVerbosity.DEBUG, + TRACER_NAME, + uriToString(this.channelTarget) + ' ' + text + ); + } + + private createSession( + address: SubchannelAddress, + credentials: ChannelCredentials, + options: ChannelOptions, + proxyConnectionResult: ProxyConnectionResult + ): Promise { + if (this.isShutdown) { + return Promise.reject(); + } + + return new Promise((resolve, reject) => { + let remoteName: string | null; + if (proxyConnectionResult.realTarget) { + remoteName = uriToString(proxyConnectionResult.realTarget); + this.trace( + 'creating HTTP/2 session through proxy to ' + + uriToString(proxyConnectionResult.realTarget) + ); + } else { + remoteName = null; + this.trace( + 'creating HTTP/2 session to ' + subchannelAddressToString(address) + ); + } + const targetAuthority = getDefaultAuthority( + proxyConnectionResult.realTarget ?? this.channelTarget + ); + let connectionOptions: http2.SecureClientSessionOptions = + credentials._getConnectionOptions() || {}; + connectionOptions.maxSendHeaderBlockLength = Number.MAX_SAFE_INTEGER; + if ('grpc-node.max_session_memory' in options) { + connectionOptions.maxSessionMemory = + options['grpc-node.max_session_memory']; + } else { + /* By default, set a very large max session memory limit, to effectively + * disable enforcement of the limit. Some testing indicates that Node's + * behavior degrades badly when this limit is reached, so we solve that + * by disabling the check entirely. */ + connectionOptions.maxSessionMemory = Number.MAX_SAFE_INTEGER; + } + let addressScheme = 'http://'; + if ('secureContext' in connectionOptions) { + addressScheme = 'https://'; + // If provided, the value of grpc.ssl_target_name_override should be used + // to override the target hostname when checking server identity. + // This option is used for testing only. + if (options['grpc.ssl_target_name_override']) { + const sslTargetNameOverride = + options['grpc.ssl_target_name_override']!; + const originalCheckServerIdentity = + connectionOptions.checkServerIdentity ?? checkServerIdentity; + connectionOptions.checkServerIdentity = ( + host: string, + cert: PeerCertificate + ): Error | undefined => { + return originalCheckServerIdentity(sslTargetNameOverride, cert); + }; + connectionOptions.servername = sslTargetNameOverride; + } else { + const authorityHostname = + splitHostPort(targetAuthority)?.host ?? 'localhost'; + // We want to always set servername to support SNI + connectionOptions.servername = authorityHostname; + } + if (proxyConnectionResult.socket) { + /* This is part of the workaround for + * https://github.com/nodejs/node/issues/32922. Without that bug, + * proxyConnectionResult.socket would always be a plaintext socket and + * this would say + * connectionOptions.socket = proxyConnectionResult.socket; */ + connectionOptions.createConnection = (authority, option) => { + return proxyConnectionResult.socket!; + }; + } + } else { + /* In all but the most recent versions of Node, http2.connect does not use + * the options when establishing plaintext connections, so we need to + * establish that connection explicitly. */ + connectionOptions.createConnection = (authority, option) => { + if (proxyConnectionResult.socket) { + return proxyConnectionResult.socket; + } else { + /* net.NetConnectOpts is declared in a way that is more restrictive + * than what net.connect will actually accept, so we use the type + * assertion to work around that. */ + return net.connect(address); + } + }; + } + + connectionOptions = { + ...connectionOptions, + ...address, + enableTrace: options['grpc-node.tls_enable_trace'] === 1, + }; + + /* http2.connect uses the options here: + * https://github.com/nodejs/node/blob/70c32a6d190e2b5d7b9ff9d5b6a459d14e8b7d59/lib/internal/http2/core.js#L3028-L3036 + * The spread operator overides earlier values with later ones, so any port + * or host values in the options will be used rather than any values extracted + * from the first argument. In addition, the path overrides the host and port, + * as documented for plaintext connections here: + * https://nodejs.org/api/net.html#net_socket_connect_options_connectlistener + * and for TLS connections here: + * https://nodejs.org/api/tls.html#tls_tls_connect_options_callback. In + * earlier versions of Node, http2.connect passes these options to + * tls.connect but not net.connect, so in the insecure case we still need + * to set the createConnection option above to create the connection + * explicitly. We cannot do that in the TLS case because http2.connect + * passes necessary additional options to tls.connect. + * The first argument just needs to be parseable as a URL and the scheme + * determines whether the connection will be established over TLS or not. + */ + const session = http2.connect( + addressScheme + targetAuthority, + connectionOptions + ); + this.session = session; + let errorMessage = 'Failed to connect'; + session.unref(); + session.once('connect', () => { + session.removeAllListeners(); + resolve(new Http2Transport(session, address, options, remoteName)); + this.session = null; + }); + session.once('close', () => { + this.session = null; + // Leave time for error event to happen before rejecting + setImmediate(() => { + reject(`${errorMessage} (${new Date().toISOString()})`); + }); + }); + session.once('error', error => { + errorMessage = (error as Error).message; + this.trace('connection failed with error ' + errorMessage); + }); + }); + } + + connect( + address: SubchannelAddress, + credentials: ChannelCredentials, + options: ChannelOptions + ): Promise { + if (this.isShutdown) { + return Promise.reject(); + } + /* Pass connection options through to the proxy so that it's able to + * upgrade it's connection to support tls if needed. + * This is a workaround for https://github.com/nodejs/node/issues/32922 + * See https://github.com/grpc/grpc-node/pull/1369 for more info. */ + const connectionOptions: ConnectionOptions = + credentials._getConnectionOptions() || {}; + + if ('secureContext' in connectionOptions) { + connectionOptions.ALPNProtocols = ['h2']; + // If provided, the value of grpc.ssl_target_name_override should be used + // to override the target hostname when checking server identity. + // This option is used for testing only. + if (options['grpc.ssl_target_name_override']) { + const sslTargetNameOverride = options['grpc.ssl_target_name_override']!; + const originalCheckServerIdentity = + connectionOptions.checkServerIdentity ?? checkServerIdentity; + connectionOptions.checkServerIdentity = ( + host: string, + cert: PeerCertificate + ): Error | undefined => { + return originalCheckServerIdentity(sslTargetNameOverride, cert); + }; + connectionOptions.servername = sslTargetNameOverride; + } else { + if ('grpc.http_connect_target' in options) { + /* This is more or less how servername will be set in createSession + * if a connection is successfully established through the proxy. + * If the proxy is not used, these connectionOptions are discarded + * anyway */ + const targetPath = getDefaultAuthority( + parseUri(options['grpc.http_connect_target'] as string) ?? { + path: 'localhost', + } + ); + const hostPort = splitHostPort(targetPath); + connectionOptions.servername = hostPort?.host ?? targetPath; + } + } + if (options['grpc-node.tls_enable_trace']) { + connectionOptions.enableTrace = true; + } + } + + return getProxiedConnection(address, options, connectionOptions).then( + result => this.createSession(address, credentials, options, result) + ); + } + + shutdown(): void { + this.isShutdown = true; + this.session?.close(); + this.session = null; + } +} diff --git a/node_modules/@grpc/grpc-js/src/uri-parser.ts b/node_modules/@grpc/grpc-js/src/uri-parser.ts new file mode 100644 index 0000000..2b2efec --- /dev/null +++ b/node_modules/@grpc/grpc-js/src/uri-parser.ts @@ -0,0 +1,127 @@ +/* + * Copyright 2020 gRPC authors. + * + * 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. + * + */ + +export interface GrpcUri { + scheme?: string; + authority?: string; + path: string; +} + +/* + * The groups correspond to URI parts as follows: + * 1. scheme + * 2. authority + * 3. path + */ +const URI_REGEX = /^(?:([A-Za-z0-9+.-]+):)?(?:\/\/([^/]*)\/)?(.+)$/; + +export function parseUri(uriString: string): GrpcUri | null { + const parsedUri = URI_REGEX.exec(uriString); + if (parsedUri === null) { + return null; + } + return { + scheme: parsedUri[1], + authority: parsedUri[2], + path: parsedUri[3], + }; +} + +export interface HostPort { + host: string; + port?: number; +} + +const NUMBER_REGEX = /^\d+$/; + +export function splitHostPort(path: string): HostPort | null { + if (path.startsWith('[')) { + const hostEnd = path.indexOf(']'); + if (hostEnd === -1) { + return null; + } + const host = path.substring(1, hostEnd); + /* Only an IPv6 address should be in bracketed notation, and an IPv6 + * address should have at least one colon */ + if (host.indexOf(':') === -1) { + return null; + } + if (path.length > hostEnd + 1) { + if (path[hostEnd + 1] === ':') { + const portString = path.substring(hostEnd + 2); + if (NUMBER_REGEX.test(portString)) { + return { + host: host, + port: +portString, + }; + } else { + return null; + } + } else { + return null; + } + } else { + return { + host, + }; + } + } else { + const splitPath = path.split(':'); + /* Exactly one colon means that this is host:port. Zero colons means that + * there is no port. And multiple colons means that this is a bare IPv6 + * address with no port */ + if (splitPath.length === 2) { + if (NUMBER_REGEX.test(splitPath[1])) { + return { + host: splitPath[0], + port: +splitPath[1], + }; + } else { + return null; + } + } else { + return { + host: path, + }; + } + } +} + +export function combineHostPort(hostPort: HostPort): string { + if (hostPort.port === undefined) { + return hostPort.host; + } else { + // Only an IPv6 host should include a colon + if (hostPort.host.includes(':')) { + return `[${hostPort.host}]:${hostPort.port}`; + } else { + return `${hostPort.host}:${hostPort.port}`; + } + } +} + +export function uriToString(uri: GrpcUri): string { + let result = ''; + if (uri.scheme !== undefined) { + result += uri.scheme + ':'; + } + if (uri.authority !== undefined) { + result += '//' + uri.authority + '/'; + } + result += uri.path; + return result; +} diff --git a/node_modules/@grpc/proto-loader/LICENSE b/node_modules/@grpc/proto-loader/LICENSE new file mode 100644 index 0000000..8dada3e --- /dev/null +++ b/node_modules/@grpc/proto-loader/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright {yyyy} {name of copyright owner} + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/node_modules/@grpc/proto-loader/README.md b/node_modules/@grpc/proto-loader/README.md new file mode 100644 index 0000000..3ee6727 --- /dev/null +++ b/node_modules/@grpc/proto-loader/README.md @@ -0,0 +1,131 @@ +# gRPC Protobuf Loader + +A utility package for loading `.proto` files for use with gRPC, using the latest Protobuf.js package. +Please refer to [protobuf.js' documentation](https://github.com/dcodeIO/protobuf.js/blob/master/README.md) +to understands its features and limitations. + +## Installation + +```sh +npm install @grpc/proto-loader +``` + +## Usage + +```js +const protoLoader = require('@grpc/proto-loader'); +const grpcLibrary = require('grpc'); +// OR +const grpcLibrary = require('@grpc/grpc-js'); + +protoLoader.load(protoFileName, options).then(packageDefinition => { + const packageObject = grpcLibrary.loadPackageDefinition(packageDefinition); +}); +// OR +const packageDefinition = protoLoader.loadSync(protoFileName, options); +const packageObject = grpcLibrary.loadPackageDefinition(packageDefinition); +``` + +The options parameter is an object that can have the following optional properties: + +| Field name | Valid values | Description +|------------|--------------|------------ +| `keepCase` | `true` or `false` | Preserve field names. The default is to change them to camel case. +| `longs` | `String` or `Number` | The type to use to represent `long` values. Defaults to a `Long` object type. +| `enums` | `String` | The type to use to represent `enum` values. Defaults to the numeric value. +| `bytes` | `Array` or `String` | The type to use to represent `bytes` values. Defaults to `Buffer`. +| `defaults` | `true` or `false` | Set default values on output objects. Defaults to `false`. +| `arrays` | `true` or `false` | Set empty arrays for missing array values even if `defaults` is `false` Defaults to `false`. +| `objects` | `true` or `false` | Set empty objects for missing object values even if `defaults` is `false` Defaults to `false`. +| `oneofs` | `true` or `false` | Set virtual oneof properties to the present field's name. Defaults to `false`. +| `json` | `true` or `false` | Represent `Infinity` and `NaN` as strings in `float` fields, and automatically decode `google.protobuf.Any` values. Defaults to `false` +| `includeDirs` | An array of strings | A list of search paths for imported `.proto` files. + +The following options object closely approximates the existing behavior of `grpc.load`: + +```js +const options = { + keepCase: true, + longs: String, + enums: String, + defaults: true, + oneofs: true +} +``` + +## Generating TypeScript types + +The `proto-loader-gen-types` script distributed with this package can be used to generate TypeScript type information for the objects loaded at runtime. More information about how to use it can be found in [the *@grpc/proto-loader TypeScript Type Generator CLI Tool* proposal document](https://github.com/grpc/proposal/blob/master/L70-node-proto-loader-type-generator.md). The arguments mostly match the `load` function's options; the full usage information is as follows: + +```console +proto-loader-gen-types.js [options] filenames... + +Options: + --help Show help [boolean] + --version Show version number [boolean] + --keepCase Preserve the case of field names + [boolean] [default: false] + --longs The type that should be used to output 64 bit integer + values. Can be String, Number[string] [default: "Long"] + --enums The type that should be used to output enum fields. Can + be String [string] [default: "number"] + --bytes The type that should be used to output bytes fields. + Can be String, Array [string] [default: "Buffer"] + --defaults Output default values for omitted fields + [boolean] [default: false] + --arrays Output default values for omitted repeated fields even + if --defaults is not set [boolean] [default: false] + --objects Output default values for omitted message fields even + if --defaults is not set [boolean] [default: false] + --oneofs Output virtual oneof fields set to the present field's + name [boolean] [default: false] + --json Represent Infinity and NaN as strings in float fields. + Also decode google.protobuf.Any automatically + [boolean] [default: false] + --includeComments Generate doc comments from comments in the original + files [boolean] [default: false] + -I, --includeDirs Directories to search for included files [array] + -O, --outDir Directory in which to output files [string] [required] + --grpcLib The gRPC implementation library that these types will + be used with. If not provided, some types will not be + generated [string] + --inputTemplate Template for mapping input or "permissive" type names + [string] [default: "%s"] + --outputTemplate Template for mapping output or "restricted" type names + [string] [default: "%s__Output"] + --inputBranded Output property for branded type for "permissive" + types with fullName of the Message as its value + [boolean] [default: false] + --outputBranded Output property for branded type for "restricted" + types with fullName of the Message as its value + [boolean] [default: false] +``` + +### Example Usage + +Generate the types: + +```sh +$(npm bin)/proto-loader-gen-types --longs=String --enums=String --defaults --oneofs --grpcLib=@grpc/grpc-js --outDir=proto/ proto/*.proto +``` + +Consume the types: + +```ts +import * as grpc from '@grpc/grpc-js'; +import * as protoLoader from '@grpc/proto-loader'; +import type { ProtoGrpcType } from './proto/example.ts'; +import type { ExampleHandlers } from './proto/example_package/Example.ts'; + +const exampleServer: ExampleHandlers = { + // server handlers implementation... +}; + +const packageDefinition = protoLoader.loadSync('./proto/example.proto'); +const proto = (grpc.loadPackageDefinition( + packageDefinition +) as unknown) as ProtoGrpcType; + +const server = new grpc.Server(); +server.addService(proto.example_package.Example.service, exampleServer); +``` diff --git a/node_modules/@grpc/proto-loader/build/bin/proto-loader-gen-types.js b/node_modules/@grpc/proto-loader/build/bin/proto-loader-gen-types.js new file mode 100755 index 0000000..8d6b70d --- /dev/null +++ b/node_modules/@grpc/proto-loader/build/bin/proto-loader-gen-types.js @@ -0,0 +1,909 @@ +#!/usr/bin/env node +"use strict"; +/** + * @license + * Copyright 2020 gRPC authors. + * + * 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. + * + */ +Object.defineProperty(exports, "__esModule", { value: true }); +const fs = require("fs"); +const path = require("path"); +const Protobuf = require("protobufjs"); +const yargs = require("yargs"); +const camelCase = require("lodash.camelcase"); +const util_1 = require("../src/util"); +const templateStr = "%s"; +const useNameFmter = ({ outputTemplate, inputTemplate }) => { + if (outputTemplate === inputTemplate) { + throw new Error('inputTemplate and outputTemplate must differ'); + } + return { + outputName: (n) => outputTemplate.replace(templateStr, n), + inputName: (n) => inputTemplate.replace(templateStr, n) + }; +}; +class TextFormatter { + constructor() { + this.indentText = ' '; + this.indentValue = 0; + this.textParts = []; + } + indent() { + this.indentValue += 1; + } + unindent() { + this.indentValue -= 1; + } + writeLine(line) { + for (let i = 0; i < this.indentValue; i += 1) { + this.textParts.push(this.indentText); + } + this.textParts.push(line); + this.textParts.push('\n'); + } + getFullText() { + return this.textParts.join(''); + } +} +// GENERATOR UTILITY FUNCTIONS +function compareName(x, y) { + if (x.name < y.name) { + return -1; + } + else if (x.name > y.name) { + return 1; + } + else { + return 0; + } +} +function isNamespaceBase(obj) { + return Array.isArray(obj.nestedArray); +} +function stripLeadingPeriod(name) { + return name.startsWith('.') ? name.substring(1) : name; +} +function getImportPath(to) { + /* If the thing we are importing is defined in a message, it is generated in + * the same file as that message. */ + if (to.parent instanceof Protobuf.Type) { + return getImportPath(to.parent); + } + return stripLeadingPeriod(to.fullName).replace(/\./g, '/'); +} +function getPath(to) { + return stripLeadingPeriod(to.fullName).replace(/\./g, '/') + '.ts'; +} +function getPathToRoot(from) { + const depth = stripLeadingPeriod(from.fullName).split('.').length - 1; + if (depth === 0) { + return './'; + } + let path = ''; + for (let i = 0; i < depth; i++) { + path += '../'; + } + return path; +} +function getRelativeImportPath(from, to) { + return getPathToRoot(from) + getImportPath(to); +} +function getTypeInterfaceName(type) { + return type.fullName.replace(/\./g, '_'); +} +function getImportLine(dependency, from, options) { + const filePath = from === undefined ? './' + getImportPath(dependency) : getRelativeImportPath(from, dependency); + const { outputName, inputName } = useNameFmter(options); + const typeInterfaceName = getTypeInterfaceName(dependency); + let importedTypes; + /* If the dependency is defined within a message, it will be generated in that + * message's file and exported using its typeInterfaceName. */ + if (dependency.parent instanceof Protobuf.Type) { + if (dependency instanceof Protobuf.Type || dependency instanceof Protobuf.Enum) { + importedTypes = `${inputName(typeInterfaceName)}, ${outputName(typeInterfaceName)}`; + } + else if (dependency instanceof Protobuf.Service) { + importedTypes = `${typeInterfaceName}Client, ${typeInterfaceName}Definition`; + } + else { + throw new Error('Invalid object passed to getImportLine'); + } + } + else { + if (dependency instanceof Protobuf.Type || dependency instanceof Protobuf.Enum) { + importedTypes = `${inputName(dependency.name)} as ${inputName(typeInterfaceName)}, ${outputName(dependency.name)} as ${outputName(typeInterfaceName)}`; + } + else if (dependency instanceof Protobuf.Service) { + importedTypes = `${dependency.name}Client as ${typeInterfaceName}Client, ${dependency.name}Definition as ${typeInterfaceName}Definition`; + } + else { + throw new Error('Invalid object passed to getImportLine'); + } + } + return `import type { ${importedTypes} } from '${filePath}';`; +} +function getChildMessagesAndEnums(namespace) { + const messageList = []; + for (const nested of namespace.nestedArray) { + if (nested instanceof Protobuf.Type || nested instanceof Protobuf.Enum) { + messageList.push(nested); + } + if (isNamespaceBase(nested)) { + messageList.push(...getChildMessagesAndEnums(nested)); + } + } + return messageList; +} +function formatComment(formatter, comment, options) { + if (!comment && !(options === null || options === void 0 ? void 0 : options.deprecated)) { + return; + } + formatter.writeLine('/**'); + if (comment) { + for (const line of comment.split('\n')) { + formatter.writeLine(` * ${line.replace(/\*\//g, '* /')}`); + } + } + if (options === null || options === void 0 ? void 0 : options.deprecated) { + formatter.writeLine(' * @deprecated'); + } + formatter.writeLine(' */'); +} +const typeBrandHint = `This field is a type brand and is not populated at runtime. Instances of this type should be created using type assertions. +https://github.com/grpc/grpc-node/pull/2281`; +function formatTypeBrand(formatter, messageType) { + formatComment(formatter, typeBrandHint); + formatter.writeLine(`__type: '${messageType.fullName}'`); +} +// GENERATOR FUNCTIONS +function getTypeNamePermissive(fieldType, resolvedType, repeated, map, options) { + const { inputName } = useNameFmter(options); + switch (fieldType) { + case 'double': + case 'float': + return 'number | string'; + case 'int32': + case 'uint32': + case 'sint32': + case 'fixed32': + case 'sfixed32': + return 'number'; + case 'int64': + case 'uint64': + case 'sint64': + case 'fixed64': + case 'sfixed64': + return 'number | string | Long'; + case 'bool': + return 'boolean'; + case 'string': + return 'string'; + case 'bytes': + return 'Buffer | Uint8Array | string'; + default: + if (resolvedType === null) { + throw new Error('Found field with no usable type'); + } + const typeInterfaceName = getTypeInterfaceName(resolvedType); + if (resolvedType instanceof Protobuf.Type) { + if (repeated || map) { + return inputName(typeInterfaceName); + } + else { + return `${inputName(typeInterfaceName)} | null`; + } + } + else { + // Enum + return inputName(typeInterfaceName); + } + } +} +function getFieldTypePermissive(field, options) { + const valueType = getTypeNamePermissive(field.type, field.resolvedType, field.repeated, field.map, options); + if (field instanceof Protobuf.MapField) { + const keyType = field.keyType === 'string' ? 'string' : 'number'; + return `{[key: ${keyType}]: ${valueType}}`; + } + else { + return valueType; + } +} +function generatePermissiveMessageInterface(formatter, messageType, options, nameOverride) { + const { inputName } = useNameFmter(options); + if (options.includeComments) { + formatComment(formatter, messageType.comment, messageType.options); + } + if (messageType.fullName === '.google.protobuf.Any') { + /* This describes the behavior of the Protobuf.js Any wrapper fromObject + * replacement function */ + formatter.writeLine(`export type ${inputName('Any')} = AnyExtension | {`); + formatter.writeLine(' type_url: string;'); + formatter.writeLine(' value: Buffer | Uint8Array | string;'); + formatter.writeLine('}'); + return; + } + formatter.writeLine(`export interface ${inputName(nameOverride !== null && nameOverride !== void 0 ? nameOverride : messageType.name)} {`); + formatter.indent(); + for (const field of messageType.fieldsArray) { + const repeatedString = field.repeated ? '[]' : ''; + const type = getFieldTypePermissive(field, options); + if (options.includeComments) { + formatComment(formatter, field.comment, field.options); + } + formatter.writeLine(`'${field.name}'?: (${type})${repeatedString};`); + } + for (const oneof of messageType.oneofsArray) { + const typeString = oneof.fieldsArray.map(field => `"${field.name}"`).join('|'); + if (options.includeComments) { + formatComment(formatter, oneof.comment, oneof.options); + } + formatter.writeLine(`'${oneof.name}'?: ${typeString};`); + } + if (options.inputBranded) { + formatTypeBrand(formatter, messageType); + } + formatter.unindent(); + formatter.writeLine('}'); +} +function getTypeNameRestricted(fieldType, resolvedType, repeated, map, options) { + const { outputName } = useNameFmter(options); + switch (fieldType) { + case 'double': + case 'float': + if (options.json) { + return 'number | string'; + } + else { + return 'number'; + } + case 'int32': + case 'uint32': + case 'sint32': + case 'fixed32': + case 'sfixed32': + return 'number'; + case 'int64': + case 'uint64': + case 'sint64': + case 'fixed64': + case 'sfixed64': + if (options.longs === Number) { + return 'number'; + } + else if (options.longs === String) { + return 'string'; + } + else { + return 'Long'; + } + case 'bool': + return 'boolean'; + case 'string': + return 'string'; + case 'bytes': + if (options.bytes === Array) { + return 'Uint8Array'; + } + else if (options.bytes === String) { + return 'string'; + } + else { + return 'Buffer'; + } + default: + if (resolvedType === null) { + throw new Error('Found field with no usable type'); + } + const typeInterfaceName = getTypeInterfaceName(resolvedType); + if (resolvedType instanceof Protobuf.Type) { + /* null is only used to represent absent message values if the defaults + * option is set, and only for non-repeated, non-map fields. */ + if (options.defaults && !repeated && !map) { + return `${outputName(typeInterfaceName)} | null`; + } + else { + return `${outputName(typeInterfaceName)}`; + } + } + else { + // Enum + return outputName(typeInterfaceName); + } + } +} +function getFieldTypeRestricted(field, options) { + const valueType = getTypeNameRestricted(field.type, field.resolvedType, field.repeated, field.map, options); + if (field instanceof Protobuf.MapField) { + const keyType = field.keyType === 'string' ? 'string' : 'number'; + return `{[key: ${keyType}]: ${valueType}}`; + } + else { + return valueType; + } +} +function generateRestrictedMessageInterface(formatter, messageType, options, nameOverride) { + var _a, _b, _c; + const { outputName } = useNameFmter(options); + if (options.includeComments) { + formatComment(formatter, messageType.comment, messageType.options); + } + if (messageType.fullName === '.google.protobuf.Any' && options.json) { + /* This describes the behavior of the Protobuf.js Any wrapper toObject + * replacement function */ + let optionalString = options.defaults ? '' : '?'; + formatter.writeLine(`export type ${outputName('Any')} = AnyExtension | {`); + formatter.writeLine(` type_url${optionalString}: string;`); + formatter.writeLine(` value${optionalString}: ${getTypeNameRestricted('bytes', null, false, false, options)};`); + formatter.writeLine('}'); + return; + } + formatter.writeLine(`export interface ${outputName(nameOverride !== null && nameOverride !== void 0 ? nameOverride : messageType.name)} {`); + formatter.indent(); + for (const field of messageType.fieldsArray) { + let fieldGuaranteed; + if (field.partOf) { + // The field is not guaranteed populated if it is part of a oneof + fieldGuaranteed = false; + } + else if (field.repeated) { + fieldGuaranteed = (_a = (options.defaults || options.arrays)) !== null && _a !== void 0 ? _a : false; + } + else if (field.map) { + fieldGuaranteed = (_b = (options.defaults || options.objects)) !== null && _b !== void 0 ? _b : false; + } + else { + fieldGuaranteed = (_c = options.defaults) !== null && _c !== void 0 ? _c : false; + } + const optionalString = fieldGuaranteed ? '' : '?'; + const repeatedString = field.repeated ? '[]' : ''; + const type = getFieldTypeRestricted(field, options); + if (options.includeComments) { + formatComment(formatter, field.comment, field.options); + } + formatter.writeLine(`'${field.name}'${optionalString}: (${type})${repeatedString};`); + } + if (options.oneofs) { + for (const oneof of messageType.oneofsArray) { + const typeString = oneof.fieldsArray.map(field => `"${field.name}"`).join('|'); + if (options.includeComments) { + formatComment(formatter, oneof.comment, oneof.options); + } + formatter.writeLine(`'${oneof.name}': ${typeString};`); + } + } + if (options.outputBranded) { + formatTypeBrand(formatter, messageType); + } + formatter.unindent(); + formatter.writeLine('}'); +} +function generateMessageInterfaces(formatter, messageType, options) { + var _a, _b; + let usesLong = false; + let seenDeps = new Set(); + const childTypes = getChildMessagesAndEnums(messageType); + formatter.writeLine(`// Original file: ${(_b = ((_a = messageType.filename) !== null && _a !== void 0 ? _a : 'null')) === null || _b === void 0 ? void 0 : _b.replace(/\\/g, '/')}`); + formatter.writeLine(''); + const isLongField = (field) => ['int64', 'uint64', 'sint64', 'fixed64', 'sfixed64'].includes(field.type); + messageType.fieldsArray.sort((fieldA, fieldB) => fieldA.id - fieldB.id); + for (const field of messageType.fieldsArray) { + if (field.resolvedType && childTypes.indexOf(field.resolvedType) < 0) { + const dependency = field.resolvedType; + if (seenDeps.has(dependency.fullName)) { + continue; + } + seenDeps.add(dependency.fullName); + formatter.writeLine(getImportLine(dependency, messageType, options)); + } + if (isLongField(field)) { + usesLong = true; + } + } + for (const childType of childTypes) { + if (childType instanceof Protobuf.Type) { + for (const field of childType.fieldsArray) { + if (field.resolvedType && childTypes.indexOf(field.resolvedType) < 0) { + const dependency = field.resolvedType; + if (seenDeps.has(dependency.fullName)) { + continue; + } + seenDeps.add(dependency.fullName); + formatter.writeLine(getImportLine(dependency, messageType, options)); + } + if (isLongField(field)) { + usesLong = true; + } + } + } + } + if (usesLong) { + formatter.writeLine("import type { Long } from '@grpc/proto-loader';"); + } + if (messageType.fullName === '.google.protobuf.Any') { + formatter.writeLine("import type { AnyExtension } from '@grpc/proto-loader';"); + } + formatter.writeLine(''); + for (const childType of childTypes.sort(compareName)) { + const nameOverride = getTypeInterfaceName(childType); + if (childType instanceof Protobuf.Type) { + generatePermissiveMessageInterface(formatter, childType, options, nameOverride); + formatter.writeLine(''); + generateRestrictedMessageInterface(formatter, childType, options, nameOverride); + } + else { + generateEnumInterface(formatter, childType, options, nameOverride); + } + formatter.writeLine(''); + } + generatePermissiveMessageInterface(formatter, messageType, options); + formatter.writeLine(''); + generateRestrictedMessageInterface(formatter, messageType, options); +} +function generateEnumInterface(formatter, enumType, options, nameOverride) { + var _a, _b, _c; + const { inputName, outputName } = useNameFmter(options); + const name = nameOverride !== null && nameOverride !== void 0 ? nameOverride : enumType.name; + formatter.writeLine(`// Original file: ${(_b = ((_a = enumType.filename) !== null && _a !== void 0 ? _a : 'null')) === null || _b === void 0 ? void 0 : _b.replace(/\\/g, '/')}`); + formatter.writeLine(''); + if (options.includeComments) { + formatComment(formatter, enumType.comment, enumType.options); + } + formatter.writeLine(`export const ${name} = {`); + formatter.indent(); + for (const key of Object.keys(enumType.values)) { + if (options.includeComments) { + formatComment(formatter, enumType.comments[key], ((_c = enumType.valuesOptions) !== null && _c !== void 0 ? _c : {})[key]); + } + formatter.writeLine(`${key}: ${options.enums == String ? `'${key}'` : enumType.values[key]},`); + } + formatter.unindent(); + formatter.writeLine('} as const;'); + // Permissive Type + formatter.writeLine(''); + if (options.includeComments) { + formatComment(formatter, enumType.comment, enumType.options); + } + formatter.writeLine(`export type ${inputName(name)} =`); + formatter.indent(); + for (const key of Object.keys(enumType.values)) { + if (options.includeComments) { + formatComment(formatter, enumType.comments[key]); + } + formatter.writeLine(`| '${key}'`); + formatter.writeLine(`| ${enumType.values[key]}`); + } + formatter.unindent(); + // Restrictive Type + formatter.writeLine(''); + if (options.includeComments) { + formatComment(formatter, enumType.comment, enumType.options); + } + formatter.writeLine(`export type ${outputName(name)} = typeof ${name}[keyof typeof ${name}]`); +} +/** + * This is a list of methods that are exist in the generic Client class in the + * gRPC libraries. TypeScript has a problem with methods in subclasses with the + * same names as methods in the superclass, but with mismatched APIs. So, we + * avoid generating methods with these names in the service client interfaces. + * We always generate two service client methods per service method: one camel + * cased, and one with the original casing. So we will still generate one + * service client method for any conflicting name. + * + * Technically, at runtime conflicting name in the service client method + * actually shadows the original method, but TypeScript does not have a good + * way to represent that. So this change is not 100% accurate, but it gets the + * generated code to compile. + * + * This is just a list of the methods in the Client class definitions in + * grpc@1.24.11 and @grpc/grpc-js@1.4.0. + */ +const CLIENT_RESERVED_METHOD_NAMES = new Set([ + 'close', + 'getChannel', + 'waitForReady', + 'makeUnaryRequest', + 'makeClientStreamRequest', + 'makeServerStreamRequest', + 'makeBidiStreamRequest', + 'resolveCallInterceptors', + /* These methods are private, but TypeScript is not happy with overriding even + * private methods with mismatched APIs. */ + 'checkOptionalUnaryResponseArguments', + 'checkMetadataAndOptions' +]); +function generateServiceClientInterface(formatter, serviceType, options) { + const { outputName, inputName } = useNameFmter(options); + if (options.includeComments) { + formatComment(formatter, serviceType.comment, serviceType.options); + } + formatter.writeLine(`export interface ${serviceType.name}Client extends grpc.Client {`); + formatter.indent(); + for (const methodName of Object.keys(serviceType.methods).sort()) { + const method = serviceType.methods[methodName]; + for (const name of new Set([methodName, camelCase(methodName)])) { + if (CLIENT_RESERVED_METHOD_NAMES.has(name)) { + continue; + } + if (options.includeComments) { + formatComment(formatter, method.comment, method.options); + } + const requestType = inputName(getTypeInterfaceName(method.resolvedRequestType)); + const responseType = outputName(getTypeInterfaceName(method.resolvedResponseType)); + const callbackType = `grpc.requestCallback<${responseType}>`; + if (method.requestStream) { + if (method.responseStream) { + // Bidi streaming + const callType = `grpc.ClientDuplexStream<${requestType}, ${responseType}>`; + formatter.writeLine(`${name}(metadata: grpc.Metadata, options?: grpc.CallOptions): ${callType};`); + formatter.writeLine(`${name}(options?: grpc.CallOptions): ${callType};`); + } + else { + // Client streaming + const callType = `grpc.ClientWritableStream<${requestType}>`; + formatter.writeLine(`${name}(metadata: grpc.Metadata, options: grpc.CallOptions, callback: ${callbackType}): ${callType};`); + formatter.writeLine(`${name}(metadata: grpc.Metadata, callback: ${callbackType}): ${callType};`); + formatter.writeLine(`${name}(options: grpc.CallOptions, callback: ${callbackType}): ${callType};`); + formatter.writeLine(`${name}(callback: ${callbackType}): ${callType};`); + } + } + else { + if (method.responseStream) { + // Server streaming + const callType = `grpc.ClientReadableStream<${responseType}>`; + formatter.writeLine(`${name}(argument: ${requestType}, metadata: grpc.Metadata, options?: grpc.CallOptions): ${callType};`); + formatter.writeLine(`${name}(argument: ${requestType}, options?: grpc.CallOptions): ${callType};`); + } + else { + // Unary + const callType = 'grpc.ClientUnaryCall'; + formatter.writeLine(`${name}(argument: ${requestType}, metadata: grpc.Metadata, options: grpc.CallOptions, callback: ${callbackType}): ${callType};`); + formatter.writeLine(`${name}(argument: ${requestType}, metadata: grpc.Metadata, callback: ${callbackType}): ${callType};`); + formatter.writeLine(`${name}(argument: ${requestType}, options: grpc.CallOptions, callback: ${callbackType}): ${callType};`); + formatter.writeLine(`${name}(argument: ${requestType}, callback: ${callbackType}): ${callType};`); + } + } + } + formatter.writeLine(''); + } + formatter.unindent(); + formatter.writeLine('}'); +} +function generateServiceHandlerInterface(formatter, serviceType, options) { + const { inputName, outputName } = useNameFmter(options); + if (options.includeComments) { + formatComment(formatter, serviceType.comment, serviceType.options); + } + formatter.writeLine(`export interface ${serviceType.name}Handlers extends grpc.UntypedServiceImplementation {`); + formatter.indent(); + for (const methodName of Object.keys(serviceType.methods).sort()) { + const method = serviceType.methods[methodName]; + if (options.includeComments) { + formatComment(formatter, method.comment, serviceType.options); + } + const requestType = outputName(getTypeInterfaceName(method.resolvedRequestType)); + const responseType = inputName(getTypeInterfaceName(method.resolvedResponseType)); + if (method.requestStream) { + if (method.responseStream) { + // Bidi streaming + formatter.writeLine(`${methodName}: grpc.handleBidiStreamingCall<${requestType}, ${responseType}>;`); + } + else { + // Client streaming + formatter.writeLine(`${methodName}: grpc.handleClientStreamingCall<${requestType}, ${responseType}>;`); + } + } + else { + if (method.responseStream) { + // Server streaming + formatter.writeLine(`${methodName}: grpc.handleServerStreamingCall<${requestType}, ${responseType}>;`); + } + else { + // Unary + formatter.writeLine(`${methodName}: grpc.handleUnaryCall<${requestType}, ${responseType}>;`); + } + } + formatter.writeLine(''); + } + formatter.unindent(); + formatter.writeLine('}'); +} +function generateServiceDefinitionInterface(formatter, serviceType, options) { + const { inputName, outputName } = useNameFmter(options); + if (options.grpcLib) { + formatter.writeLine(`export interface ${serviceType.name}Definition extends grpc.ServiceDefinition {`); + } + else { + formatter.writeLine(`export interface ${serviceType.name}Definition {`); + } + formatter.indent(); + for (const methodName of Object.keys(serviceType.methods).sort()) { + const method = serviceType.methods[methodName]; + const requestType = getTypeInterfaceName(method.resolvedRequestType); + const responseType = getTypeInterfaceName(method.resolvedResponseType); + formatter.writeLine(`${methodName}: MethodDefinition<${inputName(requestType)}, ${inputName(responseType)}, ${outputName(requestType)}, ${outputName(responseType)}>`); + } + formatter.unindent(); + formatter.writeLine('}'); +} +function generateServiceInterfaces(formatter, serviceType, options) { + var _a, _b; + formatter.writeLine(`// Original file: ${(_b = ((_a = serviceType.filename) !== null && _a !== void 0 ? _a : 'null')) === null || _b === void 0 ? void 0 : _b.replace(/\\/g, '/')}`); + formatter.writeLine(''); + if (options.grpcLib) { + const grpcImportPath = options.grpcLib.startsWith('.') ? getPathToRoot(serviceType) + options.grpcLib : options.grpcLib; + formatter.writeLine(`import type * as grpc from '${grpcImportPath}'`); + } + formatter.writeLine(`import type { MethodDefinition } from '@grpc/proto-loader'`); + const dependencies = new Set(); + for (const method of serviceType.methodsArray) { + dependencies.add(method.resolvedRequestType); + dependencies.add(method.resolvedResponseType); + } + for (const dep of Array.from(dependencies.values()).sort(compareName)) { + formatter.writeLine(getImportLine(dep, serviceType, options)); + } + formatter.writeLine(''); + if (options.grpcLib) { + generateServiceClientInterface(formatter, serviceType, options); + formatter.writeLine(''); + generateServiceHandlerInterface(formatter, serviceType, options); + formatter.writeLine(''); + } + generateServiceDefinitionInterface(formatter, serviceType, options); +} +function containsDefinition(definitionType, namespace) { + for (const nested of namespace.nestedArray.sort(compareName)) { + if (nested instanceof definitionType) { + return true; + } + else if (isNamespaceBase(nested) && !(nested instanceof Protobuf.Type) && !(nested instanceof Protobuf.Enum) && containsDefinition(definitionType, nested)) { + return true; + } + } + return false; +} +function generateDefinitionImports(formatter, namespace, options) { + const imports = []; + if (containsDefinition(Protobuf.Enum, namespace)) { + imports.push('EnumTypeDefinition'); + } + if (containsDefinition(Protobuf.Type, namespace)) { + imports.push('MessageTypeDefinition'); + } + if (imports.length) { + formatter.writeLine(`import type { ${imports.join(', ')} } from '@grpc/proto-loader';`); + } +} +function generateServiceImports(formatter, namespace, options) { + for (const nested of namespace.nestedArray.sort(compareName)) { + if (nested instanceof Protobuf.Service) { + formatter.writeLine(getImportLine(nested, undefined, options)); + } + else if (isNamespaceBase(nested) && !(nested instanceof Protobuf.Type) && !(nested instanceof Protobuf.Enum)) { + generateServiceImports(formatter, nested, options); + } + } +} +function generateSingleLoadedDefinitionType(formatter, nested, options) { + if (nested instanceof Protobuf.Service) { + if (options.includeComments) { + formatComment(formatter, nested.comment, nested.options); + } + const typeInterfaceName = getTypeInterfaceName(nested); + formatter.writeLine(`${nested.name}: SubtypeConstructor & { service: ${typeInterfaceName}Definition }`); + } + else if (nested instanceof Protobuf.Enum) { + formatter.writeLine(`${nested.name}: EnumTypeDefinition`); + } + else if (nested instanceof Protobuf.Type) { + formatter.writeLine(`${nested.name}: MessageTypeDefinition`); + } + else if (isNamespaceBase(nested)) { + generateLoadedDefinitionTypes(formatter, nested, options); + } +} +function generateLoadedDefinitionTypes(formatter, namespace, options) { + formatter.writeLine(`${namespace.name}: {`); + formatter.indent(); + for (const nested of namespace.nestedArray.sort(compareName)) { + generateSingleLoadedDefinitionType(formatter, nested, options); + } + formatter.unindent(); + formatter.writeLine('}'); +} +function generateRootFile(formatter, root, options) { + if (!options.grpcLib) { + return; + } + formatter.writeLine(`import type * as grpc from '${options.grpcLib}';`); + generateDefinitionImports(formatter, root, options); + formatter.writeLine(''); + generateServiceImports(formatter, root, options); + formatter.writeLine(''); + formatter.writeLine('type SubtypeConstructor any, Subtype> = {'); + formatter.writeLine(' new(...args: ConstructorParameters): Subtype;'); + formatter.writeLine('};'); + formatter.writeLine(''); + formatter.writeLine('export interface ProtoGrpcType {'); + formatter.indent(); + for (const nested of root.nestedArray) { + generateSingleLoadedDefinitionType(formatter, nested, options); + } + formatter.unindent(); + formatter.writeLine('}'); + formatter.writeLine(''); +} +async function writeFile(filename, contents) { + await fs.promises.mkdir(path.dirname(filename), { recursive: true }); + return fs.promises.writeFile(filename, contents); +} +function generateFilesForNamespace(namespace, options) { + const filePromises = []; + for (const nested of namespace.nestedArray) { + const fileFormatter = new TextFormatter(); + if (nested instanceof Protobuf.Type) { + generateMessageInterfaces(fileFormatter, nested, options); + if (options.verbose) { + console.log(`Writing ${options.outDir}/${getPath(nested)} from file ${nested.filename}`); + } + filePromises.push(writeFile(`${options.outDir}/${getPath(nested)}`, fileFormatter.getFullText())); + } + else if (nested instanceof Protobuf.Enum) { + generateEnumInterface(fileFormatter, nested, options); + if (options.verbose) { + console.log(`Writing ${options.outDir}/${getPath(nested)} from file ${nested.filename}`); + } + filePromises.push(writeFile(`${options.outDir}/${getPath(nested)}`, fileFormatter.getFullText())); + } + else if (nested instanceof Protobuf.Service) { + generateServiceInterfaces(fileFormatter, nested, options); + if (options.verbose) { + console.log(`Writing ${options.outDir}/${getPath(nested)} from file ${nested.filename}`); + } + filePromises.push(writeFile(`${options.outDir}/${getPath(nested)}`, fileFormatter.getFullText())); + } + else if (isNamespaceBase(nested)) { + filePromises.push(...generateFilesForNamespace(nested, options)); + } + } + return filePromises; +} +function writeFilesForRoot(root, masterFileName, options) { + const filePromises = []; + const masterFileFormatter = new TextFormatter(); + if (options.grpcLib) { + generateRootFile(masterFileFormatter, root, options); + if (options.verbose) { + console.log(`Writing ${options.outDir}/${masterFileName}`); + } + filePromises.push(writeFile(`${options.outDir}/${masterFileName}`, masterFileFormatter.getFullText())); + } + filePromises.push(...generateFilesForNamespace(root, options)); + return filePromises; +} +async function writeAllFiles(protoFiles, options) { + await fs.promises.mkdir(options.outDir, { recursive: true }); + const basenameMap = new Map(); + for (const filename of protoFiles) { + const basename = path.basename(filename).replace(/\.proto$/, '.ts'); + if (basenameMap.has(basename)) { + basenameMap.get(basename).push(filename); + } + else { + basenameMap.set(basename, [filename]); + } + } + for (const [basename, filenames] of basenameMap.entries()) { + const loadedRoot = await (0, util_1.loadProtosWithOptions)(filenames, options); + writeFilesForRoot(loadedRoot, basename, options); + } +} +async function runScript() { + const boolDefaultFalseOption = { + boolean: true, + default: false, + }; + const argv = await yargs + .parserConfiguration({ + 'parse-positional-numbers': false + }) + .option('keepCase', boolDefaultFalseOption) + .option('longs', { string: true, default: 'Long' }) + .option('enums', { string: true, default: 'number' }) + .option('bytes', { string: true, default: 'Buffer' }) + .option('defaults', boolDefaultFalseOption) + .option('arrays', boolDefaultFalseOption) + .option('objects', boolDefaultFalseOption) + .option('oneofs', boolDefaultFalseOption) + .option('json', boolDefaultFalseOption) + .boolean('verbose') + .option('includeComments', boolDefaultFalseOption) + .option('includeDirs', { + normalize: true, + array: true, + alias: 'I' + }) + .option('outDir', { + alias: 'O', + normalize: true, + }) + .option('grpcLib', { string: true }) + .option('inputTemplate', { string: true, default: `${templateStr}` }) + .option('outputTemplate', { string: true, default: `${templateStr}__Output` }) + .option('inputBranded', boolDefaultFalseOption) + .option('outputBranded', boolDefaultFalseOption) + .coerce('longs', value => { + switch (value) { + case 'String': return String; + case 'Number': return Number; + default: return undefined; + } + }).coerce('enums', value => { + if (value === 'String') { + return String; + } + else { + return undefined; + } + }).coerce('bytes', value => { + switch (value) { + case 'Array': return Array; + case 'String': return String; + default: return undefined; + } + }) + .alias({ + verbose: 'v' + }).describe({ + keepCase: 'Preserve the case of field names', + longs: 'The type that should be used to output 64 bit integer values. Can be String, Number', + enums: 'The type that should be used to output enum fields. Can be String', + bytes: 'The type that should be used to output bytes fields. Can be String, Array', + defaults: 'Output default values for omitted fields', + arrays: 'Output default values for omitted repeated fields even if --defaults is not set', + objects: 'Output default values for omitted message fields even if --defaults is not set', + oneofs: 'Output virtual oneof fields set to the present field\'s name', + json: 'Represent Infinity and NaN as strings in float fields. Also decode google.protobuf.Any automatically', + includeComments: 'Generate doc comments from comments in the original files', + includeDirs: 'Directories to search for included files', + outDir: 'Directory in which to output files', + grpcLib: 'The gRPC implementation library that these types will be used with. If not provided, some types will not be generated', + inputTemplate: 'Template for mapping input or "permissive" type names', + outputTemplate: 'Template for mapping output or "restricted" type names', + inputBranded: 'Output property for branded type for "permissive" types with fullName of the Message as its value', + outputBranded: 'Output property for branded type for "restricted" types with fullName of the Message as its value', + }).demandOption(['outDir']) + .demand(1) + .usage('$0 [options] filenames...') + .epilogue('WARNING: This tool is in alpha. The CLI and generated code are subject to change') + .argv; + if (argv.verbose) { + console.log('Parsed arguments:', argv); + } + (0, util_1.addCommonProtos)(); + writeAllFiles(argv._, Object.assign(Object.assign({}, argv), { alternateCommentMode: true })).then(() => { + if (argv.verbose) { + console.log('Success'); + } + }, (error) => { + console.error(error); + process.exit(1); + }); +} +if (require.main === module) { + runScript(); +} +//# sourceMappingURL=proto-loader-gen-types.js.map \ No newline at end of file diff --git a/node_modules/@grpc/proto-loader/build/bin/proto-loader-gen-types.js.map b/node_modules/@grpc/proto-loader/build/bin/proto-loader-gen-types.js.map new file mode 100644 index 0000000..d1fe4fc --- /dev/null +++ b/node_modules/@grpc/proto-loader/build/bin/proto-loader-gen-types.js.map @@ -0,0 +1 @@ +{"version":3,"file":"proto-loader-gen-types.js","sourceRoot":"","sources":["../../bin/proto-loader-gen-types.ts"],"names":[],"mappings":";;AACA;;;;;;;;;;;;;;;;GAgBG;;AAEH,yBAAyB;AACzB,6BAA6B;AAE7B,uCAAuC;AACvC,+BAA+B;AAE/B,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C,CAAa,kCAAM,IAAI,KAAE,oBAAoB,EAAE,IAAI,IAAE,CAAC,IAAI,CAAC,GAAG,EAAE;QACjF,IAAI,IAAI,CAAC,OAAO,EAAE;YAChB,OAAO,CAAC,GAAG,CAAC,SAAS,CAAC,CAAC;SACxB;IACH,CAAC,EAAE,CAAC,KAAK,EAAE,EAAE;QACX,OAAO,CAAC,KAAK,CAAC,KAAK,CAAC,CAAA;QACpB,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC;IAClB,CAAC,CAAC,CAAC;AACL,CAAC;AAED,IAAI,OAAO,CAAC,IAAI,KAAK,MAAM,EAAE;IAC3B,SAAS,EAAE,CAAC;CACb"} \ No newline at end of file diff --git a/node_modules/@grpc/proto-loader/build/src/index.d.ts b/node_modules/@grpc/proto-loader/build/src/index.d.ts new file mode 100644 index 0000000..ff575c0 --- /dev/null +++ b/node_modules/@grpc/proto-loader/build/src/index.d.ts @@ -0,0 +1,160 @@ +/** + * @license + * Copyright 2018 gRPC authors. + * + * 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. + * + */ +/// +import * as Protobuf from 'protobufjs'; +import * as descriptor from 'protobufjs/ext/descriptor'; +import { Options } from './util'; +import Long = require('long'); +export { Options, Long }; +/** + * This type exists for use with code generated by the proto-loader-gen-types + * tool. This type should be used with another interface, e.g. + * MessageType & AnyExtension for an object that is converted to or from a + * google.protobuf.Any message. + * For example, when processing an Any message: + * + * ```ts + * if (isAnyExtension(message)) { + * switch (message['@type']) { + * case TYPE1_URL: + * handleType1(message as AnyExtension & Type1); + * break; + * case TYPE2_URL: + * handleType2(message as AnyExtension & Type2); + * break; + * // ... + * } + * } + * ``` + */ +export interface AnyExtension { + /** + * The fully qualified name of the message type that this object represents, + * possibly including a URL prefix. + */ + '@type': string; +} +export declare function isAnyExtension(obj: object): obj is AnyExtension; +declare module 'protobufjs' { + interface Type { + toDescriptor(protoVersion: string): Protobuf.Message & descriptor.IDescriptorProto; + } + interface RootConstructor { + new (options?: Options): Root; + fromDescriptor(descriptorSet: descriptor.IFileDescriptorSet | Protobuf.Reader | Uint8Array): Root; + fromJSON(json: Protobuf.INamespace, root?: Root): Root; + } + interface Root { + toDescriptor(protoVersion: string): Protobuf.Message & descriptor.IFileDescriptorSet; + } + interface Enum { + toDescriptor(protoVersion: string): Protobuf.Message & descriptor.IEnumDescriptorProto; + } +} +export interface Serialize { + (value: T): Buffer; +} +export interface Deserialize { + (bytes: Buffer): T; +} +export interface ProtobufTypeDefinition { + format: string; + type: object; + fileDescriptorProtos: Buffer[]; +} +export interface MessageTypeDefinition extends ProtobufTypeDefinition { + format: 'Protocol Buffer 3 DescriptorProto'; +} +export interface EnumTypeDefinition extends ProtobufTypeDefinition { + format: 'Protocol Buffer 3 EnumDescriptorProto'; +} +export declare enum IdempotencyLevel { + IDEMPOTENCY_UNKNOWN = "IDEMPOTENCY_UNKNOWN", + NO_SIDE_EFFECTS = "NO_SIDE_EFFECTS", + IDEMPOTENT = "IDEMPOTENT" +} +export interface NamePart { + name_part: string; + is_extension: boolean; +} +export interface UninterpretedOption { + name?: NamePart[]; + identifier_value?: string; + positive_int_value?: number; + negative_int_value?: number; + double_value?: number; + string_value?: string; + aggregate_value?: string; +} +export interface MethodOptions { + deprecated: boolean; + idempotency_level: IdempotencyLevel; + uninterpreted_option: UninterpretedOption[]; + [k: string]: unknown; +} +export interface MethodDefinition { + path: string; + requestStream: boolean; + responseStream: boolean; + requestSerialize: Serialize; + responseSerialize: Serialize; + requestDeserialize: Deserialize; + responseDeserialize: Deserialize; + originalName?: string; + requestType: MessageTypeDefinition; + responseType: MessageTypeDefinition; + options: MethodOptions; +} +export interface ServiceDefinition { + [index: string]: MethodDefinition; +} +export declare type AnyDefinition = ServiceDefinition | MessageTypeDefinition | EnumTypeDefinition; +export interface PackageDefinition { + [index: string]: AnyDefinition; +} +/** + * Load a .proto file with the specified options. + * @param filename One or multiple file paths to load. Can be an absolute path + * or relative to an include path. + * @param options.keepCase Preserve field names. The default is to change them + * to camel case. + * @param options.longs The type that should be used to represent `long` values. + * Valid options are `Number` and `String`. Defaults to a `Long` object type + * from a library. + * @param options.enums The type that should be used to represent `enum` values. + * The only valid option is `String`. Defaults to the numeric value. + * @param options.bytes The type that should be used to represent `bytes` + * values. Valid options are `Array` and `String`. The default is to use + * `Buffer`. + * @param options.defaults Set default values on output objects. Defaults to + * `false`. + * @param options.arrays Set empty arrays for missing array values even if + * `defaults` is `false`. Defaults to `false`. + * @param options.objects Set empty objects for missing object values even if + * `defaults` is `false`. Defaults to `false`. + * @param options.oneofs Set virtual oneof properties to the present field's + * name + * @param options.json Represent Infinity and NaN as strings in float fields, + * and automatically decode google.protobuf.Any values. + * @param options.includeDirs Paths to search for imported `.proto` files. + */ +export declare function load(filename: string | string[], options?: Options): Promise; +export declare function loadSync(filename: string | string[], options?: Options): PackageDefinition; +export declare function fromJSON(json: Protobuf.INamespace, options?: Options): PackageDefinition; +export declare function loadFileDescriptorSetFromBuffer(descriptorSet: Buffer, options?: Options): PackageDefinition; +export declare function loadFileDescriptorSetFromObject(descriptorSet: Parameters[0], options?: Options): PackageDefinition; diff --git a/node_modules/@grpc/proto-loader/build/src/index.js b/node_modules/@grpc/proto-loader/build/src/index.js new file mode 100644 index 0000000..1d86395 --- /dev/null +++ b/node_modules/@grpc/proto-loader/build/src/index.js @@ -0,0 +1,244 @@ +"use strict"; +/** + * @license + * Copyright 2018 gRPC authors. + * + * 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. + * + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.loadFileDescriptorSetFromObject = exports.loadFileDescriptorSetFromBuffer = exports.fromJSON = exports.loadSync = exports.load = exports.IdempotencyLevel = exports.isAnyExtension = exports.Long = void 0; +const camelCase = require("lodash.camelcase"); +const Protobuf = require("protobufjs"); +const descriptor = require("protobufjs/ext/descriptor"); +const util_1 = require("./util"); +const Long = require("long"); +exports.Long = Long; +function isAnyExtension(obj) { + return ('@type' in obj) && (typeof obj['@type'] === 'string'); +} +exports.isAnyExtension = isAnyExtension; +var IdempotencyLevel; +(function (IdempotencyLevel) { + IdempotencyLevel["IDEMPOTENCY_UNKNOWN"] = "IDEMPOTENCY_UNKNOWN"; + IdempotencyLevel["NO_SIDE_EFFECTS"] = "NO_SIDE_EFFECTS"; + IdempotencyLevel["IDEMPOTENT"] = "IDEMPOTENT"; +})(IdempotencyLevel = exports.IdempotencyLevel || (exports.IdempotencyLevel = {})); +const descriptorOptions = { + longs: String, + enums: String, + bytes: String, + defaults: true, + oneofs: true, + json: true, +}; +function joinName(baseName, name) { + if (baseName === '') { + return name; + } + else { + return baseName + '.' + name; + } +} +function isHandledReflectionObject(obj) { + return (obj instanceof Protobuf.Service || + obj instanceof Protobuf.Type || + obj instanceof Protobuf.Enum); +} +function isNamespaceBase(obj) { + return obj instanceof Protobuf.Namespace || obj instanceof Protobuf.Root; +} +function getAllHandledReflectionObjects(obj, parentName) { + const objName = joinName(parentName, obj.name); + if (isHandledReflectionObject(obj)) { + return [[objName, obj]]; + } + else { + if (isNamespaceBase(obj) && typeof obj.nested !== 'undefined') { + return Object.keys(obj.nested) + .map(name => { + return getAllHandledReflectionObjects(obj.nested[name], objName); + }) + .reduce((accumulator, currentValue) => accumulator.concat(currentValue), []); + } + } + return []; +} +function createDeserializer(cls, options) { + return function deserialize(argBuf) { + return cls.toObject(cls.decode(argBuf), options); + }; +} +function createSerializer(cls) { + return function serialize(arg) { + if (Array.isArray(arg)) { + throw new Error(`Failed to serialize message: expected object with ${cls.name} structure, got array instead`); + } + const message = cls.fromObject(arg); + return cls.encode(message).finish(); + }; +} +function mapMethodOptions(options) { + return (options || []).reduce((obj, item) => { + for (const [key, value] of Object.entries(item)) { + switch (key) { + case 'uninterpreted_option': + obj.uninterpreted_option.push(item.uninterpreted_option); + break; + default: + obj[key] = value; + } + } + return obj; + }, { + deprecated: false, + idempotency_level: IdempotencyLevel.IDEMPOTENCY_UNKNOWN, + uninterpreted_option: [], + }); +} +function createMethodDefinition(method, serviceName, options, fileDescriptors) { + /* This is only ever called after the corresponding root.resolveAll(), so we + * can assume that the resolved request and response types are non-null */ + const requestType = method.resolvedRequestType; + const responseType = method.resolvedResponseType; + return { + path: '/' + serviceName + '/' + method.name, + requestStream: !!method.requestStream, + responseStream: !!method.responseStream, + requestSerialize: createSerializer(requestType), + requestDeserialize: createDeserializer(requestType, options), + responseSerialize: createSerializer(responseType), + responseDeserialize: createDeserializer(responseType, options), + // TODO(murgatroid99): Find a better way to handle this + originalName: camelCase(method.name), + requestType: createMessageDefinition(requestType, fileDescriptors), + responseType: createMessageDefinition(responseType, fileDescriptors), + options: mapMethodOptions(method.parsedOptions), + }; +} +function createServiceDefinition(service, name, options, fileDescriptors) { + const def = {}; + for (const method of service.methodsArray) { + def[method.name] = createMethodDefinition(method, name, options, fileDescriptors); + } + return def; +} +function createMessageDefinition(message, fileDescriptors) { + const messageDescriptor = message.toDescriptor('proto3'); + return { + format: 'Protocol Buffer 3 DescriptorProto', + type: messageDescriptor.$type.toObject(messageDescriptor, descriptorOptions), + fileDescriptorProtos: fileDescriptors, + }; +} +function createEnumDefinition(enumType, fileDescriptors) { + const enumDescriptor = enumType.toDescriptor('proto3'); + return { + format: 'Protocol Buffer 3 EnumDescriptorProto', + type: enumDescriptor.$type.toObject(enumDescriptor, descriptorOptions), + fileDescriptorProtos: fileDescriptors, + }; +} +/** + * function createDefinition(obj: Protobuf.Service, name: string, options: + * Options): ServiceDefinition; function createDefinition(obj: Protobuf.Type, + * name: string, options: Options): MessageTypeDefinition; function + * createDefinition(obj: Protobuf.Enum, name: string, options: Options): + * EnumTypeDefinition; + */ +function createDefinition(obj, name, options, fileDescriptors) { + if (obj instanceof Protobuf.Service) { + return createServiceDefinition(obj, name, options, fileDescriptors); + } + else if (obj instanceof Protobuf.Type) { + return createMessageDefinition(obj, fileDescriptors); + } + else if (obj instanceof Protobuf.Enum) { + return createEnumDefinition(obj, fileDescriptors); + } + else { + throw new Error('Type mismatch in reflection object handling'); + } +} +function createPackageDefinition(root, options) { + const def = {}; + root.resolveAll(); + const descriptorList = root.toDescriptor('proto3').file; + const bufferList = descriptorList.map(value => Buffer.from(descriptor.FileDescriptorProto.encode(value).finish())); + for (const [name, obj] of getAllHandledReflectionObjects(root, '')) { + def[name] = createDefinition(obj, name, options, bufferList); + } + return def; +} +function createPackageDefinitionFromDescriptorSet(decodedDescriptorSet, options) { + options = options || {}; + const root = Protobuf.Root.fromDescriptor(decodedDescriptorSet); + root.resolveAll(); + return createPackageDefinition(root, options); +} +/** + * Load a .proto file with the specified options. + * @param filename One or multiple file paths to load. Can be an absolute path + * or relative to an include path. + * @param options.keepCase Preserve field names. The default is to change them + * to camel case. + * @param options.longs The type that should be used to represent `long` values. + * Valid options are `Number` and `String`. Defaults to a `Long` object type + * from a library. + * @param options.enums The type that should be used to represent `enum` values. + * The only valid option is `String`. Defaults to the numeric value. + * @param options.bytes The type that should be used to represent `bytes` + * values. Valid options are `Array` and `String`. The default is to use + * `Buffer`. + * @param options.defaults Set default values on output objects. Defaults to + * `false`. + * @param options.arrays Set empty arrays for missing array values even if + * `defaults` is `false`. Defaults to `false`. + * @param options.objects Set empty objects for missing object values even if + * `defaults` is `false`. Defaults to `false`. + * @param options.oneofs Set virtual oneof properties to the present field's + * name + * @param options.json Represent Infinity and NaN as strings in float fields, + * and automatically decode google.protobuf.Any values. + * @param options.includeDirs Paths to search for imported `.proto` files. + */ +function load(filename, options) { + return (0, util_1.loadProtosWithOptions)(filename, options).then(loadedRoot => { + return createPackageDefinition(loadedRoot, options); + }); +} +exports.load = load; +function loadSync(filename, options) { + const loadedRoot = (0, util_1.loadProtosWithOptionsSync)(filename, options); + return createPackageDefinition(loadedRoot, options); +} +exports.loadSync = loadSync; +function fromJSON(json, options) { + options = options || {}; + const loadedRoot = Protobuf.Root.fromJSON(json); + loadedRoot.resolveAll(); + return createPackageDefinition(loadedRoot, options); +} +exports.fromJSON = fromJSON; +function loadFileDescriptorSetFromBuffer(descriptorSet, options) { + const decodedDescriptorSet = descriptor.FileDescriptorSet.decode(descriptorSet); + return createPackageDefinitionFromDescriptorSet(decodedDescriptorSet, options); +} +exports.loadFileDescriptorSetFromBuffer = loadFileDescriptorSetFromBuffer; +function loadFileDescriptorSetFromObject(descriptorSet, options) { + const decodedDescriptorSet = descriptor.FileDescriptorSet.fromObject(descriptorSet); + return createPackageDefinitionFromDescriptorSet(decodedDescriptorSet, options); +} +exports.loadFileDescriptorSetFromObject = loadFileDescriptorSetFromObject; +(0, util_1.addCommonProtos)(); +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/node_modules/@grpc/proto-loader/build/src/index.js.map b/node_modules/@grpc/proto-loader/build/src/index.js.map new file mode 100644 index 0000000..8ba05f1 --- /dev/null +++ b/node_modules/@grpc/proto-loader/build/src/index.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;;;;GAgBG;;;AAEH,8CAA+C;AAC/C,uCAAuC;AACvC,wDAAwD;AAExD,iCAAoG;AAEpG,6BAA8B;AAEZ,oBAAI;AA+BtB,SAAgB,cAAc,CAAC,GAAW;IACxC,OAAO,CAAC,OAAO,IAAI,GAAG,CAAC,IAAI,CAAC,OAAQ,GAAoB,CAAC,OAAO,CAAC,KAAK,QAAQ,CAAC,CAAC;AAClF,CAA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ACvD,CAAC,CAAC,CAAC;AACL,CAAC;AAPD,oBAOC;AAED,SAAgB,QAAQ,CACtB,QAA2B,EAC3B,OAAiB;IAEjB,MAAM,UAAU,GAAG,IAAA,gCAAyB,EAAC,QAAQ,EAAE,OAAO,CAAC,CAAC;IAChE,OAAO,uBAAuB,CAAC,UAAU,EAAE,OAAQ,CAAC,CAAC;AACvD,CAAC;AAND,4BAMC;AAED,SAAgB,QAAQ,CACtB,IAAyB,EACzB,OAAiB;IAEjB,OAAO,GAAG,OAAO,IAAI,EAAE,CAAC;IACxB,MAAM,UAAU,GAAG,QAAQ,CAAC,IAAI,CAAC,QAAQ,CAAC,IAAI,CAAC,CAAC;IAChD,UAAU,CAAC,UAAU,EAAE,CAAC;IACxB,OAAO,uBAAuB,CAAC,UAAU,EAAE,OAAQ,CAAC,CAAC;AACvD,CAAC;AARD,4BAQC;AAED,SAAgB,+BAA+B,CAC7C,aAAqB,EACrB,OAAiB;IAEjB,MAAM,oBAAoB,GAAG,UAAU,CAAC,iBAAiB,CAAC,MAAM,CAC9D,aAAa,CACU,CAAC;IAE1B,OAAO,wCAAwC,CAC7C,oBAAoB,EACpB,OAAO,CACR,CAAC;AACJ,CAAC;AAZD,0EAYC;AAED,SAAgB,+BAA+B,CAC7C,aAA4E,EAC5E,OAAiB;IAEjB,MAAM,oBAAoB,GAAG,UAAU,CAAC,iBAAiB,CAAC,UAAU,CAClE,aAAa,CACU,CAAC;IAE1B,OAAO,wCAAwC,CAC7C,oBAAoB,EACpB,OAAO,CACR,CAAC;AACJ,CAAC;AAZD,0EAYC;AAED,IAAA,sBAAe,GAAE,CAAC"} \ No newline at end of file diff --git a/node_modules/@grpc/proto-loader/build/src/util.d.ts b/node_modules/@grpc/proto-loader/build/src/util.d.ts new file mode 100644 index 0000000..d0b13d9 --- /dev/null +++ b/node_modules/@grpc/proto-loader/build/src/util.d.ts @@ -0,0 +1,27 @@ +/** + * @license + * Copyright 2018 gRPC authors. + * + * 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. + * + */ +import * as Protobuf from 'protobufjs'; +export declare type Options = Protobuf.IParseOptions & Protobuf.IConversionOptions & { + includeDirs?: string[]; +}; +export declare function loadProtosWithOptions(filename: string | string[], options?: Options): Promise; +export declare function loadProtosWithOptionsSync(filename: string | string[], options?: Options): Protobuf.Root; +/** + * Load Google's well-known proto files that aren't exposed by Protobuf.js. + */ +export declare function addCommonProtos(): void; diff --git a/node_modules/@grpc/proto-loader/build/src/util.js b/node_modules/@grpc/proto-loader/build/src/util.js new file mode 100644 index 0000000..7ade36b --- /dev/null +++ b/node_modules/@grpc/proto-loader/build/src/util.js @@ -0,0 +1,89 @@ +"use strict"; +/** + * @license + * Copyright 2018 gRPC authors. + * + * 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. + * + */ +Object.defineProperty(exports, "__esModule", { value: true }); +exports.addCommonProtos = exports.loadProtosWithOptionsSync = exports.loadProtosWithOptions = void 0; +const fs = require("fs"); +const path = require("path"); +const Protobuf = require("protobufjs"); +function addIncludePathResolver(root, includePaths) { + const originalResolvePath = root.resolvePath; + root.resolvePath = (origin, target) => { + if (path.isAbsolute(target)) { + return target; + } + for (const directory of includePaths) { + const fullPath = path.join(directory, target); + try { + fs.accessSync(fullPath, fs.constants.R_OK); + return fullPath; + } + catch (err) { + continue; + } + } + process.emitWarning(`${target} not found in any of the include paths ${includePaths}`); + return originalResolvePath(origin, target); + }; +} +async function loadProtosWithOptions(filename, options) { + const root = new Protobuf.Root(); + options = options || {}; + if (!!options.includeDirs) { + if (!Array.isArray(options.includeDirs)) { + return Promise.reject(new Error('The includeDirs option must be an array')); + } + addIncludePathResolver(root, options.includeDirs); + } + const loadedRoot = await root.load(filename, options); + loadedRoot.resolveAll(); + return loadedRoot; +} +exports.loadProtosWithOptions = loadProtosWithOptions; +function loadProtosWithOptionsSync(filename, options) { + const root = new Protobuf.Root(); + options = options || {}; + if (!!options.includeDirs) { + if (!Array.isArray(options.includeDirs)) { + throw new Error('The includeDirs option must be an array'); + } + addIncludePathResolver(root, options.includeDirs); + } + const loadedRoot = root.loadSync(filename, options); + loadedRoot.resolveAll(); + return loadedRoot; +} +exports.loadProtosWithOptionsSync = loadProtosWithOptionsSync; +/** + * Load Google's well-known proto files that aren't exposed by Protobuf.js. + */ +function addCommonProtos() { + // Protobuf.js exposes: any, duration, empty, field_mask, struct, timestamp, + // and wrappers. compiler/plugin is excluded in Protobuf.js and here. + // Using constant strings for compatibility with tools like Webpack + const apiDescriptor = require('protobufjs/google/protobuf/api.json'); + const descriptorDescriptor = require('protobufjs/google/protobuf/descriptor.json'); + const sourceContextDescriptor = require('protobufjs/google/protobuf/source_context.json'); + const typeDescriptor = require('protobufjs/google/protobuf/type.json'); + Protobuf.common('api', apiDescriptor.nested.google.nested.protobuf.nested); + Protobuf.common('descriptor', descriptorDescriptor.nested.google.nested.protobuf.nested); + Protobuf.common('source_context', sourceContextDescriptor.nested.google.nested.protobuf.nested); + Protobuf.common('type', typeDescriptor.nested.google.nested.protobuf.nested); +} +exports.addCommonProtos = addCommonProtos; +//# sourceMappingURL=util.js.map \ No newline at end of file diff --git a/node_modules/@grpc/proto-loader/build/src/util.js.map b/node_modules/@grpc/proto-loader/build/src/util.js.map new file mode 100644 index 0000000..bb517f7 --- /dev/null +++ b/node_modules/@grpc/proto-loader/build/src/util.js.map @@ -0,0 +1 @@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CAAC,MAAM,CACb,YAAY,EACZ,oBAAoB,CAAC,MAAM,CAAC,MAAM,CAAC,MAAM,CAAC,QAAQ,CAAC,MAAM,CAC1D,CAAC;IACF,QAAQ,CAAC,MAAM,CACb,gBAAgB,EAChB,uBAAuB,CAAC,MAAM,CAAC,MAAM,CAAC,MAAM,CAAC,QAAQ,CAAC,MAAM,CAC7D,CAAC;IACF,QAAQ,CAAC,MAAM,CACb,MAAM,EACN,cAAc,CAAC,MAAM,CAAC,MAAM,CAAC,MAAM,CAAC,QAAQ,CAAC,MAAM,CACpD,CAAC;AACJ,CAAC;AA1BD,0CA0BC"} \ No newline at end of file diff --git a/node_modules/@grpc/proto-loader/package.json b/node_modules/@grpc/proto-loader/package.json new file mode 100644 index 0000000..290ed84 --- /dev/null +++ b/node_modules/@grpc/proto-loader/package.json @@ -0,0 +1,69 @@ +{ + "name": "@grpc/proto-loader", + "version": "0.7.13", + "author": "Google Inc.", + "contributors": [ + { + "name": "Michael Lumish", + "email": "mlumish@google.com" + } + ], + "description": "gRPC utility library for loading .proto files", + "homepage": "https://grpc.io/", + "main": "build/src/index.js", + "typings": "build/src/index.d.ts", + "scripts": { + "build": "npm run compile", + "clean": "rimraf ./build", + "compile": "tsc -p .", + "format": "clang-format -i -style=\"{Language: JavaScript, BasedOnStyle: Google, ColumnLimit: 80}\" src/*.ts test/*.ts", + "lint": "tslint -c node_modules/google-ts-style/tslint.json -p . -t codeFrame --type-check", + "prepare": "npm run compile", + "test": "gulp test", + "check": "gts check", + "fix": "gts fix", + "pretest": "npm run compile", + "posttest": "npm run check", + "generate-golden": "node ./build/bin/proto-loader-gen-types.js --keepCase --longs=String --enums=String --defaults --oneofs --json --includeComments --inputTemplate=I%s --outputTemplate=O%s -I deps/gapic-showcase/schema/ deps/googleapis/ -O ./golden-generated --grpcLib @grpc/grpc-js google/showcase/v1beta1/echo.proto", + "validate-golden": "rm -rf ./golden-generated-old && mv ./golden-generated/ ./golden-generated-old && npm run generate-golden && diff -rb ./golden-generated ./golden-generated-old" + }, + "repository": { + "type": "git", + "url": "https://github.com/grpc/grpc-node.git" + }, + "license": "Apache-2.0", + "bugs": { + "url": "https://github.com/grpc/grpc-node/issues" + }, + "files": [ + "LICENSE", + "build/src/*.d.ts", + "build/src/*.{js,js.map}", + "build/bin/*.{js,js.map}" + ], + "bin": { + "proto-loader-gen-types": "./build/bin/proto-loader-gen-types.js" + }, + "dependencies": { + "lodash.camelcase": "^4.3.0", + "long": "^5.0.0", + "protobufjs": "^7.2.5", + "yargs": "^17.7.2" + }, + "devDependencies": { + "@types/lodash.camelcase": "^4.3.4", + "@types/mkdirp": "^1.0.1", + "@types/mocha": "^5.2.7", + "@types/node": "^10.17.26", + "@types/yargs": "^17.0.24", + "clang-format": "^1.2.2", + "google-proto-files": "^3.0.2", + "gts": "^3.1.0", + "rimraf": "^3.0.2", + "ts-node": "^10.9.2", + "typescript": "~4.7.4" + }, + "engines": { + "node": ">=6" + } +} diff --git a/node_modules/@js-sdsl/ordered-map/CHANGELOG.md b/node_modules/@js-sdsl/ordered-map/CHANGELOG.md new file mode 100644 index 0000000..4bd804b --- /dev/null +++ b/node_modules/@js-sdsl/ordered-map/CHANGELOG.md @@ -0,0 +1,237 @@ +# Change Log + +All notable changes to this project will be documented in this file. + +The format is based on Keep a Changelog and this project adheres to Semantic Versioning. + +## [4.4.2] - 2023.07.21 + +### Fixed + +- The pointer of Adapter container's iterator cannot as array to be deconstructed. + +### Added + +- Add `isAccessible` function to iterators for iterable containers. + +## [4.4.1] - 2023.06.05 + +### Fixed + +- Tree container with less than 3 items reverse iteration infinite loop + +## [4.4.0] - 2023.03.17 + +### Changed + +- Optimized inOrder travel function for tree container. +- Optimized `Symbol.iterator` function. +- Optimized `TreeContainer` `erase` function. +- Optimized some details of deque. +- Change `reverse` and `sort` returned value to `this`. + +## [4.3.0] - 2023.01.20 + +### Added + +- Add public member `container` to `Iterator` which means the container that the iterator pointed to. + +### Changed + +- Reimplement `Queue`, separate `Queue` from `Deque`. + +## [4.2.0] - 2022.11.20 + +### Changed + +- Optimized the structure of class `TreeNodeEnableIndex`. +- Change the `iterator access denied` error message to reduce the packing size. +- Change the internal storage of the hash container to the form of a linked list, traversing in insertion order. +- Standardize hash container. Make it extends from `Container` and add general functions. +- Refactor `LinkList` to do optimization. + +### Added + +- Add public `length` property to all the container. +- Add returned value to `pop` function including `popBack` and `popFront` to all the container which has such function. +- Add returned value to `eraseElementByKey` which means whether erase successfully. +- Add returned value to `push` or `insert` function which means the size of the container. + +### Fixed + +- Fixed wrong error type when `updateKeyByIterator`. +- Fixed wrong iterator was returned when erase tree reverse iterator. + +## [4.2.0-beta.1] - 2022.11.06 + +### Changed + +- Remove all the arrow function to optimize. +- Modify `HashContainer` implementation to optimize. + +## [4.2.0-beta.0] - 2022.10.30 + +### Added + +- Add `ts` sourcemap for debug mode. +- Add `this` param for `forEach` function. +- Support single package umd build. + +### Changed + +- Changed the packaging method of isolation packages release and the method of the member export. + +## [4.1.5] - 2022.09.30 + +### Added + +- Add `find`, `remove`, `updateItem` and `toArray` functions to `PriorityQueue`. +- Support single package release (use scope @js-sdsl). + +## [4.1.5-beta.1] - 2022.09.23 + +### Fixed + +- Get wrong tree index when size is 0. + +## [4.1.5-beta.0] - 2022.09.23 + +### Added + +- Add `index` property to tree iterator which represents the sequential index of the iterator in the tree. + +### Changed + +- Minimal optimization with private properties mangling, macro inlining and const enum. +- Private properties are now mangled. +- Remove `checkWithinAccessParams` function. +- Constants of `HashContainer` are moved to `HashContainerConst` const enum. +- The iteratorType parameter in the constructor now changed from `boolean` type to `IteratorType` const enum type. +- The type of `TreeNode.color` is now changed from `boolean` to `TreeNodeColor` const enum. +- Turn some member exports into export-only types. + +### Fixed + +- Fixed wrong iterator error message. + +## [4.1.4] - 2022.09.07 + +### Added + +- Add some notes. + +### Changed + +- Optimize hash container. +- Abstracting out the hash container. + +### Fixed + +- Fixed tree get height function return one larger than the real height. +- Tree-shaking not work in ES module. +- `Queue` and `Deque` should return `undefined` when container is empty. + +## [4.1.4-beta.0] - 2022.08.31 + +### Added + +- Add function update key by iterator. +- Add iterator copy function to get a copy of itself. +- Add insert by iterator hint function in tree container. + +### Changed + +- Changed OrderedMap's iterator pointer get from `Object.defineProperty'` to `Proxy`. +- Improve iterator performance by remove some judgment. +- Change iterator type description from `normal` and `reverse` to boolean. + +## [4.1.2-beta.0] - 2022.08.27 + +### Added + +- Make `SequentialContainer` and `TreeBaseContainer` export in the index. + +### Changed + +- Change rbTree binary search from recursive to loop implementation (don't effect using). +- Reduce memory waste during deque initialization. + +### Fixed + +- Fixed priority queue not dereference on pop. + +## [4.1.1] - 2022.08.23 + +### Fixed + +- Forgot to reset root node on rotation in red-black tree delete operation. +- Fix iterator invalidation after tree container removes iterator. + +## [4.1.0] - 2022.08.21 + +### Changed + +- Change some functions from recursive to loop implementation (don't effect using). +- Change some iterator function parameter type. +- Change commonjs target to `es6`. +- Change `Deque` from sequential queue to circular queue. +- Optimize so many places (don't affect using). + +### Fixed + +- Fix `Vector` length bugs. + +## [4.0.3] - 2022-08-13 + +### Changed + +- Change `if (this.empty())` to `if (!this.length)`. +- Change some unit test. +- Change class type and optimized type design. + +### Fixed + +- Fix can push undefined to deque. + +## [4.0.0] - 2022-07-30 + +### Changed + +- Remove InternalError error as much as possible (don't affect using). +- Change `HashSet` api `eraseElementByValue`'s name to `eraseElementByKey`. +- Change some unit tests to improve coverage (don't affect using). + +## [4.0.0-beta.0] - 2022-07-24 + +### Added + +- Complete test examples (don't effect using). +- The error thrown is standardized, you can catch it according to the error type. + +### Changed + +- Refactor all container from function to class (don't affect using). +- Abstracting tree containers and hash containers, change `Set`'s and `Map`'s name to `OrderedSet` and `OrderedMap` to distinguish it from the official container. +- Change `OrderedSet` api `eraseElementByValue`'s name to `eraseElementByKey`. + +### Fixed + +- Fixed so many bugs. + +## [3.0.0-beta.0] - 2022-04-29 + +### Added + +- Bidirectional iterator is provided for all containers except Stack, Queue, HashSet and HashMap. +- Added begin, end, rBegin and rEnd functions to some containers for using iterator. +- Added `eraseElementByIterator` function. + +### Changed + +- Changed Pair type `T, K` to `K, V` (don't affect using). +- Changed `find`, `lowerBound`, `upperBound`, `reverseLowerBound` and `reverseUpperBound` function's returned value to `Iterator`. + +### Fixed + +- Fixed an error when the insert value was 0. +- Fixed the problem that the lower version browser does not recognize symbol Compilation error caused by iterator. diff --git a/node_modules/@js-sdsl/ordered-map/LICENSE b/node_modules/@js-sdsl/ordered-map/LICENSE new file mode 100644 index 0000000..d46bd7e --- /dev/null +++ b/node_modules/@js-sdsl/ordered-map/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2021 Zilong Yao + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/node_modules/@js-sdsl/ordered-map/README.md b/node_modules/@js-sdsl/ordered-map/README.md new file mode 100644 index 0000000..5b68d20 --- /dev/null +++ b/node_modules/@js-sdsl/ordered-map/README.md @@ -0,0 +1,270 @@ +

+ + js-sdsl logo + +

+ +

A javascript standard data structure library which benchmark against C++ STL

+ +

+ NPM Version + Build Status + Coverage Status + GITHUB Star + NPM Downloads + Gzip Size + Rate this package + MIT-license + GITHUB-language +

+ +

English | 简体中文

+ +## ✨ Included data structures + +- **Stack** - first in last out stack. +- **Queue** - first in first out queue. +- **PriorityQueue** - heap-implemented priority queue. +- **Vector** - protected array, cannot to operate properties like `length` directly. +- **LinkList** - linked list of non-contiguous memory addresses. +- **Deque** - double-ended-queue, O(1) time complexity to `unshift` or getting elements by index. +- **OrderedSet** - sorted set which implemented by red black tree. +- **OrderedMap** - sorted map which implemented by red black tree. +- **HashSet** - refer to the [polyfill of ES6 Set](https://github.com/rousan/collections-es6). +- **HashMap** - refer to the [polyfill of ES6 Map](https://github.com/rousan/collections-es6). + +## ⚔️ Benchmark + +We are benchmarking against other popular data structure libraries. In some ways we're better than the best library. See [benchmark](https://js-sdsl.org/#/test/benchmark-analyze). + +## 🖥 Supported platforms + +| ![][Edge-Icon]
IE / Edge | ![][Firefox-Icon]
Firefox | ![][Chrome-Icon]
Chrome | ![][Safari-Icon]
Safari | ![][Opera-Icon]
Opera | ![][NodeJs-Icon]
NodeJs | +|:----------------------------:|:-----------------------------:|:---------------------------:|:---------------------------:|:-------------------------:|:---------------------------:| +| Edge 12 | 36 | 49 | 10 | 36 | 10 | + +## 📦 Download + +Download directly by cdn: + +- [js-sdsl.js](https://unpkg.com/js-sdsl/dist/umd/js-sdsl.js) (for development) +- [js-sdsl.min.js](https://unpkg.com/js-sdsl/dist/umd/js-sdsl.min.js) (for production) + +Or install js-sdsl using npm: + +```bash +npm install js-sdsl +``` + +Or you can download the isolation packages containing only the containers you want: + +| package | npm | size | docs | +|---------------------------------------------------|-----------------------------------------------------------------------|------------------------------------------------------------------|-----------------------------| +| [@js-sdsl/stack][stack-package] | [![NPM Package][stack-npm-version]][stack-npm-link] | [![GZIP Size][stack-umd-size]][stack-umd-link] | [link][stack-docs] | +| [@js-sdsl/queue][queue-package] | [![NPM Package][queue-npm-version]][queue-npm-link] | [![GZIP Size][queue-umd-size]][queue-umd-link] | [link][queue-docs] | +| [@js-sdsl/priority-queue][priority-queue-package] | [![NPM Package][priority-queue-npm-version]][priority-queue-npm-link] | [![GZIP Size][priority-queue-umd-size]][priority-queue-umd-link] | [link][priority-queue-docs] | +| [@js-sdsl/vector][vector-package] | [![NPM Package][vector-npm-version]][vector-npm-link] | [![GZIP Size][vector-umd-size]][vector-umd-link] | [link][vector-docs] | +| [@js-sdsl/link-list][link-list-package] | [![NPM Package][link-list-npm-version]][link-list-npm-link] | [![GZIP Size][link-list-umd-size]][link-list-umd-link] | [link][link-list-docs] | +| [@js-sdsl/deque][deque-package] | [![NPM Package][deque-npm-version]][deque-npm-link] | [![GZIP Size][deque-umd-size]][deque-umd-link] | [link][deque-docs] | +| [@js-sdsl/ordered-set][ordered-set-package] | [![NPM Package][ordered-set-npm-version]][ordered-set-npm-link] | [![GZIP Size][ordered-set-umd-size]][ordered-set-umd-link] | [link][ordered-set-docs] | +| [@js-sdsl/ordered-map][ordered-map-package] | [![NPM Package][ordered-map-npm-version]][ordered-map-npm-link] | [![GZIP Size][ordered-map-umd-size]][ordered-map-umd-link] | [link][ordered-map-docs] | +| [@js-sdsl/hash-set][hash-set-package] | [![NPM Package][hash-set-npm-version]][hash-set-npm-link] | [![GZIP Size][hash-set-umd-size]][hash-set-umd-link] | [link][hash-set-docs] | +| [@js-sdsl/hash-map][hash-map-package] | [![NPM Package][hash-map-npm-version]][hash-map-npm-link] | [![GZIP Size][hash-map-umd-size]][hash-map-umd-link] | [link][hash-map-docs] | + +## 🪒 Usage + +You can visit our [official website](https://js-sdsl.org/) to get more information. + +To help you have a better use, we also provide this [API document](https://js-sdsl.org/js-sdsl/index.html). + +For previous versions of the documentation, please visit: + +`https://js-sdsl.org/js-sdsl/previous/v${version}/index.html` + +E.g. + +[https://js-sdsl.org/js-sdsl/previous/v4.1.5/index.html](https://js-sdsl.org/js-sdsl/previous/v4.1.5/index.html) + +### For browser + +```html + + +``` + +### For npm + +```javascript +// esModule +import { OrderedMap } from 'js-sdsl'; +// commonJs +const { OrderedMap } = require('js-sdsl'); +const myOrderedMap = new OrderedMap(); +myOrderedMap.setElement(1, 2); +console.log(myOrderedMap.getElementByKey(1)); // 2 +``` + +## 🛠 Test + +### Unit test + +We use [karma](https://karma-runner.github.io/) and [mocha](https://mochajs.org/) frame to do unit tests and synchronize to [coveralls](https://coveralls.io/github/js-sdsl/js-sdsl). You can run `yarn test:unit` command to reproduce it. + +### For performance + +We tested most of the functions for efficiency. You can go to [`gh-pages/performance.md`](https://github.com/js-sdsl/js-sdsl/blob/gh-pages/performance.md) to see our running results or reproduce it with `yarn test:performance` command. + +You can also visit [here](https://js-sdsl.org/#/test/performance-test) to get the result. + +## ⌨️ Development + +Use Gitpod, a free online dev environment for GitHub. + +[![Open in Gippod](https://gitpod.io/button/open-in-gitpod.svg)](https://gitpod.io/#https://github.com/js-sdsl/js-sdsl) + +Or clone locally: + +```bash +$ git clone https://github.com/js-sdsl/js-sdsl.git +$ cd js-sdsl +$ npm install +$ npm run dev # development mode +``` + +Then you can see the output in `dist/cjs` folder. + +## 🤝 Contributing + +Feel free to dive in! Open an issue or submit PRs. It may be helpful to read the [Contributor Guide](https://github.com/js-sdsl/js-sdsl/blob/main/.github/CONTRIBUTING.md). + +### Contributors + +Thanks goes to these wonderful people: + + + + + + + + + + + +

Takatoshi Kondo

💻 ⚠️

noname

💻
+ + + + + + +This project follows the [all-contributors](https://github.com/all-contributors/all-contributors) specification. Contributions of any kind welcome! + +## ❤️ Sponsors and Backers + +The special thanks to these sponsors or backers because they provided support at a very early stage: + +eslint logo + +Thanks also give to these sponsors or backers: + +[![sponsors](https://opencollective.com/js-sdsl/tiers/sponsors.svg?avatarHeight=36)](https://opencollective.com/js-sdsl#support) + +[![backers](https://opencollective.com/js-sdsl/tiers/backers.svg?avatarHeight=36)](https://opencollective.com/js-sdsl#support) + +## 🪪 License + +[MIT](https://github.com/js-sdsl/js-sdsl/blob/main/LICENSE) © [ZLY201](https://github.com/zly201) + +[Edge-Icon]: https://js-sdsl.org/assets/image/platform/edge.png +[Firefox-Icon]: https://js-sdsl.org/assets/image/platform/firefox.png +[Chrome-Icon]: https://js-sdsl.org/assets/image/platform/chrome.png +[Safari-Icon]: https://js-sdsl.org/assets/image/platform/safari.png +[Opera-Icon]: https://js-sdsl.org/assets/image/platform/opera.png +[NodeJs-Icon]: https://js-sdsl.org/assets/image/platform/nodejs.png + +[stack-package]: https://github.com/js-sdsl/js-sdsl/blob/main/src/container/OtherContainer/Stack.ts +[stack-npm-version]: https://img.shields.io/npm/v/@js-sdsl/stack +[stack-npm-link]: https://www.npmjs.com/package/@js-sdsl/stack +[stack-umd-size]: https://img.badgesize.io/https://unpkg.com/@js-sdsl/stack/dist/umd/stack.min.js?compression=gzip&style=flat-square/ +[stack-umd-link]: https://unpkg.com/@js-sdsl/stack/dist/umd/stack.min.js +[stack-docs]: https://js-sdsl.org/js-sdsl/classes/Stack.html + +[queue-package]: https://github.com/js-sdsl/js-sdsl/blob/main/src/container/OtherContainer/Queue.ts +[queue-npm-version]: https://img.shields.io/npm/v/@js-sdsl/queue +[queue-npm-link]: https://www.npmjs.com/package/@js-sdsl/queue +[queue-umd-size]: https://img.badgesize.io/https://unpkg.com/@js-sdsl/queue/dist/umd/queue.min.js?compression=gzip&style=flat-square/ +[queue-umd-link]: https://unpkg.com/@js-sdsl/queue/dist/umd/queue.min.js +[queue-docs]: https://js-sdsl.org/js-sdsl/classes/Queue.html + +[priority-queue-package]: https://github.com/js-sdsl/js-sdsl/blob/main/src/container/OtherContainer/PriorityQueue.ts +[priority-queue-npm-version]: https://img.shields.io/npm/v/@js-sdsl/priority-queue +[priority-queue-npm-link]: https://www.npmjs.com/package/@js-sdsl/priority-queue +[priority-queue-umd-size]: https://img.badgesize.io/https://unpkg.com/@js-sdsl/priority-queue/dist/umd/priority-queue.min.js?compression=gzip&style=flat-square/ +[priority-queue-umd-link]: https://unpkg.com/@js-sdsl/priority-queue/dist/umd/priority-queue.min.js +[priority-queue-docs]: https://js-sdsl.org/js-sdsl/classes/PriorityQueue.html + +[vector-package]: https://github.com/js-sdsl/js-sdsl/blob/main/src/container/SequentialContainer/Vector.ts +[vector-npm-version]: https://img.shields.io/npm/v/@js-sdsl/vector +[vector-npm-link]: https://www.npmjs.com/package/@js-sdsl/vector +[vector-umd-size]: https://img.badgesize.io/https://unpkg.com/@js-sdsl/vector/dist/umd/vector.min.js?compression=gzip&style=flat-square/ +[vector-umd-link]: https://unpkg.com/@js-sdsl/vector/dist/umd/vector.min.js +[vector-docs]: https://js-sdsl.org/js-sdsl/classes/Vector.html + +[link-list-package]: https://github.com/js-sdsl/js-sdsl/blob/main/src/container/SequentialContainer/LinkList.ts +[link-list-npm-version]: https://img.shields.io/npm/v/@js-sdsl/link-list +[link-list-npm-link]: https://www.npmjs.com/package/@js-sdsl/link-list +[link-list-umd-size]: https://img.badgesize.io/https://unpkg.com/@js-sdsl/link-list/dist/umd/link-list.min.js?compression=gzip&style=flat-square/ +[link-list-umd-link]: https://unpkg.com/@js-sdsl/link-list/dist/umd/link-list.min.js +[link-list-docs]: https://js-sdsl.org/js-sdsl/classes/LinkList.html + +[deque-package]: https://github.com/js-sdsl/js-sdsl/blob/main/src/container/SequentialContainer/Deque.ts +[deque-npm-version]: https://img.shields.io/npm/v/@js-sdsl/deque +[deque-npm-link]: https://www.npmjs.com/package/@js-sdsl/deque +[deque-umd-size]: https://img.badgesize.io/https://unpkg.com/@js-sdsl/deque/dist/umd/deque.min.js?compression=gzip&style=flat-square/ +[deque-umd-link]: https://unpkg.com/@js-sdsl/deque/dist/umd/deque.min.js +[deque-docs]: https://js-sdsl.org/js-sdsl/classes/Deque.html + +[ordered-set-package]: https://github.com/js-sdsl/js-sdsl/blob/main/src/container/TreeContainer/OrderedSet.ts +[ordered-set-npm-version]: https://img.shields.io/npm/v/@js-sdsl/ordered-set +[ordered-set-npm-link]: https://www.npmjs.com/package/@js-sdsl/ordered-set +[ordered-set-umd-size]: https://img.badgesize.io/https://unpkg.com/@js-sdsl/ordered-set/dist/umd/ordered-set.min.js?compression=gzip&style=flat-square/ +[ordered-set-umd-link]: https://unpkg.com/@js-sdsl/ordered-set/dist/umd/ordered-set.min.js +[ordered-set-docs]: https://js-sdsl.org/js-sdsl/classes/OrderedSet.html + +[ordered-map-package]: https://github.com/js-sdsl/js-sdsl/blob/main/src/container/TreeContainer/OrderedMap.ts +[ordered-map-npm-version]: https://img.shields.io/npm/v/@js-sdsl/ordered-map +[ordered-map-npm-link]: https://www.npmjs.com/package/@js-sdsl/ordered-map +[ordered-map-umd-size]: https://img.badgesize.io/https://unpkg.com/@js-sdsl/ordered-map/dist/umd/ordered-map.min.js?compression=gzip&style=flat-square/ +[ordered-map-umd-link]: https://unpkg.com/@js-sdsl/ordered-map/dist/umd/ordered-map.min.js +[ordered-map-docs]: https://js-sdsl.org/js-sdsl/classes/OrderedMap.html + +[hash-set-package]: https://github.com/js-sdsl/js-sdsl/blob/main/src/container/HashContainer/HashSet.ts +[hash-set-npm-version]: https://img.shields.io/npm/v/@js-sdsl/hash-set +[hash-set-npm-link]: https://www.npmjs.com/package/@js-sdsl/hash-set +[hash-set-umd-size]: https://img.badgesize.io/https://unpkg.com/@js-sdsl/hash-set/dist/umd/hash-set.min.js?compression=gzip&style=flat-square/ +[hash-set-umd-link]: https://unpkg.com/@js-sdsl/hash-set/dist/umd/hash-set.min.js +[hash-set-docs]: https://js-sdsl.org/js-sdsl/classes/HashSet.html + +[hash-map-package]: https://github.com/js-sdsl/js-sdsl/blob/main/src/container/HashContainer/HashMap.ts +[hash-map-npm-version]: https://img.shields.io/npm/v/@js-sdsl/hash-map +[hash-map-npm-link]: https://www.npmjs.com/package/@js-sdsl/hash-map +[hash-map-umd-size]: https://img.badgesize.io/https://unpkg.com/@js-sdsl/hash-map/dist/umd/hash-map.min.js?compression=gzip&style=flat-square/ +[hash-map-umd-link]: https://unpkg.com/@js-sdsl/hash-map/dist/umd/hash-map.min.js +[hash-map-docs]: https://js-sdsl.org/js-sdsl/classes/HashMap.html diff --git a/node_modules/@js-sdsl/ordered-map/README.zh-CN.md b/node_modules/@js-sdsl/ordered-map/README.zh-CN.md new file mode 100644 index 0000000..a10ef17 --- /dev/null +++ b/node_modules/@js-sdsl/ordered-map/README.zh-CN.md @@ -0,0 +1,272 @@ +

+ + js-sdsl logo + +

+ +

一款参考 C++ STL 实现的 JavaScript 标准数据结构库

+ +

+ NPM Version + Build Status + Coverage Status + GITHUB Star + NPM Downloads + Gzip Size + Rate this package + MIT-license + GITHUB-language +

+ +

English | 简体中文

+ +## ✨ 包含的数据结构 + +- **Stack** - 先进后出的堆栈 +- **Queue** - 先进先出的队列 +- **PriorityQueue** - 堆实现的优先级队列 +- **Vector** - 受保护的数组,不能直接操作像 `length` 这样的属性 +- **LinkList** - 非连续内存地址的链表 +- **Deque** - 双端队列,向前和向后插入元素或按索引获取元素的时间复杂度为 O(1) +- **OrderedSet** - 由红黑树实现的排序集合 +- **OrderedMap** - 由红黑树实现的排序字典 +- **HashSet** - 参考 [ES6 Set polyfill](https://github.com/rousan/collections-es6) 实现的哈希集合 +- **HashMap** - 参考 [ES6 Set polyfill](https://github.com/rousan/collections-es6) 实现的哈希字典 + +## ⚔️ 基准测试 + +我们和其他数据结构库进行了基准测试,在某些场景我们甚至超过了当前最流行的库 + +查看 [benchmark](https://js-sdsl.org/#/zh-cn/test/benchmark-analyze) 以获取更多信息 + +## 🖥 支持的平台 + +| ![][Edge-Icon]
IE / Edge | ![][Firefox-Icon]
Firefox | ![][Chrome-Icon]
Chrome | ![][Safari-Icon]
Safari | ![][Opera-Icon]
Opera | ![][NodeJs-Icon]
NodeJs | +|:----------------------------:|:-----------------------------:|:---------------------------:|:---------------------------:|:-------------------------:|:---------------------------:| +| Edge 12 | 36 | 49 | 10 | 36 | 10 | + +## 📦 下载 + +使用 cdn 直接引入 + +- [js-sdsl.js](https://unpkg.com/js-sdsl/dist/umd/js-sdsl.js) (for development) +- [js-sdsl.min.js](https://unpkg.com/js-sdsl/dist/umd/js-sdsl.min.js) (for production) + +使用 npm 下载 + +```bash +npm install js-sdsl +``` + +或者根据需要安装以下任意单个包 + +| package | npm | size | docs | +|---------------------------------------------------|-----------------------------------------------------------------------|------------------------------------------------------------------|-----------------------------| +| [@js-sdsl/stack][stack-package] | [![NPM Package][stack-npm-version]][stack-npm-link] | [![GZIP Size][stack-umd-size]][stack-umd-link] | [link][stack-docs] | +| [@js-sdsl/queue][queue-package] | [![NPM Package][queue-npm-version]][queue-npm-link] | [![GZIP Size][queue-umd-size]][queue-umd-link] | [link][queue-docs] | +| [@js-sdsl/priority-queue][priority-queue-package] | [![NPM Package][priority-queue-npm-version]][priority-queue-npm-link] | [![GZIP Size][priority-queue-umd-size]][priority-queue-umd-link] | [link][priority-queue-docs] | +| [@js-sdsl/vector][vector-package] | [![NPM Package][vector-npm-version]][vector-npm-link] | [![GZIP Size][vector-umd-size]][vector-umd-link] | [link][vector-docs] | +| [@js-sdsl/link-list][link-list-package] | [![NPM Package][link-list-npm-version]][link-list-npm-link] | [![GZIP Size][link-list-umd-size]][link-list-umd-link] | [link][link-list-docs] | +| [@js-sdsl/deque][deque-package] | [![NPM Package][deque-npm-version]][deque-npm-link] | [![GZIP Size][deque-umd-size]][deque-umd-link] | [link][deque-docs] | +| [@js-sdsl/ordered-set][ordered-set-package] | [![NPM Package][ordered-set-npm-version]][ordered-set-npm-link] | [![GZIP Size][ordered-set-umd-size]][ordered-set-umd-link] | [link][ordered-set-docs] | +| [@js-sdsl/ordered-map][ordered-map-package] | [![NPM Package][ordered-map-npm-version]][ordered-map-npm-link] | [![GZIP Size][ordered-map-umd-size]][ordered-map-umd-link] | [link][ordered-map-docs] | +| [@js-sdsl/hash-set][hash-set-package] | [![NPM Package][hash-set-npm-version]][hash-set-npm-link] | [![GZIP Size][hash-set-umd-size]][hash-set-umd-link] | [link][hash-set-docs] | +| [@js-sdsl/hash-map][hash-map-package] | [![NPM Package][hash-map-npm-version]][hash-map-npm-link] | [![GZIP Size][hash-map-umd-size]][hash-map-umd-link] | [link][hash-map-docs] | + +## 🪒 使用说明 + +您可以[访问我们的主页](https://js-sdsl.org/)获取更多信息 + +并且我们提供了完整的 [API 文档](https://js-sdsl.org/js-sdsl/index.html)供您参考 + +想要查看从前版本的文档,请访问: + +`https://js-sdsl.org/js-sdsl/previous/v${version}/index.html` + +例如: + +[https://js-sdsl.org/js-sdsl/previous/v4.1.5/index.html](https://js-sdsl.org/js-sdsl/previous/v4.1.5/index.html) + +### 在浏览器中使用 + +```html + + +``` + +### npm 引入 + +```javascript +// esModule +import { OrderedMap } from 'js-sdsl'; +// commonJs +const { OrderedMap } = require('js-sdsl'); +const myOrderedMap = new OrderedMap(); +myOrderedMap.setElement(1, 2); +console.log(myOrderedMap.getElementByKey(1)); // 2 +``` + +## 🛠 测试 + +### 单元测试 + +我们使用 [karma](https://karma-runner.github.io/) 和 [mocha](https://mochajs.org/) 框架进行单元测试,并同步到 [coveralls](https://coveralls.io/github/js-sdsl/js-sdsl) 上,你可以使用 `yarn test:unit` 命令来重建它 + +### 对于性能的校验 + +我们对于编写的所有 API 进行了性能测试,并将结果同步到了 [`gh-pages/performance.md`](https://github.com/js-sdsl/js-sdsl/blob/gh-pages/performance.md) 中,你可以通过 `yarn test:performance` 命令来重现它 + +您也可以访问[我们的网站](https://js-sdsl.org/#/zh-cn/test/performance-test)来获取结果 + +## ⌨️ 开发 + +可以使用 Gitpod 进行在线编辑: + +[![Open in Gippod](https://gitpod.io/button/open-in-gitpod.svg)](https://gitpod.io/#https://github.com/js-sdsl/js-sdsl) + +或者在本地使用以下命令获取源码进行开发: + +```bash +$ git clone https://github.com/js-sdsl/js-sdsl.git +$ cd js-sdsl +$ npm install +$ npm run dev # development mode +``` + +之后您在 `dist/cjs` 文件夹中可以看到在 `dev` 模式下打包生成的产物 + +## 🤝 贡献 + +我们欢迎所有的开发人员提交 issue 或 pull request,阅读[贡献者指南](https://github.com/js-sdsl/js-sdsl/blob/main/.github/CONTRIBUTING.md)可能会有所帮助 + +### 贡献者 + +感谢对本项目做出贡献的开发者们: + + + + + + + + + + + +

Takatoshi Kondo

💻 ⚠️

noname

💻
+ + + + + + +本项目遵循 [all-contributors](https://github.com/all-contributors/all-contributors) 规范。 欢迎任何形式的贡献! + +## ❤️ 赞助者 + +特别鸣谢下列赞助商和支持者们,他们在非常早期的时候为我们提供了支持: + +eslint logo + +同样感谢这些赞助商和支持者们: + +[![sponsors](https://opencollective.com/js-sdsl/tiers/sponsors.svg?avatarHeight=36)](https://opencollective.com/js-sdsl#support) + +[![backers](https://opencollective.com/js-sdsl/tiers/backers.svg?avatarHeight=36)](https://opencollective.com/js-sdsl#support) + +## 🪪 许可证 + +[MIT](https://github.com/js-sdsl/js-sdsl/blob/main/LICENSE) © [ZLY201](https://github.com/zly201) + +[Edge-Icon]: https://js-sdsl.org/assets/image/platform/edge.png +[Firefox-Icon]: https://js-sdsl.org/assets/image/platform/firefox.png +[Chrome-Icon]: https://js-sdsl.org/assets/image/platform/chrome.png +[Safari-Icon]: https://js-sdsl.org/assets/image/platform/safari.png +[Opera-Icon]: https://js-sdsl.org/assets/image/platform/opera.png +[NodeJs-Icon]: https://js-sdsl.org/assets/image/platform/nodejs.png + +[stack-package]: https://github.com/js-sdsl/js-sdsl/blob/main/src/container/OtherContainer/Stack.ts +[stack-npm-version]: https://img.shields.io/npm/v/@js-sdsl/stack +[stack-npm-link]: https://www.npmjs.com/package/@js-sdsl/stack +[stack-umd-size]: https://img.badgesize.io/https://unpkg.com/@js-sdsl/stack/dist/umd/stack.min.js?compression=gzip&style=flat-square/ +[stack-umd-link]: https://unpkg.com/@js-sdsl/stack/dist/umd/stack.min.js +[stack-docs]: https://js-sdsl.org/js-sdsl/classes/Stack.html + +[queue-package]: https://github.com/js-sdsl/js-sdsl/blob/main/src/container/OtherContainer/Queue.ts +[queue-npm-version]: https://img.shields.io/npm/v/@js-sdsl/queue +[queue-npm-link]: https://www.npmjs.com/package/@js-sdsl/queue +[queue-umd-size]: https://img.badgesize.io/https://unpkg.com/@js-sdsl/queue/dist/umd/queue.min.js?compression=gzip&style=flat-square/ +[queue-umd-link]: https://unpkg.com/@js-sdsl/queue/dist/umd/queue.min.js +[queue-docs]: https://js-sdsl.org/js-sdsl/classes/Queue.html + +[priority-queue-package]: https://github.com/js-sdsl/js-sdsl/blob/main/src/container/OtherContainer/PriorityQueue.ts +[priority-queue-npm-version]: https://img.shields.io/npm/v/@js-sdsl/priority-queue +[priority-queue-npm-link]: https://www.npmjs.com/package/@js-sdsl/priority-queue +[priority-queue-umd-size]: https://img.badgesize.io/https://unpkg.com/@js-sdsl/priority-queue/dist/umd/priority-queue.min.js?compression=gzip&style=flat-square/ +[priority-queue-umd-link]: https://unpkg.com/@js-sdsl/priority-queue/dist/umd/priority-queue.min.js +[priority-queue-docs]: https://js-sdsl.org/js-sdsl/classes/PriorityQueue.html + +[vector-package]: https://github.com/js-sdsl/js-sdsl/blob/main/src/container/SequentialContainer/Vector.ts +[vector-npm-version]: https://img.shields.io/npm/v/@js-sdsl/vector +[vector-npm-link]: https://www.npmjs.com/package/@js-sdsl/vector +[vector-umd-size]: https://img.badgesize.io/https://unpkg.com/@js-sdsl/vector/dist/umd/vector.min.js?compression=gzip&style=flat-square/ +[vector-umd-link]: https://unpkg.com/@js-sdsl/vector/dist/umd/vector.min.js +[vector-docs]: https://js-sdsl.org/js-sdsl/classes/Vector.html + +[link-list-package]: https://github.com/js-sdsl/js-sdsl/blob/main/src/container/SequentialContainer/LinkList.ts +[link-list-npm-version]: https://img.shields.io/npm/v/@js-sdsl/link-list +[link-list-npm-link]: https://www.npmjs.com/package/@js-sdsl/link-list +[link-list-umd-size]: https://img.badgesize.io/https://unpkg.com/@js-sdsl/link-list/dist/umd/link-list.min.js?compression=gzip&style=flat-square/ +[link-list-umd-link]: https://unpkg.com/@js-sdsl/link-list/dist/umd/link-list.min.js +[link-list-docs]: https://js-sdsl.org/js-sdsl/classes/LinkList.html + +[deque-package]: https://github.com/js-sdsl/js-sdsl/blob/main/src/container/SequentialContainer/Deque.ts +[deque-npm-version]: https://img.shields.io/npm/v/@js-sdsl/deque +[deque-npm-link]: https://www.npmjs.com/package/@js-sdsl/deque +[deque-umd-size]: https://img.badgesize.io/https://unpkg.com/@js-sdsl/deque/dist/umd/deque.min.js?compression=gzip&style=flat-square/ +[deque-umd-link]: https://unpkg.com/@js-sdsl/deque/dist/umd/deque.min.js +[deque-docs]: https://js-sdsl.org/js-sdsl/classes/Deque.html + +[ordered-set-package]: https://github.com/js-sdsl/js-sdsl/blob/main/src/container/TreeContainer/OrderedSet.ts +[ordered-set-npm-version]: https://img.shields.io/npm/v/@js-sdsl/ordered-set +[ordered-set-npm-link]: https://www.npmjs.com/package/@js-sdsl/ordered-set +[ordered-set-umd-size]: https://img.badgesize.io/https://unpkg.com/@js-sdsl/ordered-set/dist/umd/ordered-set.min.js?compression=gzip&style=flat-square/ +[ordered-set-umd-link]: https://unpkg.com/@js-sdsl/ordered-set/dist/umd/ordered-set.min.js +[ordered-set-docs]: https://js-sdsl.org/js-sdsl/classes/OrderedSet.html + +[ordered-map-package]: https://github.com/js-sdsl/js-sdsl/blob/main/src/container/TreeContainer/OrderedMap.ts +[ordered-map-npm-version]: https://img.shields.io/npm/v/@js-sdsl/ordered-map +[ordered-map-npm-link]: https://www.npmjs.com/package/@js-sdsl/ordered-map +[ordered-map-umd-size]: https://img.badgesize.io/https://unpkg.com/@js-sdsl/ordered-map/dist/umd/ordered-map.min.js?compression=gzip&style=flat-square/ +[ordered-map-umd-link]: https://unpkg.com/@js-sdsl/ordered-map/dist/umd/ordered-map.min.js +[ordered-map-docs]: https://js-sdsl.org/js-sdsl/classes/OrderedMap.html + +[hash-set-package]: https://github.com/js-sdsl/js-sdsl/blob/main/src/container/HashContainer/HashSet.ts +[hash-set-npm-version]: https://img.shields.io/npm/v/@js-sdsl/hash-set +[hash-set-npm-link]: https://www.npmjs.com/package/@js-sdsl/hash-set +[hash-set-umd-size]: https://img.badgesize.io/https://unpkg.com/@js-sdsl/hash-set/dist/umd/hash-set.min.js?compression=gzip&style=flat-square/ +[hash-set-umd-link]: https://unpkg.com/@js-sdsl/hash-set/dist/umd/hash-set.min.js +[hash-set-docs]: https://js-sdsl.org/js-sdsl/classes/HashSet.html + +[hash-map-package]: https://github.com/js-sdsl/js-sdsl/blob/main/src/container/HashContainer/HashMap.ts +[hash-map-npm-version]: https://img.shields.io/npm/v/@js-sdsl/hash-map +[hash-map-npm-link]: https://www.npmjs.com/package/@js-sdsl/hash-map +[hash-map-umd-size]: https://img.badgesize.io/https://unpkg.com/@js-sdsl/hash-map/dist/umd/hash-map.min.js?compression=gzip&style=flat-square/ +[hash-map-umd-link]: https://unpkg.com/@js-sdsl/hash-map/dist/umd/hash-map.min.js +[hash-map-docs]: https://js-sdsl.org/js-sdsl/classes/HashMap.html diff --git a/node_modules/@js-sdsl/ordered-map/dist/cjs/index.d.ts b/node_modules/@js-sdsl/ordered-map/dist/cjs/index.d.ts new file mode 100644 index 0000000..8615f37 --- /dev/null +++ b/node_modules/@js-sdsl/ordered-map/dist/cjs/index.d.ts @@ -0,0 +1,402 @@ +/** + * @description The iterator type including `NORMAL` and `REVERSE`. + */ +declare const enum IteratorType { + NORMAL = 0, + REVERSE = 1 +} +declare abstract class ContainerIterator { + /** + * @description The container pointed to by the iterator. + */ + abstract readonly container: Container; + /** + * @description Iterator's type. + * @example + * console.log(container.end().iteratorType === IteratorType.NORMAL); // true + */ + readonly iteratorType: IteratorType; + /** + * @param iter - The other iterator you want to compare. + * @returns Whether this equals to obj. + * @example + * container.find(1).equals(container.end()); + */ + equals(iter: ContainerIterator): boolean; + /** + * @description Pointers to element. + * @returns The value of the pointer's element. + * @example + * const val = container.begin().pointer; + */ + abstract get pointer(): T; + /** + * @description Set pointer's value (some containers are unavailable). + * @param newValue - The new value you want to set. + * @example + * (>container).begin().pointer = 1; + */ + abstract set pointer(newValue: T); + /** + * @description Move `this` iterator to pre. + * @returns The iterator's self. + * @example + * const iter = container.find(1); // container = [0, 1] + * const pre = iter.pre(); + * console.log(pre === iter); // true + * console.log(pre.equals(iter)); // true + * console.log(pre.pointer, iter.pointer); // 0, 0 + */ + abstract pre(): this; + /** + * @description Move `this` iterator to next. + * @returns The iterator's self. + * @example + * const iter = container.find(1); // container = [1, 2] + * const next = iter.next(); + * console.log(next === iter); // true + * console.log(next.equals(iter)); // true + * console.log(next.pointer, iter.pointer); // 2, 2 + */ + abstract next(): this; + /** + * @description Get a copy of itself. + * @returns The copy of self. + * @example + * const iter = container.find(1); // container = [1, 2] + * const next = iter.copy().next(); + * console.log(next === iter); // false + * console.log(next.equals(iter)); // false + * console.log(next.pointer, iter.pointer); // 2, 1 + */ + abstract copy(): ContainerIterator; + abstract isAccessible(): boolean; +} +declare abstract class Base { + /** + * @returns The size of the container. + * @example + * const container = new Vector([1, 2]); + * console.log(container.length); // 2 + */ + get length(): number; + /** + * @returns The size of the container. + * @example + * const container = new Vector([1, 2]); + * console.log(container.size()); // 2 + */ + size(): number; + /** + * @returns Whether the container is empty. + * @example + * container.clear(); + * console.log(container.empty()); // true + */ + empty(): boolean; + /** + * @description Clear the container. + * @example + * container.clear(); + * console.log(container.empty()); // true + */ + abstract clear(): void; +} +declare abstract class Container extends Base { + /** + * @returns Iterator pointing to the beginning element. + * @example + * const begin = container.begin(); + * const end = container.end(); + * for (const it = begin; !it.equals(end); it.next()) { + * doSomething(it.pointer); + * } + */ + abstract begin(): ContainerIterator; + /** + * @returns Iterator pointing to the super end like c++. + * @example + * const begin = container.begin(); + * const end = container.end(); + * for (const it = begin; !it.equals(end); it.next()) { + * doSomething(it.pointer); + * } + */ + abstract end(): ContainerIterator; + /** + * @returns Iterator pointing to the end element. + * @example + * const rBegin = container.rBegin(); + * const rEnd = container.rEnd(); + * for (const it = rBegin; !it.equals(rEnd); it.next()) { + * doSomething(it.pointer); + * } + */ + abstract rBegin(): ContainerIterator; + /** + * @returns Iterator pointing to the super begin like c++. + * @example + * const rBegin = container.rBegin(); + * const rEnd = container.rEnd(); + * for (const it = rBegin; !it.equals(rEnd); it.next()) { + * doSomething(it.pointer); + * } + */ + abstract rEnd(): ContainerIterator; + /** + * @returns The first element of the container. + */ + abstract front(): T | undefined; + /** + * @returns The last element of the container. + */ + abstract back(): T | undefined; + /** + * @param element - The element you want to find. + * @returns An iterator pointing to the element if found, or super end if not found. + * @example + * container.find(1).equals(container.end()); + */ + abstract find(element: T): ContainerIterator; + /** + * @description Iterate over all elements in the container. + * @param callback - Callback function like Array.forEach. + * @example + * container.forEach((element, index) => console.log(element, index)); + */ + abstract forEach(callback: (element: T, index: number, container: Container) => void): void; + /** + * @description Gets the value of the element at the specified position. + * @example + * const val = container.getElementByPos(-1); // throw a RangeError + */ + abstract getElementByPos(pos: number): T; + /** + * @description Removes the element at the specified position. + * @param pos - The element's position you want to remove. + * @returns The container length after erasing. + * @example + * container.eraseElementByPos(-1); // throw a RangeError + */ + abstract eraseElementByPos(pos: number): number; + /** + * @description Removes element by iterator and move `iter` to next. + * @param iter - The iterator you want to erase. + * @returns The next iterator. + * @example + * container.eraseElementByIterator(container.begin()); + * container.eraseElementByIterator(container.end()); // throw a RangeError + */ + abstract eraseElementByIterator(iter: ContainerIterator): ContainerIterator; + /** + * @description Using for `for...of` syntax like Array. + * @example + * for (const element of container) { + * console.log(element); + * } + */ + abstract [Symbol.iterator](): Generator; +} +/** + * @description The initial data type passed in when initializing the container. + */ +type initContainer = { + size?: number | (() => number); + length?: number; + forEach: (callback: (el: T) => void) => void; +}; +declare abstract class TreeIterator extends ContainerIterator { + abstract readonly container: TreeContainer; + /** + * @description Get the sequential index of the iterator in the tree container.
+ * Note: + * This function only takes effect when the specified tree container `enableIndex = true`. + * @returns The index subscript of the node in the tree. + * @example + * const st = new OrderedSet([1, 2, 3], true); + * console.log(st.begin().next().index); // 1 + */ + get index(): number; + isAccessible(): boolean; + // @ts-ignore + pre(): this; + // @ts-ignore + next(): this; +} +declare const enum TreeNodeColor { + RED = 1, + BLACK = 0 +} +declare class TreeNode { + _color: TreeNodeColor; + _key: K | undefined; + _value: V | undefined; + _left: TreeNode | undefined; + _right: TreeNode | undefined; + _parent: TreeNode | undefined; + constructor(key?: K, value?: V, color?: TreeNodeColor); + /** + * @description Get the pre node. + * @returns TreeNode about the pre node. + */ + _pre(): TreeNode; + /** + * @description Get the next node. + * @returns TreeNode about the next node. + */ + _next(): TreeNode; + /** + * @description Rotate left. + * @returns TreeNode about moved to original position after rotation. + */ + _rotateLeft(): TreeNode; + /** + * @description Rotate right. + * @returns TreeNode about moved to original position after rotation. + */ + _rotateRight(): TreeNode; +} +declare abstract class TreeContainer extends Container { + enableIndex: boolean; + protected _inOrderTraversal(): TreeNode[]; + protected _inOrderTraversal(pos: number): TreeNode; + protected _inOrderTraversal(callback: (node: TreeNode, index: number, map: this) => void): TreeNode; + clear(): void; + /** + * @description Update node's key by iterator. + * @param iter - The iterator you want to change. + * @param key - The key you want to update. + * @returns Whether the modification is successful. + * @example + * const st = new orderedSet([1, 2, 5]); + * const iter = st.find(2); + * st.updateKeyByIterator(iter, 3); // then st will become [1, 3, 5] + */ + updateKeyByIterator(iter: TreeIterator, key: K): boolean; + eraseElementByPos(pos: number): number; + /** + * @description Remove the element of the specified key. + * @param key - The key you want to remove. + * @returns Whether erase successfully. + */ + eraseElementByKey(key: K): boolean; + eraseElementByIterator(iter: TreeIterator): TreeIterator; + /** + * @description Get the height of the tree. + * @returns Number about the height of the RB-tree. + */ + getHeight(): number; + /** + * @param key - The given key you want to compare. + * @returns An iterator to the first element less than the given key. + */ + abstract reverseUpperBound(key: K): TreeIterator; + /** + * @description Union the other tree to self. + * @param other - The other tree container you want to merge. + * @returns The size of the tree after union. + */ + abstract union(other: TreeContainer): number; + /** + * @param key - The given key you want to compare. + * @returns An iterator to the first element not greater than the given key. + */ + abstract reverseLowerBound(key: K): TreeIterator; + /** + * @param key - The given key you want to compare. + * @returns An iterator to the first element not less than the given key. + */ + abstract lowerBound(key: K): TreeIterator; + /** + * @param key - The given key you want to compare. + * @returns An iterator to the first element greater than the given key. + */ + abstract upperBound(key: K): TreeIterator; +} +declare class OrderedMapIterator extends TreeIterator { + container: OrderedMap; + constructor(node: TreeNode, header: TreeNode, container: OrderedMap, iteratorType?: IteratorType); + get pointer(): [ + K, + V + ]; + copy(): OrderedMapIterator; + // @ts-ignore + equals(iter: OrderedMapIterator): boolean; +} +declare class OrderedMap extends TreeContainer { + /** + * @param container - The initialization container. + * @param cmp - The compare function. + * @param enableIndex - Whether to enable iterator indexing function. + * @example + * new OrderedMap(); + * new OrderedMap([[0, 1], [2, 1]]); + * new OrderedMap([[0, 1], [2, 1]], (x, y) => x - y); + * new OrderedMap([[0, 1], [2, 1]], (x, y) => x - y, true); + */ + constructor(container?: initContainer<[ + K, + V + ]>, cmp?: (x: K, y: K) => number, enableIndex?: boolean); + begin(): OrderedMapIterator; + end(): OrderedMapIterator; + rBegin(): OrderedMapIterator; + rEnd(): OrderedMapIterator; + front(): [ + K, + V + ] | undefined; + back(): [ + K, + V + ] | undefined; + lowerBound(key: K): OrderedMapIterator; + upperBound(key: K): OrderedMapIterator; + reverseLowerBound(key: K): OrderedMapIterator; + reverseUpperBound(key: K): OrderedMapIterator; + forEach(callback: (element: [ + K, + V + ], index: number, map: OrderedMap) => void): void; + /** + * @description Insert a key-value pair or set value by the given key. + * @param key - The key want to insert. + * @param value - The value want to set. + * @param hint - You can give an iterator hint to improve insertion efficiency. + * @return The size of container after setting. + * @example + * const mp = new OrderedMap([[2, 0], [4, 0], [5, 0]]); + * const iter = mp.begin(); + * mp.setElement(1, 0); + * mp.setElement(3, 0, iter); // give a hint will be faster. + */ + setElement(key: K, value: V, hint?: OrderedMapIterator): number; + getElementByPos(pos: number): [ + K, + V + ]; + find(key: K): OrderedMapIterator; + /** + * @description Get the value of the element of the specified key. + * @param key - The specified key you want to get. + * @example + * const val = container.getElementByKey(1); + */ + getElementByKey(key: K): V | undefined; + union(other: OrderedMap): number; + [Symbol.iterator](): Generator<[ + K, + V + ], void, unknown>; + // @ts-ignore + eraseElementByIterator(iter: OrderedMapIterator): OrderedMapIterator; +} +export { OrderedMap }; +export type { OrderedMapIterator, IteratorType, Container, ContainerIterator, TreeContainer }; diff --git a/node_modules/@js-sdsl/ordered-map/dist/cjs/index.js b/node_modules/@js-sdsl/ordered-map/dist/cjs/index.js new file mode 100644 index 0000000..575a7fa --- /dev/null +++ b/node_modules/@js-sdsl/ordered-map/dist/cjs/index.js @@ -0,0 +1,795 @@ +"use strict"; + +Object.defineProperty(exports, "t", { + value: true +}); + +class TreeNode { + constructor(t, e, s = 1) { + this.i = undefined; + this.h = undefined; + this.o = undefined; + this.u = t; + this.l = e; + this.p = s; + } + I() { + let t = this; + const e = t.o.o === t; + if (e && t.p === 1) { + t = t.h; + } else if (t.i) { + t = t.i; + while (t.h) { + t = t.h; + } + } else { + if (e) { + return t.o; + } + let s = t.o; + while (s.i === t) { + t = s; + s = t.o; + } + t = s; + } + return t; + } + B() { + let t = this; + if (t.h) { + t = t.h; + while (t.i) { + t = t.i; + } + return t; + } else { + let e = t.o; + while (e.h === t) { + t = e; + e = t.o; + } + if (t.h !== e) { + return e; + } else return t; + } + } + _() { + const t = this.o; + const e = this.h; + const s = e.i; + if (t.o === this) t.o = e; else if (t.i === this) t.i = e; else t.h = e; + e.o = t; + e.i = this; + this.o = e; + this.h = s; + if (s) s.o = this; + return e; + } + g() { + const t = this.o; + const e = this.i; + const s = e.h; + if (t.o === this) t.o = e; else if (t.i === this) t.i = e; else t.h = e; + e.o = t; + e.h = this; + this.o = e; + this.i = s; + if (s) s.o = this; + return e; + } +} + +class TreeNodeEnableIndex extends TreeNode { + constructor() { + super(...arguments); + this.M = 1; + } + _() { + const t = super._(); + this.O(); + t.O(); + return t; + } + g() { + const t = super.g(); + this.O(); + t.O(); + return t; + } + O() { + this.M = 1; + if (this.i) { + this.M += this.i.M; + } + if (this.h) { + this.M += this.h.M; + } + } +} + +class ContainerIterator { + constructor(t = 0) { + this.iteratorType = t; + } + equals(t) { + return this.T === t.T; + } +} + +class Base { + constructor() { + this.m = 0; + } + get length() { + return this.m; + } + size() { + return this.m; + } + empty() { + return this.m === 0; + } +} + +class Container extends Base {} + +function throwIteratorAccessError() { + throw new RangeError("Iterator access denied!"); +} + +class TreeContainer extends Container { + constructor(t = function(t, e) { + if (t < e) return -1; + if (t > e) return 1; + return 0; + }, e = false) { + super(); + this.v = undefined; + this.A = t; + this.enableIndex = e; + this.N = e ? TreeNodeEnableIndex : TreeNode; + this.C = new this.N; + } + R(t, e) { + let s = this.C; + while (t) { + const i = this.A(t.u, e); + if (i < 0) { + t = t.h; + } else if (i > 0) { + s = t; + t = t.i; + } else return t; + } + return s; + } + K(t, e) { + let s = this.C; + while (t) { + const i = this.A(t.u, e); + if (i <= 0) { + t = t.h; + } else { + s = t; + t = t.i; + } + } + return s; + } + L(t, e) { + let s = this.C; + while (t) { + const i = this.A(t.u, e); + if (i < 0) { + s = t; + t = t.h; + } else if (i > 0) { + t = t.i; + } else return t; + } + return s; + } + k(t, e) { + let s = this.C; + while (t) { + const i = this.A(t.u, e); + if (i < 0) { + s = t; + t = t.h; + } else { + t = t.i; + } + } + return s; + } + P(t) { + while (true) { + const e = t.o; + if (e === this.C) return; + if (t.p === 1) { + t.p = 0; + return; + } + if (t === e.i) { + const s = e.h; + if (s.p === 1) { + s.p = 0; + e.p = 1; + if (e === this.v) { + this.v = e._(); + } else e._(); + } else { + if (s.h && s.h.p === 1) { + s.p = e.p; + e.p = 0; + s.h.p = 0; + if (e === this.v) { + this.v = e._(); + } else e._(); + return; + } else if (s.i && s.i.p === 1) { + s.p = 1; + s.i.p = 0; + s.g(); + } else { + s.p = 1; + t = e; + } + } + } else { + const s = e.i; + if (s.p === 1) { + s.p = 0; + e.p = 1; + if (e === this.v) { + this.v = e.g(); + } else e.g(); + } else { + if (s.i && s.i.p === 1) { + s.p = e.p; + e.p = 0; + s.i.p = 0; + if (e === this.v) { + this.v = e.g(); + } else e.g(); + return; + } else if (s.h && s.h.p === 1) { + s.p = 1; + s.h.p = 0; + s._(); + } else { + s.p = 1; + t = e; + } + } + } + } + } + S(t) { + if (this.m === 1) { + this.clear(); + return; + } + let e = t; + while (e.i || e.h) { + if (e.h) { + e = e.h; + while (e.i) e = e.i; + } else { + e = e.i; + } + const s = t.u; + t.u = e.u; + e.u = s; + const i = t.l; + t.l = e.l; + e.l = i; + t = e; + } + if (this.C.i === e) { + this.C.i = e.o; + } else if (this.C.h === e) { + this.C.h = e.o; + } + this.P(e); + let s = e.o; + if (e === s.i) { + s.i = undefined; + } else s.h = undefined; + this.m -= 1; + this.v.p = 0; + if (this.enableIndex) { + while (s !== this.C) { + s.M -= 1; + s = s.o; + } + } + } + U(t) { + const e = typeof t === "number" ? t : undefined; + const s = typeof t === "function" ? t : undefined; + const i = typeof t === "undefined" ? [] : undefined; + let r = 0; + let n = this.v; + const h = []; + while (h.length || n) { + if (n) { + h.push(n); + n = n.i; + } else { + n = h.pop(); + if (r === e) return n; + i && i.push(n); + s && s(n, r, this); + r += 1; + n = n.h; + } + } + return i; + } + j(t) { + while (true) { + const e = t.o; + if (e.p === 0) return; + const s = e.o; + if (e === s.i) { + const i = s.h; + if (i && i.p === 1) { + i.p = e.p = 0; + if (s === this.v) return; + s.p = 1; + t = s; + continue; + } else if (t === e.h) { + t.p = 0; + if (t.i) { + t.i.o = e; + } + if (t.h) { + t.h.o = s; + } + e.h = t.i; + s.i = t.h; + t.i = e; + t.h = s; + if (s === this.v) { + this.v = t; + this.C.o = t; + } else { + const e = s.o; + if (e.i === s) { + e.i = t; + } else e.h = t; + } + t.o = s.o; + e.o = t; + s.o = t; + s.p = 1; + } else { + e.p = 0; + if (s === this.v) { + this.v = s.g(); + } else s.g(); + s.p = 1; + return; + } + } else { + const i = s.i; + if (i && i.p === 1) { + i.p = e.p = 0; + if (s === this.v) return; + s.p = 1; + t = s; + continue; + } else if (t === e.i) { + t.p = 0; + if (t.i) { + t.i.o = s; + } + if (t.h) { + t.h.o = e; + } + s.h = t.i; + e.i = t.h; + t.i = s; + t.h = e; + if (s === this.v) { + this.v = t; + this.C.o = t; + } else { + const e = s.o; + if (e.i === s) { + e.i = t; + } else e.h = t; + } + t.o = s.o; + e.o = t; + s.o = t; + s.p = 1; + } else { + e.p = 0; + if (s === this.v) { + this.v = s._(); + } else s._(); + s.p = 1; + return; + } + } + if (this.enableIndex) { + e.O(); + s.O(); + t.O(); + } + return; + } + } + q(t, e, s) { + if (this.v === undefined) { + this.m += 1; + this.v = new this.N(t, e, 0); + this.v.o = this.C; + this.C.o = this.C.i = this.C.h = this.v; + return this.m; + } + let i; + const r = this.C.i; + const n = this.A(r.u, t); + if (n === 0) { + r.l = e; + return this.m; + } else if (n > 0) { + r.i = new this.N(t, e); + r.i.o = r; + i = r.i; + this.C.i = i; + } else { + const r = this.C.h; + const n = this.A(r.u, t); + if (n === 0) { + r.l = e; + return this.m; + } else if (n < 0) { + r.h = new this.N(t, e); + r.h.o = r; + i = r.h; + this.C.h = i; + } else { + if (s !== undefined) { + const r = s.T; + if (r !== this.C) { + const s = this.A(r.u, t); + if (s === 0) { + r.l = e; + return this.m; + } else if (s > 0) { + const s = r.I(); + const n = this.A(s.u, t); + if (n === 0) { + s.l = e; + return this.m; + } else if (n < 0) { + i = new this.N(t, e); + if (s.h === undefined) { + s.h = i; + i.o = s; + } else { + r.i = i; + i.o = r; + } + } + } + } + } + if (i === undefined) { + i = this.v; + while (true) { + const s = this.A(i.u, t); + if (s > 0) { + if (i.i === undefined) { + i.i = new this.N(t, e); + i.i.o = i; + i = i.i; + break; + } + i = i.i; + } else if (s < 0) { + if (i.h === undefined) { + i.h = new this.N(t, e); + i.h.o = i; + i = i.h; + break; + } + i = i.h; + } else { + i.l = e; + return this.m; + } + } + } + } + } + if (this.enableIndex) { + let t = i.o; + while (t !== this.C) { + t.M += 1; + t = t.o; + } + } + this.j(i); + this.m += 1; + return this.m; + } + H(t, e) { + while (t) { + const s = this.A(t.u, e); + if (s < 0) { + t = t.h; + } else if (s > 0) { + t = t.i; + } else return t; + } + return t || this.C; + } + clear() { + this.m = 0; + this.v = undefined; + this.C.o = undefined; + this.C.i = this.C.h = undefined; + } + updateKeyByIterator(t, e) { + const s = t.T; + if (s === this.C) { + throwIteratorAccessError(); + } + if (this.m === 1) { + s.u = e; + return true; + } + const i = s.B().u; + if (s === this.C.i) { + if (this.A(i, e) > 0) { + s.u = e; + return true; + } + return false; + } + const r = s.I().u; + if (s === this.C.h) { + if (this.A(r, e) < 0) { + s.u = e; + return true; + } + return false; + } + if (this.A(r, e) >= 0 || this.A(i, e) <= 0) return false; + s.u = e; + return true; + } + eraseElementByPos(t) { + if (t < 0 || t > this.m - 1) { + throw new RangeError; + } + const e = this.U(t); + this.S(e); + return this.m; + } + eraseElementByKey(t) { + if (this.m === 0) return false; + const e = this.H(this.v, t); + if (e === this.C) return false; + this.S(e); + return true; + } + eraseElementByIterator(t) { + const e = t.T; + if (e === this.C) { + throwIteratorAccessError(); + } + const s = e.h === undefined; + const i = t.iteratorType === 0; + if (i) { + if (s) t.next(); + } else { + if (!s || e.i === undefined) t.next(); + } + this.S(e); + return t; + } + getHeight() { + if (this.m === 0) return 0; + function traversal(t) { + if (!t) return 0; + return Math.max(traversal(t.i), traversal(t.h)) + 1; + } + return traversal(this.v); + } +} + +class TreeIterator extends ContainerIterator { + constructor(t, e, s) { + super(s); + this.T = t; + this.C = e; + if (this.iteratorType === 0) { + this.pre = function() { + if (this.T === this.C.i) { + throwIteratorAccessError(); + } + this.T = this.T.I(); + return this; + }; + this.next = function() { + if (this.T === this.C) { + throwIteratorAccessError(); + } + this.T = this.T.B(); + return this; + }; + } else { + this.pre = function() { + if (this.T === this.C.h) { + throwIteratorAccessError(); + } + this.T = this.T.B(); + return this; + }; + this.next = function() { + if (this.T === this.C) { + throwIteratorAccessError(); + } + this.T = this.T.I(); + return this; + }; + } + } + get index() { + let t = this.T; + const e = this.C.o; + if (t === this.C) { + if (e) { + return e.M - 1; + } + return 0; + } + let s = 0; + if (t.i) { + s += t.i.M; + } + while (t !== e) { + const e = t.o; + if (t === e.h) { + s += 1; + if (e.i) { + s += e.i.M; + } + } + t = e; + } + return s; + } + isAccessible() { + return this.T !== this.C; + } +} + +class OrderedMapIterator extends TreeIterator { + constructor(t, e, s, i) { + super(t, e, i); + this.container = s; + } + get pointer() { + if (this.T === this.C) { + throwIteratorAccessError(); + } + const t = this; + return new Proxy([], { + get(e, s) { + if (s === "0") return t.T.u; else if (s === "1") return t.T.l; + e[0] = t.T.u; + e[1] = t.T.l; + return e[s]; + }, + set(e, s, i) { + if (s !== "1") { + throw new TypeError("prop must be 1"); + } + t.T.l = i; + return true; + } + }); + } + copy() { + return new OrderedMapIterator(this.T, this.C, this.container, this.iteratorType); + } +} + +class OrderedMap extends TreeContainer { + constructor(t = [], e, s) { + super(e, s); + const i = this; + t.forEach((function(t) { + i.setElement(t[0], t[1]); + })); + } + begin() { + return new OrderedMapIterator(this.C.i || this.C, this.C, this); + } + end() { + return new OrderedMapIterator(this.C, this.C, this); + } + rBegin() { + return new OrderedMapIterator(this.C.h || this.C, this.C, this, 1); + } + rEnd() { + return new OrderedMapIterator(this.C, this.C, this, 1); + } + front() { + if (this.m === 0) return; + const t = this.C.i; + return [ t.u, t.l ]; + } + back() { + if (this.m === 0) return; + const t = this.C.h; + return [ t.u, t.l ]; + } + lowerBound(t) { + const e = this.R(this.v, t); + return new OrderedMapIterator(e, this.C, this); + } + upperBound(t) { + const e = this.K(this.v, t); + return new OrderedMapIterator(e, this.C, this); + } + reverseLowerBound(t) { + const e = this.L(this.v, t); + return new OrderedMapIterator(e, this.C, this); + } + reverseUpperBound(t) { + const e = this.k(this.v, t); + return new OrderedMapIterator(e, this.C, this); + } + forEach(t) { + this.U((function(e, s, i) { + t([ e.u, e.l ], s, i); + })); + } + setElement(t, e, s) { + return this.q(t, e, s); + } + getElementByPos(t) { + if (t < 0 || t > this.m - 1) { + throw new RangeError; + } + const e = this.U(t); + return [ e.u, e.l ]; + } + find(t) { + const e = this.H(this.v, t); + return new OrderedMapIterator(e, this.C, this); + } + getElementByKey(t) { + const e = this.H(this.v, t); + return e.l; + } + union(t) { + const e = this; + t.forEach((function(t) { + e.setElement(t[0], t[1]); + })); + return this.m; + } + * [Symbol.iterator]() { + const t = this.m; + const e = this.U(); + for (let s = 0; s < t; ++s) { + const t = e[s]; + yield [ t.u, t.l ]; + } + } +} + +exports.OrderedMap = OrderedMap; +//# sourceMappingURL=index.js.map diff --git a/node_modules/@js-sdsl/ordered-map/dist/cjs/index.js.map b/node_modules/@js-sdsl/ordered-map/dist/cjs/index.js.map new file mode 100644 index 0000000..36400a9 --- /dev/null +++ b/node_modules/@js-sdsl/ordered-map/dist/cjs/index.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["index.js","../../../.build-data/copied-source/src/container/TreeContainer/Base/TreeNode.ts","../../../.build-data/copied-source/src/container/ContainerBase/index.ts","../../../.build-data/copied-source/src/utils/throwError.ts","../../../.build-data/copied-source/src/container/TreeContainer/Base/index.ts","../../../.build-data/copied-source/src/container/TreeContainer/Base/TreeIterator.ts","../../../.build-data/copied-source/src/container/TreeContainer/OrderedMap.ts"],"names":["Object","defineProperty","exports","value","TreeNode","constructor","key","color","this","_left","undefined","_right","_parent","_key","_value","_color","_pre","preNode","isRootOrHeader","pre","_next","nextNode","_rotateLeft","PP","V","R","_rotateRight","F","K","TreeNodeEnableIndex","super","arguments","_subTreeSize","parent","_recount","ContainerIterator","iteratorType","equals","iter","_node","Base","_length","length","size","empty","Container","throwIteratorAccessError","RangeError","TreeContainer","cmp","x","y","enableIndex","_root","_cmp","_TreeNodeClass","_header","_lowerBound","curNode","resNode","cmpResult","_upperBound","_reverseLowerBound","_reverseUpperBound","_eraseNodeSelfBalance","parentNode","brother","_eraseNode","clear","swapNode","_inOrderTraversal","param","pos","callback","nodeList","index","stack","push","pop","_insertNodeSelfBalance","grandParent","uncle","GP","_set","hint","minNode","compareToMin","maxNode","compareToMax","iterNode","iterCmpRes","preCmpRes","_getTreeNodeByKey","updateKeyByIterator","node","nextKey","preKey","eraseElementByPos","eraseElementByKey","eraseElementByIterator","hasNoRight","isNormal","next","getHeight","traversal","Math","max","TreeIterator","header","root","isAccessible","OrderedMapIterator","container","pointer","self","Proxy","get","target","prop","set","_","newValue","TypeError","copy","OrderedMap","forEach","el","setElement","begin","end","rBegin","rEnd","front","back","lowerBound","upperBound","reverseLowerBound","reverseUpperBound","map","getElementByPos","find","getElementByKey","union","other","Symbol","iterator","i"],"mappings":"AAAA;;AAEAA,OAAOC,eAAeC,SAAS,KAAc;IAAEC,OAAO;;;AAEtD,MCCaC;IAOXC,WAAAA,CACEC,GACAH,GACAI,IAAwC;QAN1CC,KAAKC,IAA+BC;QACpCF,KAAMG,IAA+BD;QACrCF,KAAOI,IAA+BF;QAMpCF,KAAKK,IAAOP;QACZE,KAAKM,IAASX;QACdK,KAAKO,IAASR;AACf;IAKDS,CAAAA;QACE,IAAIC,IAA0BT;QAC9B,MAAMU,IAAiBD,EAAQL,EAASA,MAAYK;QACpD,IAAIC,KAAkBD,EAAQF,MAAM,GAAwB;YAC1DE,IAAUA,EAAQN;AACnB,eAAM,IAAIM,EAAQR,GAAO;YACxBQ,IAAUA,EAAQR;YAClB,OAAOQ,EAAQN,GAAQ;gBACrBM,IAAUA,EAAQN;AACnB;AACF,eAAM;YAEL,IAAIO,GAAgB;gBAClB,OAAOD,EAAQL;AAChB;YACD,IAAIO,IAAMF,EAAQL;YAClB,OAAOO,EAAIV,MAAUQ,GAAS;gBAC5BA,IAAUE;gBACVA,IAAMF,EAAQL;AACf;YACDK,IAAUE;AACX;QACD,OAAOF;AACR;IAKDG,CAAAA;QACE,IAAIC,IAA2Bb;QAC/B,IAAIa,EAASV,GAAQ;YACnBU,IAAWA,EAASV;YACpB,OAAOU,EAASZ,GAAO;gBACrBY,IAAWA,EAASZ;AACrB;YACD,OAAOY;AACR,eAAM;YACL,IAAIF,IAAME,EAAST;YACnB,OAAOO,EAAIR,MAAWU,GAAU;gBAC9BA,IAAWF;gBACXA,IAAME,EAAST;AAChB;YACD,IAAIS,EAASV,MAAWQ,G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K7E,GAAKH,GAAOiF;AAC9B;IACDuD,eAAAA,CAAgBnE;QACY,IAAAA,IAAG,KAAHA,IAAQhE,KAAKiC,IArIf,GAAA;YAAC,MAAU,IAAIM;AAC1C;QAqIG,MAAM+C,IAAOtF,KAAK8D,EAAkBE;QACpC,OAAe,EAACsB,EAAKjF,GAAMiF,EAAKhF;AACjC;IACD8H,IAAAA,CAAKtI;QACH,MAAMoD,IAAUlD,KAAKoF,EAAkBpF,KAAK6C,GAAO/C;QACnD,OAAO,IAAIyG,mBAAyBrD,GAASlD,KAAKgD,GAAShD;AAC5D;IAODqI,eAAAA,CAAgBvI;QACd,MAAMoD,IAAUlD,KAAKoF,EAAkBpF,KAAK6C,GAAO/C;QACnD,OAAOoD,EAAQ5C;AAChB;IACDgI,KAAAA,CAAMC;QACJ,MAAM7B,IAAO1G;QACbuI,EAAMlB,SAAQ,SAAUC;YACtBZ,EAAKa,WAAWD,EAAG,IAAIA,EAAG;AAC3B;QACD,OAAOtH,KAAKiC;AACb;IACD,GAAGuG,OAAOC;QACR,MAAMvG,IAASlC,KAAKiC;QACpB,MAAMiC,IAAWlE,KAAK8D;QACtB,KAAK,IAAI4E,IAAI,GAAGA,IAAIxG,KAAUwG,GAAG;YAC/B,MAAMpD,IAAOpB,EAASwE;kBACR,EAACpD,EAAKjF,GAAMiF,EAAKhF;AAChC;AACF;;;ANwwBHZ,QAAQ0H,aAAaA","file":"index.js","sourcesContent":["'use strict';\n\nObject.defineProperty(exports, '__esModule', { value: true });\n\nclass TreeNode {\n constructor(key, value, color = 1 /* TreeNodeColor.RED */) {\n this._left = undefined;\n this._right = undefined;\n this._parent = undefined;\n this._key = key;\n this._value = value;\n this._color = color;\n }\n /**\n * @description Get the pre node.\n * @returns TreeNode about the pre node.\n */\n _pre() {\n let preNode = this;\n const isRootOrHeader = preNode._parent._parent === preNode;\n if (isRootOrHeader && preNode._color === 1 /* TreeNodeColor.RED */) {\n preNode = preNode._right;\n } else if (preNode._left) {\n preNode = preNode._left;\n while (preNode._right) {\n preNode = preNode._right;\n }\n } else {\n // Must be root and left is null\n if (isRootOrHeader) {\n return preNode._parent;\n }\n let pre = preNode._parent;\n while (pre._left === preNode) {\n preNode = pre;\n pre = preNode._parent;\n }\n preNode = pre;\n }\n return preNode;\n }\n /**\n * @description Get the next node.\n * @returns TreeNode about the next node.\n */\n _next() {\n let nextNode = this;\n if (nextNode._right) {\n nextNode = nextNode._right;\n while (nextNode._left) {\n nextNode = nextNode._left;\n }\n return nextNode;\n } else {\n let pre = nextNode._parent;\n while (pre._right === nextNode) {\n nextNode = pre;\n pre = nextNode._parent;\n }\n if (nextNode._right !== pre) {\n return pre;\n } else return nextNode;\n }\n }\n /**\n * @description Rotate left.\n * @returns TreeNode about moved to original position after rotation.\n */\n _rotateLeft() {\n const PP = this._parent;\n const V = this._right;\n const R = V._left;\n if (PP._parent === this) PP._parent = V;else if (PP._left === this) PP._left = V;else PP._right = V;\n V._parent = PP;\n V._left = this;\n this._parent = V;\n this._right = R;\n if (R) R._parent = this;\n return V;\n }\n /**\n * @description Rotate right.\n * @returns TreeNode about moved to original position after rotation.\n */\n _rotateRight() {\n const PP = this._parent;\n const F = this._left;\n const K = F._right;\n if (PP._parent === this) PP._parent = F;else if (PP._left === this) PP._left = F;else PP._right = F;\n F._parent = PP;\n F._right = this;\n this._parent = F;\n this._left = K;\n if (K) K._parent = this;\n return F;\n }\n}\nclass TreeNodeEnableIndex extends TreeNode {\n constructor() {\n super(...arguments);\n this._subTreeSize = 1;\n }\n /**\n * @description Rotate left and do recount.\n * @returns TreeNode about moved to original position after rotation.\n */\n _rotateLeft() {\n const parent = super._rotateLeft();\n this._recount();\n parent._recount();\n return parent;\n }\n /**\n * @description Rotate right and do recount.\n * @returns TreeNode about moved to original position after rotation.\n */\n _rotateRight() {\n const parent = super._rotateRight();\n this._recount();\n parent._recount();\n return parent;\n }\n _recount() {\n this._subTreeSize = 1;\n if (this._left) {\n this._subTreeSize += this._left._subTreeSize;\n }\n if (this._right) {\n this._subTreeSize += this._right._subTreeSize;\n }\n }\n}\n\nclass ContainerIterator {\n /**\n * @internal\n */\n constructor(iteratorType = 0 /* IteratorType.NORMAL */) {\n this.iteratorType = iteratorType;\n }\n /**\n * @param iter - The other iterator you want to compare.\n * @returns Whether this equals to obj.\n * @example\n * container.find(1).equals(container.end());\n */\n equals(iter) {\n return this._node === iter._node;\n }\n}\nclass Base {\n constructor() {\n /**\n * @description Container's size.\n * @internal\n */\n this._length = 0;\n }\n /**\n * @returns The size of the container.\n * @example\n * const container = new Vector([1, 2]);\n * console.log(container.length); // 2\n */\n get length() {\n return this._length;\n }\n /**\n * @returns The size of the container.\n * @example\n * const container = new Vector([1, 2]);\n * console.log(container.size()); // 2\n */\n size() {\n return this._length;\n }\n /**\n * @returns Whether the container is empty.\n * @example\n * container.clear();\n * console.log(container.empty()); // true\n */\n empty() {\n return this._length === 0;\n }\n}\nclass Container extends Base {}\n\n/**\n * @description Throw an iterator access error.\n * @internal\n */\nfunction throwIteratorAccessError() {\n throw new RangeError('Iterator access denied!');\n}\n\nclass TreeContainer extends Container {\n /**\n * @internal\n */\n constructor(cmp = function (x, y) {\n if (x < y) return -1;\n if (x > y) return 1;\n return 0;\n }, enableIndex = false) {\n super();\n /**\n * @internal\n */\n this._root = undefined;\n this._cmp = cmp;\n this.enableIndex = enableIndex;\n this._TreeNodeClass = enableIndex ? TreeNodeEnableIndex : TreeNode;\n this._header = new this._TreeNodeClass();\n }\n /**\n * @internal\n */\n _lowerBound(curNode, key) {\n let resNode = this._header;\n while (curNode) {\n const cmpResult = this._cmp(curNode._key, key);\n if (cmpResult < 0) {\n curNode = curNode._right;\n } else if (cmpResult > 0) {\n resNode = curNode;\n curNode = curNode._left;\n } else return curNode;\n }\n return resNode;\n }\n /**\n * @internal\n */\n _upperBound(curNode, key) {\n let resNode = this._header;\n while (curNode) {\n const cmpResult = this._cmp(curNode._key, key);\n if (cmpResult <= 0) {\n curNode = curNode._right;\n } else {\n resNode = curNode;\n curNode = curNode._left;\n }\n }\n return resNode;\n }\n /**\n * @internal\n */\n _reverseLowerBound(curNode, key) {\n let resNode = this._header;\n while (curNode) {\n const cmpResult = this._cmp(curNode._key, key);\n if (cmpResult < 0) {\n resNode = curNode;\n curNode = curNode._right;\n } else if (cmpResult > 0) {\n curNode = curNode._left;\n } else return curNode;\n }\n return resNode;\n }\n /**\n * @internal\n */\n _reverseUpperBound(curNode, key) {\n let resNode = this._header;\n while (curNode) {\n const cmpResult = this._cmp(curNode._key, key);\n if (cmpResult < 0) {\n resNode = curNode;\n curNode = curNode._right;\n } else {\n curNode = curNode._left;\n }\n }\n return resNode;\n }\n /**\n * @internal\n */\n _eraseNodeSelfBalance(curNode) {\n while (true) {\n const parentNode = curNode._parent;\n if (parentNode === this._header) return;\n if (curNode._color === 1 /* TreeNodeColor.RED */) {\n curNode._color = 0 /* TreeNodeColor.BLACK */;\n return;\n }\n if (curNode === parentNode._left) {\n const brother = parentNode._right;\n if (brother._color === 1 /* TreeNodeColor.RED */) {\n brother._color = 0 /* TreeNodeColor.BLACK */;\n parentNode._color = 1 /* TreeNodeColor.RED */;\n if (parentNode === this._root) {\n this._root = parentNode._rotateLeft();\n } else parentNode._rotateLeft();\n } else {\n if (brother._right && brother._right._color === 1 /* TreeNodeColor.RED */) {\n brother._color = parentNode._color;\n parentNode._color = 0 /* TreeNodeColor.BLACK */;\n brother._right._color = 0 /* TreeNodeColor.BLACK */;\n if (parentNode === this._root) {\n this._root = parentNode._rotateLeft();\n } else parentNode._rotateLeft();\n return;\n } else if (brother._left && brother._left._color === 1 /* TreeNodeColor.RED */) {\n brother._color = 1 /* TreeNodeColor.RED */;\n brother._left._color = 0 /* TreeNodeColor.BLACK */;\n brother._rotateRight();\n } else {\n brother._color = 1 /* TreeNodeColor.RED */;\n curNode = parentNode;\n }\n }\n } else {\n const brother = parentNode._left;\n if (brother._color === 1 /* TreeNodeColor.RED */) {\n brother._color = 0 /* TreeNodeColor.BLACK */;\n parentNode._color = 1 /* TreeNodeColor.RED */;\n if (parentNode === this._root) {\n this._root = parentNode._rotateRight();\n } else parentNode._rotateRight();\n } else {\n if (brother._left && brother._left._color === 1 /* TreeNodeColor.RED */) {\n brother._color = parentNode._color;\n parentNode._color = 0 /* TreeNodeColor.BLACK */;\n brother._left._color = 0 /* TreeNodeColor.BLACK */;\n if (parentNode === this._root) {\n this._root = parentNode._rotateRight();\n } else parentNode._rotateRight();\n return;\n } else if (brother._right && brother._right._color === 1 /* TreeNodeColor.RED */) {\n brother._color = 1 /* TreeNodeColor.RED */;\n brother._right._color = 0 /* TreeNodeColor.BLACK */;\n brother._rotateLeft();\n } else {\n brother._color = 1 /* TreeNodeColor.RED */;\n curNode = parentNode;\n }\n }\n }\n }\n }\n /**\n * @internal\n */\n _eraseNode(curNode) {\n if (this._length === 1) {\n this.clear();\n return;\n }\n let swapNode = curNode;\n while (swapNode._left || swapNode._right) {\n if (swapNode._right) {\n swapNode = swapNode._right;\n while (swapNode._left) swapNode = swapNode._left;\n } else {\n swapNode = swapNode._left;\n }\n const key = curNode._key;\n curNode._key = swapNode._key;\n swapNode._key = key;\n const value = curNode._value;\n curNode._value = swapNode._value;\n swapNode._value = value;\n curNode = swapNode;\n }\n if (this._header._left === swapNode) {\n this._header._left = swapNode._parent;\n } else if (this._header._right === swapNode) {\n this._header._right = swapNode._parent;\n }\n this._eraseNodeSelfBalance(swapNode);\n let _parent = swapNode._parent;\n if (swapNode === _parent._left) {\n _parent._left = undefined;\n } else _parent._right = undefined;\n this._length -= 1;\n this._root._color = 0 /* TreeNodeColor.BLACK */;\n if (this.enableIndex) {\n while (_parent !== this._header) {\n _parent._subTreeSize -= 1;\n _parent = _parent._parent;\n }\n }\n }\n /**\n * @internal\n */\n _inOrderTraversal(param) {\n const pos = typeof param === 'number' ? param : undefined;\n const callback = typeof param === 'function' ? param : undefined;\n const nodeList = typeof param === 'undefined' ? [] : undefined;\n let index = 0;\n let curNode = this._root;\n const stack = [];\n while (stack.length || curNode) {\n if (curNode) {\n stack.push(curNode);\n curNode = curNode._left;\n } else {\n curNode = stack.pop();\n if (index === pos) return curNode;\n nodeList && nodeList.push(curNode);\n callback && callback(curNode, index, this);\n index += 1;\n curNode = curNode._right;\n }\n }\n return nodeList;\n }\n /**\n * @internal\n */\n _insertNodeSelfBalance(curNode) {\n while (true) {\n const parentNode = curNode._parent;\n if (parentNode._color === 0 /* TreeNodeColor.BLACK */) return;\n const grandParent = parentNode._parent;\n if (parentNode === grandParent._left) {\n const uncle = grandParent._right;\n if (uncle && uncle._color === 1 /* TreeNodeColor.RED */) {\n uncle._color = parentNode._color = 0 /* TreeNodeColor.BLACK */;\n if (grandParent === this._root) return;\n grandParent._color = 1 /* TreeNodeColor.RED */;\n curNode = grandParent;\n continue;\n } else if (curNode === parentNode._right) {\n curNode._color = 0 /* TreeNodeColor.BLACK */;\n if (curNode._left) {\n curNode._left._parent = parentNode;\n }\n if (curNode._right) {\n curNode._right._parent = grandParent;\n }\n parentNode._right = curNode._left;\n grandParent._left = curNode._right;\n curNode._left = parentNode;\n curNode._right = grandParent;\n if (grandParent === this._root) {\n this._root = curNode;\n this._header._parent = curNode;\n } else {\n const GP = grandParent._parent;\n if (GP._left === grandParent) {\n GP._left = curNode;\n } else GP._right = curNode;\n }\n curNode._parent = grandParent._parent;\n parentNode._parent = curNode;\n grandParent._parent = curNode;\n grandParent._color = 1 /* TreeNodeColor.RED */;\n } else {\n parentNode._color = 0 /* TreeNodeColor.BLACK */;\n if (grandParent === this._root) {\n this._root = grandParent._rotateRight();\n } else grandParent._rotateRight();\n grandParent._color = 1 /* TreeNodeColor.RED */;\n return;\n }\n } else {\n const uncle = grandParent._left;\n if (uncle && uncle._color === 1 /* TreeNodeColor.RED */) {\n uncle._color = parentNode._color = 0 /* TreeNodeColor.BLACK */;\n if (grandParent === this._root) return;\n grandParent._color = 1 /* TreeNodeColor.RED */;\n curNode = grandParent;\n continue;\n } else if (curNode === parentNode._left) {\n curNode._color = 0 /* TreeNodeColor.BLACK */;\n if (curNode._left) {\n curNode._left._parent = grandParent;\n }\n if (curNode._right) {\n curNode._right._parent = parentNode;\n }\n grandParent._right = curNode._left;\n parentNode._left = curNode._right;\n curNode._left = grandParent;\n curNode._right = parentNode;\n if (grandParent === this._root) {\n this._root = curNode;\n this._header._parent = curNode;\n } else {\n const GP = grandParent._parent;\n if (GP._left === grandParent) {\n GP._left = curNode;\n } else GP._right = curNode;\n }\n curNode._parent = grandParent._parent;\n parentNode._parent = curNode;\n grandParent._parent = curNode;\n grandParent._color = 1 /* TreeNodeColor.RED */;\n } else {\n parentNode._color = 0 /* TreeNodeColor.BLACK */;\n if (grandParent === this._root) {\n this._root = grandParent._rotateLeft();\n } else grandParent._rotateLeft();\n grandParent._color = 1 /* TreeNodeColor.RED */;\n return;\n }\n }\n if (this.enableIndex) {\n parentNode._recount();\n grandParent._recount();\n curNode._recount();\n }\n return;\n }\n }\n /**\n * @internal\n */\n _set(key, value, hint) {\n if (this._root === undefined) {\n this._length += 1;\n this._root = new this._TreeNodeClass(key, value, 0 /* TreeNodeColor.BLACK */);\n this._root._parent = this._header;\n this._header._parent = this._header._left = this._header._right = this._root;\n return this._length;\n }\n let curNode;\n const minNode = this._header._left;\n const compareToMin = this._cmp(minNode._key, key);\n if (compareToMin === 0) {\n minNode._value = value;\n return this._length;\n } else if (compareToMin > 0) {\n minNode._left = new this._TreeNodeClass(key, value);\n minNode._left._parent = minNode;\n curNode = minNode._left;\n this._header._left = curNode;\n } else {\n const maxNode = this._header._right;\n const compareToMax = this._cmp(maxNode._key, key);\n if (compareToMax === 0) {\n maxNode._value = value;\n return this._length;\n } else if (compareToMax < 0) {\n maxNode._right = new this._TreeNodeClass(key, value);\n maxNode._right._parent = maxNode;\n curNode = maxNode._right;\n this._header._right = curNode;\n } else {\n if (hint !== undefined) {\n const iterNode = hint._node;\n if (iterNode !== this._header) {\n const iterCmpRes = this._cmp(iterNode._key, key);\n if (iterCmpRes === 0) {\n iterNode._value = value;\n return this._length;\n } else /* istanbul ignore else */if (iterCmpRes > 0) {\n const preNode = iterNode._pre();\n const preCmpRes = this._cmp(preNode._key, key);\n if (preCmpRes === 0) {\n preNode._value = value;\n return this._length;\n } else if (preCmpRes < 0) {\n curNode = new this._TreeNodeClass(key, value);\n if (preNode._right === undefined) {\n preNode._right = curNode;\n curNode._parent = preNode;\n } else {\n iterNode._left = curNode;\n curNode._parent = iterNode;\n }\n }\n }\n }\n }\n if (curNode === undefined) {\n curNode = this._root;\n while (true) {\n const cmpResult = this._cmp(curNode._key, key);\n if (cmpResult > 0) {\n if (curNode._left === undefined) {\n curNode._left = new this._TreeNodeClass(key, value);\n curNode._left._parent = curNode;\n curNode = curNode._left;\n break;\n }\n curNode = curNode._left;\n } else if (cmpResult < 0) {\n if (curNode._right === undefined) {\n curNode._right = new this._TreeNodeClass(key, value);\n curNode._right._parent = curNode;\n curNode = curNode._right;\n break;\n }\n curNode = curNode._right;\n } else {\n curNode._value = value;\n return this._length;\n }\n }\n }\n }\n }\n if (this.enableIndex) {\n let parent = curNode._parent;\n while (parent !== this._header) {\n parent._subTreeSize += 1;\n parent = parent._parent;\n }\n }\n this._insertNodeSelfBalance(curNode);\n this._length += 1;\n return this._length;\n }\n /**\n * @internal\n */\n _getTreeNodeByKey(curNode, key) {\n while (curNode) {\n const cmpResult = this._cmp(curNode._key, key);\n if (cmpResult < 0) {\n curNode = curNode._right;\n } else if (cmpResult > 0) {\n curNode = curNode._left;\n } else return curNode;\n }\n return curNode || this._header;\n }\n clear() {\n this._length = 0;\n this._root = undefined;\n this._header._parent = undefined;\n this._header._left = this._header._right = undefined;\n }\n /**\n * @description Update node's key by iterator.\n * @param iter - The iterator you want to change.\n * @param key - The key you want to update.\n * @returns Whether the modification is successful.\n * @example\n * const st = new orderedSet([1, 2, 5]);\n * const iter = st.find(2);\n * st.updateKeyByIterator(iter, 3); // then st will become [1, 3, 5]\n */\n updateKeyByIterator(iter, key) {\n const node = iter._node;\n if (node === this._header) {\n throwIteratorAccessError();\n }\n if (this._length === 1) {\n node._key = key;\n return true;\n }\n const nextKey = node._next()._key;\n if (node === this._header._left) {\n if (this._cmp(nextKey, key) > 0) {\n node._key = key;\n return true;\n }\n return false;\n }\n const preKey = node._pre()._key;\n if (node === this._header._right) {\n if (this._cmp(preKey, key) < 0) {\n node._key = key;\n return true;\n }\n return false;\n }\n if (this._cmp(preKey, key) >= 0 || this._cmp(nextKey, key) <= 0) return false;\n node._key = key;\n return true;\n }\n eraseElementByPos(pos) {\n if (pos < 0 || pos > this._length - 1) {\n throw new RangeError();\n }\n const node = this._inOrderTraversal(pos);\n this._eraseNode(node);\n return this._length;\n }\n /**\n * @description Remove the element of the specified key.\n * @param key - The key you want to remove.\n * @returns Whether erase successfully.\n */\n eraseElementByKey(key) {\n if (this._length === 0) return false;\n const curNode = this._getTreeNodeByKey(this._root, key);\n if (curNode === this._header) return false;\n this._eraseNode(curNode);\n return true;\n }\n eraseElementByIterator(iter) {\n const node = iter._node;\n if (node === this._header) {\n throwIteratorAccessError();\n }\n const hasNoRight = node._right === undefined;\n const isNormal = iter.iteratorType === 0 /* IteratorType.NORMAL */;\n // For the normal iterator, the `next` node will be swapped to `this` node when has right.\n if (isNormal) {\n // So we should move it to next when it's right is null.\n if (hasNoRight) iter.next();\n } else {\n // For the reverse iterator, only when it doesn't have right and has left the `next` node will be swapped.\n // So when it has right, or it is a leaf node we should move it to `next`.\n if (!hasNoRight || node._left === undefined) iter.next();\n }\n this._eraseNode(node);\n return iter;\n }\n /**\n * @description Get the height of the tree.\n * @returns Number about the height of the RB-tree.\n */\n getHeight() {\n if (this._length === 0) return 0;\n function traversal(curNode) {\n if (!curNode) return 0;\n return Math.max(traversal(curNode._left), traversal(curNode._right)) + 1;\n }\n return traversal(this._root);\n }\n}\n\nclass TreeIterator extends ContainerIterator {\n /**\n * @internal\n */\n constructor(node, header, iteratorType) {\n super(iteratorType);\n this._node = node;\n this._header = header;\n if (this.iteratorType === 0 /* IteratorType.NORMAL */) {\n this.pre = function () {\n if (this._node === this._header._left) {\n throwIteratorAccessError();\n }\n this._node = this._node._pre();\n return this;\n };\n this.next = function () {\n if (this._node === this._header) {\n throwIteratorAccessError();\n }\n this._node = this._node._next();\n return this;\n };\n } else {\n this.pre = function () {\n if (this._node === this._header._right) {\n throwIteratorAccessError();\n }\n this._node = this._node._next();\n return this;\n };\n this.next = function () {\n if (this._node === this._header) {\n throwIteratorAccessError();\n }\n this._node = this._node._pre();\n return this;\n };\n }\n }\n /**\n * @description Get the sequential index of the iterator in the tree container.
\n * Note:\n * This function only takes effect when the specified tree container `enableIndex = true`.\n * @returns The index subscript of the node in the tree.\n * @example\n * const st = new OrderedSet([1, 2, 3], true);\n * console.log(st.begin().next().index); // 1\n */\n get index() {\n let _node = this._node;\n const root = this._header._parent;\n if (_node === this._header) {\n if (root) {\n return root._subTreeSize - 1;\n }\n return 0;\n }\n let index = 0;\n if (_node._left) {\n index += _node._left._subTreeSize;\n }\n while (_node !== root) {\n const _parent = _node._parent;\n if (_node === _parent._right) {\n index += 1;\n if (_parent._left) {\n index += _parent._left._subTreeSize;\n }\n }\n _node = _parent;\n }\n return index;\n }\n isAccessible() {\n return this._node !== this._header;\n }\n}\n\nclass OrderedMapIterator extends TreeIterator {\n constructor(node, header, container, iteratorType) {\n super(node, header, iteratorType);\n this.container = container;\n }\n get pointer() {\n if (this._node === this._header) {\n throwIteratorAccessError();\n }\n const self = this;\n return new Proxy([], {\n get(target, prop) {\n if (prop === '0') return self._node._key;else if (prop === '1') return self._node._value;\n target[0] = self._node._key;\n target[1] = self._node._value;\n return target[prop];\n },\n set(_, prop, newValue) {\n if (prop !== '1') {\n throw new TypeError('prop must be 1');\n }\n self._node._value = newValue;\n return true;\n }\n });\n }\n copy() {\n return new OrderedMapIterator(this._node, this._header, this.container, this.iteratorType);\n }\n}\nclass OrderedMap extends TreeContainer {\n /**\n * @param container - The initialization container.\n * @param cmp - The compare function.\n * @param enableIndex - Whether to enable iterator indexing function.\n * @example\n * new OrderedMap();\n * new OrderedMap([[0, 1], [2, 1]]);\n * new OrderedMap([[0, 1], [2, 1]], (x, y) => x - y);\n * new OrderedMap([[0, 1], [2, 1]], (x, y) => x - y, true);\n */\n constructor(container = [], cmp, enableIndex) {\n super(cmp, enableIndex);\n const self = this;\n container.forEach(function (el) {\n self.setElement(el[0], el[1]);\n });\n }\n begin() {\n return new OrderedMapIterator(this._header._left || this._header, this._header, this);\n }\n end() {\n return new OrderedMapIterator(this._header, this._header, this);\n }\n rBegin() {\n return new OrderedMapIterator(this._header._right || this._header, this._header, this, 1 /* IteratorType.REVERSE */);\n }\n\n rEnd() {\n return new OrderedMapIterator(this._header, this._header, this, 1 /* IteratorType.REVERSE */);\n }\n\n front() {\n if (this._length === 0) return;\n const minNode = this._header._left;\n return [minNode._key, minNode._value];\n }\n back() {\n if (this._length === 0) return;\n const maxNode = this._header._right;\n return [maxNode._key, maxNode._value];\n }\n lowerBound(key) {\n const resNode = this._lowerBound(this._root, key);\n return new OrderedMapIterator(resNode, this._header, this);\n }\n upperBound(key) {\n const resNode = this._upperBound(this._root, key);\n return new OrderedMapIterator(resNode, this._header, this);\n }\n reverseLowerBound(key) {\n const resNode = this._reverseLowerBound(this._root, key);\n return new OrderedMapIterator(resNode, this._header, this);\n }\n reverseUpperBound(key) {\n const resNode = this._reverseUpperBound(this._root, key);\n return new OrderedMapIterator(resNode, this._header, this);\n }\n forEach(callback) {\n this._inOrderTraversal(function (node, index, map) {\n callback([node._key, node._value], index, map);\n });\n }\n /**\n * @description Insert a key-value pair or set value by the given key.\n * @param key - The key want to insert.\n * @param value - The value want to set.\n * @param hint - You can give an iterator hint to improve insertion efficiency.\n * @return The size of container after setting.\n * @example\n * const mp = new OrderedMap([[2, 0], [4, 0], [5, 0]]);\n * const iter = mp.begin();\n * mp.setElement(1, 0);\n * mp.setElement(3, 0, iter); // give a hint will be faster.\n */\n setElement(key, value, hint) {\n return this._set(key, value, hint);\n }\n getElementByPos(pos) {\n if (pos < 0 || pos > this._length - 1) {\n throw new RangeError();\n }\n const node = this._inOrderTraversal(pos);\n return [node._key, node._value];\n }\n find(key) {\n const curNode = this._getTreeNodeByKey(this._root, key);\n return new OrderedMapIterator(curNode, this._header, this);\n }\n /**\n * @description Get the value of the element of the specified key.\n * @param key - The specified key you want to get.\n * @example\n * const val = container.getElementByKey(1);\n */\n getElementByKey(key) {\n const curNode = this._getTreeNodeByKey(this._root, key);\n return curNode._value;\n }\n union(other) {\n const self = this;\n other.forEach(function (el) {\n self.setElement(el[0], el[1]);\n });\n return this._length;\n }\n *[Symbol.iterator]() {\n const length = this._length;\n const nodeList = this._inOrderTraversal();\n for (let i = 0; i < length; ++i) {\n const node = nodeList[i];\n yield [node._key, node._value];\n }\n }\n}\n\nexports.OrderedMap = OrderedMap;\n//# sourceMappingURL=index.js.map\n","export const enum TreeNodeColor {\n RED = 1,\n BLACK = 0\n}\n\nexport class TreeNode {\n _color: TreeNodeColor;\n _key: K | undefined;\n _value: V | undefined;\n _left: TreeNode | undefined = undefined;\n _right: TreeNode | undefined = undefined;\n _parent: TreeNode | undefined = undefined;\n constructor(\n key?: K,\n value?: V,\n color: TreeNodeColor = TreeNodeColor.RED\n ) {\n this._key = key;\n this._value = value;\n this._color = color;\n }\n /**\n * @description Get the pre node.\n * @returns TreeNode about the pre node.\n */\n _pre() {\n let preNode: TreeNode = this;\n const isRootOrHeader = preNode._parent!._parent === preNode;\n if (isRootOrHeader && preNode._color === TreeNodeColor.RED) {\n preNode = preNode._right!;\n } else if (preNode._left) {\n preNode = preNode._left;\n while (preNode._right) {\n preNode = preNode._right;\n }\n } else {\n // Must be root and left is null\n if (isRootOrHeader) {\n return preNode._parent!;\n }\n let pre = preNode._parent!;\n while (pre._left === preNode) {\n preNode = pre;\n pre = preNode._parent!;\n }\n preNode = pre;\n }\n return preNode;\n }\n /**\n * @description Get the next node.\n * @returns TreeNode about the next node.\n */\n _next() {\n let nextNode: TreeNode = this;\n if (nextNode._right) {\n nextNode = nextNode._right;\n while (nextNode._left) {\n nextNode = nextNode._left;\n }\n return nextNode;\n } else {\n let pre = nextNode._parent!;\n while (pre._right === nextNode) {\n nextNode = pre;\n pre = nextNode._parent!;\n }\n if (nextNode._right !== pre) {\n return pre;\n } else return nextNode;\n }\n }\n /**\n * @description Rotate left.\n * @returns TreeNode about moved to original position after rotation.\n */\n _rotateLeft() {\n const PP = this._parent!;\n const V = this._right!;\n const R = V._left;\n\n if (PP._parent === this) PP._parent = V;\n else if (PP._left === this) PP._left = V;\n else PP._right = V;\n\n V._parent = PP;\n V._left = this;\n\n this._parent = V;\n this._right = R;\n\n if (R) R._parent = this;\n\n return V;\n }\n /**\n * @description Rotate right.\n * @returns TreeNode about moved to original position after rotation.\n */\n _rotateRight() {\n const PP = this._parent!;\n const F = this._left!;\n const K = F._right;\n\n if (PP._parent === this) PP._parent = F;\n else if (PP._left === this) PP._left = F;\n else PP._right = F;\n\n F._parent = PP;\n F._right = this;\n\n this._parent = F;\n this._left = K;\n\n if (K) K._parent = this;\n\n return F;\n }\n}\n\nexport class TreeNodeEnableIndex extends TreeNode {\n _subTreeSize = 1;\n /**\n * @description Rotate left and do recount.\n * @returns TreeNode about moved to original position after rotation.\n */\n _rotateLeft() {\n const parent = super._rotateLeft() as TreeNodeEnableIndex;\n this._recount();\n parent._recount();\n return parent;\n }\n /**\n * @description Rotate right and do recount.\n * @returns TreeNode about moved to original position after rotation.\n */\n _rotateRight() {\n const parent = super._rotateRight() as TreeNodeEnableIndex;\n this._recount();\n parent._recount();\n return parent;\n }\n _recount() {\n this._subTreeSize = 1;\n if (this._left) {\n this._subTreeSize += (this._left as TreeNodeEnableIndex)._subTreeSize;\n }\n if (this._right) {\n this._subTreeSize += (this._right as TreeNodeEnableIndex)._subTreeSize;\n }\n }\n}\n","/**\n * @description The iterator type including `NORMAL` and `REVERSE`.\n */\nexport const enum IteratorType {\n NORMAL = 0,\n REVERSE = 1\n}\n\nexport abstract class ContainerIterator {\n /**\n * @description The container pointed to by the iterator.\n */\n abstract readonly container: Container;\n /**\n * @internal\n */\n abstract _node: unknown;\n /**\n * @description Iterator's type.\n * @example\n * console.log(container.end().iteratorType === IteratorType.NORMAL); // true\n */\n readonly iteratorType: IteratorType;\n /**\n * @internal\n */\n protected constructor(iteratorType = IteratorType.NORMAL) {\n this.iteratorType = iteratorType;\n }\n /**\n * @param iter - The other iterator you want to compare.\n * @returns Whether this equals to obj.\n * @example\n * container.find(1).equals(container.end());\n */\n equals(iter: ContainerIterator) {\n return this._node === iter._node;\n }\n /**\n * @description Pointers to element.\n * @returns The value of the pointer's element.\n * @example\n * const val = container.begin().pointer;\n */\n abstract get pointer(): T;\n /**\n * @description Set pointer's value (some containers are unavailable).\n * @param newValue - The new value you want to set.\n * @example\n * (>container).begin().pointer = 1;\n */\n abstract set pointer(newValue: T);\n /**\n * @description Move `this` iterator to pre.\n * @returns The iterator's self.\n * @example\n * const iter = container.find(1); // container = [0, 1]\n * const pre = iter.pre();\n * console.log(pre === iter); // true\n * console.log(pre.equals(iter)); // true\n * console.log(pre.pointer, iter.pointer); // 0, 0\n */\n abstract pre(): this;\n /**\n * @description Move `this` iterator to next.\n * @returns The iterator's self.\n * @example\n * const iter = container.find(1); // container = [1, 2]\n * const next = iter.next();\n * console.log(next === iter); // true\n * console.log(next.equals(iter)); // true\n * console.log(next.pointer, iter.pointer); // 2, 2\n */\n abstract next(): this;\n /**\n * @description Get a copy of itself.\n * @returns The copy of self.\n * @example\n * const iter = container.find(1); // container = [1, 2]\n * const next = iter.copy().next();\n * console.log(next === iter); // false\n * console.log(next.equals(iter)); // false\n * console.log(next.pointer, iter.pointer); // 2, 1\n */\n abstract copy(): ContainerIterator;\n abstract isAccessible(): boolean;\n}\n\nexport abstract class Base {\n /**\n * @description Container's size.\n * @internal\n */\n protected _length = 0;\n /**\n * @returns The size of the container.\n * @example\n * const container = new Vector([1, 2]);\n * console.log(container.length); // 2\n */\n get length() {\n return this._length;\n }\n /**\n * @returns The size of the container.\n * @example\n * const container = new Vector([1, 2]);\n * console.log(container.size()); // 2\n */\n size() {\n return this._length;\n }\n /**\n * @returns Whether the container is empty.\n * @example\n * container.clear();\n * console.log(container.empty()); // true\n */\n empty() {\n return this._length === 0;\n }\n /**\n * @description Clear the container.\n * @example\n * container.clear();\n * console.log(container.empty()); // true\n */\n abstract clear(): void;\n}\n\nexport abstract class Container extends Base {\n /**\n * @returns Iterator pointing to the beginning element.\n * @example\n * const begin = container.begin();\n * const end = container.end();\n * for (const it = begin; !it.equals(end); it.next()) {\n * doSomething(it.pointer);\n * }\n */\n abstract begin(): ContainerIterator;\n /**\n * @returns Iterator pointing to the super end like c++.\n * @example\n * const begin = container.begin();\n * const end = container.end();\n * for (const it = begin; !it.equals(end); it.next()) {\n * doSomething(it.pointer);\n * }\n */\n abstract end(): ContainerIterator;\n /**\n * @returns Iterator pointing to the end element.\n * @example\n * const rBegin = container.rBegin();\n * const rEnd = container.rEnd();\n * for (const it = rBegin; !it.equals(rEnd); it.next()) {\n * doSomething(it.pointer);\n * }\n */\n abstract rBegin(): ContainerIterator;\n /**\n * @returns Iterator pointing to the super begin like c++.\n * @example\n * const rBegin = container.rBegin();\n * const rEnd = container.rEnd();\n * for (const it = rBegin; !it.equals(rEnd); it.next()) {\n * doSomething(it.pointer);\n * }\n */\n abstract rEnd(): ContainerIterator;\n /**\n * @returns The first element of the container.\n */\n abstract front(): T | undefined;\n /**\n * @returns The last element of the container.\n */\n abstract back(): T | undefined;\n /**\n * @param element - The element you want to find.\n * @returns An iterator pointing to the element if found, or super end if not found.\n * @example\n * container.find(1).equals(container.end());\n */\n abstract find(element: T): ContainerIterator;\n /**\n * @description Iterate over all elements in the container.\n * @param callback - Callback function like Array.forEach.\n * @example\n * container.forEach((element, index) => console.log(element, index));\n */\n abstract forEach(callback: (element: T, index: number, container: Container) => void): void;\n /**\n * @description Gets the value of the element at the specified position.\n * @example\n * const val = container.getElementByPos(-1); // throw a RangeError\n */\n abstract getElementByPos(pos: number): T;\n /**\n * @description Removes the element at the specified position.\n * @param pos - The element's position you want to remove.\n * @returns The container length after erasing.\n * @example\n * container.eraseElementByPos(-1); // throw a RangeError\n */\n abstract eraseElementByPos(pos: number): number;\n /**\n * @description Removes element by iterator and move `iter` to next.\n * @param iter - The iterator you want to erase.\n * @returns The next iterator.\n * @example\n * container.eraseElementByIterator(container.begin());\n * container.eraseElementByIterator(container.end()); // throw a RangeError\n */\n abstract eraseElementByIterator(\n iter: ContainerIterator\n ): ContainerIterator;\n /**\n * @description Using for `for...of` syntax like Array.\n * @example\n * for (const element of container) {\n * console.log(element);\n * }\n */\n abstract [Symbol.iterator](): Generator;\n}\n\n/**\n * @description The initial data type passed in when initializing the container.\n */\nexport type initContainer = {\n size?: number | (() => number);\n length?: number;\n forEach: (callback: (el: T) => void) => void;\n}\n","/**\n * @description Throw an iterator access error.\n * @internal\n */\nexport function throwIteratorAccessError() {\n throw new RangeError('Iterator access denied!');\n}\n","import type TreeIterator from './TreeIterator';\nimport { TreeNode, TreeNodeColor, TreeNodeEnableIndex } from './TreeNode';\nimport { Container, IteratorType } from '@/container/ContainerBase';\nimport $checkWithinAccessParams from '@/utils/checkParams.macro';\nimport { throwIteratorAccessError } from '@/utils/throwError';\n\nabstract class TreeContainer extends Container {\n enableIndex: boolean;\n /**\n * @internal\n */\n protected _header: TreeNode;\n /**\n * @internal\n */\n protected _root: TreeNode | undefined = undefined;\n /**\n * @internal\n */\n protected readonly _cmp: (x: K, y: K) => number;\n /**\n * @internal\n */\n protected readonly _TreeNodeClass: typeof TreeNode | typeof TreeNodeEnableIndex;\n /**\n * @internal\n */\n protected constructor(\n cmp: (x: K, y: K) => number =\n function (x: K, y: K) {\n if (x < y) return -1;\n if (x > y) return 1;\n return 0;\n },\n enableIndex = false\n ) {\n super();\n this._cmp = cmp;\n this.enableIndex = enableIndex;\n this._TreeNodeClass = enableIndex ? TreeNodeEnableIndex : TreeNode;\n this._header = new this._TreeNodeClass();\n }\n /**\n * @internal\n */\n protected _lowerBound(curNode: TreeNode | undefined, key: K) {\n let resNode = this._header;\n while (curNode) {\n const cmpResult = this._cmp(curNode._key!, key);\n if (cmpResult < 0) {\n curNode = curNode._right;\n } else if (cmpResult > 0) {\n resNode = curNode;\n curNode = curNode._left;\n } else return curNode;\n }\n return resNode;\n }\n /**\n * @internal\n */\n protected _upperBound(curNode: TreeNode | undefined, key: K) {\n let resNode = this._header;\n while (curNode) {\n const cmpResult = this._cmp(curNode._key!, key);\n if (cmpResult <= 0) {\n curNode = curNode._right;\n } else {\n resNode = curNode;\n curNode = curNode._left;\n }\n }\n return resNode;\n }\n /**\n * @internal\n */\n protected _reverseLowerBound(curNode: TreeNode | undefined, key: K) {\n let resNode = this._header;\n while (curNode) {\n const cmpResult = this._cmp(curNode._key!, key);\n if (cmpResult < 0) {\n resNode = curNode;\n curNode = curNode._right;\n } else if (cmpResult > 0) {\n curNode = curNode._left;\n } else return curNode;\n }\n return resNode;\n }\n /**\n * @internal\n */\n protected _reverseUpperBound(curNode: TreeNode | undefined, key: K) {\n let resNode = this._header;\n while (curNode) {\n const cmpResult = this._cmp(curNode._key!, key);\n if (cmpResult < 0) {\n resNode = curNode;\n curNode = curNode._right;\n } else {\n curNode = curNode._left;\n }\n }\n return resNode;\n }\n /**\n * @internal\n */\n protected _eraseNodeSelfBalance(curNode: TreeNode) {\n while (true) {\n const parentNode = curNode._parent!;\n if (parentNode === this._header) return;\n if (curNode._color === TreeNodeColor.RED) {\n curNode._color = TreeNodeColor.BLACK;\n return;\n }\n if (curNode === parentNode._left) {\n const brother = parentNode._right!;\n if (brother._color === TreeNodeColor.RED) {\n brother._color = TreeNodeColor.BLACK;\n parentNode._color = TreeNodeColor.RED;\n if (parentNode === this._root) {\n this._root = parentNode._rotateLeft();\n } else parentNode._rotateLeft();\n } else {\n if (brother._right && brother._right._color === TreeNodeColor.RED) {\n brother._color = parentNode._color;\n parentNode._color = TreeNodeColor.BLACK;\n brother._right._color = TreeNodeColor.BLACK;\n if (parentNode === this._root) {\n this._root = parentNode._rotateLeft();\n } else parentNode._rotateLeft();\n return;\n } else if (brother._left && brother._left._color === TreeNodeColor.RED) {\n brother._color = TreeNodeColor.RED;\n brother._left._color = TreeNodeColor.BLACK;\n brother._rotateRight();\n } else {\n brother._color = TreeNodeColor.RED;\n curNode = parentNode;\n }\n }\n } else {\n const brother = parentNode._left!;\n if (brother._color === TreeNodeColor.RED) {\n brother._color = TreeNodeColor.BLACK;\n parentNode._color = TreeNodeColor.RED;\n if (parentNode === this._root) {\n this._root = parentNode._rotateRight();\n } else parentNode._rotateRight();\n } else {\n if (brother._left && brother._left._color === TreeNodeColor.RED) {\n brother._color = parentNode._color;\n parentNode._color = TreeNodeColor.BLACK;\n brother._left._color = TreeNodeColor.BLACK;\n if (parentNode === this._root) {\n this._root = parentNode._rotateRight();\n } else parentNode._rotateRight();\n return;\n } else if (brother._right && brother._right._color === TreeNodeColor.RED) {\n brother._color = TreeNodeColor.RED;\n brother._right._color = TreeNodeColor.BLACK;\n brother._rotateLeft();\n } else {\n brother._color = TreeNodeColor.RED;\n curNode = parentNode;\n }\n }\n }\n }\n }\n /**\n * @internal\n */\n protected _eraseNode(curNode: TreeNode) {\n if (this._length === 1) {\n this.clear();\n return;\n }\n let swapNode = curNode;\n while (swapNode._left || swapNode._right) {\n if (swapNode._right) {\n swapNode = swapNode._right;\n while (swapNode._left) swapNode = swapNode._left;\n } else {\n swapNode = swapNode._left!;\n }\n const key = curNode._key;\n curNode._key = swapNode._key;\n swapNode._key = key;\n const value = curNode._value;\n curNode._value = swapNode._value;\n swapNode._value = value;\n curNode = swapNode;\n }\n if (this._header._left === swapNode) {\n this._header._left = swapNode._parent;\n } else if (this._header._right === swapNode) {\n this._header._right = swapNode._parent;\n }\n this._eraseNodeSelfBalance(swapNode);\n let _parent = swapNode._parent as TreeNodeEnableIndex;\n if (swapNode === _parent._left) {\n _parent._left = undefined;\n } else _parent._right = undefined;\n this._length -= 1;\n this._root!._color = TreeNodeColor.BLACK;\n if (this.enableIndex) {\n while (_parent !== this._header) {\n _parent._subTreeSize -= 1;\n _parent = _parent._parent as TreeNodeEnableIndex;\n }\n }\n }\n protected _inOrderTraversal(): TreeNode[];\n protected _inOrderTraversal(pos: number): TreeNode;\n protected _inOrderTraversal(\n callback: (node: TreeNode, index: number, map: this) => void\n ): TreeNode;\n /**\n * @internal\n */\n protected _inOrderTraversal(\n param?: number | ((node: TreeNode, index: number, map: this) => void)\n ) {\n const pos = typeof param === 'number' ? param : undefined;\n const callback = typeof param === 'function' ? param : undefined;\n const nodeList = typeof param === 'undefined' ? []>[] : undefined;\n let index = 0;\n let curNode = this._root;\n const stack: TreeNode[] = [];\n while (stack.length || curNode) {\n if (curNode) {\n stack.push(curNode);\n curNode = curNode._left;\n } else {\n curNode = stack.pop()!;\n if (index === pos) return curNode;\n nodeList && nodeList.push(curNode);\n callback && callback(curNode, index, this);\n index += 1;\n curNode = curNode._right;\n }\n }\n return nodeList;\n }\n /**\n * @internal\n */\n protected _insertNodeSelfBalance(curNode: TreeNode) {\n while (true) {\n const parentNode = curNode._parent!;\n if (parentNode._color === TreeNodeColor.BLACK) return;\n const grandParent = parentNode._parent!;\n if (parentNode === grandParent._left) {\n const uncle = grandParent._right;\n if (uncle && uncle._color === TreeNodeColor.RED) {\n uncle._color = parentNode._color = TreeNodeColor.BLACK;\n if (grandParent === this._root) return;\n grandParent._color = TreeNodeColor.RED;\n curNode = grandParent;\n continue;\n } else if (curNode === parentNode._right) {\n curNode._color = TreeNodeColor.BLACK;\n if (curNode._left) {\n curNode._left._parent = parentNode;\n }\n if (curNode._right) {\n curNode._right._parent = grandParent;\n }\n parentNode._right = curNode._left;\n grandParent._left = curNode._right;\n curNode._left = parentNode;\n curNode._right = grandParent;\n if (grandParent === this._root) {\n this._root = curNode;\n this._header._parent = curNode;\n } else {\n const GP = grandParent._parent!;\n if (GP._left === grandParent) {\n GP._left = curNode;\n } else GP._right = curNode;\n }\n curNode._parent = grandParent._parent;\n parentNode._parent = curNode;\n grandParent._parent = curNode;\n grandParent._color = TreeNodeColor.RED;\n } else {\n parentNode._color = TreeNodeColor.BLACK;\n if (grandParent === this._root) {\n this._root = grandParent._rotateRight();\n } else grandParent._rotateRight();\n grandParent._color = TreeNodeColor.RED;\n return;\n }\n } else {\n const uncle = grandParent._left;\n if (uncle && uncle._color === TreeNodeColor.RED) {\n uncle._color = parentNode._color = TreeNodeColor.BLACK;\n if (grandParent === this._root) return;\n grandParent._color = TreeNodeColor.RED;\n curNode = grandParent;\n continue;\n } else if (curNode === parentNode._left) {\n curNode._color = TreeNodeColor.BLACK;\n if (curNode._left) {\n curNode._left._parent = grandParent;\n }\n if (curNode._right) {\n curNode._right._parent = parentNode;\n }\n grandParent._right = curNode._left;\n parentNode._left = curNode._right;\n curNode._left = grandParent;\n curNode._right = parentNode;\n if (grandParent === this._root) {\n this._root = curNode;\n this._header._parent = curNode;\n } else {\n const GP = grandParent._parent!;\n if (GP._left === grandParent) {\n GP._left = curNode;\n } else GP._right = curNode;\n }\n curNode._parent = grandParent._parent;\n parentNode._parent = curNode;\n grandParent._parent = curNode;\n grandParent._color = TreeNodeColor.RED;\n } else {\n parentNode._color = TreeNodeColor.BLACK;\n if (grandParent === this._root) {\n this._root = grandParent._rotateLeft();\n } else grandParent._rotateLeft();\n grandParent._color = TreeNodeColor.RED;\n return;\n }\n }\n if (this.enableIndex) {\n (>parentNode)._recount();\n (>grandParent)._recount();\n (>curNode)._recount();\n }\n return;\n }\n }\n /**\n * @internal\n */\n protected _set(key: K, value?: V, hint?: TreeIterator) {\n if (this._root === undefined) {\n this._length += 1;\n this._root = new this._TreeNodeClass(key, value, TreeNodeColor.BLACK);\n this._root._parent = this._header;\n this._header._parent = this._header._left = this._header._right = this._root;\n return this._length;\n }\n let curNode;\n const minNode = this._header._left!;\n const compareToMin = this._cmp(minNode._key!, key);\n if (compareToMin === 0) {\n minNode._value = value;\n return this._length;\n } else if (compareToMin > 0) {\n minNode._left = new this._TreeNodeClass(key, value);\n minNode._left._parent = minNode;\n curNode = minNode._left;\n this._header._left = curNode;\n } else {\n const maxNode = this._header._right!;\n const compareToMax = this._cmp(maxNode._key!, key);\n if (compareToMax === 0) {\n maxNode._value = value;\n return this._length;\n } else if (compareToMax < 0) {\n maxNode._right = new this._TreeNodeClass(key, value);\n maxNode._right._parent = maxNode;\n curNode = maxNode._right;\n this._header._right = curNode;\n } else {\n if (hint !== undefined) {\n const iterNode = hint._node;\n if (iterNode !== this._header) {\n const iterCmpRes = this._cmp(iterNode._key!, key);\n if (iterCmpRes === 0) {\n iterNode._value = value;\n return this._length;\n } else /* istanbul ignore else */ if (iterCmpRes > 0) {\n const preNode = iterNode._pre();\n const preCmpRes = this._cmp(preNode._key!, key);\n if (preCmpRes === 0) {\n preNode._value = value;\n return this._length;\n } else if (preCmpRes < 0) {\n curNode = new this._TreeNodeClass(key, value);\n if (preNode._right === undefined) {\n preNode._right = curNode;\n curNode._parent = preNode;\n } else {\n iterNode._left = curNode;\n curNode._parent = iterNode;\n }\n }\n }\n }\n }\n if (curNode === undefined) {\n curNode = this._root;\n while (true) {\n const cmpResult = this._cmp(curNode._key!, key);\n if (cmpResult > 0) {\n if (curNode._left === undefined) {\n curNode._left = new this._TreeNodeClass(key, value);\n curNode._left._parent = curNode;\n curNode = curNode._left;\n break;\n }\n curNode = curNode._left;\n } else if (cmpResult < 0) {\n if (curNode._right === undefined) {\n curNode._right = new this._TreeNodeClass(key, value);\n curNode._right._parent = curNode;\n curNode = curNode._right;\n break;\n }\n curNode = curNode._right;\n } else {\n curNode._value = value;\n return this._length;\n }\n }\n }\n }\n }\n if (this.enableIndex) {\n let parent = curNode._parent as TreeNodeEnableIndex;\n while (parent !== this._header) {\n parent._subTreeSize += 1;\n parent = parent._parent as TreeNodeEnableIndex;\n }\n }\n this._insertNodeSelfBalance(curNode);\n this._length += 1;\n return this._length;\n }\n /**\n * @internal\n */\n protected _getTreeNodeByKey(curNode: TreeNode | undefined, key: K) {\n while (curNode) {\n const cmpResult = this._cmp(curNode._key!, key);\n if (cmpResult < 0) {\n curNode = curNode._right;\n } else if (cmpResult > 0) {\n curNode = curNode._left;\n } else return curNode;\n }\n return curNode || this._header;\n }\n clear() {\n this._length = 0;\n this._root = undefined;\n this._header._parent = undefined;\n this._header._left = this._header._right = undefined;\n }\n /**\n * @description Update node's key by iterator.\n * @param iter - The iterator you want to change.\n * @param key - The key you want to update.\n * @returns Whether the modification is successful.\n * @example\n * const st = new orderedSet([1, 2, 5]);\n * const iter = st.find(2);\n * st.updateKeyByIterator(iter, 3); // then st will become [1, 3, 5]\n */\n updateKeyByIterator(iter: TreeIterator, key: K): boolean {\n const node = iter._node;\n if (node === this._header) {\n throwIteratorAccessError();\n }\n if (this._length === 1) {\n node._key = key;\n return true;\n }\n const nextKey = node._next()._key!;\n if (node === this._header._left) {\n if (this._cmp(nextKey, key) > 0) {\n node._key = key;\n return true;\n }\n return false;\n }\n const preKey = node._pre()._key!;\n if (node === this._header._right) {\n if (this._cmp(preKey, key) < 0) {\n node._key = key;\n return true;\n }\n return false;\n }\n if (\n this._cmp(preKey, key) >= 0 ||\n this._cmp(nextKey, key) <= 0\n ) return false;\n node._key = key;\n return true;\n }\n eraseElementByPos(pos: number) {\n $checkWithinAccessParams!(pos, 0, this._length - 1);\n const node = this._inOrderTraversal(pos);\n this._eraseNode(node);\n return this._length;\n }\n /**\n * @description Remove the element of the specified key.\n * @param key - The key you want to remove.\n * @returns Whether erase successfully.\n */\n eraseElementByKey(key: K) {\n if (this._length === 0) return false;\n const curNode = this._getTreeNodeByKey(this._root, key);\n if (curNode === this._header) return false;\n this._eraseNode(curNode);\n return true;\n }\n eraseElementByIterator(iter: TreeIterator) {\n const node = iter._node;\n if (node === this._header) {\n throwIteratorAccessError();\n }\n const hasNoRight = node._right === undefined;\n const isNormal = iter.iteratorType === IteratorType.NORMAL;\n // For the normal iterator, the `next` node will be swapped to `this` node when has right.\n if (isNormal) {\n // So we should move it to next when it's right is null.\n if (hasNoRight) iter.next();\n } else {\n // For the reverse iterator, only when it doesn't have right and has left the `next` node will be swapped.\n // So when it has right, or it is a leaf node we should move it to `next`.\n if (!hasNoRight || node._left === undefined) iter.next();\n }\n this._eraseNode(node);\n return iter;\n }\n /**\n * @description Get the height of the tree.\n * @returns Number about the height of the RB-tree.\n */\n getHeight() {\n if (this._length === 0) return 0;\n function traversal(curNode: TreeNode | undefined): number {\n if (!curNode) return 0;\n return Math.max(traversal(curNode._left), traversal(curNode._right)) + 1;\n }\n return traversal(this._root);\n }\n /**\n * @param key - The given key you want to compare.\n * @returns An iterator to the first element less than the given key.\n */\n abstract reverseUpperBound(key: K): TreeIterator;\n /**\n * @description Union the other tree to self.\n * @param other - The other tree container you want to merge.\n * @returns The size of the tree after union.\n */\n abstract union(other: TreeContainer): number;\n /**\n * @param key - The given key you want to compare.\n * @returns An iterator to the first element not greater than the given key.\n */\n abstract reverseLowerBound(key: K): TreeIterator;\n /**\n * @param key - The given key you want to compare.\n * @returns An iterator to the first element not less than the given key.\n */\n abstract lowerBound(key: K): TreeIterator;\n /**\n * @param key - The given key you want to compare.\n * @returns An iterator to the first element greater than the given key.\n */\n abstract upperBound(key: K): TreeIterator;\n}\n\nexport default TreeContainer;\n","import { TreeNode } from './TreeNode';\nimport type { TreeNodeEnableIndex } from './TreeNode';\nimport { ContainerIterator, IteratorType } from '@/container/ContainerBase';\nimport TreeContainer from '@/container/TreeContainer/Base/index';\nimport { throwIteratorAccessError } from '@/utils/throwError';\n\nabstract class TreeIterator extends ContainerIterator {\n abstract readonly container: TreeContainer;\n /**\n * @internal\n */\n _node: TreeNode;\n /**\n * @internal\n */\n protected _header: TreeNode;\n /**\n * @internal\n */\n protected constructor(\n node: TreeNode,\n header: TreeNode,\n iteratorType?: IteratorType\n ) {\n super(iteratorType);\n this._node = node;\n this._header = header;\n if (this.iteratorType === IteratorType.NORMAL) {\n this.pre = function () {\n if (this._node === this._header._left) {\n throwIteratorAccessError();\n }\n this._node = this._node._pre();\n return this;\n };\n\n this.next = function () {\n if (this._node === this._header) {\n throwIteratorAccessError();\n }\n this._node = this._node._next();\n return this;\n };\n } else {\n this.pre = function () {\n if (this._node === this._header._right) {\n throwIteratorAccessError();\n }\n this._node = this._node._next();\n return this;\n };\n\n this.next = function () {\n if (this._node === this._header) {\n throwIteratorAccessError();\n }\n this._node = this._node._pre();\n return this;\n };\n }\n }\n /**\n * @description Get the sequential index of the iterator in the tree container.
\n * Note:\n * This function only takes effect when the specified tree container `enableIndex = true`.\n * @returns The index subscript of the node in the tree.\n * @example\n * const st = new OrderedSet([1, 2, 3], true);\n * console.log(st.begin().next().index); // 1\n */\n get index() {\n let _node = this._node as TreeNodeEnableIndex;\n const root = this._header._parent as TreeNodeEnableIndex;\n if (_node === this._header) {\n if (root) {\n return root._subTreeSize - 1;\n }\n return 0;\n }\n let index = 0;\n if (_node._left) {\n index += (_node._left as TreeNodeEnableIndex)._subTreeSize;\n }\n while (_node !== root) {\n const _parent = _node._parent as TreeNodeEnableIndex;\n if (_node === _parent._right) {\n index += 1;\n if (_parent._left) {\n index += (_parent._left as TreeNodeEnableIndex)._subTreeSize;\n }\n }\n _node = _parent;\n }\n return index;\n }\n isAccessible() {\n return this._node !== this._header;\n }\n // @ts-ignore\n pre(): this;\n // @ts-ignore\n next(): this;\n}\n\nexport default TreeIterator;\n","import TreeContainer from './Base';\nimport TreeIterator from './Base/TreeIterator';\nimport { TreeNode } from './Base/TreeNode';\nimport { initContainer, IteratorType } from '@/container/ContainerBase';\nimport $checkWithinAccessParams from '@/utils/checkParams.macro';\nimport { throwIteratorAccessError } from '@/utils/throwError';\n\nclass OrderedMapIterator extends TreeIterator {\n container: OrderedMap;\n constructor(\n node: TreeNode,\n header: TreeNode,\n container: OrderedMap,\n iteratorType?: IteratorType\n ) {\n super(node, header, iteratorType);\n this.container = container;\n }\n get pointer() {\n if (this._node === this._header) {\n throwIteratorAccessError();\n }\n const self = this;\n return new Proxy(<[K, V]>[], {\n get(target, prop: '0' | '1') {\n if (prop === '0') return self._node._key!;\n else if (prop === '1') return self._node._value!;\n target[0] = self._node._key!;\n target[1] = self._node._value!;\n return target[prop];\n },\n set(_, prop: '1', newValue: V) {\n if (prop !== '1') {\n throw new TypeError('prop must be 1');\n }\n self._node._value = newValue;\n return true;\n }\n });\n }\n copy() {\n return new OrderedMapIterator(\n this._node,\n this._header,\n this.container,\n this.iteratorType\n );\n }\n // @ts-ignore\n equals(iter: OrderedMapIterator): boolean;\n}\n\nexport type { OrderedMapIterator };\n\nclass OrderedMap extends TreeContainer {\n /**\n * @param container - The initialization container.\n * @param cmp - The compare function.\n * @param enableIndex - Whether to enable iterator indexing function.\n * @example\n * new OrderedMap();\n * new OrderedMap([[0, 1], [2, 1]]);\n * new OrderedMap([[0, 1], [2, 1]], (x, y) => x - y);\n * new OrderedMap([[0, 1], [2, 1]], (x, y) => x - y, true);\n */\n constructor(\n container: initContainer<[K, V]> = [],\n cmp?: (x: K, y: K) => number,\n enableIndex?: boolean\n ) {\n super(cmp, enableIndex);\n const self = this;\n container.forEach(function (el) {\n self.setElement(el[0], el[1]);\n });\n }\n begin() {\n return new OrderedMapIterator(this._header._left || this._header, this._header, this);\n }\n end() {\n return new OrderedMapIterator(this._header, this._header, this);\n }\n rBegin() {\n return new OrderedMapIterator(\n this._header._right || this._header,\n this._header,\n this,\n IteratorType.REVERSE\n );\n }\n rEnd() {\n return new OrderedMapIterator(this._header, this._header, this, IteratorType.REVERSE);\n }\n front() {\n if (this._length === 0) return;\n const minNode = this._header._left!;\n return <[K, V]>[minNode._key, minNode._value];\n }\n back() {\n if (this._length === 0) return;\n const maxNode = this._header._right!;\n return <[K, V]>[maxNode._key, maxNode._value];\n }\n lowerBound(key: K) {\n const resNode = this._lowerBound(this._root, key);\n return new OrderedMapIterator(resNode, this._header, this);\n }\n upperBound(key: K) {\n const resNode = this._upperBound(this._root, key);\n return new OrderedMapIterator(resNode, this._header, this);\n }\n reverseLowerBound(key: K) {\n const resNode = this._reverseLowerBound(this._root, key);\n return new OrderedMapIterator(resNode, this._header, this);\n }\n reverseUpperBound(key: K) {\n const resNode = this._reverseUpperBound(this._root, key);\n return new OrderedMapIterator(resNode, this._header, this);\n }\n forEach(callback: (element: [K, V], index: number, map: OrderedMap) => void) {\n this._inOrderTraversal(function (node, index, map) {\n callback(<[K, V]>[node._key, node._value], index, map);\n });\n }\n /**\n * @description Insert a key-value pair or set value by the given key.\n * @param key - The key want to insert.\n * @param value - The value want to set.\n * @param hint - You can give an iterator hint to improve insertion efficiency.\n * @return The size of container after setting.\n * @example\n * const mp = new OrderedMap([[2, 0], [4, 0], [5, 0]]);\n * const iter = mp.begin();\n * mp.setElement(1, 0);\n * mp.setElement(3, 0, iter); // give a hint will be faster.\n */\n setElement(key: K, value: V, hint?: OrderedMapIterator) {\n return this._set(key, value, hint);\n }\n getElementByPos(pos: number) {\n $checkWithinAccessParams!(pos, 0, this._length - 1);\n const node = this._inOrderTraversal(pos);\n return <[K, V]>[node._key, node._value];\n }\n find(key: K) {\n const curNode = this._getTreeNodeByKey(this._root, key);\n return new OrderedMapIterator(curNode, this._header, this);\n }\n /**\n * @description Get the value of the element of the specified key.\n * @param key - The specified key you want to get.\n * @example\n * const val = container.getElementByKey(1);\n */\n getElementByKey(key: K) {\n const curNode = this._getTreeNodeByKey(this._root, key);\n return curNode._value;\n }\n union(other: OrderedMap) {\n const self = this;\n other.forEach(function (el) {\n self.setElement(el[0], el[1]);\n });\n return this._length;\n }\n * [Symbol.iterator]() {\n const length = this._length;\n const nodeList = this._inOrderTraversal();\n for (let i = 0; i < length; ++i) {\n const node = nodeList[i];\n yield <[K, V]>[node._key, node._value];\n }\n }\n // @ts-ignore\n eraseElementByIterator(iter: OrderedMapIterator): OrderedMapIterator;\n}\n\nexport default OrderedMap;\n"]} \ No newline at end of file diff --git a/node_modules/@js-sdsl/ordered-map/dist/esm/index.d.ts b/node_modules/@js-sdsl/ordered-map/dist/esm/index.d.ts new file mode 100644 index 0000000..8615f37 --- /dev/null +++ b/node_modules/@js-sdsl/ordered-map/dist/esm/index.d.ts @@ -0,0 +1,402 @@ +/** + * @description The iterator type including `NORMAL` and `REVERSE`. + */ +declare const enum IteratorType { + NORMAL = 0, + REVERSE = 1 +} +declare abstract class ContainerIterator { + /** + * @description The container pointed to by the iterator. + */ + abstract readonly container: Container; + /** + * @description Iterator's type. + * @example + * console.log(container.end().iteratorType === IteratorType.NORMAL); // true + */ + readonly iteratorType: IteratorType; + /** + * @param iter - The other iterator you want to compare. + * @returns Whether this equals to obj. + * @example + * container.find(1).equals(container.end()); + */ + equals(iter: ContainerIterator): boolean; + /** + * @description Pointers to element. + * @returns The value of the pointer's element. + * @example + * const val = container.begin().pointer; + */ + abstract get pointer(): T; + /** + * @description Set pointer's value (some containers are unavailable). + * @param newValue - The new value you want to set. + * @example + * (>container).begin().pointer = 1; + */ + abstract set pointer(newValue: T); + /** + * @description Move `this` iterator to pre. + * @returns The iterator's self. + * @example + * const iter = container.find(1); // container = [0, 1] + * const pre = iter.pre(); + * console.log(pre === iter); // true + * console.log(pre.equals(iter)); // true + * console.log(pre.pointer, iter.pointer); // 0, 0 + */ + abstract pre(): this; + /** + * @description Move `this` iterator to next. + * @returns The iterator's self. + * @example + * const iter = container.find(1); // container = [1, 2] + * const next = iter.next(); + * console.log(next === iter); // true + * console.log(next.equals(iter)); // true + * console.log(next.pointer, iter.pointer); // 2, 2 + */ + abstract next(): this; + /** + * @description Get a copy of itself. + * @returns The copy of self. + * @example + * const iter = container.find(1); // container = [1, 2] + * const next = iter.copy().next(); + * console.log(next === iter); // false + * console.log(next.equals(iter)); // false + * console.log(next.pointer, iter.pointer); // 2, 1 + */ + abstract copy(): ContainerIterator; + abstract isAccessible(): boolean; +} +declare abstract class Base { + /** + * @returns The size of the container. + * @example + * const container = new Vector([1, 2]); + * console.log(container.length); // 2 + */ + get length(): number; + /** + * @returns The size of the container. + * @example + * const container = new Vector([1, 2]); + * console.log(container.size()); // 2 + */ + size(): number; + /** + * @returns Whether the container is empty. + * @example + * container.clear(); + * console.log(container.empty()); // true + */ + empty(): boolean; + /** + * @description Clear the container. + * @example + * container.clear(); + * console.log(container.empty()); // true + */ + abstract clear(): void; +} +declare abstract class Container extends Base { + /** + * @returns Iterator pointing to the beginning element. + * @example + * const begin = container.begin(); + * const end = container.end(); + * for (const it = begin; !it.equals(end); it.next()) { + * doSomething(it.pointer); + * } + */ + abstract begin(): ContainerIterator; + /** + * @returns Iterator pointing to the super end like c++. + * @example + * const begin = container.begin(); + * const end = container.end(); + * for (const it = begin; !it.equals(end); it.next()) { + * doSomething(it.pointer); + * } + */ + abstract end(): ContainerIterator; + /** + * @returns Iterator pointing to the end element. + * @example + * const rBegin = container.rBegin(); + * const rEnd = container.rEnd(); + * for (const it = rBegin; !it.equals(rEnd); it.next()) { + * doSomething(it.pointer); + * } + */ + abstract rBegin(): ContainerIterator; + /** + * @returns Iterator pointing to the super begin like c++. + * @example + * const rBegin = container.rBegin(); + * const rEnd = container.rEnd(); + * for (const it = rBegin; !it.equals(rEnd); it.next()) { + * doSomething(it.pointer); + * } + */ + abstract rEnd(): ContainerIterator; + /** + * @returns The first element of the container. + */ + abstract front(): T | undefined; + /** + * @returns The last element of the container. + */ + abstract back(): T | undefined; + /** + * @param element - The element you want to find. + * @returns An iterator pointing to the element if found, or super end if not found. + * @example + * container.find(1).equals(container.end()); + */ + abstract find(element: T): ContainerIterator; + /** + * @description Iterate over all elements in the container. + * @param callback - Callback function like Array.forEach. + * @example + * container.forEach((element, index) => console.log(element, index)); + */ + abstract forEach(callback: (element: T, index: number, container: Container) => void): void; + /** + * @description Gets the value of the element at the specified position. + * @example + * const val = container.getElementByPos(-1); // throw a RangeError + */ + abstract getElementByPos(pos: number): T; + /** + * @description Removes the element at the specified position. + * @param pos - The element's position you want to remove. + * @returns The container length after erasing. + * @example + * container.eraseElementByPos(-1); // throw a RangeError + */ + abstract eraseElementByPos(pos: number): number; + /** + * @description Removes element by iterator and move `iter` to next. + * @param iter - The iterator you want to erase. + * @returns The next iterator. + * @example + * container.eraseElementByIterator(container.begin()); + * container.eraseElementByIterator(container.end()); // throw a RangeError + */ + abstract eraseElementByIterator(iter: ContainerIterator): ContainerIterator; + /** + * @description Using for `for...of` syntax like Array. + * @example + * for (const element of container) { + * console.log(element); + * } + */ + abstract [Symbol.iterator](): Generator; +} +/** + * @description The initial data type passed in when initializing the container. + */ +type initContainer = { + size?: number | (() => number); + length?: number; + forEach: (callback: (el: T) => void) => void; +}; +declare abstract class TreeIterator extends ContainerIterator { + abstract readonly container: TreeContainer; + /** + * @description Get the sequential index of the iterator in the tree container.
+ * Note: + * This function only takes effect when the specified tree container `enableIndex = true`. + * @returns The index subscript of the node in the tree. + * @example + * const st = new OrderedSet([1, 2, 3], true); + * console.log(st.begin().next().index); // 1 + */ + get index(): number; + isAccessible(): boolean; + // @ts-ignore + pre(): this; + // @ts-ignore + next(): this; +} +declare const enum TreeNodeColor { + RED = 1, + BLACK = 0 +} +declare class TreeNode { + _color: TreeNodeColor; + _key: K | undefined; + _value: V | undefined; + _left: TreeNode | undefined; + _right: TreeNode | undefined; + _parent: TreeNode | undefined; + constructor(key?: K, value?: V, color?: TreeNodeColor); + /** + * @description Get the pre node. + * @returns TreeNode about the pre node. + */ + _pre(): TreeNode; + /** + * @description Get the next node. + * @returns TreeNode about the next node. + */ + _next(): TreeNode; + /** + * @description Rotate left. + * @returns TreeNode about moved to original position after rotation. + */ + _rotateLeft(): TreeNode; + /** + * @description Rotate right. + * @returns TreeNode about moved to original position after rotation. + */ + _rotateRight(): TreeNode; +} +declare abstract class TreeContainer extends Container { + enableIndex: boolean; + protected _inOrderTraversal(): TreeNode[]; + protected _inOrderTraversal(pos: number): TreeNode; + protected _inOrderTraversal(callback: (node: TreeNode, index: number, map: this) => void): TreeNode; + clear(): void; + /** + * @description Update node's key by iterator. + * @param iter - The iterator you want to change. + * @param key - The key you want to update. + * @returns Whether the modification is successful. + * @example + * const st = new orderedSet([1, 2, 5]); + * const iter = st.find(2); + * st.updateKeyByIterator(iter, 3); // then st will become [1, 3, 5] + */ + updateKeyByIterator(iter: TreeIterator, key: K): boolean; + eraseElementByPos(pos: number): number; + /** + * @description Remove the element of the specified key. + * @param key - The key you want to remove. + * @returns Whether erase successfully. + */ + eraseElementByKey(key: K): boolean; + eraseElementByIterator(iter: TreeIterator): TreeIterator; + /** + * @description Get the height of the tree. + * @returns Number about the height of the RB-tree. + */ + getHeight(): number; + /** + * @param key - The given key you want to compare. + * @returns An iterator to the first element less than the given key. + */ + abstract reverseUpperBound(key: K): TreeIterator; + /** + * @description Union the other tree to self. + * @param other - The other tree container you want to merge. + * @returns The size of the tree after union. + */ + abstract union(other: TreeContainer): number; + /** + * @param key - The given key you want to compare. + * @returns An iterator to the first element not greater than the given key. + */ + abstract reverseLowerBound(key: K): TreeIterator; + /** + * @param key - The given key you want to compare. + * @returns An iterator to the first element not less than the given key. + */ + abstract lowerBound(key: K): TreeIterator; + /** + * @param key - The given key you want to compare. + * @returns An iterator to the first element greater than the given key. + */ + abstract upperBound(key: K): TreeIterator; +} +declare class OrderedMapIterator extends TreeIterator { + container: OrderedMap; + constructor(node: TreeNode, header: TreeNode, container: OrderedMap, iteratorType?: IteratorType); + get pointer(): [ + K, + V + ]; + copy(): OrderedMapIterator; + // @ts-ignore + equals(iter: OrderedMapIterator): boolean; +} +declare class OrderedMap extends TreeContainer { + /** + * @param container - The initialization container. + * @param cmp - The compare function. + * @param enableIndex - Whether to enable iterator indexing function. + * @example + * new OrderedMap(); + * new OrderedMap([[0, 1], [2, 1]]); + * new OrderedMap([[0, 1], [2, 1]], (x, y) => x - y); + * new OrderedMap([[0, 1], [2, 1]], (x, y) => x - y, true); + */ + constructor(container?: initContainer<[ + K, + V + ]>, cmp?: (x: K, y: K) => number, enableIndex?: boolean); + begin(): OrderedMapIterator; + end(): OrderedMapIterator; + rBegin(): OrderedMapIterator; + rEnd(): OrderedMapIterator; + front(): [ + K, + V + ] | undefined; + back(): [ + K, + V + ] | undefined; + lowerBound(key: K): OrderedMapIterator; + upperBound(key: K): OrderedMapIterator; + reverseLowerBound(key: K): OrderedMapIterator; + reverseUpperBound(key: K): OrderedMapIterator; + forEach(callback: (element: [ + K, + V + ], index: number, map: OrderedMap) => void): void; + /** + * @description Insert a key-value pair or set value by the given key. + * @param key - The key want to insert. + * @param value - The value want to set. + * @param hint - You can give an iterator hint to improve insertion efficiency. + * @return The size of container after setting. + * @example + * const mp = new OrderedMap([[2, 0], [4, 0], [5, 0]]); + * const iter = mp.begin(); + * mp.setElement(1, 0); + * mp.setElement(3, 0, iter); // give a hint will be faster. + */ + setElement(key: K, value: V, hint?: OrderedMapIterator): number; + getElementByPos(pos: number): [ + K, + V + ]; + find(key: K): OrderedMapIterator; + /** + * @description Get the value of the element of the specified key. + * @param key - The specified key you want to get. + * @example + * const val = container.getElementByKey(1); + */ + getElementByKey(key: K): V | undefined; + union(other: OrderedMap): number; + [Symbol.iterator](): Generator<[ + K, + V + ], void, unknown>; + // @ts-ignore + eraseElementByIterator(iter: OrderedMapIterator): OrderedMapIterator; +} +export { OrderedMap }; +export type { OrderedMapIterator, IteratorType, Container, ContainerIterator, TreeContainer }; diff --git a/node_modules/@js-sdsl/ordered-map/dist/esm/index.js b/node_modules/@js-sdsl/ordered-map/dist/esm/index.js new file mode 100644 index 0000000..1504ce8 --- /dev/null +++ b/node_modules/@js-sdsl/ordered-map/dist/esm/index.js @@ -0,0 +1,975 @@ +var extendStatics = function(e, r) { + extendStatics = Object.setPrototypeOf || { + __proto__: [] + } instanceof Array && function(e, r) { + e.__proto__ = r; + } || function(e, r) { + for (var t in r) if (Object.prototype.hasOwnProperty.call(r, t)) e[t] = r[t]; + }; + return extendStatics(e, r); +}; + +function __extends(e, r) { + if (typeof r !== "function" && r !== null) throw new TypeError("Class extends value " + String(r) + " is not a constructor or null"); + extendStatics(e, r); + function __() { + this.constructor = e; + } + e.prototype = r === null ? Object.create(r) : (__.prototype = r.prototype, new __); +} + +function __generator(e, r) { + var t = { + label: 0, + sent: function() { + if (s[0] & 1) throw s[1]; + return s[1]; + }, + trys: [], + ops: [] + }, i, n, s, h; + return h = { + next: verb(0), + throw: verb(1), + return: verb(2) + }, typeof Symbol === "function" && (h[Symbol.iterator] = function() { + return this; + }), h; + function verb(e) { + return function(r) { + return step([ e, r ]); + }; + } + function step(a) { + if (i) throw new TypeError("Generator is already executing."); + while (h && (h = 0, a[0] && (t = 0)), t) try { + if (i = 1, n && (s = a[0] & 2 ? n["return"] : a[0] ? n["throw"] || ((s = n["return"]) && s.call(n), + 0) : n.next) && !(s = s.call(n, a[1])).done) return s; + if (n = 0, s) a = [ a[0] & 2, s.value ]; + switch (a[0]) { + case 0: + case 1: + s = a; + break; + + case 4: + t.label++; + return { + value: a[1], + done: false + }; + + case 5: + t.label++; + n = a[1]; + a = [ 0 ]; + continue; + + case 7: + a = t.ops.pop(); + t.trys.pop(); + continue; + + default: + if (!(s = t.trys, s = s.length > 0 && s[s.length - 1]) && (a[0] === 6 || a[0] === 2)) { + t = 0; + continue; + } + if (a[0] === 3 && (!s || a[1] > s[0] && a[1] < s[3])) { + t.label = a[1]; + break; + } + if (a[0] === 6 && t.label < s[1]) { + t.label = s[1]; + s = a; + break; + } + if (s && t.label < s[2]) { + t.label = s[2]; + t.ops.push(a); + break; + } + if (s[2]) t.ops.pop(); + t.trys.pop(); + continue; + } + a = r.call(e, t); + } catch (e) { + a = [ 6, e ]; + n = 0; + } finally { + i = s = 0; + } + if (a[0] & 5) throw a[1]; + return { + value: a[0] ? a[1] : void 0, + done: true + }; + } +} + +typeof SuppressedError === "function" ? SuppressedError : function(e, r, t) { + var i = new Error(t); + return i.name = "SuppressedError", i.error = e, i.suppressed = r, i; +}; + +var TreeNode = function() { + function TreeNode(e, r, t) { + if (t === void 0) { + t = 1; + } + this.t = undefined; + this.i = undefined; + this.h = undefined; + this.u = e; + this.o = r; + this.l = t; + } + TreeNode.prototype.v = function() { + var e = this; + var r = e.h.h === e; + if (r && e.l === 1) { + e = e.i; + } else if (e.t) { + e = e.t; + while (e.i) { + e = e.i; + } + } else { + if (r) { + return e.h; + } + var t = e.h; + while (t.t === e) { + e = t; + t = e.h; + } + e = t; + } + return e; + }; + TreeNode.prototype.p = function() { + var e = this; + if (e.i) { + e = e.i; + while (e.t) { + e = e.t; + } + return e; + } else { + var r = e.h; + while (r.i === e) { + e = r; + r = e.h; + } + if (e.i !== r) { + return r; + } else return e; + } + }; + TreeNode.prototype.T = function() { + var e = this.h; + var r = this.i; + var t = r.t; + if (e.h === this) e.h = r; else if (e.t === this) e.t = r; else e.i = r; + r.h = e; + r.t = this; + this.h = r; + this.i = t; + if (t) t.h = this; + return r; + }; + TreeNode.prototype.I = function() { + var e = this.h; + var r = this.t; + var t = r.i; + if (e.h === this) e.h = r; else if (e.t === this) e.t = r; else e.i = r; + r.h = e; + r.i = this; + this.h = r; + this.t = t; + if (t) t.h = this; + return r; + }; + return TreeNode; +}(); + +var TreeNodeEnableIndex = function(e) { + __extends(TreeNodeEnableIndex, e); + function TreeNodeEnableIndex() { + var r = e !== null && e.apply(this, arguments) || this; + r.O = 1; + return r; + } + TreeNodeEnableIndex.prototype.T = function() { + var r = e.prototype.T.call(this); + this.M(); + r.M(); + return r; + }; + TreeNodeEnableIndex.prototype.I = function() { + var r = e.prototype.I.call(this); + this.M(); + r.M(); + return r; + }; + TreeNodeEnableIndex.prototype.M = function() { + this.O = 1; + if (this.t) { + this.O += this.t.O; + } + if (this.i) { + this.O += this.i.O; + } + }; + return TreeNodeEnableIndex; +}(TreeNode); + +var ContainerIterator = function() { + function ContainerIterator(e) { + if (e === void 0) { + e = 0; + } + this.iteratorType = e; + } + ContainerIterator.prototype.equals = function(e) { + return this.C === e.C; + }; + return ContainerIterator; +}(); + +var Base = function() { + function Base() { + this._ = 0; + } + Object.defineProperty(Base.prototype, "length", { + get: function() { + return this._; + }, + enumerable: false, + configurable: true + }); + Base.prototype.size = function() { + return this._; + }; + Base.prototype.empty = function() { + return this._ === 0; + }; + return Base; +}(); + +var Container = function(e) { + __extends(Container, e); + function Container() { + return e !== null && e.apply(this, arguments) || this; + } + return Container; +}(Base); + +function throwIteratorAccessError() { + throw new RangeError("Iterator access denied!"); +} + +var TreeContainer = function(e) { + __extends(TreeContainer, e); + function TreeContainer(r, t) { + if (r === void 0) { + r = function(e, r) { + if (e < r) return -1; + if (e > r) return 1; + return 0; + }; + } + if (t === void 0) { + t = false; + } + var i = e.call(this) || this; + i.N = undefined; + i.g = r; + i.enableIndex = t; + i.S = t ? TreeNodeEnableIndex : TreeNode; + i.A = new i.S; + return i; + } + TreeContainer.prototype.m = function(e, r) { + var t = this.A; + while (e) { + var i = this.g(e.u, r); + if (i < 0) { + e = e.i; + } else if (i > 0) { + t = e; + e = e.t; + } else return e; + } + return t; + }; + TreeContainer.prototype.B = function(e, r) { + var t = this.A; + while (e) { + var i = this.g(e.u, r); + if (i <= 0) { + e = e.i; + } else { + t = e; + e = e.t; + } + } + return t; + }; + TreeContainer.prototype.j = function(e, r) { + var t = this.A; + while (e) { + var i = this.g(e.u, r); + if (i < 0) { + t = e; + e = e.i; + } else if (i > 0) { + e = e.t; + } else return e; + } + return t; + }; + TreeContainer.prototype.k = function(e, r) { + var t = this.A; + while (e) { + var i = this.g(e.u, r); + if (i < 0) { + t = e; + e = e.i; + } else { + e = e.t; + } + } + return t; + }; + TreeContainer.prototype.R = function(e) { + while (true) { + var r = e.h; + if (r === this.A) return; + if (e.l === 1) { + e.l = 0; + return; + } + if (e === r.t) { + var t = r.i; + if (t.l === 1) { + t.l = 0; + r.l = 1; + if (r === this.N) { + this.N = r.T(); + } else r.T(); + } else { + if (t.i && t.i.l === 1) { + t.l = r.l; + r.l = 0; + t.i.l = 0; + if (r === this.N) { + this.N = r.T(); + } else r.T(); + return; + } else if (t.t && t.t.l === 1) { + t.l = 1; + t.t.l = 0; + t.I(); + } else { + t.l = 1; + e = r; + } + } + } else { + var t = r.t; + if (t.l === 1) { + t.l = 0; + r.l = 1; + if (r === this.N) { + this.N = r.I(); + } else r.I(); + } else { + if (t.t && t.t.l === 1) { + t.l = r.l; + r.l = 0; + t.t.l = 0; + if (r === this.N) { + this.N = r.I(); + } else r.I(); + return; + } else if (t.i && t.i.l === 1) { + t.l = 1; + t.i.l = 0; + t.T(); + } else { + t.l = 1; + e = r; + } + } + } + } + }; + TreeContainer.prototype.G = function(e) { + if (this._ === 1) { + this.clear(); + return; + } + var r = e; + while (r.t || r.i) { + if (r.i) { + r = r.i; + while (r.t) r = r.t; + } else { + r = r.t; + } + var t = e.u; + e.u = r.u; + r.u = t; + var i = e.o; + e.o = r.o; + r.o = i; + e = r; + } + if (this.A.t === r) { + this.A.t = r.h; + } else if (this.A.i === r) { + this.A.i = r.h; + } + this.R(r); + var n = r.h; + if (r === n.t) { + n.t = undefined; + } else n.i = undefined; + this._ -= 1; + this.N.l = 0; + if (this.enableIndex) { + while (n !== this.A) { + n.O -= 1; + n = n.h; + } + } + }; + TreeContainer.prototype.P = function(e) { + var r = typeof e === "number" ? e : undefined; + var t = typeof e === "function" ? e : undefined; + var i = typeof e === "undefined" ? [] : undefined; + var n = 0; + var s = this.N; + var h = []; + while (h.length || s) { + if (s) { + h.push(s); + s = s.t; + } else { + s = h.pop(); + if (n === r) return s; + i && i.push(s); + t && t(s, n, this); + n += 1; + s = s.i; + } + } + return i; + }; + TreeContainer.prototype.q = function(e) { + while (true) { + var r = e.h; + if (r.l === 0) return; + var t = r.h; + if (r === t.t) { + var i = t.i; + if (i && i.l === 1) { + i.l = r.l = 0; + if (t === this.N) return; + t.l = 1; + e = t; + continue; + } else if (e === r.i) { + e.l = 0; + if (e.t) { + e.t.h = r; + } + if (e.i) { + e.i.h = t; + } + r.i = e.t; + t.t = e.i; + e.t = r; + e.i = t; + if (t === this.N) { + this.N = e; + this.A.h = e; + } else { + var n = t.h; + if (n.t === t) { + n.t = e; + } else n.i = e; + } + e.h = t.h; + r.h = e; + t.h = e; + t.l = 1; + } else { + r.l = 0; + if (t === this.N) { + this.N = t.I(); + } else t.I(); + t.l = 1; + return; + } + } else { + var i = t.t; + if (i && i.l === 1) { + i.l = r.l = 0; + if (t === this.N) return; + t.l = 1; + e = t; + continue; + } else if (e === r.t) { + e.l = 0; + if (e.t) { + e.t.h = t; + } + if (e.i) { + e.i.h = r; + } + t.i = e.t; + r.t = e.i; + e.t = t; + e.i = r; + if (t === this.N) { + this.N = e; + this.A.h = e; + } else { + var n = t.h; + if (n.t === t) { + n.t = e; + } else n.i = e; + } + e.h = t.h; + r.h = e; + t.h = e; + t.l = 1; + } else { + r.l = 0; + if (t === this.N) { + this.N = t.T(); + } else t.T(); + t.l = 1; + return; + } + } + if (this.enableIndex) { + r.M(); + t.M(); + e.M(); + } + return; + } + }; + TreeContainer.prototype.D = function(e, r, t) { + if (this.N === undefined) { + this._ += 1; + this.N = new this.S(e, r, 0); + this.N.h = this.A; + this.A.h = this.A.t = this.A.i = this.N; + return this._; + } + var i; + var n = this.A.t; + var s = this.g(n.u, e); + if (s === 0) { + n.o = r; + return this._; + } else if (s > 0) { + n.t = new this.S(e, r); + n.t.h = n; + i = n.t; + this.A.t = i; + } else { + var h = this.A.i; + var a = this.g(h.u, e); + if (a === 0) { + h.o = r; + return this._; + } else if (a < 0) { + h.i = new this.S(e, r); + h.i.h = h; + i = h.i; + this.A.i = i; + } else { + if (t !== undefined) { + var u = t.C; + if (u !== this.A) { + var f = this.g(u.u, e); + if (f === 0) { + u.o = r; + return this._; + } else if (f > 0) { + var o = u.v(); + var d = this.g(o.u, e); + if (d === 0) { + o.o = r; + return this._; + } else if (d < 0) { + i = new this.S(e, r); + if (o.i === undefined) { + o.i = i; + i.h = o; + } else { + u.t = i; + i.h = u; + } + } + } + } + } + if (i === undefined) { + i = this.N; + while (true) { + var c = this.g(i.u, e); + if (c > 0) { + if (i.t === undefined) { + i.t = new this.S(e, r); + i.t.h = i; + i = i.t; + break; + } + i = i.t; + } else if (c < 0) { + if (i.i === undefined) { + i.i = new this.S(e, r); + i.i.h = i; + i = i.i; + break; + } + i = i.i; + } else { + i.o = r; + return this._; + } + } + } + } + } + if (this.enableIndex) { + var l = i.h; + while (l !== this.A) { + l.O += 1; + l = l.h; + } + } + this.q(i); + this._ += 1; + return this._; + }; + TreeContainer.prototype.F = function(e, r) { + while (e) { + var t = this.g(e.u, r); + if (t < 0) { + e = e.i; + } else if (t > 0) { + e = e.t; + } else return e; + } + return e || this.A; + }; + TreeContainer.prototype.clear = function() { + this._ = 0; + this.N = undefined; + this.A.h = undefined; + this.A.t = this.A.i = undefined; + }; + TreeContainer.prototype.updateKeyByIterator = function(e, r) { + var t = e.C; + if (t === this.A) { + throwIteratorAccessError(); + } + if (this._ === 1) { + t.u = r; + return true; + } + var i = t.p().u; + if (t === this.A.t) { + if (this.g(i, r) > 0) { + t.u = r; + return true; + } + return false; + } + var n = t.v().u; + if (t === this.A.i) { + if (this.g(n, r) < 0) { + t.u = r; + return true; + } + return false; + } + if (this.g(n, r) >= 0 || this.g(i, r) <= 0) return false; + t.u = r; + return true; + }; + TreeContainer.prototype.eraseElementByPos = function(e) { + if (e < 0 || e > this._ - 1) { + throw new RangeError; + } + var r = this.P(e); + this.G(r); + return this._; + }; + TreeContainer.prototype.eraseElementByKey = function(e) { + if (this._ === 0) return false; + var r = this.F(this.N, e); + if (r === this.A) return false; + this.G(r); + return true; + }; + TreeContainer.prototype.eraseElementByIterator = function(e) { + var r = e.C; + if (r === this.A) { + throwIteratorAccessError(); + } + var t = r.i === undefined; + var i = e.iteratorType === 0; + if (i) { + if (t) e.next(); + } else { + if (!t || r.t === undefined) e.next(); + } + this.G(r); + return e; + }; + TreeContainer.prototype.getHeight = function() { + if (this._ === 0) return 0; + function traversal(e) { + if (!e) return 0; + return Math.max(traversal(e.t), traversal(e.i)) + 1; + } + return traversal(this.N); + }; + return TreeContainer; +}(Container); + +var TreeIterator = function(e) { + __extends(TreeIterator, e); + function TreeIterator(r, t, i) { + var n = e.call(this, i) || this; + n.C = r; + n.A = t; + if (n.iteratorType === 0) { + n.pre = function() { + if (this.C === this.A.t) { + throwIteratorAccessError(); + } + this.C = this.C.v(); + return this; + }; + n.next = function() { + if (this.C === this.A) { + throwIteratorAccessError(); + } + this.C = this.C.p(); + return this; + }; + } else { + n.pre = function() { + if (this.C === this.A.i) { + throwIteratorAccessError(); + } + this.C = this.C.p(); + return this; + }; + n.next = function() { + if (this.C === this.A) { + throwIteratorAccessError(); + } + this.C = this.C.v(); + return this; + }; + } + return n; + } + Object.defineProperty(TreeIterator.prototype, "index", { + get: function() { + var e = this.C; + var r = this.A.h; + if (e === this.A) { + if (r) { + return r.O - 1; + } + return 0; + } + var t = 0; + if (e.t) { + t += e.t.O; + } + while (e !== r) { + var i = e.h; + if (e === i.i) { + t += 1; + if (i.t) { + t += i.t.O; + } + } + e = i; + } + return t; + }, + enumerable: false, + configurable: true + }); + TreeIterator.prototype.isAccessible = function() { + return this.C !== this.A; + }; + return TreeIterator; +}(ContainerIterator); + +var OrderedMapIterator = function(e) { + __extends(OrderedMapIterator, e); + function OrderedMapIterator(r, t, i, n) { + var s = e.call(this, r, t, n) || this; + s.container = i; + return s; + } + Object.defineProperty(OrderedMapIterator.prototype, "pointer", { + get: function() { + if (this.C === this.A) { + throwIteratorAccessError(); + } + var e = this; + return new Proxy([], { + get: function(r, t) { + if (t === "0") return e.C.u; else if (t === "1") return e.C.o; + r[0] = e.C.u; + r[1] = e.C.o; + return r[t]; + }, + set: function(r, t, i) { + if (t !== "1") { + throw new TypeError("prop must be 1"); + } + e.C.o = i; + return true; + } + }); + }, + enumerable: false, + configurable: true + }); + OrderedMapIterator.prototype.copy = function() { + return new OrderedMapIterator(this.C, this.A, this.container, this.iteratorType); + }; + return OrderedMapIterator; +}(TreeIterator); + +var OrderedMap = function(e) { + __extends(OrderedMap, e); + function OrderedMap(r, t, i) { + if (r === void 0) { + r = []; + } + var n = e.call(this, t, i) || this; + var s = n; + r.forEach((function(e) { + s.setElement(e[0], e[1]); + })); + return n; + } + OrderedMap.prototype.begin = function() { + return new OrderedMapIterator(this.A.t || this.A, this.A, this); + }; + OrderedMap.prototype.end = function() { + return new OrderedMapIterator(this.A, this.A, this); + }; + OrderedMap.prototype.rBegin = function() { + return new OrderedMapIterator(this.A.i || this.A, this.A, this, 1); + }; + OrderedMap.prototype.rEnd = function() { + return new OrderedMapIterator(this.A, this.A, this, 1); + }; + OrderedMap.prototype.front = function() { + if (this._ === 0) return; + var e = this.A.t; + return [ e.u, e.o ]; + }; + OrderedMap.prototype.back = function() { + if (this._ === 0) return; + var e = this.A.i; + return [ e.u, e.o ]; + }; + OrderedMap.prototype.lowerBound = function(e) { + var r = this.m(this.N, e); + return new OrderedMapIterator(r, this.A, this); + }; + OrderedMap.prototype.upperBound = function(e) { + var r = this.B(this.N, e); + return new OrderedMapIterator(r, this.A, this); + }; + OrderedMap.prototype.reverseLowerBound = function(e) { + var r = this.j(this.N, e); + return new OrderedMapIterator(r, this.A, this); + }; + OrderedMap.prototype.reverseUpperBound = function(e) { + var r = this.k(this.N, e); + return new OrderedMapIterator(r, this.A, this); + }; + OrderedMap.prototype.forEach = function(e) { + this.P((function(r, t, i) { + e([ r.u, r.o ], t, i); + })); + }; + OrderedMap.prototype.setElement = function(e, r, t) { + return this.D(e, r, t); + }; + OrderedMap.prototype.getElementByPos = function(e) { + if (e < 0 || e > this._ - 1) { + throw new RangeError; + } + var r = this.P(e); + return [ r.u, r.o ]; + }; + OrderedMap.prototype.find = function(e) { + var r = this.F(this.N, e); + return new OrderedMapIterator(r, this.A, this); + }; + OrderedMap.prototype.getElementByKey = function(e) { + var r = this.F(this.N, e); + return r.o; + }; + OrderedMap.prototype.union = function(e) { + var r = this; + e.forEach((function(e) { + r.setElement(e[0], e[1]); + })); + return this._; + }; + OrderedMap.prototype[Symbol.iterator] = function() { + var e, r, t, i; + return __generator(this, (function(n) { + switch (n.label) { + case 0: + e = this._; + r = this.P(); + t = 0; + n.label = 1; + + case 1: + if (!(t < e)) return [ 3, 4 ]; + i = r[t]; + return [ 4, [ i.u, i.o ] ]; + + case 2: + n.sent(); + n.label = 3; + + case 3: + ++t; + return [ 3, 1 ]; + + case 4: + return [ 2 ]; + } + })); + }; + return OrderedMap; +}(TreeContainer); + +export { OrderedMap }; +//# sourceMappingURL=index.js.map diff --git a/node_modules/@js-sdsl/ordered-map/dist/esm/index.js.map b/node_modules/@js-sdsl/ordered-map/dist/esm/index.js.map new file mode 100644 index 0000000..3b8a588 --- /dev/null +++ b/node_modules/@js-sdsl/ordered-map/dist/esm/index.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["../../../../../node_modules/tslib/tslib.es6.js","index.js","../../../.build-data/copied-source/src/container/TreeContainer/Base/TreeNode.ts","../../../.build-data/copied-source/src/container/ContainerBase/index.ts","../../../.build-data/copied-source/src/utils/throwError.ts","../../../.build-data/copied-source/src/container/TreeContainer/Base/index.ts","../../../.build-data/copied-source/src/container/TreeContainer/Base/TreeIterator.ts","../../../.build-data/copied-source/src/container/TreeContainer/OrderedMap.ts"],"names":["extendStatics","d","b","Object","setPrototypeOf","__proto__","Array","p","prototype","hasOwnProperty","call","__extends","TypeError","String","__","this","constructor","create","__generator","thisArg","body","_","label","sent","t","trys","ops","f","y","g","next","verb","throw","return","Symbol","iterator","n","v","step","op","done","value","pop","length","push","e","SuppressedError","error","suppressed","message","Error","name","TreeNode","key","color","_left","undefined","_right","_parent","_key","_value","_color","_pre","preNode","isRootOrHeader","pre","_next","nextNode","_rotateLeft","PP","V","R","_rotateRight","F","K","TreeNodeEnableIndex","_super","_this","apply","arguments","_subTreeSize","parent","_recount","ContainerIterator","iteratorType","equals","iter","_node","Base","_length","defineProperty","get","enumerable","configurable","size","empty","Container","throwIteratorAccessError","RangeError","TreeContainer","cmp","enableIndex","x","_root","_cmp","_TreeNodeClass","_header","_lowerBound","curNode","resNode","cmpResult","_upperBound","_reverseLowerBound","_reverseUpperBound","_eraseNodeSelfBalance","parentNode","brother","_eraseNode","clear","swapNode","_inOrderTraversal","param","pos","callback","nodeList","index","stack","_insertNodeSelfBalance","grandParent","uncle","GP","_set","hint","minNode","compareToMin","maxNode","compareToMax","iterNode","iterCmpRes","preCmpRes","parent_1","_getTreeNodeByKey","updateKeyByIterator","node","nextKey","preKey","eraseElementByPos","eraseElementByKey","eraseElementByIterator","hasNoRight","isNormal","getHeight","traversal","Math","max","TreeIterator","header","root","isAccessible","OrderedMapIterator","container","self","Proxy","target","prop","set","newValue","copy","OrderedMap","forEach","el","setElement","begin","end","rBegin","rEnd","front","back","lowerBound","upperBound","reverseLowerBound","reverseUpperBound","map","getElementByPos","find","getElementByKey","union","other","i","_a"],"mappings":"AAgBA,IAAIA,gBAAgB,SAASC,GAAGC;IAC5BF,gBAAgBG,OAAOC,kBAClB;QAAEC,WAAW;iBAAgBC,SAAS,SAAUL,GAAGC;QAAKD,EAAEI,YAAYH;AAAG,SAC1E,SAAUD,GAAGC;QAAK,KAAK,IAAIK,KAAKL,GAAG,IAAIC,OAAOK,UAAUC,eAAeC,KAAKR,GAAGK,IAAIN,EAAEM,KAAKL,EAAEK;ACIlG;IDHE,OAAOP,cAAcC,GAAGC;AAC5B;;AAEO,SAASS,UAAUV,GAAGC;IACzB,WAAWA,MAAM,cAAcA,MAAM,MACjC,MAAM,IAAIU,UAAU,yBAAyBC,OAAOX,KAAK;IAC7DF,cAAcC,GAAGC;IACjB,SAASY;QAAOC,KAAKC,cAAcf;AAAG;IACtCA,EAAEO,YAAYN,MAAM,OAAOC,OAAOc,OAAOf,MAAMY,GAAGN,YAAYN,EAAEM,WAAW,IAAIM;AACnF;;AA+FO,SAASI,YAAYC,GAASC;IACjC,IAAIC,IAAI;QAAEC,OAAO;QAAGC,MAAM;YAAa,IAAIC,EAAE,KAAK,GAAG,MAAMA,EAAE;YAAI,OAAOA,EAAE;ACrFxE;QDqF+EC,MAAM;QAAIC,KAAK;OAAMC,GAAGC,GAAGJ,GAAGK;IAC/G,OAAOA,IAAI;QAAEC,MAAMC,KAAK;QAAIC,OAASD,KAAK;QAAIE,QAAUF,KAAK;cAAaG,WAAW,eAAeL,EAAEK,OAAOC,YAAY;QAAa,OAAOpB;ACxE/I,QDwEyJc;IACvJ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AKnF;;cN07B7B,KAAK;gBM17BPiI,EAAAtK;gBN47BIsK,EAAGvK,QAAQ;;cACb,KAAK;kBM/7BqBsK;gBNi8BxB,OAAO,EAAC,GAAa;;cACvB,KAAK;gBACH,OAAO,EAAC;;AAEd;AACF;IM/7BF,OAACpB;AAAD,CAzHA,CAA+BrE;;SN6jCtBqE","file":"index.js","sourcesContent":["/******************************************************************************\r\nCopyright (c) Microsoft Corporation.\r\n\r\nPermission to use, copy, modify, and/or distribute this software for any\r\npurpose with or without fee is hereby granted.\r\n\r\nTHE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH\r\nREGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY\r\nAND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,\r\nINDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM\r\nLOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR\r\nOTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR\r\nPERFORMANCE OF THIS SOFTWARE.\r\n***************************************************************************** */\r\n/* global Reflect, Promise, SuppressedError, Symbol */\r\n\r\nvar extendStatics = function(d, b) {\r\n extendStatics = Object.setPrototypeOf ||\r\n ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||\r\n function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };\r\n return extendStatics(d, b);\r\n};\r\n\r\nexport function __extends(d, b) {\r\n if (typeof b !== \"function\" && b !== null)\r\n throw new TypeError(\"Class extends value \" + String(b) + \" is not a constructor or null\");\r\n extendStatics(d, b);\r\n function __() { this.constructor = d; }\r\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\r\n}\r\n\r\nexport var __assign = function() {\r\n __assign = Object.assign || function __assign(t) {\r\n for (var s, i = 1, n = arguments.length; i < n; i++) {\r\n s = arguments[i];\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p];\r\n }\r\n return t;\r\n }\r\n return __assign.apply(this, arguments);\r\n}\r\n\r\nexport function __rest(s, e) {\r\n var t = {};\r\n for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)\r\n t[p] = s[p];\r\n if (s != null && typeof Object.getOwnPropertySymbols === \"function\")\r\n for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {\r\n if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))\r\n t[p[i]] = s[p[i]];\r\n }\r\n return t;\r\n}\r\n\r\nexport function __decorate(decorators, target, key, desc) {\r\n var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;\r\n if (typeof Reflect === \"object\" && typeof Reflect.decorate === \"function\") r = Reflect.decorate(decorators, target, key, desc);\r\n else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;\r\n return c > 3 && r && Object.defineProperty(target, key, r), r;\r\n}\r\n\r\nexport function __param(paramIndex, decorator) {\r\n return function (target, key) { decorator(target, key, paramIndex); }\r\n}\r\n\r\nexport function __esDecorate(ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) {\r\n function accept(f) { if (f !== void 0 && typeof f !== \"function\") throw new TypeError(\"Function expected\"); return f; }\r\n var kind = contextIn.kind, key = kind === \"getter\" ? \"get\" : kind === \"setter\" ? \"set\" : \"value\";\r\n var target = !descriptorIn && ctor ? contextIn[\"static\"] ? ctor : ctor.prototype : null;\r\n var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {});\r\n var _, done = false;\r\n for (var i = decorators.length - 1; i >= 0; i--) {\r\n var context = {};\r\n for (var p in contextIn) context[p] = p === \"access\" ? {} : contextIn[p];\r\n for (var p in contextIn.access) context.access[p] = contextIn.access[p];\r\n context.addInitializer = function (f) { if (done) throw new TypeError(\"Cannot add initializers after decoration has completed\"); extraInitializers.push(accept(f || null)); };\r\n var result = (0, decorators[i])(kind === \"accessor\" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context);\r\n if (kind === \"accessor\") {\r\n if (result === void 0) continue;\r\n if (result === null || typeof result !== \"object\") throw new TypeError(\"Object expected\");\r\n if (_ = accept(result.get)) descriptor.get = _;\r\n if (_ = accept(result.set)) descriptor.set = _;\r\n if (_ = accept(result.init)) initializers.unshift(_);\r\n }\r\n else if (_ = accept(result)) {\r\n if (kind === \"field\") initializers.unshift(_);\r\n else descriptor[key] = _;\r\n }\r\n }\r\n if (target) Object.defineProperty(target, contextIn.name, descriptor);\r\n done = true;\r\n};\r\n\r\nexport function __runInitializers(thisArg, initializers, value) {\r\n var useValue = arguments.length > 2;\r\n for (var i = 0; i < initializers.length; i++) {\r\n value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg);\r\n }\r\n return useValue ? value : void 0;\r\n};\r\n\r\nexport function __propKey(x) {\r\n return typeof x === \"symbol\" ? x : \"\".concat(x);\r\n};\r\n\r\nexport function __setFunctionName(f, name, prefix) {\r\n if (typeof name === \"symbol\") name = name.description ? \"[\".concat(name.description, \"]\") : \"\";\r\n return Object.defineProperty(f, \"name\", { configurable: true, value: prefix ? \"\".concat(prefix, \" \", name) : name });\r\n};\r\n\r\nexport function __metadata(metadataKey, metadataValue) {\r\n if (typeof Reflect === \"object\" && typeof Reflect.metadata === \"function\") return Reflect.metadata(metadataKey, metadataValue);\r\n}\r\n\r\nexport function __awaiter(thisArg, _arguments, P, generator) {\r\n function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }\r\n return new (P || (P = Promise))(function (resolve, reject) {\r\n function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }\r\n function rejected(value) { try { step(generator[\"throw\"](value)); } catch (e) { reject(e); } }\r\n function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }\r\n step((generator = generator.apply(thisArg, _arguments || [])).next());\r\n });\r\n}\r\n\r\nexport function __generator(thisArg, body) {\r\n var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;\r\n return g = { next: verb(0), \"throw\": verb(1), \"return\": verb(2) }, typeof Symbol === \"function\" && (g[Symbol.iterator] = function() { return this; }), g;\r\n function verb(n) { return function (v) { return step([n, v]); }; }\r\n function step(op) {\r\n if (f) throw new TypeError(\"Generator is already executing.\");\r\n while (g && (g = 0, op[0] && (_ = 0)), _) try {\r\n if (f = 1, y && (t = op[0] & 2 ? y[\"return\"] : op[0] ? y[\"throw\"] || ((t = y[\"return\"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;\r\n if (y = 0, t) op = [op[0] & 2, t.value];\r\n switch (op[0]) {\r\n case 0: case 1: t = op; break;\r\n case 4: _.label++; return { value: op[1], done: false };\r\n case 5: _.label++; y = op[1]; op = [0]; continue;\r\n case 7: op = _.ops.pop(); _.trys.pop(); continue;\r\n default:\r\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }\r\n if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }\r\n if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }\r\n if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }\r\n if (t[2]) _.ops.pop();\r\n _.trys.pop(); continue;\r\n }\r\n op = body.call(thisArg, _);\r\n } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }\r\n if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };\r\n }\r\n}\r\n\r\nexport var __createBinding = Object.create ? (function(o, m, k, k2) {\r\n if (k2 === undefined) k2 = k;\r\n var desc = Object.getOwnPropertyDescriptor(m, k);\r\n if (!desc || (\"get\" in desc ? !m.__esModule : desc.writable || desc.configurable)) {\r\n desc = { enumerable: true, get: function() { return m[k]; } };\r\n }\r\n Object.defineProperty(o, k2, desc);\r\n}) : (function(o, m, k, k2) {\r\n if (k2 === undefined) k2 = k;\r\n o[k2] = m[k];\r\n});\r\n\r\nexport function __exportStar(m, o) {\r\n for (var p in m) if (p !== \"default\" && !Object.prototype.hasOwnProperty.call(o, p)) __createBinding(o, m, p);\r\n}\r\n\r\nexport function __values(o) {\r\n var s = typeof Symbol === \"function\" && Symbol.iterator, m = s && o[s], i = 0;\r\n if (m) return m.call(o);\r\n if (o && typeof o.length === \"number\") return {\r\n next: function () {\r\n if (o && i >= o.length) o = void 0;\r\n return { value: o && o[i++], done: !o };\r\n }\r\n };\r\n throw new TypeError(s ? \"Object is not iterable.\" : \"Symbol.iterator is not defined.\");\r\n}\r\n\r\nexport function __read(o, n) {\r\n var m = typeof Symbol === \"function\" && o[Symbol.iterator];\r\n if (!m) return o;\r\n var i = m.call(o), r, ar = [], e;\r\n try {\r\n while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);\r\n }\r\n catch (error) { e = { error: error }; }\r\n finally {\r\n try {\r\n if (r && !r.done && (m = i[\"return\"])) m.call(i);\r\n }\r\n finally { if (e) throw e.error; }\r\n }\r\n return ar;\r\n}\r\n\r\n/** @deprecated */\r\nexport function __spread() {\r\n for (var ar = [], i = 0; i < arguments.length; i++)\r\n ar = ar.concat(__read(arguments[i]));\r\n return ar;\r\n}\r\n\r\n/** @deprecated */\r\nexport function __spreadArrays() {\r\n for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;\r\n for (var r = Array(s), k = 0, i = 0; i < il; i++)\r\n for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)\r\n r[k] = a[j];\r\n return r;\r\n}\r\n\r\nexport function __spreadArray(to, from, pack) {\r\n if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {\r\n if (ar || !(i in from)) {\r\n if (!ar) ar = Array.prototype.slice.call(from, 0, i);\r\n ar[i] = from[i];\r\n }\r\n }\r\n return to.concat(ar || Array.prototype.slice.call(from));\r\n}\r\n\r\nexport function __await(v) {\r\n return this instanceof __await ? (this.v = v, this) : new __await(v);\r\n}\r\n\r\nexport function __asyncGenerator(thisArg, _arguments, generator) {\r\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n var g = generator.apply(thisArg, _arguments || []), i, q = [];\r\n return i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i;\r\n function verb(n) { if (g[n]) i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; }\r\n function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } }\r\n function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); }\r\n function fulfill(value) { resume(\"next\", value); }\r\n function reject(value) { resume(\"throw\", value); }\r\n function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); }\r\n}\r\n\r\nexport function __asyncDelegator(o) {\r\n var i, p;\r\n return i = {}, verb(\"next\"), verb(\"throw\", function (e) { throw e; }), verb(\"return\"), i[Symbol.iterator] = function () { return this; }, i;\r\n function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: false } : f ? f(v) : v; } : f; }\r\n}\r\n\r\nexport function __asyncValues(o) {\r\n if (!Symbol.asyncIterator) throw new TypeError(\"Symbol.asyncIterator is not defined.\");\r\n var m = o[Symbol.asyncIterator], i;\r\n return m ? m.call(o) : (o = typeof __values === \"function\" ? __values(o) : o[Symbol.iterator](), i = {}, verb(\"next\"), verb(\"throw\"), verb(\"return\"), i[Symbol.asyncIterator] = function () { return this; }, i);\r\n function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; }\r\n function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); }\r\n}\r\n\r\nexport function __makeTemplateObject(cooked, raw) {\r\n if (Object.defineProperty) { Object.defineProperty(cooked, \"raw\", { value: raw }); } else { cooked.raw = raw; }\r\n return cooked;\r\n};\r\n\r\nvar __setModuleDefault = Object.create ? (function(o, v) {\r\n Object.defineProperty(o, \"default\", { enumerable: true, value: v });\r\n}) : function(o, v) {\r\n o[\"default\"] = v;\r\n};\r\n\r\nexport function __importStar(mod) {\r\n if (mod && mod.__esModule) return mod;\r\n var result = {};\r\n if (mod != null) for (var k in mod) if (k !== \"default\" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);\r\n __setModuleDefault(result, mod);\r\n return result;\r\n}\r\n\r\nexport function __importDefault(mod) {\r\n return (mod && mod.__esModule) ? mod : { default: mod };\r\n}\r\n\r\nexport function __classPrivateFieldGet(receiver, state, kind, f) {\r\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a getter\");\r\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot read private member from an object whose class did not declare it\");\r\n return kind === \"m\" ? f : kind === \"a\" ? f.call(receiver) : f ? f.value : state.get(receiver);\r\n}\r\n\r\nexport function __classPrivateFieldSet(receiver, state, value, kind, f) {\r\n if (kind === \"m\") throw new TypeError(\"Private method is not writable\");\r\n if (kind === \"a\" && !f) throw new TypeError(\"Private accessor was defined without a setter\");\r\n if (typeof state === \"function\" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError(\"Cannot write private member to an object whose class did not declare it\");\r\n return (kind === \"a\" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value;\r\n}\r\n\r\nexport function __classPrivateFieldIn(state, receiver) {\r\n if (receiver === null || (typeof receiver !== \"object\" && typeof receiver !== \"function\")) throw new TypeError(\"Cannot use 'in' operator on non-object\");\r\n return typeof state === \"function\" ? receiver === state : state.has(receiver);\r\n}\r\n\r\nexport function __addDisposableResource(env, value, async) {\r\n if (value !== null && value !== void 0) {\r\n if (typeof value !== \"object\") throw new TypeError(\"Object expected.\");\r\n var dispose;\r\n if (async) {\r\n if (!Symbol.asyncDispose) throw new TypeError(\"Symbol.asyncDispose is not defined.\");\r\n dispose = value[Symbol.asyncDispose];\r\n }\r\n if (dispose === void 0) {\r\n if (!Symbol.dispose) throw new TypeError(\"Symbol.dispose is not defined.\");\r\n dispose = value[Symbol.dispose];\r\n }\r\n if (typeof dispose !== \"function\") throw new TypeError(\"Object not disposable.\");\r\n env.stack.push({ value: value, dispose: dispose, async: async });\r\n }\r\n else if (async) {\r\n env.stack.push({ async: true });\r\n }\r\n return value;\r\n}\r\n\r\nvar _SuppressedError = typeof SuppressedError === \"function\" ? SuppressedError : function (error, suppressed, message) {\r\n var e = new Error(message);\r\n return e.name = \"SuppressedError\", e.error = error, e.suppressed = suppressed, e;\r\n};\r\n\r\nexport function __disposeResources(env) {\r\n function fail(e) {\r\n env.error = env.hasError ? new _SuppressedError(e, env.error, \"An error was suppressed during disposal.\") : e;\r\n env.hasError = true;\r\n }\r\n function next() {\r\n while (env.stack.length) {\r\n var rec = env.stack.pop();\r\n try {\r\n var result = rec.dispose && rec.dispose.call(rec.value);\r\n if (rec.async) return Promise.resolve(result).then(next, function(e) { fail(e); return next(); });\r\n }\r\n catch (e) {\r\n fail(e);\r\n }\r\n }\r\n if (env.hasError) throw env.error;\r\n }\r\n return next();\r\n}\r\n\r\nexport default {\r\n __extends,\r\n __assign,\r\n __rest,\r\n __decorate,\r\n __param,\r\n __metadata,\r\n __awaiter,\r\n __generator,\r\n __createBinding,\r\n __exportStar,\r\n __values,\r\n __read,\r\n __spread,\r\n __spreadArrays,\r\n __spreadArray,\r\n __await,\r\n __asyncGenerator,\r\n __asyncDelegator,\r\n __asyncValues,\r\n __makeTemplateObject,\r\n __importStar,\r\n __importDefault,\r\n __classPrivateFieldGet,\r\n __classPrivateFieldSet,\r\n __classPrivateFieldIn,\r\n __addDisposableResource,\r\n __disposeResources,\r\n};\r\n","/******************************************************************************\r\nCopyright (c) Microsoft Corporation.\r\n\r\nPermission to use, copy, modify, and/or distribute this software for any\r\npurpose with or without fee is hereby granted.\r\n\r\nTHE SOFTWARE IS PROVIDED \"AS IS\" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH\r\nREGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY\r\nAND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,\r\nINDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM\r\nLOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR\r\nOTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR\r\nPERFORMANCE OF THIS SOFTWARE.\r\n***************************************************************************** */\n/* global Reflect, Promise, SuppressedError, Symbol */\n\nvar extendStatics = function (d, b) {\n extendStatics = Object.setPrototypeOf || {\n __proto__: []\n } instanceof Array && function (d, b) {\n d.__proto__ = b;\n } || function (d, b) {\n for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p];\n };\n return extendStatics(d, b);\n};\nfunction __extends(d, b) {\n if (typeof b !== \"function\" && b !== null) throw new TypeError(\"Class extends value \" + String(b) + \" is not a constructor or null\");\n extendStatics(d, b);\n function __() {\n this.constructor = d;\n }\n d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());\n}\nfunction __generator(thisArg, body) {\n var _ = {\n label: 0,\n sent: function () {\n if (t[0] & 1) throw t[1];\n return t[1];\n },\n trys: [],\n ops: []\n },\n f,\n y,\n t,\n g;\n return g = {\n next: verb(0),\n \"throw\": verb(1),\n \"return\": verb(2)\n }, typeof Symbol === \"function\" && (g[Symbol.iterator] = function () {\n return this;\n }), g;\n function verb(n) {\n return function (v) {\n return step([n, v]);\n };\n }\n function step(op) {\n if (f) throw new TypeError(\"Generator is already executing.\");\n while (g && (g = 0, op[0] && (_ = 0)), _) try {\n if (f = 1, y && (t = op[0] & 2 ? y[\"return\"] : op[0] ? y[\"throw\"] || ((t = y[\"return\"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;\n if (y = 0, t) op = [op[0] & 2, t.value];\n switch (op[0]) {\n case 0:\n case 1:\n t = op;\n break;\n case 4:\n _.label++;\n return {\n value: op[1],\n done: false\n };\n case 5:\n _.label++;\n y = op[1];\n op = [0];\n continue;\n case 7:\n op = _.ops.pop();\n _.trys.pop();\n continue;\n default:\n if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) {\n _ = 0;\n continue;\n }\n if (op[0] === 3 && (!t || op[1] > t[0] && op[1] < t[3])) {\n _.label = op[1];\n break;\n }\n if (op[0] === 6 && _.label < t[1]) {\n _.label = t[1];\n t = op;\n break;\n }\n if (t && _.label < t[2]) {\n _.label = t[2];\n _.ops.push(op);\n break;\n }\n if (t[2]) _.ops.pop();\n _.trys.pop();\n continue;\n }\n op = body.call(thisArg, _);\n } catch (e) {\n op = [6, e];\n y = 0;\n } finally {\n f = t = 0;\n }\n if (op[0] & 5) throw op[1];\n return {\n value: op[0] ? op[1] : void 0,\n done: true\n };\n }\n}\ntypeof SuppressedError === \"function\" ? SuppressedError : function (error, suppressed, message) {\n var e = new Error(message);\n return e.name = \"SuppressedError\", e.error = error, e.suppressed = suppressed, e;\n};\n\nvar TreeNode = /** @class */function () {\n function TreeNode(key, value, color) {\n if (color === void 0) {\n color = 1 /* TreeNodeColor.RED */;\n }\n this._left = undefined;\n this._right = undefined;\n this._parent = undefined;\n this._key = key;\n this._value = value;\n this._color = color;\n }\n /**\n * @description Get the pre node.\n * @returns TreeNode about the pre node.\n */\n TreeNode.prototype._pre = function () {\n var preNode = this;\n var isRootOrHeader = preNode._parent._parent === preNode;\n if (isRootOrHeader && preNode._color === 1 /* TreeNodeColor.RED */) {\n preNode = preNode._right;\n } else if (preNode._left) {\n preNode = preNode._left;\n while (preNode._right) {\n preNode = preNode._right;\n }\n } else {\n // Must be root and left is null\n if (isRootOrHeader) {\n return preNode._parent;\n }\n var pre = preNode._parent;\n while (pre._left === preNode) {\n preNode = pre;\n pre = preNode._parent;\n }\n preNode = pre;\n }\n return preNode;\n };\n /**\n * @description Get the next node.\n * @returns TreeNode about the next node.\n */\n TreeNode.prototype._next = function () {\n var nextNode = this;\n if (nextNode._right) {\n nextNode = nextNode._right;\n while (nextNode._left) {\n nextNode = nextNode._left;\n }\n return nextNode;\n } else {\n var pre = nextNode._parent;\n while (pre._right === nextNode) {\n nextNode = pre;\n pre = nextNode._parent;\n }\n if (nextNode._right !== pre) {\n return pre;\n } else return nextNode;\n }\n };\n /**\n * @description Rotate left.\n * @returns TreeNode about moved to original position after rotation.\n */\n TreeNode.prototype._rotateLeft = function () {\n var PP = this._parent;\n var V = this._right;\n var R = V._left;\n if (PP._parent === this) PP._parent = V;else if (PP._left === this) PP._left = V;else PP._right = V;\n V._parent = PP;\n V._left = this;\n this._parent = V;\n this._right = R;\n if (R) R._parent = this;\n return V;\n };\n /**\n * @description Rotate right.\n * @returns TreeNode about moved to original position after rotation.\n */\n TreeNode.prototype._rotateRight = function () {\n var PP = this._parent;\n var F = this._left;\n var K = F._right;\n if (PP._parent === this) PP._parent = F;else if (PP._left === this) PP._left = F;else PP._right = F;\n F._parent = PP;\n F._right = this;\n this._parent = F;\n this._left = K;\n if (K) K._parent = this;\n return F;\n };\n return TreeNode;\n}();\nvar TreeNodeEnableIndex = /** @class */function (_super) {\n __extends(TreeNodeEnableIndex, _super);\n function TreeNodeEnableIndex() {\n var _this = _super !== null && _super.apply(this, arguments) || this;\n _this._subTreeSize = 1;\n return _this;\n }\n /**\n * @description Rotate left and do recount.\n * @returns TreeNode about moved to original position after rotation.\n */\n TreeNodeEnableIndex.prototype._rotateLeft = function () {\n var parent = _super.prototype._rotateLeft.call(this);\n this._recount();\n parent._recount();\n return parent;\n };\n /**\n * @description Rotate right and do recount.\n * @returns TreeNode about moved to original position after rotation.\n */\n TreeNodeEnableIndex.prototype._rotateRight = function () {\n var parent = _super.prototype._rotateRight.call(this);\n this._recount();\n parent._recount();\n return parent;\n };\n TreeNodeEnableIndex.prototype._recount = function () {\n this._subTreeSize = 1;\n if (this._left) {\n this._subTreeSize += this._left._subTreeSize;\n }\n if (this._right) {\n this._subTreeSize += this._right._subTreeSize;\n }\n };\n return TreeNodeEnableIndex;\n}(TreeNode);\n\nvar ContainerIterator = /** @class */function () {\n /**\n * @internal\n */\n function ContainerIterator(iteratorType) {\n if (iteratorType === void 0) {\n iteratorType = 0 /* IteratorType.NORMAL */;\n }\n this.iteratorType = iteratorType;\n }\n /**\n * @param iter - The other iterator you want to compare.\n * @returns Whether this equals to obj.\n * @example\n * container.find(1).equals(container.end());\n */\n ContainerIterator.prototype.equals = function (iter) {\n return this._node === iter._node;\n };\n return ContainerIterator;\n}();\nvar Base = /** @class */function () {\n function Base() {\n /**\n * @description Container's size.\n * @internal\n */\n this._length = 0;\n }\n Object.defineProperty(Base.prototype, \"length\", {\n /**\n * @returns The size of the container.\n * @example\n * const container = new Vector([1, 2]);\n * console.log(container.length); // 2\n */\n get: function () {\n return this._length;\n },\n enumerable: false,\n configurable: true\n });\n /**\n * @returns The size of the container.\n * @example\n * const container = new Vector([1, 2]);\n * console.log(container.size()); // 2\n */\n Base.prototype.size = function () {\n return this._length;\n };\n /**\n * @returns Whether the container is empty.\n * @example\n * container.clear();\n * console.log(container.empty()); // true\n */\n Base.prototype.empty = function () {\n return this._length === 0;\n };\n return Base;\n}();\nvar Container = /** @class */function (_super) {\n __extends(Container, _super);\n function Container() {\n return _super !== null && _super.apply(this, arguments) || this;\n }\n return Container;\n}(Base);\n\n/**\n * @description Throw an iterator access error.\n * @internal\n */\nfunction throwIteratorAccessError() {\n throw new RangeError('Iterator access denied!');\n}\n\nvar TreeContainer = /** @class */function (_super) {\n __extends(TreeContainer, _super);\n /**\n * @internal\n */\n function TreeContainer(cmp, enableIndex) {\n if (cmp === void 0) {\n cmp = function (x, y) {\n if (x < y) return -1;\n if (x > y) return 1;\n return 0;\n };\n }\n if (enableIndex === void 0) {\n enableIndex = false;\n }\n var _this = _super.call(this) || this;\n /**\n * @internal\n */\n _this._root = undefined;\n _this._cmp = cmp;\n _this.enableIndex = enableIndex;\n _this._TreeNodeClass = enableIndex ? TreeNodeEnableIndex : TreeNode;\n _this._header = new _this._TreeNodeClass();\n return _this;\n }\n /**\n * @internal\n */\n TreeContainer.prototype._lowerBound = function (curNode, key) {\n var resNode = this._header;\n while (curNode) {\n var cmpResult = this._cmp(curNode._key, key);\n if (cmpResult < 0) {\n curNode = curNode._right;\n } else if (cmpResult > 0) {\n resNode = curNode;\n curNode = curNode._left;\n } else return curNode;\n }\n return resNode;\n };\n /**\n * @internal\n */\n TreeContainer.prototype._upperBound = function (curNode, key) {\n var resNode = this._header;\n while (curNode) {\n var cmpResult = this._cmp(curNode._key, key);\n if (cmpResult <= 0) {\n curNode = curNode._right;\n } else {\n resNode = curNode;\n curNode = curNode._left;\n }\n }\n return resNode;\n };\n /**\n * @internal\n */\n TreeContainer.prototype._reverseLowerBound = function (curNode, key) {\n var resNode = this._header;\n while (curNode) {\n var cmpResult = this._cmp(curNode._key, key);\n if (cmpResult < 0) {\n resNode = curNode;\n curNode = curNode._right;\n } else if (cmpResult > 0) {\n curNode = curNode._left;\n } else return curNode;\n }\n return resNode;\n };\n /**\n * @internal\n */\n TreeContainer.prototype._reverseUpperBound = function (curNode, key) {\n var resNode = this._header;\n while (curNode) {\n var cmpResult = this._cmp(curNode._key, key);\n if (cmpResult < 0) {\n resNode = curNode;\n curNode = curNode._right;\n } else {\n curNode = curNode._left;\n }\n }\n return resNode;\n };\n /**\n * @internal\n */\n TreeContainer.prototype._eraseNodeSelfBalance = function (curNode) {\n while (true) {\n var parentNode = curNode._parent;\n if (parentNode === this._header) return;\n if (curNode._color === 1 /* TreeNodeColor.RED */) {\n curNode._color = 0 /* TreeNodeColor.BLACK */;\n return;\n }\n if (curNode === parentNode._left) {\n var brother = parentNode._right;\n if (brother._color === 1 /* TreeNodeColor.RED */) {\n brother._color = 0 /* TreeNodeColor.BLACK */;\n parentNode._color = 1 /* TreeNodeColor.RED */;\n if (parentNode === this._root) {\n this._root = parentNode._rotateLeft();\n } else parentNode._rotateLeft();\n } else {\n if (brother._right && brother._right._color === 1 /* TreeNodeColor.RED */) {\n brother._color = parentNode._color;\n parentNode._color = 0 /* TreeNodeColor.BLACK */;\n brother._right._color = 0 /* TreeNodeColor.BLACK */;\n if (parentNode === this._root) {\n this._root = parentNode._rotateLeft();\n } else parentNode._rotateLeft();\n return;\n } else if (brother._left && brother._left._color === 1 /* TreeNodeColor.RED */) {\n brother._color = 1 /* TreeNodeColor.RED */;\n brother._left._color = 0 /* TreeNodeColor.BLACK */;\n brother._rotateRight();\n } else {\n brother._color = 1 /* TreeNodeColor.RED */;\n curNode = parentNode;\n }\n }\n } else {\n var brother = parentNode._left;\n if (brother._color === 1 /* TreeNodeColor.RED */) {\n brother._color = 0 /* TreeNodeColor.BLACK */;\n parentNode._color = 1 /* TreeNodeColor.RED */;\n if (parentNode === this._root) {\n this._root = parentNode._rotateRight();\n } else parentNode._rotateRight();\n } else {\n if (brother._left && brother._left._color === 1 /* TreeNodeColor.RED */) {\n brother._color = parentNode._color;\n parentNode._color = 0 /* TreeNodeColor.BLACK */;\n brother._left._color = 0 /* TreeNodeColor.BLACK */;\n if (parentNode === this._root) {\n this._root = parentNode._rotateRight();\n } else parentNode._rotateRight();\n return;\n } else if (brother._right && brother._right._color === 1 /* TreeNodeColor.RED */) {\n brother._color = 1 /* TreeNodeColor.RED */;\n brother._right._color = 0 /* TreeNodeColor.BLACK */;\n brother._rotateLeft();\n } else {\n brother._color = 1 /* TreeNodeColor.RED */;\n curNode = parentNode;\n }\n }\n }\n }\n };\n /**\n * @internal\n */\n TreeContainer.prototype._eraseNode = function (curNode) {\n if (this._length === 1) {\n this.clear();\n return;\n }\n var swapNode = curNode;\n while (swapNode._left || swapNode._right) {\n if (swapNode._right) {\n swapNode = swapNode._right;\n while (swapNode._left) swapNode = swapNode._left;\n } else {\n swapNode = swapNode._left;\n }\n var key = curNode._key;\n curNode._key = swapNode._key;\n swapNode._key = key;\n var value = curNode._value;\n curNode._value = swapNode._value;\n swapNode._value = value;\n curNode = swapNode;\n }\n if (this._header._left === swapNode) {\n this._header._left = swapNode._parent;\n } else if (this._header._right === swapNode) {\n this._header._right = swapNode._parent;\n }\n this._eraseNodeSelfBalance(swapNode);\n var _parent = swapNode._parent;\n if (swapNode === _parent._left) {\n _parent._left = undefined;\n } else _parent._right = undefined;\n this._length -= 1;\n this._root._color = 0 /* TreeNodeColor.BLACK */;\n if (this.enableIndex) {\n while (_parent !== this._header) {\n _parent._subTreeSize -= 1;\n _parent = _parent._parent;\n }\n }\n };\n /**\n * @internal\n */\n TreeContainer.prototype._inOrderTraversal = function (param) {\n var pos = typeof param === 'number' ? param : undefined;\n var callback = typeof param === 'function' ? param : undefined;\n var nodeList = typeof param === 'undefined' ? [] : undefined;\n var index = 0;\n var curNode = this._root;\n var stack = [];\n while (stack.length || curNode) {\n if (curNode) {\n stack.push(curNode);\n curNode = curNode._left;\n } else {\n curNode = stack.pop();\n if (index === pos) return curNode;\n nodeList && nodeList.push(curNode);\n callback && callback(curNode, index, this);\n index += 1;\n curNode = curNode._right;\n }\n }\n return nodeList;\n };\n /**\n * @internal\n */\n TreeContainer.prototype._insertNodeSelfBalance = function (curNode) {\n while (true) {\n var parentNode = curNode._parent;\n if (parentNode._color === 0 /* TreeNodeColor.BLACK */) return;\n var grandParent = parentNode._parent;\n if (parentNode === grandParent._left) {\n var uncle = grandParent._right;\n if (uncle && uncle._color === 1 /* TreeNodeColor.RED */) {\n uncle._color = parentNode._color = 0 /* TreeNodeColor.BLACK */;\n if (grandParent === this._root) return;\n grandParent._color = 1 /* TreeNodeColor.RED */;\n curNode = grandParent;\n continue;\n } else if (curNode === parentNode._right) {\n curNode._color = 0 /* TreeNodeColor.BLACK */;\n if (curNode._left) {\n curNode._left._parent = parentNode;\n }\n if (curNode._right) {\n curNode._right._parent = grandParent;\n }\n parentNode._right = curNode._left;\n grandParent._left = curNode._right;\n curNode._left = parentNode;\n curNode._right = grandParent;\n if (grandParent === this._root) {\n this._root = curNode;\n this._header._parent = curNode;\n } else {\n var GP = grandParent._parent;\n if (GP._left === grandParent) {\n GP._left = curNode;\n } else GP._right = curNode;\n }\n curNode._parent = grandParent._parent;\n parentNode._parent = curNode;\n grandParent._parent = curNode;\n grandParent._color = 1 /* TreeNodeColor.RED */;\n } else {\n parentNode._color = 0 /* TreeNodeColor.BLACK */;\n if (grandParent === this._root) {\n this._root = grandParent._rotateRight();\n } else grandParent._rotateRight();\n grandParent._color = 1 /* TreeNodeColor.RED */;\n return;\n }\n } else {\n var uncle = grandParent._left;\n if (uncle && uncle._color === 1 /* TreeNodeColor.RED */) {\n uncle._color = parentNode._color = 0 /* TreeNodeColor.BLACK */;\n if (grandParent === this._root) return;\n grandParent._color = 1 /* TreeNodeColor.RED */;\n curNode = grandParent;\n continue;\n } else if (curNode === parentNode._left) {\n curNode._color = 0 /* TreeNodeColor.BLACK */;\n if (curNode._left) {\n curNode._left._parent = grandParent;\n }\n if (curNode._right) {\n curNode._right._parent = parentNode;\n }\n grandParent._right = curNode._left;\n parentNode._left = curNode._right;\n curNode._left = grandParent;\n curNode._right = parentNode;\n if (grandParent === this._root) {\n this._root = curNode;\n this._header._parent = curNode;\n } else {\n var GP = grandParent._parent;\n if (GP._left === grandParent) {\n GP._left = curNode;\n } else GP._right = curNode;\n }\n curNode._parent = grandParent._parent;\n parentNode._parent = curNode;\n grandParent._parent = curNode;\n grandParent._color = 1 /* TreeNodeColor.RED */;\n } else {\n parentNode._color = 0 /* TreeNodeColor.BLACK */;\n if (grandParent === this._root) {\n this._root = grandParent._rotateLeft();\n } else grandParent._rotateLeft();\n grandParent._color = 1 /* TreeNodeColor.RED */;\n return;\n }\n }\n if (this.enableIndex) {\n parentNode._recount();\n grandParent._recount();\n curNode._recount();\n }\n return;\n }\n };\n /**\n * @internal\n */\n TreeContainer.prototype._set = function (key, value, hint) {\n if (this._root === undefined) {\n this._length += 1;\n this._root = new this._TreeNodeClass(key, value, 0 /* TreeNodeColor.BLACK */);\n this._root._parent = this._header;\n this._header._parent = this._header._left = this._header._right = this._root;\n return this._length;\n }\n var curNode;\n var minNode = this._header._left;\n var compareToMin = this._cmp(minNode._key, key);\n if (compareToMin === 0) {\n minNode._value = value;\n return this._length;\n } else if (compareToMin > 0) {\n minNode._left = new this._TreeNodeClass(key, value);\n minNode._left._parent = minNode;\n curNode = minNode._left;\n this._header._left = curNode;\n } else {\n var maxNode = this._header._right;\n var compareToMax = this._cmp(maxNode._key, key);\n if (compareToMax === 0) {\n maxNode._value = value;\n return this._length;\n } else if (compareToMax < 0) {\n maxNode._right = new this._TreeNodeClass(key, value);\n maxNode._right._parent = maxNode;\n curNode = maxNode._right;\n this._header._right = curNode;\n } else {\n if (hint !== undefined) {\n var iterNode = hint._node;\n if (iterNode !== this._header) {\n var iterCmpRes = this._cmp(iterNode._key, key);\n if (iterCmpRes === 0) {\n iterNode._value = value;\n return this._length;\n } else /* istanbul ignore else */if (iterCmpRes > 0) {\n var preNode = iterNode._pre();\n var preCmpRes = this._cmp(preNode._key, key);\n if (preCmpRes === 0) {\n preNode._value = value;\n return this._length;\n } else if (preCmpRes < 0) {\n curNode = new this._TreeNodeClass(key, value);\n if (preNode._right === undefined) {\n preNode._right = curNode;\n curNode._parent = preNode;\n } else {\n iterNode._left = curNode;\n curNode._parent = iterNode;\n }\n }\n }\n }\n }\n if (curNode === undefined) {\n curNode = this._root;\n while (true) {\n var cmpResult = this._cmp(curNode._key, key);\n if (cmpResult > 0) {\n if (curNode._left === undefined) {\n curNode._left = new this._TreeNodeClass(key, value);\n curNode._left._parent = curNode;\n curNode = curNode._left;\n break;\n }\n curNode = curNode._left;\n } else if (cmpResult < 0) {\n if (curNode._right === undefined) {\n curNode._right = new this._TreeNodeClass(key, value);\n curNode._right._parent = curNode;\n curNode = curNode._right;\n break;\n }\n curNode = curNode._right;\n } else {\n curNode._value = value;\n return this._length;\n }\n }\n }\n }\n }\n if (this.enableIndex) {\n var parent_1 = curNode._parent;\n while (parent_1 !== this._header) {\n parent_1._subTreeSize += 1;\n parent_1 = parent_1._parent;\n }\n }\n this._insertNodeSelfBalance(curNode);\n this._length += 1;\n return this._length;\n };\n /**\n * @internal\n */\n TreeContainer.prototype._getTreeNodeByKey = function (curNode, key) {\n while (curNode) {\n var cmpResult = this._cmp(curNode._key, key);\n if (cmpResult < 0) {\n curNode = curNode._right;\n } else if (cmpResult > 0) {\n curNode = curNode._left;\n } else return curNode;\n }\n return curNode || this._header;\n };\n TreeContainer.prototype.clear = function () {\n this._length = 0;\n this._root = undefined;\n this._header._parent = undefined;\n this._header._left = this._header._right = undefined;\n };\n /**\n * @description Update node's key by iterator.\n * @param iter - The iterator you want to change.\n * @param key - The key you want to update.\n * @returns Whether the modification is successful.\n * @example\n * const st = new orderedSet([1, 2, 5]);\n * const iter = st.find(2);\n * st.updateKeyByIterator(iter, 3); // then st will become [1, 3, 5]\n */\n TreeContainer.prototype.updateKeyByIterator = function (iter, key) {\n var node = iter._node;\n if (node === this._header) {\n throwIteratorAccessError();\n }\n if (this._length === 1) {\n node._key = key;\n return true;\n }\n var nextKey = node._next()._key;\n if (node === this._header._left) {\n if (this._cmp(nextKey, key) > 0) {\n node._key = key;\n return true;\n }\n return false;\n }\n var preKey = node._pre()._key;\n if (node === this._header._right) {\n if (this._cmp(preKey, key) < 0) {\n node._key = key;\n return true;\n }\n return false;\n }\n if (this._cmp(preKey, key) >= 0 || this._cmp(nextKey, key) <= 0) return false;\n node._key = key;\n return true;\n };\n TreeContainer.prototype.eraseElementByPos = function (pos) {\n if (pos < 0 || pos > this._length - 1) {\n throw new RangeError();\n }\n var node = this._inOrderTraversal(pos);\n this._eraseNode(node);\n return this._length;\n };\n /**\n * @description Remove the element of the specified key.\n * @param key - The key you want to remove.\n * @returns Whether erase successfully.\n */\n TreeContainer.prototype.eraseElementByKey = function (key) {\n if (this._length === 0) return false;\n var curNode = this._getTreeNodeByKey(this._root, key);\n if (curNode === this._header) return false;\n this._eraseNode(curNode);\n return true;\n };\n TreeContainer.prototype.eraseElementByIterator = function (iter) {\n var node = iter._node;\n if (node === this._header) {\n throwIteratorAccessError();\n }\n var hasNoRight = node._right === undefined;\n var isNormal = iter.iteratorType === 0 /* IteratorType.NORMAL */;\n // For the normal iterator, the `next` node will be swapped to `this` node when has right.\n if (isNormal) {\n // So we should move it to next when it's right is null.\n if (hasNoRight) iter.next();\n } else {\n // For the reverse iterator, only when it doesn't have right and has left the `next` node will be swapped.\n // So when it has right, or it is a leaf node we should move it to `next`.\n if (!hasNoRight || node._left === undefined) iter.next();\n }\n this._eraseNode(node);\n return iter;\n };\n /**\n * @description Get the height of the tree.\n * @returns Number about the height of the RB-tree.\n */\n TreeContainer.prototype.getHeight = function () {\n if (this._length === 0) return 0;\n function traversal(curNode) {\n if (!curNode) return 0;\n return Math.max(traversal(curNode._left), traversal(curNode._right)) + 1;\n }\n return traversal(this._root);\n };\n return TreeContainer;\n}(Container);\n\nvar TreeIterator = /** @class */function (_super) {\n __extends(TreeIterator, _super);\n /**\n * @internal\n */\n function TreeIterator(node, header, iteratorType) {\n var _this = _super.call(this, iteratorType) || this;\n _this._node = node;\n _this._header = header;\n if (_this.iteratorType === 0 /* IteratorType.NORMAL */) {\n _this.pre = function () {\n if (this._node === this._header._left) {\n throwIteratorAccessError();\n }\n this._node = this._node._pre();\n return this;\n };\n _this.next = function () {\n if (this._node === this._header) {\n throwIteratorAccessError();\n }\n this._node = this._node._next();\n return this;\n };\n } else {\n _this.pre = function () {\n if (this._node === this._header._right) {\n throwIteratorAccessError();\n }\n this._node = this._node._next();\n return this;\n };\n _this.next = function () {\n if (this._node === this._header) {\n throwIteratorAccessError();\n }\n this._node = this._node._pre();\n return this;\n };\n }\n return _this;\n }\n Object.defineProperty(TreeIterator.prototype, \"index\", {\n /**\n * @description Get the sequential index of the iterator in the tree container.
\n * Note:\n * This function only takes effect when the specified tree container `enableIndex = true`.\n * @returns The index subscript of the node in the tree.\n * @example\n * const st = new OrderedSet([1, 2, 3], true);\n * console.log(st.begin().next().index); // 1\n */\n get: function () {\n var _node = this._node;\n var root = this._header._parent;\n if (_node === this._header) {\n if (root) {\n return root._subTreeSize - 1;\n }\n return 0;\n }\n var index = 0;\n if (_node._left) {\n index += _node._left._subTreeSize;\n }\n while (_node !== root) {\n var _parent = _node._parent;\n if (_node === _parent._right) {\n index += 1;\n if (_parent._left) {\n index += _parent._left._subTreeSize;\n }\n }\n _node = _parent;\n }\n return index;\n },\n enumerable: false,\n configurable: true\n });\n TreeIterator.prototype.isAccessible = function () {\n return this._node !== this._header;\n };\n return TreeIterator;\n}(ContainerIterator);\n\nvar OrderedMapIterator = /** @class */function (_super) {\n __extends(OrderedMapIterator, _super);\n function OrderedMapIterator(node, header, container, iteratorType) {\n var _this = _super.call(this, node, header, iteratorType) || this;\n _this.container = container;\n return _this;\n }\n Object.defineProperty(OrderedMapIterator.prototype, \"pointer\", {\n get: function () {\n if (this._node === this._header) {\n throwIteratorAccessError();\n }\n var self = this;\n return new Proxy([], {\n get: function (target, prop) {\n if (prop === '0') return self._node._key;else if (prop === '1') return self._node._value;\n target[0] = self._node._key;\n target[1] = self._node._value;\n return target[prop];\n },\n set: function (_, prop, newValue) {\n if (prop !== '1') {\n throw new TypeError('prop must be 1');\n }\n self._node._value = newValue;\n return true;\n }\n });\n },\n enumerable: false,\n configurable: true\n });\n OrderedMapIterator.prototype.copy = function () {\n return new OrderedMapIterator(this._node, this._header, this.container, this.iteratorType);\n };\n return OrderedMapIterator;\n}(TreeIterator);\nvar OrderedMap = /** @class */function (_super) {\n __extends(OrderedMap, _super);\n /**\n * @param container - The initialization container.\n * @param cmp - The compare function.\n * @param enableIndex - Whether to enable iterator indexing function.\n * @example\n * new OrderedMap();\n * new OrderedMap([[0, 1], [2, 1]]);\n * new OrderedMap([[0, 1], [2, 1]], (x, y) => x - y);\n * new OrderedMap([[0, 1], [2, 1]], (x, y) => x - y, true);\n */\n function OrderedMap(container, cmp, enableIndex) {\n if (container === void 0) {\n container = [];\n }\n var _this = _super.call(this, cmp, enableIndex) || this;\n var self = _this;\n container.forEach(function (el) {\n self.setElement(el[0], el[1]);\n });\n return _this;\n }\n OrderedMap.prototype.begin = function () {\n return new OrderedMapIterator(this._header._left || this._header, this._header, this);\n };\n OrderedMap.prototype.end = function () {\n return new OrderedMapIterator(this._header, this._header, this);\n };\n OrderedMap.prototype.rBegin = function () {\n return new OrderedMapIterator(this._header._right || this._header, this._header, this, 1 /* IteratorType.REVERSE */);\n };\n\n OrderedMap.prototype.rEnd = function () {\n return new OrderedMapIterator(this._header, this._header, this, 1 /* IteratorType.REVERSE */);\n };\n\n OrderedMap.prototype.front = function () {\n if (this._length === 0) return;\n var minNode = this._header._left;\n return [minNode._key, minNode._value];\n };\n OrderedMap.prototype.back = function () {\n if (this._length === 0) return;\n var maxNode = this._header._right;\n return [maxNode._key, maxNode._value];\n };\n OrderedMap.prototype.lowerBound = function (key) {\n var resNode = this._lowerBound(this._root, key);\n return new OrderedMapIterator(resNode, this._header, this);\n };\n OrderedMap.prototype.upperBound = function (key) {\n var resNode = this._upperBound(this._root, key);\n return new OrderedMapIterator(resNode, this._header, this);\n };\n OrderedMap.prototype.reverseLowerBound = function (key) {\n var resNode = this._reverseLowerBound(this._root, key);\n return new OrderedMapIterator(resNode, this._header, this);\n };\n OrderedMap.prototype.reverseUpperBound = function (key) {\n var resNode = this._reverseUpperBound(this._root, key);\n return new OrderedMapIterator(resNode, this._header, this);\n };\n OrderedMap.prototype.forEach = function (callback) {\n this._inOrderTraversal(function (node, index, map) {\n callback([node._key, node._value], index, map);\n });\n };\n /**\n * @description Insert a key-value pair or set value by the given key.\n * @param key - The key want to insert.\n * @param value - The value want to set.\n * @param hint - You can give an iterator hint to improve insertion efficiency.\n * @return The size of container after setting.\n * @example\n * const mp = new OrderedMap([[2, 0], [4, 0], [5, 0]]);\n * const iter = mp.begin();\n * mp.setElement(1, 0);\n * mp.setElement(3, 0, iter); // give a hint will be faster.\n */\n OrderedMap.prototype.setElement = function (key, value, hint) {\n return this._set(key, value, hint);\n };\n OrderedMap.prototype.getElementByPos = function (pos) {\n if (pos < 0 || pos > this._length - 1) {\n throw new RangeError();\n }\n var node = this._inOrderTraversal(pos);\n return [node._key, node._value];\n };\n OrderedMap.prototype.find = function (key) {\n var curNode = this._getTreeNodeByKey(this._root, key);\n return new OrderedMapIterator(curNode, this._header, this);\n };\n /**\n * @description Get the value of the element of the specified key.\n * @param key - The specified key you want to get.\n * @example\n * const val = container.getElementByKey(1);\n */\n OrderedMap.prototype.getElementByKey = function (key) {\n var curNode = this._getTreeNodeByKey(this._root, key);\n return curNode._value;\n };\n OrderedMap.prototype.union = function (other) {\n var self = this;\n other.forEach(function (el) {\n self.setElement(el[0], el[1]);\n });\n return this._length;\n };\n OrderedMap.prototype[Symbol.iterator] = function () {\n var length, nodeList, i, node;\n return __generator(this, function (_a) {\n switch (_a.label) {\n case 0:\n length = this._length;\n nodeList = this._inOrderTraversal();\n i = 0;\n _a.label = 1;\n case 1:\n if (!(i < length)) return [3 /*break*/, 4];\n node = nodeList[i];\n return [4 /*yield*/, [node._key, node._value]];\n case 2:\n _a.sent();\n _a.label = 3;\n case 3:\n ++i;\n return [3 /*break*/, 1];\n case 4:\n return [2 /*return*/];\n }\n });\n };\n\n return OrderedMap;\n}(TreeContainer);\n\nexport { OrderedMap };\n//# sourceMappingURL=index.js.map\n","export const enum TreeNodeColor {\n RED = 1,\n BLACK = 0\n}\n\nexport class TreeNode {\n _color: TreeNodeColor;\n _key: K | undefined;\n _value: V | undefined;\n _left: TreeNode | undefined = undefined;\n _right: TreeNode | undefined = undefined;\n _parent: TreeNode | undefined = undefined;\n constructor(\n key?: K,\n value?: V,\n color: TreeNodeColor = TreeNodeColor.RED\n ) {\n this._key = key;\n this._value = value;\n this._color = color;\n }\n /**\n * @description Get the pre node.\n * @returns TreeNode about the pre node.\n */\n _pre() {\n let preNode: TreeNode = this;\n const isRootOrHeader = preNode._parent!._parent === preNode;\n if (isRootOrHeader && preNode._color === TreeNodeColor.RED) {\n preNode = preNode._right!;\n } else if (preNode._left) {\n preNode = preNode._left;\n while (preNode._right) {\n preNode = preNode._right;\n }\n } else {\n // Must be root and left is null\n if (isRootOrHeader) {\n return preNode._parent!;\n }\n let pre = preNode._parent!;\n while (pre._left === preNode) {\n preNode = pre;\n pre = preNode._parent!;\n }\n preNode = pre;\n }\n return preNode;\n }\n /**\n * @description Get the next node.\n * @returns TreeNode about the next node.\n */\n _next() {\n let nextNode: TreeNode = this;\n if (nextNode._right) {\n nextNode = nextNode._right;\n while (nextNode._left) {\n nextNode = nextNode._left;\n }\n return nextNode;\n } else {\n let pre = nextNode._parent!;\n while (pre._right === nextNode) {\n nextNode = pre;\n pre = nextNode._parent!;\n }\n if (nextNode._right !== pre) {\n return pre;\n } else return nextNode;\n }\n }\n /**\n * @description Rotate left.\n * @returns TreeNode about moved to original position after rotation.\n */\n _rotateLeft() {\n const PP = this._parent!;\n const V = this._right!;\n const R = V._left;\n\n if (PP._parent === this) PP._parent = V;\n else if (PP._left === this) PP._left = V;\n else PP._right = V;\n\n V._parent = PP;\n V._left = this;\n\n this._parent = V;\n this._right = R;\n\n if (R) R._parent = this;\n\n return V;\n }\n /**\n * @description Rotate right.\n * @returns TreeNode about moved to original position after rotation.\n */\n _rotateRight() {\n const PP = this._parent!;\n const F = this._left!;\n const K = F._right;\n\n if (PP._parent === this) PP._parent = F;\n else if (PP._left === this) PP._left = F;\n else PP._right = F;\n\n F._parent = PP;\n F._right = this;\n\n this._parent = F;\n this._left = K;\n\n if (K) K._parent = this;\n\n return F;\n }\n}\n\nexport class TreeNodeEnableIndex extends TreeNode {\n _subTreeSize = 1;\n /**\n * @description Rotate left and do recount.\n * @returns TreeNode about moved to original position after rotation.\n */\n _rotateLeft() {\n const parent = super._rotateLeft() as TreeNodeEnableIndex;\n this._recount();\n parent._recount();\n return parent;\n }\n /**\n * @description Rotate right and do recount.\n * @returns TreeNode about moved to original position after rotation.\n */\n _rotateRight() {\n const parent = super._rotateRight() as TreeNodeEnableIndex;\n this._recount();\n parent._recount();\n return parent;\n }\n _recount() {\n this._subTreeSize = 1;\n if (this._left) {\n this._subTreeSize += (this._left as TreeNodeEnableIndex)._subTreeSize;\n }\n if (this._right) {\n this._subTreeSize += (this._right as TreeNodeEnableIndex)._subTreeSize;\n }\n }\n}\n","/**\n * @description The iterator type including `NORMAL` and `REVERSE`.\n */\nexport const enum IteratorType {\n NORMAL = 0,\n REVERSE = 1\n}\n\nexport abstract class ContainerIterator {\n /**\n * @description The container pointed to by the iterator.\n */\n abstract readonly container: Container;\n /**\n * @internal\n */\n abstract _node: unknown;\n /**\n * @description Iterator's type.\n * @example\n * console.log(container.end().iteratorType === IteratorType.NORMAL); // true\n */\n readonly iteratorType: IteratorType;\n /**\n * @internal\n */\n protected constructor(iteratorType = IteratorType.NORMAL) {\n this.iteratorType = iteratorType;\n }\n /**\n * @param iter - The other iterator you want to compare.\n * @returns Whether this equals to obj.\n * @example\n * container.find(1).equals(container.end());\n */\n equals(iter: ContainerIterator) {\n return this._node === iter._node;\n }\n /**\n * @description Pointers to element.\n * @returns The value of the pointer's element.\n * @example\n * const val = container.begin().pointer;\n */\n abstract get pointer(): T;\n /**\n * @description Set pointer's value (some containers are unavailable).\n * @param newValue - The new value you want to set.\n * @example\n * (>container).begin().pointer = 1;\n */\n abstract set pointer(newValue: T);\n /**\n * @description Move `this` iterator to pre.\n * @returns The iterator's self.\n * @example\n * const iter = container.find(1); // container = [0, 1]\n * const pre = iter.pre();\n * console.log(pre === iter); // true\n * console.log(pre.equals(iter)); // true\n * console.log(pre.pointer, iter.pointer); // 0, 0\n */\n abstract pre(): this;\n /**\n * @description Move `this` iterator to next.\n * @returns The iterator's self.\n * @example\n * const iter = container.find(1); // container = [1, 2]\n * const next = iter.next();\n * console.log(next === iter); // true\n * console.log(next.equals(iter)); // true\n * console.log(next.pointer, iter.pointer); // 2, 2\n */\n abstract next(): this;\n /**\n * @description Get a copy of itself.\n * @returns The copy of self.\n * @example\n * const iter = container.find(1); // container = [1, 2]\n * const next = iter.copy().next();\n * console.log(next === iter); // false\n * console.log(next.equals(iter)); // false\n * console.log(next.pointer, iter.pointer); // 2, 1\n */\n abstract copy(): ContainerIterator;\n abstract isAccessible(): boolean;\n}\n\nexport abstract class Base {\n /**\n * @description Container's size.\n * @internal\n */\n protected _length = 0;\n /**\n * @returns The size of the container.\n * @example\n * const container = new Vector([1, 2]);\n * console.log(container.length); // 2\n */\n get length() {\n return this._length;\n }\n /**\n * @returns The size of the container.\n * @example\n * const container = new Vector([1, 2]);\n * console.log(container.size()); // 2\n */\n size() {\n return this._length;\n }\n /**\n * @returns Whether the container is empty.\n * @example\n * container.clear();\n * console.log(container.empty()); // true\n */\n empty() {\n return this._length === 0;\n }\n /**\n * @description Clear the container.\n * @example\n * container.clear();\n * console.log(container.empty()); // true\n */\n abstract clear(): void;\n}\n\nexport abstract class Container extends Base {\n /**\n * @returns Iterator pointing to the beginning element.\n * @example\n * const begin = container.begin();\n * const end = container.end();\n * for (const it = begin; !it.equals(end); it.next()) {\n * doSomething(it.pointer);\n * }\n */\n abstract begin(): ContainerIterator;\n /**\n * @returns Iterator pointing to the super end like c++.\n * @example\n * const begin = container.begin();\n * const end = container.end();\n * for (const it = begin; !it.equals(end); it.next()) {\n * doSomething(it.pointer);\n * }\n */\n abstract end(): ContainerIterator;\n /**\n * @returns Iterator pointing to the end element.\n * @example\n * const rBegin = container.rBegin();\n * const rEnd = container.rEnd();\n * for (const it = rBegin; !it.equals(rEnd); it.next()) {\n * doSomething(it.pointer);\n * }\n */\n abstract rBegin(): ContainerIterator;\n /**\n * @returns Iterator pointing to the super begin like c++.\n * @example\n * const rBegin = container.rBegin();\n * const rEnd = container.rEnd();\n * for (const it = rBegin; !it.equals(rEnd); it.next()) {\n * doSomething(it.pointer);\n * }\n */\n abstract rEnd(): ContainerIterator;\n /**\n * @returns The first element of the container.\n */\n abstract front(): T | undefined;\n /**\n * @returns The last element of the container.\n */\n abstract back(): T | undefined;\n /**\n * @param element - The element you want to find.\n * @returns An iterator pointing to the element if found, or super end if not found.\n * @example\n * container.find(1).equals(container.end());\n */\n abstract find(element: T): ContainerIterator;\n /**\n * @description Iterate over all elements in the container.\n * @param callback - Callback function like Array.forEach.\n * @example\n * container.forEach((element, index) => console.log(element, index));\n */\n abstract forEach(callback: (element: T, index: number, container: Container) => void): void;\n /**\n * @description Gets the value of the element at the specified position.\n * @example\n * const val = container.getElementByPos(-1); // throw a RangeError\n */\n abstract getElementByPos(pos: number): T;\n /**\n * @description Removes the element at the specified position.\n * @param pos - The element's position you want to remove.\n * @returns The container length after erasing.\n * @example\n * container.eraseElementByPos(-1); // throw a RangeError\n */\n abstract eraseElementByPos(pos: number): number;\n /**\n * @description Removes element by iterator and move `iter` to next.\n * @param iter - The iterator you want to erase.\n * @returns The next iterator.\n * @example\n * container.eraseElementByIterator(container.begin());\n * container.eraseElementByIterator(container.end()); // throw a RangeError\n */\n abstract eraseElementByIterator(\n iter: ContainerIterator\n ): ContainerIterator;\n /**\n * @description Using for `for...of` syntax like Array.\n * @example\n * for (const element of container) {\n * console.log(element);\n * }\n */\n abstract [Symbol.iterator](): Generator;\n}\n\n/**\n * @description The initial data type passed in when initializing the container.\n */\nexport type initContainer = {\n size?: number | (() => number);\n length?: number;\n forEach: (callback: (el: T) => void) => void;\n}\n","/**\n * @description Throw an iterator access error.\n * @internal\n */\nexport function throwIteratorAccessError() {\n throw new RangeError('Iterator access denied!');\n}\n","import type TreeIterator from './TreeIterator';\nimport { TreeNode, TreeNodeColor, TreeNodeEnableIndex } from './TreeNode';\nimport { Container, IteratorType } from '@/container/ContainerBase';\nimport $checkWithinAccessParams from '@/utils/checkParams.macro';\nimport { throwIteratorAccessError } from '@/utils/throwError';\n\nabstract class TreeContainer extends Container {\n enableIndex: boolean;\n /**\n * @internal\n */\n protected _header: TreeNode;\n /**\n * @internal\n */\n protected _root: TreeNode | undefined = undefined;\n /**\n * @internal\n */\n protected readonly _cmp: (x: K, y: K) => number;\n /**\n * @internal\n */\n protected readonly _TreeNodeClass: typeof TreeNode | typeof TreeNodeEnableIndex;\n /**\n * @internal\n */\n protected constructor(\n cmp: (x: K, y: K) => number =\n function (x: K, y: K) {\n if (x < y) return -1;\n if (x > y) return 1;\n return 0;\n },\n enableIndex = false\n ) {\n super();\n this._cmp = cmp;\n this.enableIndex = enableIndex;\n this._TreeNodeClass = enableIndex ? TreeNodeEnableIndex : TreeNode;\n this._header = new this._TreeNodeClass();\n }\n /**\n * @internal\n */\n protected _lowerBound(curNode: TreeNode | undefined, key: K) {\n let resNode = this._header;\n while (curNode) {\n const cmpResult = this._cmp(curNode._key!, key);\n if (cmpResult < 0) {\n curNode = curNode._right;\n } else if (cmpResult > 0) {\n resNode = curNode;\n curNode = curNode._left;\n } else return curNode;\n }\n return resNode;\n }\n /**\n * @internal\n */\n protected _upperBound(curNode: TreeNode | undefined, key: K) {\n let resNode = this._header;\n while (curNode) {\n const cmpResult = this._cmp(curNode._key!, key);\n if (cmpResult <= 0) {\n curNode = curNode._right;\n } else {\n resNode = curNode;\n curNode = curNode._left;\n }\n }\n return resNode;\n }\n /**\n * @internal\n */\n protected _reverseLowerBound(curNode: TreeNode | undefined, key: K) {\n let resNode = this._header;\n while (curNode) {\n const cmpResult = this._cmp(curNode._key!, key);\n if (cmpResult < 0) {\n resNode = curNode;\n curNode = curNode._right;\n } else if (cmpResult > 0) {\n curNode = curNode._left;\n } else return curNode;\n }\n return resNode;\n }\n /**\n * @internal\n */\n protected _reverseUpperBound(curNode: TreeNode | undefined, key: K) {\n let resNode = this._header;\n while (curNode) {\n const cmpResult = this._cmp(curNode._key!, key);\n if (cmpResult < 0) {\n resNode = curNode;\n curNode = curNode._right;\n } else {\n curNode = curNode._left;\n }\n }\n return resNode;\n }\n /**\n * @internal\n */\n protected _eraseNodeSelfBalance(curNode: TreeNode) {\n while (true) {\n const parentNode = curNode._parent!;\n if (parentNode === this._header) return;\n if (curNode._color === TreeNodeColor.RED) {\n curNode._color = TreeNodeColor.BLACK;\n return;\n }\n if (curNode === parentNode._left) {\n const brother = parentNode._right!;\n if (brother._color === TreeNodeColor.RED) {\n brother._color = TreeNodeColor.BLACK;\n parentNode._color = TreeNodeColor.RED;\n if (parentNode === this._root) {\n this._root = parentNode._rotateLeft();\n } else parentNode._rotateLeft();\n } else {\n if (brother._right && brother._right._color === TreeNodeColor.RED) {\n brother._color = parentNode._color;\n parentNode._color = TreeNodeColor.BLACK;\n brother._right._color = TreeNodeColor.BLACK;\n if (parentNode === this._root) {\n this._root = parentNode._rotateLeft();\n } else parentNode._rotateLeft();\n return;\n } else if (brother._left && brother._left._color === TreeNodeColor.RED) {\n brother._color = TreeNodeColor.RED;\n brother._left._color = TreeNodeColor.BLACK;\n brother._rotateRight();\n } else {\n brother._color = TreeNodeColor.RED;\n curNode = parentNode;\n }\n }\n } else {\n const brother = parentNode._left!;\n if (brother._color === TreeNodeColor.RED) {\n brother._color = TreeNodeColor.BLACK;\n parentNode._color = TreeNodeColor.RED;\n if (parentNode === this._root) {\n this._root = parentNode._rotateRight();\n } else parentNode._rotateRight();\n } else {\n if (brother._left && brother._left._color === TreeNodeColor.RED) {\n brother._color = parentNode._color;\n parentNode._color = TreeNodeColor.BLACK;\n brother._left._color = TreeNodeColor.BLACK;\n if (parentNode === this._root) {\n this._root = parentNode._rotateRight();\n } else parentNode._rotateRight();\n return;\n } else if (brother._right && brother._right._color === TreeNodeColor.RED) {\n brother._color = TreeNodeColor.RED;\n brother._right._color = TreeNodeColor.BLACK;\n brother._rotateLeft();\n } else {\n brother._color = TreeNodeColor.RED;\n curNode = parentNode;\n }\n }\n }\n }\n }\n /**\n * @internal\n */\n protected _eraseNode(curNode: TreeNode) {\n if (this._length === 1) {\n this.clear();\n return;\n }\n let swapNode = curNode;\n while (swapNode._left || swapNode._right) {\n if (swapNode._right) {\n swapNode = swapNode._right;\n while (swapNode._left) swapNode = swapNode._left;\n } else {\n swapNode = swapNode._left!;\n }\n const key = curNode._key;\n curNode._key = swapNode._key;\n swapNode._key = key;\n const value = curNode._value;\n curNode._value = swapNode._value;\n swapNode._value = value;\n curNode = swapNode;\n }\n if (this._header._left === swapNode) {\n this._header._left = swapNode._parent;\n } else if (this._header._right === swapNode) {\n this._header._right = swapNode._parent;\n }\n this._eraseNodeSelfBalance(swapNode);\n let _parent = swapNode._parent as TreeNodeEnableIndex;\n if (swapNode === _parent._left) {\n _parent._left = undefined;\n } else _parent._right = undefined;\n this._length -= 1;\n this._root!._color = TreeNodeColor.BLACK;\n if (this.enableIndex) {\n while (_parent !== this._header) {\n _parent._subTreeSize -= 1;\n _parent = _parent._parent as TreeNodeEnableIndex;\n }\n }\n }\n protected _inOrderTraversal(): TreeNode[];\n protected _inOrderTraversal(pos: number): TreeNode;\n protected _inOrderTraversal(\n callback: (node: TreeNode, index: number, map: this) => void\n ): TreeNode;\n /**\n * @internal\n */\n protected _inOrderTraversal(\n param?: number | ((node: TreeNode, index: number, map: this) => void)\n ) {\n const pos = typeof param === 'number' ? param : undefined;\n const callback = typeof param === 'function' ? param : undefined;\n const nodeList = typeof param === 'undefined' ? []>[] : undefined;\n let index = 0;\n let curNode = this._root;\n const stack: TreeNode[] = [];\n while (stack.length || curNode) {\n if (curNode) {\n stack.push(curNode);\n curNode = curNode._left;\n } else {\n curNode = stack.pop()!;\n if (index === pos) return curNode;\n nodeList && nodeList.push(curNode);\n callback && callback(curNode, index, this);\n index += 1;\n curNode = curNode._right;\n }\n }\n return nodeList;\n }\n /**\n * @internal\n */\n protected _insertNodeSelfBalance(curNode: TreeNode) {\n while (true) {\n const parentNode = curNode._parent!;\n if (parentNode._color === TreeNodeColor.BLACK) return;\n const grandParent = parentNode._parent!;\n if (parentNode === grandParent._left) {\n const uncle = grandParent._right;\n if (uncle && uncle._color === TreeNodeColor.RED) {\n uncle._color = parentNode._color = TreeNodeColor.BLACK;\n if (grandParent === this._root) return;\n grandParent._color = TreeNodeColor.RED;\n curNode = grandParent;\n continue;\n } else if (curNode === parentNode._right) {\n curNode._color = TreeNodeColor.BLACK;\n if (curNode._left) {\n curNode._left._parent = parentNode;\n }\n if (curNode._right) {\n curNode._right._parent = grandParent;\n }\n parentNode._right = curNode._left;\n grandParent._left = curNode._right;\n curNode._left = parentNode;\n curNode._right = grandParent;\n if (grandParent === this._root) {\n this._root = curNode;\n this._header._parent = curNode;\n } else {\n const GP = grandParent._parent!;\n if (GP._left === grandParent) {\n GP._left = curNode;\n } else GP._right = curNode;\n }\n curNode._parent = grandParent._parent;\n parentNode._parent = curNode;\n grandParent._parent = curNode;\n grandParent._color = TreeNodeColor.RED;\n } else {\n parentNode._color = TreeNodeColor.BLACK;\n if (grandParent === this._root) {\n this._root = grandParent._rotateRight();\n } else grandParent._rotateRight();\n grandParent._color = TreeNodeColor.RED;\n return;\n }\n } else {\n const uncle = grandParent._left;\n if (uncle && uncle._color === TreeNodeColor.RED) {\n uncle._color = parentNode._color = TreeNodeColor.BLACK;\n if (grandParent === this._root) return;\n grandParent._color = TreeNodeColor.RED;\n curNode = grandParent;\n continue;\n } else if (curNode === parentNode._left) {\n curNode._color = TreeNodeColor.BLACK;\n if (curNode._left) {\n curNode._left._parent = grandParent;\n }\n if (curNode._right) {\n curNode._right._parent = parentNode;\n }\n grandParent._right = curNode._left;\n parentNode._left = curNode._right;\n curNode._left = grandParent;\n curNode._right = parentNode;\n if (grandParent === this._root) {\n this._root = curNode;\n this._header._parent = curNode;\n } else {\n const GP = grandParent._parent!;\n if (GP._left === grandParent) {\n GP._left = curNode;\n } else GP._right = curNode;\n }\n curNode._parent = grandParent._parent;\n parentNode._parent = curNode;\n grandParent._parent = curNode;\n grandParent._color = TreeNodeColor.RED;\n } else {\n parentNode._color = TreeNodeColor.BLACK;\n if (grandParent === this._root) {\n this._root = grandParent._rotateLeft();\n } else grandParent._rotateLeft();\n grandParent._color = TreeNodeColor.RED;\n return;\n }\n }\n if (this.enableIndex) {\n (>parentNode)._recount();\n (>grandParent)._recount();\n (>curNode)._recount();\n }\n return;\n }\n }\n /**\n * @internal\n */\n protected _set(key: K, value?: V, hint?: TreeIterator) {\n if (this._root === undefined) {\n this._length += 1;\n this._root = new this._TreeNodeClass(key, value, TreeNodeColor.BLACK);\n this._root._parent = this._header;\n this._header._parent = this._header._left = this._header._right = this._root;\n return this._length;\n }\n let curNode;\n const minNode = this._header._left!;\n const compareToMin = this._cmp(minNode._key!, key);\n if (compareToMin === 0) {\n minNode._value = value;\n return this._length;\n } else if (compareToMin > 0) {\n minNode._left = new this._TreeNodeClass(key, value);\n minNode._left._parent = minNode;\n curNode = minNode._left;\n this._header._left = curNode;\n } else {\n const maxNode = this._header._right!;\n const compareToMax = this._cmp(maxNode._key!, key);\n if (compareToMax === 0) {\n maxNode._value = value;\n return this._length;\n } else if (compareToMax < 0) {\n maxNode._right = new this._TreeNodeClass(key, value);\n maxNode._right._parent = maxNode;\n curNode = maxNode._right;\n this._header._right = curNode;\n } else {\n if (hint !== undefined) {\n const iterNode = hint._node;\n if (iterNode !== this._header) {\n const iterCmpRes = this._cmp(iterNode._key!, key);\n if (iterCmpRes === 0) {\n iterNode._value = value;\n return this._length;\n } else /* istanbul ignore else */ if (iterCmpRes > 0) {\n const preNode = iterNode._pre();\n const preCmpRes = this._cmp(preNode._key!, key);\n if (preCmpRes === 0) {\n preNode._value = value;\n return this._length;\n } else if (preCmpRes < 0) {\n curNode = new this._TreeNodeClass(key, value);\n if (preNode._right === undefined) {\n preNode._right = curNode;\n curNode._parent = preNode;\n } else {\n iterNode._left = curNode;\n curNode._parent = iterNode;\n }\n }\n }\n }\n }\n if (curNode === undefined) {\n curNode = this._root;\n while (true) {\n const cmpResult = this._cmp(curNode._key!, key);\n if (cmpResult > 0) {\n if (curNode._left === undefined) {\n curNode._left = new this._TreeNodeClass(key, value);\n curNode._left._parent = curNode;\n curNode = curNode._left;\n break;\n }\n curNode = curNode._left;\n } else if (cmpResult < 0) {\n if (curNode._right === undefined) {\n curNode._right = new this._TreeNodeClass(key, value);\n curNode._right._parent = curNode;\n curNode = curNode._right;\n break;\n }\n curNode = curNode._right;\n } else {\n curNode._value = value;\n return this._length;\n }\n }\n }\n }\n }\n if (this.enableIndex) {\n let parent = curNode._parent as TreeNodeEnableIndex;\n while (parent !== this._header) {\n parent._subTreeSize += 1;\n parent = parent._parent as TreeNodeEnableIndex;\n }\n }\n this._insertNodeSelfBalance(curNode);\n this._length += 1;\n return this._length;\n }\n /**\n * @internal\n */\n protected _getTreeNodeByKey(curNode: TreeNode | undefined, key: K) {\n while (curNode) {\n const cmpResult = this._cmp(curNode._key!, key);\n if (cmpResult < 0) {\n curNode = curNode._right;\n } else if (cmpResult > 0) {\n curNode = curNode._left;\n } else return curNode;\n }\n return curNode || this._header;\n }\n clear() {\n this._length = 0;\n this._root = undefined;\n this._header._parent = undefined;\n this._header._left = this._header._right = undefined;\n }\n /**\n * @description Update node's key by iterator.\n * @param iter - The iterator you want to change.\n * @param key - The key you want to update.\n * @returns Whether the modification is successful.\n * @example\n * const st = new orderedSet([1, 2, 5]);\n * const iter = st.find(2);\n * st.updateKeyByIterator(iter, 3); // then st will become [1, 3, 5]\n */\n updateKeyByIterator(iter: TreeIterator, key: K): boolean {\n const node = iter._node;\n if (node === this._header) {\n throwIteratorAccessError();\n }\n if (this._length === 1) {\n node._key = key;\n return true;\n }\n const nextKey = node._next()._key!;\n if (node === this._header._left) {\n if (this._cmp(nextKey, key) > 0) {\n node._key = key;\n return true;\n }\n return false;\n }\n const preKey = node._pre()._key!;\n if (node === this._header._right) {\n if (this._cmp(preKey, key) < 0) {\n node._key = key;\n return true;\n }\n return false;\n }\n if (\n this._cmp(preKey, key) >= 0 ||\n this._cmp(nextKey, key) <= 0\n ) return false;\n node._key = key;\n return true;\n }\n eraseElementByPos(pos: number) {\n $checkWithinAccessParams!(pos, 0, this._length - 1);\n const node = this._inOrderTraversal(pos);\n this._eraseNode(node);\n return this._length;\n }\n /**\n * @description Remove the element of the specified key.\n * @param key - The key you want to remove.\n * @returns Whether erase successfully.\n */\n eraseElementByKey(key: K) {\n if (this._length === 0) return false;\n const curNode = this._getTreeNodeByKey(this._root, key);\n if (curNode === this._header) return false;\n this._eraseNode(curNode);\n return true;\n }\n eraseElementByIterator(iter: TreeIterator) {\n const node = iter._node;\n if (node === this._header) {\n throwIteratorAccessError();\n }\n const hasNoRight = node._right === undefined;\n const isNormal = iter.iteratorType === IteratorType.NORMAL;\n // For the normal iterator, the `next` node will be swapped to `this` node when has right.\n if (isNormal) {\n // So we should move it to next when it's right is null.\n if (hasNoRight) iter.next();\n } else {\n // For the reverse iterator, only when it doesn't have right and has left the `next` node will be swapped.\n // So when it has right, or it is a leaf node we should move it to `next`.\n if (!hasNoRight || node._left === undefined) iter.next();\n }\n this._eraseNode(node);\n return iter;\n }\n /**\n * @description Get the height of the tree.\n * @returns Number about the height of the RB-tree.\n */\n getHeight() {\n if (this._length === 0) return 0;\n function traversal(curNode: TreeNode | undefined): number {\n if (!curNode) return 0;\n return Math.max(traversal(curNode._left), traversal(curNode._right)) + 1;\n }\n return traversal(this._root);\n }\n /**\n * @param key - The given key you want to compare.\n * @returns An iterator to the first element less than the given key.\n */\n abstract reverseUpperBound(key: K): TreeIterator;\n /**\n * @description Union the other tree to self.\n * @param other - The other tree container you want to merge.\n * @returns The size of the tree after union.\n */\n abstract union(other: TreeContainer): number;\n /**\n * @param key - The given key you want to compare.\n * @returns An iterator to the first element not greater than the given key.\n */\n abstract reverseLowerBound(key: K): TreeIterator;\n /**\n * @param key - The given key you want to compare.\n * @returns An iterator to the first element not less than the given key.\n */\n abstract lowerBound(key: K): TreeIterator;\n /**\n * @param key - The given key you want to compare.\n * @returns An iterator to the first element greater than the given key.\n */\n abstract upperBound(key: K): TreeIterator;\n}\n\nexport default TreeContainer;\n","import { TreeNode } from './TreeNode';\nimport type { TreeNodeEnableIndex } from './TreeNode';\nimport { ContainerIterator, IteratorType } from '@/container/ContainerBase';\nimport TreeContainer from '@/container/TreeContainer/Base/index';\nimport { throwIteratorAccessError } from '@/utils/throwError';\n\nabstract class TreeIterator extends ContainerIterator {\n abstract readonly container: TreeContainer;\n /**\n * @internal\n */\n _node: TreeNode;\n /**\n * @internal\n */\n protected _header: TreeNode;\n /**\n * @internal\n */\n protected constructor(\n node: TreeNode,\n header: TreeNode,\n iteratorType?: IteratorType\n ) {\n super(iteratorType);\n this._node = node;\n this._header = header;\n if (this.iteratorType === IteratorType.NORMAL) {\n this.pre = function () {\n if (this._node === this._header._left) {\n throwIteratorAccessError();\n }\n this._node = this._node._pre();\n return this;\n };\n\n this.next = function () {\n if (this._node === this._header) {\n throwIteratorAccessError();\n }\n this._node = this._node._next();\n return this;\n };\n } else {\n this.pre = function () {\n if (this._node === this._header._right) {\n throwIteratorAccessError();\n }\n this._node = this._node._next();\n return this;\n };\n\n this.next = function () {\n if (this._node === this._header) {\n throwIteratorAccessError();\n }\n this._node = this._node._pre();\n return this;\n };\n }\n }\n /**\n * @description Get the sequential index of the iterator in the tree container.
\n * Note:\n * This function only takes effect when the specified tree container `enableIndex = true`.\n * @returns The index subscript of the node in the tree.\n * @example\n * const st = new OrderedSet([1, 2, 3], true);\n * console.log(st.begin().next().index); // 1\n */\n get index() {\n let _node = this._node as TreeNodeEnableIndex;\n const root = this._header._parent as TreeNodeEnableIndex;\n if (_node === this._header) {\n if (root) {\n return root._subTreeSize - 1;\n }\n return 0;\n }\n let index = 0;\n if (_node._left) {\n index += (_node._left as TreeNodeEnableIndex)._subTreeSize;\n }\n while (_node !== root) {\n const _parent = _node._parent as TreeNodeEnableIndex;\n if (_node === _parent._right) {\n index += 1;\n if (_parent._left) {\n index += (_parent._left as TreeNodeEnableIndex)._subTreeSize;\n }\n }\n _node = _parent;\n }\n return index;\n }\n isAccessible() {\n return this._node !== this._header;\n }\n // @ts-ignore\n pre(): this;\n // @ts-ignore\n next(): this;\n}\n\nexport default TreeIterator;\n","import TreeContainer from './Base';\nimport TreeIterator from './Base/TreeIterator';\nimport { TreeNode } from './Base/TreeNode';\nimport { initContainer, IteratorType } from '@/container/ContainerBase';\nimport $checkWithinAccessParams from '@/utils/checkParams.macro';\nimport { throwIteratorAccessError } from '@/utils/throwError';\n\nclass OrderedMapIterator extends TreeIterator {\n container: OrderedMap;\n constructor(\n node: TreeNode,\n header: TreeNode,\n container: OrderedMap,\n iteratorType?: IteratorType\n ) {\n super(node, header, iteratorType);\n this.container = container;\n }\n get pointer() {\n if (this._node === this._header) {\n throwIteratorAccessError();\n }\n const self = this;\n return new Proxy(<[K, V]>[], {\n get(target, prop: '0' | '1') {\n if (prop === '0') return self._node._key!;\n else if (prop === '1') return self._node._value!;\n target[0] = self._node._key!;\n target[1] = self._node._value!;\n return target[prop];\n },\n set(_, prop: '1', newValue: V) {\n if (prop !== '1') {\n throw new TypeError('prop must be 1');\n }\n self._node._value = newValue;\n return true;\n }\n });\n }\n copy() {\n return new OrderedMapIterator(\n this._node,\n this._header,\n this.container,\n this.iteratorType\n );\n }\n // @ts-ignore\n equals(iter: OrderedMapIterator): boolean;\n}\n\nexport type { OrderedMapIterator };\n\nclass OrderedMap extends TreeContainer {\n /**\n * @param container - The initialization container.\n * @param cmp - The compare function.\n * @param enableIndex - Whether to enable iterator indexing function.\n * @example\n * new OrderedMap();\n * new OrderedMap([[0, 1], [2, 1]]);\n * new OrderedMap([[0, 1], [2, 1]], (x, y) => x - y);\n * new OrderedMap([[0, 1], [2, 1]], (x, y) => x - y, true);\n */\n constructor(\n container: initContainer<[K, V]> = [],\n cmp?: (x: K, y: K) => number,\n enableIndex?: boolean\n ) {\n super(cmp, enableIndex);\n const self = this;\n container.forEach(function (el) {\n self.setElement(el[0], el[1]);\n });\n }\n begin() {\n return new OrderedMapIterator(this._header._left || this._header, this._header, this);\n }\n end() {\n return new OrderedMapIterator(this._header, this._header, this);\n }\n rBegin() {\n return new OrderedMapIterator(\n this._header._right || this._header,\n this._header,\n this,\n IteratorType.REVERSE\n );\n }\n rEnd() {\n return new OrderedMapIterator(this._header, this._header, this, IteratorType.REVERSE);\n }\n front() {\n if (this._length === 0) return;\n const minNode = this._header._left!;\n return <[K, V]>[minNode._key, minNode._value];\n }\n back() {\n if (this._length === 0) return;\n const maxNode = this._header._right!;\n return <[K, V]>[maxNode._key, maxNode._value];\n }\n lowerBound(key: K) {\n const resNode = this._lowerBound(this._root, key);\n return new OrderedMapIterator(resNode, this._header, this);\n }\n upperBound(key: K) {\n const resNode = this._upperBound(this._root, key);\n return new OrderedMapIterator(resNode, this._header, this);\n }\n reverseLowerBound(key: K) {\n const resNode = this._reverseLowerBound(this._root, key);\n return new OrderedMapIterator(resNode, this._header, this);\n }\n reverseUpperBound(key: K) {\n const resNode = this._reverseUpperBound(this._root, key);\n return new OrderedMapIterator(resNode, this._header, this);\n }\n forEach(callback: (element: [K, V], index: number, map: OrderedMap) => void) {\n this._inOrderTraversal(function (node, index, map) {\n callback(<[K, V]>[node._key, node._value], index, map);\n });\n }\n /**\n * @description Insert a key-value pair or set value by the given key.\n * @param key - The key want to insert.\n * @param value - The value want to set.\n * @param hint - You can give an iterator hint to improve insertion efficiency.\n * @return The size of container after setting.\n * @example\n * const mp = new OrderedMap([[2, 0], [4, 0], [5, 0]]);\n * const iter = mp.begin();\n * mp.setElement(1, 0);\n * mp.setElement(3, 0, iter); // give a hint will be faster.\n */\n setElement(key: K, value: V, hint?: OrderedMapIterator) {\n return this._set(key, value, hint);\n }\n getElementByPos(pos: number) {\n $checkWithinAccessParams!(pos, 0, this._length - 1);\n const node = this._inOrderTraversal(pos);\n return <[K, V]>[node._key, node._value];\n }\n find(key: K) {\n const curNode = this._getTreeNodeByKey(this._root, key);\n return new OrderedMapIterator(curNode, this._header, this);\n }\n /**\n * @description Get the value of the element of the specified key.\n * @param key - The specified key you want to get.\n * @example\n * const val = container.getElementByKey(1);\n */\n getElementByKey(key: K) {\n const curNode = this._getTreeNodeByKey(this._root, key);\n return curNode._value;\n }\n union(other: OrderedMap) {\n const self = this;\n other.forEach(function (el) {\n self.setElement(el[0], el[1]);\n });\n return this._length;\n }\n * [Symbol.iterator]() {\n const length = this._length;\n const nodeList = this._inOrderTraversal();\n for (let i = 0; i < length; ++i) {\n const node = nodeList[i];\n yield <[K, V]>[node._key, node._value];\n }\n }\n // @ts-ignore\n eraseElementByIterator(iter: OrderedMapIterator): OrderedMapIterator;\n}\n\nexport default OrderedMap;\n"]} \ No newline at end of file diff --git a/node_modules/@js-sdsl/ordered-map/dist/umd/ordered-map.js b/node_modules/@js-sdsl/ordered-map/dist/umd/ordered-map.js new file mode 100644 index 0000000..92a2a84 --- /dev/null +++ b/node_modules/@js-sdsl/ordered-map/dist/umd/ordered-map.js @@ -0,0 +1,1157 @@ +/*! + * @js-sdsl/ordered-map v4.4.2 + * https://github.com/js-sdsl/js-sdsl + * (c) 2021-present ZLY201 + * MIT license + */ + +(function (global, factory) { + typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) : + typeof define === 'function' && define.amd ? define(['exports'], factory) : + (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.sdsl = {})); +})(this, (function (exports) { 'use strict'; + + /****************************************************************************** + 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, SuppressedError, Symbol */ + + 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 (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; + }; + return extendStatics(d, b); + }; + function __extends(d, b) { + if (typeof b !== "function" && b !== null) throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); + extendStatics(d, b); + function __() { + this.constructor = d; + } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + } + 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 (g && (g = 0, op[0] && (_ = 0)), _) 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 + }; + } + } + typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) { + var e = new Error(message); + return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e; + }; + + var TreeNode = /** @class */function () { + function TreeNode(key, value, color) { + if (color === void 0) { + color = 1 /* TreeNodeColor.RED */; + } + this._left = undefined; + this._right = undefined; + this._parent = undefined; + this._key = key; + this._value = value; + this._color = color; + } + /** + * @description Get the pre node. + * @returns TreeNode about the pre node. + */ + TreeNode.prototype._pre = function () { + var preNode = this; + var isRootOrHeader = preNode._parent._parent === preNode; + if (isRootOrHeader && preNode._color === 1 /* TreeNodeColor.RED */) { + preNode = preNode._right; + } else if (preNode._left) { + preNode = preNode._left; + while (preNode._right) { + preNode = preNode._right; + } + } else { + // Must be root and left is null + if (isRootOrHeader) { + return preNode._parent; + } + var pre = preNode._parent; + while (pre._left === preNode) { + preNode = pre; + pre = preNode._parent; + } + preNode = pre; + } + return preNode; + }; + /** + * @description Get the next node. + * @returns TreeNode about the next node. + */ + TreeNode.prototype._next = function () { + var nextNode = this; + if (nextNode._right) { + nextNode = nextNode._right; + while (nextNode._left) { + nextNode = nextNode._left; + } + return nextNode; + } else { + var pre = nextNode._parent; + while (pre._right === nextNode) { + nextNode = pre; + pre = nextNode._parent; + } + if (nextNode._right !== pre) { + return pre; + } else return nextNode; + } + }; + /** + * @description Rotate left. + * @returns TreeNode about moved to original position after rotation. + */ + TreeNode.prototype._rotateLeft = function () { + var PP = this._parent; + var V = this._right; + var R = V._left; + if (PP._parent === this) PP._parent = V;else if (PP._left === this) PP._left = V;else PP._right = V; + V._parent = PP; + V._left = this; + this._parent = V; + this._right = R; + if (R) R._parent = this; + return V; + }; + /** + * @description Rotate right. + * @returns TreeNode about moved to original position after rotation. + */ + TreeNode.prototype._rotateRight = function () { + var PP = this._parent; + var F = this._left; + var K = F._right; + if (PP._parent === this) PP._parent = F;else if (PP._left === this) PP._left = F;else PP._right = F; + F._parent = PP; + F._right = this; + this._parent = F; + this._left = K; + if (K) K._parent = this; + return F; + }; + return TreeNode; + }(); + var TreeNodeEnableIndex = /** @class */function (_super) { + __extends(TreeNodeEnableIndex, _super); + function TreeNodeEnableIndex() { + var _this = _super !== null && _super.apply(this, arguments) || this; + _this._subTreeSize = 1; + return _this; + } + /** + * @description Rotate left and do recount. + * @returns TreeNode about moved to original position after rotation. + */ + TreeNodeEnableIndex.prototype._rotateLeft = function () { + var parent = _super.prototype._rotateLeft.call(this); + this._recount(); + parent._recount(); + return parent; + }; + /** + * @description Rotate right and do recount. + * @returns TreeNode about moved to original position after rotation. + */ + TreeNodeEnableIndex.prototype._rotateRight = function () { + var parent = _super.prototype._rotateRight.call(this); + this._recount(); + parent._recount(); + return parent; + }; + TreeNodeEnableIndex.prototype._recount = function () { + this._subTreeSize = 1; + if (this._left) { + this._subTreeSize += this._left._subTreeSize; + } + if (this._right) { + this._subTreeSize += this._right._subTreeSize; + } + }; + return TreeNodeEnableIndex; + }(TreeNode); + + var ContainerIterator = /** @class */function () { + /** + * @internal + */ + function ContainerIterator(iteratorType) { + if (iteratorType === void 0) { + iteratorType = 0 /* IteratorType.NORMAL */; + } + this.iteratorType = iteratorType; + } + /** + * @param iter - The other iterator you want to compare. + * @returns Whether this equals to obj. + * @example + * container.find(1).equals(container.end()); + */ + ContainerIterator.prototype.equals = function (iter) { + return this._node === iter._node; + }; + return ContainerIterator; + }(); + var Base = /** @class */function () { + function Base() { + /** + * @description Container's size. + * @internal + */ + this._length = 0; + } + Object.defineProperty(Base.prototype, "length", { + /** + * @returns The size of the container. + * @example + * const container = new Vector([1, 2]); + * console.log(container.length); // 2 + */ + get: function () { + return this._length; + }, + enumerable: false, + configurable: true + }); + /** + * @returns The size of the container. + * @example + * const container = new Vector([1, 2]); + * console.log(container.size()); // 2 + */ + Base.prototype.size = function () { + return this._length; + }; + /** + * @returns Whether the container is empty. + * @example + * container.clear(); + * console.log(container.empty()); // true + */ + Base.prototype.empty = function () { + return this._length === 0; + }; + return Base; + }(); + var Container = /** @class */function (_super) { + __extends(Container, _super); + function Container() { + return _super !== null && _super.apply(this, arguments) || this; + } + return Container; + }(Base); + + /** + * @description Throw an iterator access error. + * @internal + */ + function throwIteratorAccessError() { + throw new RangeError('Iterator access denied!'); + } + + var TreeContainer = /** @class */function (_super) { + __extends(TreeContainer, _super); + /** + * @internal + */ + function TreeContainer(cmp, enableIndex) { + if (cmp === void 0) { + cmp = function (x, y) { + if (x < y) return -1; + if (x > y) return 1; + return 0; + }; + } + if (enableIndex === void 0) { + enableIndex = false; + } + var _this = _super.call(this) || this; + /** + * @internal + */ + _this._root = undefined; + _this._cmp = cmp; + _this.enableIndex = enableIndex; + _this._TreeNodeClass = enableIndex ? TreeNodeEnableIndex : TreeNode; + _this._header = new _this._TreeNodeClass(); + return _this; + } + /** + * @internal + */ + TreeContainer.prototype._lowerBound = function (curNode, key) { + var resNode = this._header; + while (curNode) { + var cmpResult = this._cmp(curNode._key, key); + if (cmpResult < 0) { + curNode = curNode._right; + } else if (cmpResult > 0) { + resNode = curNode; + curNode = curNode._left; + } else return curNode; + } + return resNode; + }; + /** + * @internal + */ + TreeContainer.prototype._upperBound = function (curNode, key) { + var resNode = this._header; + while (curNode) { + var cmpResult = this._cmp(curNode._key, key); + if (cmpResult <= 0) { + curNode = curNode._right; + } else { + resNode = curNode; + curNode = curNode._left; + } + } + return resNode; + }; + /** + * @internal + */ + TreeContainer.prototype._reverseLowerBound = function (curNode, key) { + var resNode = this._header; + while (curNode) { + var cmpResult = this._cmp(curNode._key, key); + if (cmpResult < 0) { + resNode = curNode; + curNode = curNode._right; + } else if (cmpResult > 0) { + curNode = curNode._left; + } else return curNode; + } + return resNode; + }; + /** + * @internal + */ + TreeContainer.prototype._reverseUpperBound = function (curNode, key) { + var resNode = this._header; + while (curNode) { + var cmpResult = this._cmp(curNode._key, key); + if (cmpResult < 0) { + resNode = curNode; + curNode = curNode._right; + } else { + curNode = curNode._left; + } + } + return resNode; + }; + /** + * @internal + */ + TreeContainer.prototype._eraseNodeSelfBalance = function (curNode) { + while (true) { + var parentNode = curNode._parent; + if (parentNode === this._header) return; + if (curNode._color === 1 /* TreeNodeColor.RED */) { + curNode._color = 0 /* TreeNodeColor.BLACK */; + return; + } + if (curNode === parentNode._left) { + var brother = parentNode._right; + if (brother._color === 1 /* TreeNodeColor.RED */) { + brother._color = 0 /* TreeNodeColor.BLACK */; + parentNode._color = 1 /* TreeNodeColor.RED */; + if (parentNode === this._root) { + this._root = parentNode._rotateLeft(); + } else parentNode._rotateLeft(); + } else { + if (brother._right && brother._right._color === 1 /* TreeNodeColor.RED */) { + brother._color = parentNode._color; + parentNode._color = 0 /* TreeNodeColor.BLACK */; + brother._right._color = 0 /* TreeNodeColor.BLACK */; + if (parentNode === this._root) { + this._root = parentNode._rotateLeft(); + } else parentNode._rotateLeft(); + return; + } else if (brother._left && brother._left._color === 1 /* TreeNodeColor.RED */) { + brother._color = 1 /* TreeNodeColor.RED */; + brother._left._color = 0 /* TreeNodeColor.BLACK */; + brother._rotateRight(); + } else { + brother._color = 1 /* TreeNodeColor.RED */; + curNode = parentNode; + } + } + } else { + var brother = parentNode._left; + if (brother._color === 1 /* TreeNodeColor.RED */) { + brother._color = 0 /* TreeNodeColor.BLACK */; + parentNode._color = 1 /* TreeNodeColor.RED */; + if (parentNode === this._root) { + this._root = parentNode._rotateRight(); + } else parentNode._rotateRight(); + } else { + if (brother._left && brother._left._color === 1 /* TreeNodeColor.RED */) { + brother._color = parentNode._color; + parentNode._color = 0 /* TreeNodeColor.BLACK */; + brother._left._color = 0 /* TreeNodeColor.BLACK */; + if (parentNode === this._root) { + this._root = parentNode._rotateRight(); + } else parentNode._rotateRight(); + return; + } else if (brother._right && brother._right._color === 1 /* TreeNodeColor.RED */) { + brother._color = 1 /* TreeNodeColor.RED */; + brother._right._color = 0 /* TreeNodeColor.BLACK */; + brother._rotateLeft(); + } else { + brother._color = 1 /* TreeNodeColor.RED */; + curNode = parentNode; + } + } + } + } + }; + /** + * @internal + */ + TreeContainer.prototype._eraseNode = function (curNode) { + if (this._length === 1) { + this.clear(); + return; + } + var swapNode = curNode; + while (swapNode._left || swapNode._right) { + if (swapNode._right) { + swapNode = swapNode._right; + while (swapNode._left) swapNode = swapNode._left; + } else { + swapNode = swapNode._left; + } + var key = curNode._key; + curNode._key = swapNode._key; + swapNode._key = key; + var value = curNode._value; + curNode._value = swapNode._value; + swapNode._value = value; + curNode = swapNode; + } + if (this._header._left === swapNode) { + this._header._left = swapNode._parent; + } else if (this._header._right === swapNode) { + this._header._right = swapNode._parent; + } + this._eraseNodeSelfBalance(swapNode); + var _parent = swapNode._parent; + if (swapNode === _parent._left) { + _parent._left = undefined; + } else _parent._right = undefined; + this._length -= 1; + this._root._color = 0 /* TreeNodeColor.BLACK */; + if (this.enableIndex) { + while (_parent !== this._header) { + _parent._subTreeSize -= 1; + _parent = _parent._parent; + } + } + }; + /** + * @internal + */ + TreeContainer.prototype._inOrderTraversal = function (param) { + var pos = typeof param === 'number' ? param : undefined; + var callback = typeof param === 'function' ? param : undefined; + var nodeList = typeof param === 'undefined' ? [] : undefined; + var index = 0; + var curNode = this._root; + var stack = []; + while (stack.length || curNode) { + if (curNode) { + stack.push(curNode); + curNode = curNode._left; + } else { + curNode = stack.pop(); + if (index === pos) return curNode; + nodeList && nodeList.push(curNode); + callback && callback(curNode, index, this); + index += 1; + curNode = curNode._right; + } + } + return nodeList; + }; + /** + * @internal + */ + TreeContainer.prototype._insertNodeSelfBalance = function (curNode) { + while (true) { + var parentNode = curNode._parent; + if (parentNode._color === 0 /* TreeNodeColor.BLACK */) return; + var grandParent = parentNode._parent; + if (parentNode === grandParent._left) { + var uncle = grandParent._right; + if (uncle && uncle._color === 1 /* TreeNodeColor.RED */) { + uncle._color = parentNode._color = 0 /* TreeNodeColor.BLACK */; + if (grandParent === this._root) return; + grandParent._color = 1 /* TreeNodeColor.RED */; + curNode = grandParent; + continue; + } else if (curNode === parentNode._right) { + curNode._color = 0 /* TreeNodeColor.BLACK */; + if (curNode._left) { + curNode._left._parent = parentNode; + } + if (curNode._right) { + curNode._right._parent = grandParent; + } + parentNode._right = curNode._left; + grandParent._left = curNode._right; + curNode._left = parentNode; + curNode._right = grandParent; + if (grandParent === this._root) { + this._root = curNode; + this._header._parent = curNode; + } else { + var GP = grandParent._parent; + if (GP._left === grandParent) { + GP._left = curNode; + } else GP._right = curNode; + } + curNode._parent = grandParent._parent; + parentNode._parent = curNode; + grandParent._parent = curNode; + grandParent._color = 1 /* TreeNodeColor.RED */; + } else { + parentNode._color = 0 /* TreeNodeColor.BLACK */; + if (grandParent === this._root) { + this._root = grandParent._rotateRight(); + } else grandParent._rotateRight(); + grandParent._color = 1 /* TreeNodeColor.RED */; + return; + } + } else { + var uncle = grandParent._left; + if (uncle && uncle._color === 1 /* TreeNodeColor.RED */) { + uncle._color = parentNode._color = 0 /* TreeNodeColor.BLACK */; + if (grandParent === this._root) return; + grandParent._color = 1 /* TreeNodeColor.RED */; + curNode = grandParent; + continue; + } else if (curNode === parentNode._left) { + curNode._color = 0 /* TreeNodeColor.BLACK */; + if (curNode._left) { + curNode._left._parent = grandParent; + } + if (curNode._right) { + curNode._right._parent = parentNode; + } + grandParent._right = curNode._left; + parentNode._left = curNode._right; + curNode._left = grandParent; + curNode._right = parentNode; + if (grandParent === this._root) { + this._root = curNode; + this._header._parent = curNode; + } else { + var GP = grandParent._parent; + if (GP._left === grandParent) { + GP._left = curNode; + } else GP._right = curNode; + } + curNode._parent = grandParent._parent; + parentNode._parent = curNode; + grandParent._parent = curNode; + grandParent._color = 1 /* TreeNodeColor.RED */; + } else { + parentNode._color = 0 /* TreeNodeColor.BLACK */; + if (grandParent === this._root) { + this._root = grandParent._rotateLeft(); + } else grandParent._rotateLeft(); + grandParent._color = 1 /* TreeNodeColor.RED */; + return; + } + } + if (this.enableIndex) { + parentNode._recount(); + grandParent._recount(); + curNode._recount(); + } + return; + } + }; + /** + * @internal + */ + TreeContainer.prototype._set = function (key, value, hint) { + if (this._root === undefined) { + this._length += 1; + this._root = new this._TreeNodeClass(key, value, 0 /* TreeNodeColor.BLACK */); + this._root._parent = this._header; + this._header._parent = this._header._left = this._header._right = this._root; + return this._length; + } + var curNode; + var minNode = this._header._left; + var compareToMin = this._cmp(minNode._key, key); + if (compareToMin === 0) { + minNode._value = value; + return this._length; + } else if (compareToMin > 0) { + minNode._left = new this._TreeNodeClass(key, value); + minNode._left._parent = minNode; + curNode = minNode._left; + this._header._left = curNode; + } else { + var maxNode = this._header._right; + var compareToMax = this._cmp(maxNode._key, key); + if (compareToMax === 0) { + maxNode._value = value; + return this._length; + } else if (compareToMax < 0) { + maxNode._right = new this._TreeNodeClass(key, value); + maxNode._right._parent = maxNode; + curNode = maxNode._right; + this._header._right = curNode; + } else { + if (hint !== undefined) { + var iterNode = hint._node; + if (iterNode !== this._header) { + var iterCmpRes = this._cmp(iterNode._key, key); + if (iterCmpRes === 0) { + iterNode._value = value; + return this._length; + } else /* istanbul ignore else */if (iterCmpRes > 0) { + var preNode = iterNode._pre(); + var preCmpRes = this._cmp(preNode._key, key); + if (preCmpRes === 0) { + preNode._value = value; + return this._length; + } else if (preCmpRes < 0) { + curNode = new this._TreeNodeClass(key, value); + if (preNode._right === undefined) { + preNode._right = curNode; + curNode._parent = preNode; + } else { + iterNode._left = curNode; + curNode._parent = iterNode; + } + } + } + } + } + if (curNode === undefined) { + curNode = this._root; + while (true) { + var cmpResult = this._cmp(curNode._key, key); + if (cmpResult > 0) { + if (curNode._left === undefined) { + curNode._left = new this._TreeNodeClass(key, value); + curNode._left._parent = curNode; + curNode = curNode._left; + break; + } + curNode = curNode._left; + } else if (cmpResult < 0) { + if (curNode._right === undefined) { + curNode._right = new this._TreeNodeClass(key, value); + curNode._right._parent = curNode; + curNode = curNode._right; + break; + } + curNode = curNode._right; + } else { + curNode._value = value; + return this._length; + } + } + } + } + } + if (this.enableIndex) { + var parent_1 = curNode._parent; + while (parent_1 !== this._header) { + parent_1._subTreeSize += 1; + parent_1 = parent_1._parent; + } + } + this._insertNodeSelfBalance(curNode); + this._length += 1; + return this._length; + }; + /** + * @internal + */ + TreeContainer.prototype._getTreeNodeByKey = function (curNode, key) { + while (curNode) { + var cmpResult = this._cmp(curNode._key, key); + if (cmpResult < 0) { + curNode = curNode._right; + } else if (cmpResult > 0) { + curNode = curNode._left; + } else return curNode; + } + return curNode || this._header; + }; + TreeContainer.prototype.clear = function () { + this._length = 0; + this._root = undefined; + this._header._parent = undefined; + this._header._left = this._header._right = undefined; + }; + /** + * @description Update node's key by iterator. + * @param iter - The iterator you want to change. + * @param key - The key you want to update. + * @returns Whether the modification is successful. + * @example + * const st = new orderedSet([1, 2, 5]); + * const iter = st.find(2); + * st.updateKeyByIterator(iter, 3); // then st will become [1, 3, 5] + */ + TreeContainer.prototype.updateKeyByIterator = function (iter, key) { + var node = iter._node; + if (node === this._header) { + throwIteratorAccessError(); + } + if (this._length === 1) { + node._key = key; + return true; + } + var nextKey = node._next()._key; + if (node === this._header._left) { + if (this._cmp(nextKey, key) > 0) { + node._key = key; + return true; + } + return false; + } + var preKey = node._pre()._key; + if (node === this._header._right) { + if (this._cmp(preKey, key) < 0) { + node._key = key; + return true; + } + return false; + } + if (this._cmp(preKey, key) >= 0 || this._cmp(nextKey, key) <= 0) return false; + node._key = key; + return true; + }; + TreeContainer.prototype.eraseElementByPos = function (pos) { + if (pos < 0 || pos > this._length - 1) { + throw new RangeError(); + } + var node = this._inOrderTraversal(pos); + this._eraseNode(node); + return this._length; + }; + /** + * @description Remove the element of the specified key. + * @param key - The key you want to remove. + * @returns Whether erase successfully. + */ + TreeContainer.prototype.eraseElementByKey = function (key) { + if (this._length === 0) return false; + var curNode = this._getTreeNodeByKey(this._root, key); + if (curNode === this._header) return false; + this._eraseNode(curNode); + return true; + }; + TreeContainer.prototype.eraseElementByIterator = function (iter) { + var node = iter._node; + if (node === this._header) { + throwIteratorAccessError(); + } + var hasNoRight = node._right === undefined; + var isNormal = iter.iteratorType === 0 /* IteratorType.NORMAL */; + // For the normal iterator, the `next` node will be swapped to `this` node when has right. + if (isNormal) { + // So we should move it to next when it's right is null. + if (hasNoRight) iter.next(); + } else { + // For the reverse iterator, only when it doesn't have right and has left the `next` node will be swapped. + // So when it has right, or it is a leaf node we should move it to `next`. + if (!hasNoRight || node._left === undefined) iter.next(); + } + this._eraseNode(node); + return iter; + }; + /** + * @description Get the height of the tree. + * @returns Number about the height of the RB-tree. + */ + TreeContainer.prototype.getHeight = function () { + if (this._length === 0) return 0; + function traversal(curNode) { + if (!curNode) return 0; + return Math.max(traversal(curNode._left), traversal(curNode._right)) + 1; + } + return traversal(this._root); + }; + return TreeContainer; + }(Container); + + var TreeIterator = /** @class */function (_super) { + __extends(TreeIterator, _super); + /** + * @internal + */ + function TreeIterator(node, header, iteratorType) { + var _this = _super.call(this, iteratorType) || this; + _this._node = node; + _this._header = header; + if (_this.iteratorType === 0 /* IteratorType.NORMAL */) { + _this.pre = function () { + if (this._node === this._header._left) { + throwIteratorAccessError(); + } + this._node = this._node._pre(); + return this; + }; + _this.next = function () { + if (this._node === this._header) { + throwIteratorAccessError(); + } + this._node = this._node._next(); + return this; + }; + } else { + _this.pre = function () { + if (this._node === this._header._right) { + throwIteratorAccessError(); + } + this._node = this._node._next(); + return this; + }; + _this.next = function () { + if (this._node === this._header) { + throwIteratorAccessError(); + } + this._node = this._node._pre(); + return this; + }; + } + return _this; + } + Object.defineProperty(TreeIterator.prototype, "index", { + /** + * @description Get the sequential index of the iterator in the tree container.
+ * Note: + * This function only takes effect when the specified tree container `enableIndex = true`. + * @returns The index subscript of the node in the tree. + * @example + * const st = new OrderedSet([1, 2, 3], true); + * console.log(st.begin().next().index); // 1 + */ + get: function () { + var _node = this._node; + var root = this._header._parent; + if (_node === this._header) { + if (root) { + return root._subTreeSize - 1; + } + return 0; + } + var index = 0; + if (_node._left) { + index += _node._left._subTreeSize; + } + while (_node !== root) { + var _parent = _node._parent; + if (_node === _parent._right) { + index += 1; + if (_parent._left) { + index += _parent._left._subTreeSize; + } + } + _node = _parent; + } + return index; + }, + enumerable: false, + configurable: true + }); + TreeIterator.prototype.isAccessible = function () { + return this._node !== this._header; + }; + return TreeIterator; + }(ContainerIterator); + + var OrderedMapIterator = /** @class */function (_super) { + __extends(OrderedMapIterator, _super); + function OrderedMapIterator(node, header, container, iteratorType) { + var _this = _super.call(this, node, header, iteratorType) || this; + _this.container = container; + return _this; + } + Object.defineProperty(OrderedMapIterator.prototype, "pointer", { + get: function () { + if (this._node === this._header) { + throwIteratorAccessError(); + } + var self = this; + return new Proxy([], { + get: function (target, prop) { + if (prop === '0') return self._node._key;else if (prop === '1') return self._node._value; + target[0] = self._node._key; + target[1] = self._node._value; + return target[prop]; + }, + set: function (_, prop, newValue) { + if (prop !== '1') { + throw new TypeError('prop must be 1'); + } + self._node._value = newValue; + return true; + } + }); + }, + enumerable: false, + configurable: true + }); + OrderedMapIterator.prototype.copy = function () { + return new OrderedMapIterator(this._node, this._header, this.container, this.iteratorType); + }; + return OrderedMapIterator; + }(TreeIterator); + var OrderedMap = /** @class */function (_super) { + __extends(OrderedMap, _super); + /** + * @param container - The initialization container. + * @param cmp - The compare function. + * @param enableIndex - Whether to enable iterator indexing function. + * @example + * new OrderedMap(); + * new OrderedMap([[0, 1], [2, 1]]); + * new OrderedMap([[0, 1], [2, 1]], (x, y) => x - y); + * new OrderedMap([[0, 1], [2, 1]], (x, y) => x - y, true); + */ + function OrderedMap(container, cmp, enableIndex) { + if (container === void 0) { + container = []; + } + var _this = _super.call(this, cmp, enableIndex) || this; + var self = _this; + container.forEach(function (el) { + self.setElement(el[0], el[1]); + }); + return _this; + } + OrderedMap.prototype.begin = function () { + return new OrderedMapIterator(this._header._left || this._header, this._header, this); + }; + OrderedMap.prototype.end = function () { + return new OrderedMapIterator(this._header, this._header, this); + }; + OrderedMap.prototype.rBegin = function () { + return new OrderedMapIterator(this._header._right || this._header, this._header, this, 1 /* IteratorType.REVERSE */); + }; + + OrderedMap.prototype.rEnd = function () { + return new OrderedMapIterator(this._header, this._header, this, 1 /* IteratorType.REVERSE */); + }; + + OrderedMap.prototype.front = function () { + if (this._length === 0) return; + var minNode = this._header._left; + return [minNode._key, minNode._value]; + }; + OrderedMap.prototype.back = function () { + if (this._length === 0) return; + var maxNode = this._header._right; + return [maxNode._key, maxNode._value]; + }; + OrderedMap.prototype.lowerBound = function (key) { + var resNode = this._lowerBound(this._root, key); + return new OrderedMapIterator(resNode, this._header, this); + }; + OrderedMap.prototype.upperBound = function (key) { + var resNode = this._upperBound(this._root, key); + return new OrderedMapIterator(resNode, this._header, this); + }; + OrderedMap.prototype.reverseLowerBound = function (key) { + var resNode = this._reverseLowerBound(this._root, key); + return new OrderedMapIterator(resNode, this._header, this); + }; + OrderedMap.prototype.reverseUpperBound = function (key) { + var resNode = this._reverseUpperBound(this._root, key); + return new OrderedMapIterator(resNode, this._header, this); + }; + OrderedMap.prototype.forEach = function (callback) { + this._inOrderTraversal(function (node, index, map) { + callback([node._key, node._value], index, map); + }); + }; + /** + * @description Insert a key-value pair or set value by the given key. + * @param key - The key want to insert. + * @param value - The value want to set. + * @param hint - You can give an iterator hint to improve insertion efficiency. + * @return The size of container after setting. + * @example + * const mp = new OrderedMap([[2, 0], [4, 0], [5, 0]]); + * const iter = mp.begin(); + * mp.setElement(1, 0); + * mp.setElement(3, 0, iter); // give a hint will be faster. + */ + OrderedMap.prototype.setElement = function (key, value, hint) { + return this._set(key, value, hint); + }; + OrderedMap.prototype.getElementByPos = function (pos) { + if (pos < 0 || pos > this._length - 1) { + throw new RangeError(); + } + var node = this._inOrderTraversal(pos); + return [node._key, node._value]; + }; + OrderedMap.prototype.find = function (key) { + var curNode = this._getTreeNodeByKey(this._root, key); + return new OrderedMapIterator(curNode, this._header, this); + }; + /** + * @description Get the value of the element of the specified key. + * @param key - The specified key you want to get. + * @example + * const val = container.getElementByKey(1); + */ + OrderedMap.prototype.getElementByKey = function (key) { + var curNode = this._getTreeNodeByKey(this._root, key); + return curNode._value; + }; + OrderedMap.prototype.union = function (other) { + var self = this; + other.forEach(function (el) { + self.setElement(el[0], el[1]); + }); + return this._length; + }; + OrderedMap.prototype[Symbol.iterator] = function () { + var length, nodeList, i, node; + return __generator(this, function (_a) { + switch (_a.label) { + case 0: + length = this._length; + nodeList = this._inOrderTraversal(); + i = 0; + _a.label = 1; + case 1: + if (!(i < length)) return [3 /*break*/, 4]; + node = nodeList[i]; + return [4 /*yield*/, [node._key, node._value]]; + case 2: + _a.sent(); + _a.label = 3; + case 3: + ++i; + return [3 /*break*/, 1]; + case 4: + return [2 /*return*/]; + } + }); + }; + + return OrderedMap; + }(TreeContainer); + + exports.OrderedMap = OrderedMap; + + Object.defineProperty(exports, '__esModule', { value: true }); + +})); diff --git a/node_modules/@js-sdsl/ordered-map/dist/umd/ordered-map.min.js b/node_modules/@js-sdsl/ordered-map/dist/umd/ordered-map.min.js new file mode 100644 index 0000000..3c9dbf4 --- /dev/null +++ b/node_modules/@js-sdsl/ordered-map/dist/umd/ordered-map.min.js @@ -0,0 +1,8 @@ +/*! + * @js-sdsl/ordered-map v4.4.2 + * https://github.com/js-sdsl/js-sdsl + * (c) 2021-present ZLY201 + * MIT license + */ +!function(t,i){"object"==typeof exports&&"undefined"!=typeof module?i(exports):"function"==typeof define&&define.amd?define(["exports"],i):i((t="undefined"!=typeof globalThis?globalThis:t||self).sdsl={})}(this,function(t){"use strict";var r=function(t,i){return(r=Object.setPrototypeOf||({__proto__:[]}instanceof Array?function(t,i){t.__proto__=i}:function(t,i){for(var e in i)Object.prototype.hasOwnProperty.call(i,e)&&(t[e]=i[e])}))(t,i)};function i(t,i){if("function"!=typeof i&&null!==i)throw new TypeError("Class extends value "+String(i)+" is not a constructor or null");function e(){this.constructor=t}r(t,i),t.prototype=null===i?Object.create(i):(e.prototype=i.prototype,new e)}function o(r,n){var o,s,h,u={label:0,sent:function(){if(1&h[0])throw h[1];return h[1]},trys:[],ops:[]},f={next:t(0),throw:t(1),return:t(2)};return"function"==typeof Symbol&&(f[Symbol.iterator]=function(){return this}),f;function t(e){return function(t){var i=[e,t];if(o)throw new TypeError("Generator is already executing.");for(;u=f&&i[f=0]?0:u;)try{if(o=1,s&&(h=2&i[0]?s.return:i[0]?s.throw||((h=s.return)&&h.call(s),0):s.next)&&!(h=h.call(s,i[1])).done)return h;switch(s=0,(i=h?[2&i[0],h.value]:i)[0]){case 0:case 1:h=i;break;case 4:return u.label++,{value:i[1],done:!1};case 5:u.label++,s=i[1],i=[0];continue;case 7:i=u.ops.pop(),u.trys.pop();continue;default:if(!(h=0<(h=u.trys).length&&h[h.length-1])&&(6===i[0]||2===i[0])){u=0;continue}if(3===i[0]&&(!h||i[1]>h[0]&&i[1]this.C-1)throw new RangeError;t=this.P(t);return this.G(t),this.C},A.prototype.eraseElementByKey=function(t){return 0!==this.C&&(t=this.F(this.g,t))!==this.A&&(this.G(t),!0)},A.prototype.eraseElementByIterator=function(t){var i=t.M,e=(i===this.A&&v(),void 0===i.i);return 0===t.iteratorType?e&&t.next():e&&void 0!==i.t||t.next(),this.G(i),t},A.prototype.getHeight=function(){return 0===this.C?0:function t(i){return i?Math.max(t(i.t),t(i.i))+1:0}(this.g)};var d,a=A;function A(t,i){void 0===t&&(t=function(t,i){return tthis.C-1)throw new RangeError;t=this.P(t);return[t.h,t.o]},O.prototype.find=function(t){t=this.F(this.g,t);return new M(t,this.A,this)},O.prototype.getElementByKey=function(t){return this.F(this.g,t).o},O.prototype.union=function(t){var i=this;return t.forEach(function(t){i.setElement(t[0],t[1])}),this.C},O.prototype[Symbol.iterator]=function(){var i,e,r,n;return o(this,function(t){switch(t.label){case 0:i=this.C,e=this.P(),r=0,t.label=1;case 1:return r`**
+ Returns a promise from a node-style callback function. + +**License:** [BSD 3-Clause License](https://opensource.org/licenses/BSD-3-Clause) diff --git a/node_modules/@protobufjs/aspromise/index.d.ts b/node_modules/@protobufjs/aspromise/index.d.ts new file mode 100644 index 0000000..afbd89a --- /dev/null +++ b/node_modules/@protobufjs/aspromise/index.d.ts @@ -0,0 +1,13 @@ +export = asPromise; + +type asPromiseCallback = (error: Error | null, ...params: any[]) => {}; + +/** + * Returns a promise from a node-style callback function. + * @memberof util + * @param {asPromiseCallback} fn Function to call + * @param {*} ctx Function context + * @param {...*} params Function arguments + * @returns {Promise<*>} Promisified function + */ +declare function asPromise(fn: asPromiseCallback, ctx: any, ...params: any[]): Promise; diff --git a/node_modules/@protobufjs/aspromise/index.js b/node_modules/@protobufjs/aspromise/index.js new file mode 100644 index 0000000..b10f826 --- /dev/null +++ b/node_modules/@protobufjs/aspromise/index.js @@ -0,0 +1,52 @@ +"use strict"; +module.exports = asPromise; + +/** + * Callback as used by {@link util.asPromise}. + * @typedef asPromiseCallback + * @type {function} + * @param {Error|null} error Error, if any + * @param {...*} params Additional arguments + * @returns {undefined} + */ + +/** + * Returns a promise from a node-style callback function. + * @memberof util + * @param {asPromiseCallback} fn Function to call + * @param {*} ctx Function context + * @param {...*} params Function arguments + * @returns {Promise<*>} Promisified function + */ +function asPromise(fn, ctx/*, varargs */) { + var params = new Array(arguments.length - 1), + offset = 0, + index = 2, + pending = true; + while (index < arguments.length) + params[offset++] = arguments[index++]; + return new Promise(function executor(resolve, reject) { + params[offset] = function callback(err/*, varargs */) { + if (pending) { + pending = false; + if (err) + reject(err); + else { + var params = new Array(arguments.length - 1), + offset = 0; + while (offset < params.length) + params[offset++] = arguments[offset]; + resolve.apply(null, params); + } + } + }; + try { + fn.apply(ctx || null, params); + } catch (err) { + if (pending) { + pending = false; + reject(err); + } + } + }); +} diff --git a/node_modules/@protobufjs/aspromise/package.json b/node_modules/@protobufjs/aspromise/package.json new file mode 100644 index 0000000..2d7e503 --- /dev/null +++ b/node_modules/@protobufjs/aspromise/package.json @@ -0,0 +1,21 @@ +{ + "name": "@protobufjs/aspromise", + "description": "Returns a promise from a node-style callback function.", + "version": "1.1.2", + "author": "Daniel Wirtz ", + "repository": { + "type": "git", + "url": "https://github.com/dcodeIO/protobuf.js.git" + }, + "license": "BSD-3-Clause", + "main": "index.js", + "types": "index.d.ts", + "devDependencies": { + "istanbul": "^0.4.5", + "tape": "^4.6.3" + }, + "scripts": { + "test": "tape tests/*.js", + "coverage": "istanbul cover node_modules/tape/bin/tape tests/*.js" + } +} \ No newline at end of file diff --git a/node_modules/@protobufjs/aspromise/tests/index.js b/node_modules/@protobufjs/aspromise/tests/index.js new file mode 100644 index 0000000..6d8d24c --- /dev/null +++ b/node_modules/@protobufjs/aspromise/tests/index.js @@ -0,0 +1,130 @@ +var tape = require("tape"); + +var asPromise = require(".."); + +tape.test("aspromise", function(test) { + + test.test(this.name + " - resolve", function(test) { + + function fn(arg1, arg2, callback) { + test.equal(this, ctx, "function should be called with this = ctx"); + test.equal(arg1, 1, "function should be called with arg1 = 1"); + test.equal(arg2, 2, "function should be called with arg2 = 2"); + callback(null, arg2); + } + + var ctx = {}; + + var promise = asPromise(fn, ctx, 1, 2); + promise.then(function(arg2) { + test.equal(arg2, 2, "promise should be resolved with arg2 = 2"); + test.end(); + }).catch(function(err) { + test.fail("promise should not be rejected (" + err + ")"); + }); + }); + + test.test(this.name + " - reject", function(test) { + + function fn(arg1, arg2, callback) { + test.equal(this, ctx, "function should be called with this = ctx"); + test.equal(arg1, 1, "function should be called with arg1 = 1"); + test.equal(arg2, 2, "function should be called with arg2 = 2"); + callback(arg1); + } + + var ctx = {}; + + var promise = asPromise(fn, ctx, 1, 2); + promise.then(function() { + test.fail("promise should not be resolved"); + }).catch(function(err) { + test.equal(err, 1, "promise should be rejected with err = 1"); + test.end(); + }); + }); + + test.test(this.name + " - resolve twice", function(test) { + + function fn(arg1, arg2, callback) { + test.equal(this, ctx, "function should be called with this = ctx"); + test.equal(arg1, 1, "function should be called with arg1 = 1"); + test.equal(arg2, 2, "function should be called with arg2 = 2"); + callback(null, arg2); + callback(null, arg1); + } + + var ctx = {}; + var count = 0; + + var promise = asPromise(fn, ctx, 1, 2); + promise.then(function(arg2) { + test.equal(arg2, 2, "promise should be resolved with arg2 = 2"); + if (++count > 1) + test.fail("promise should not be resolved twice"); + test.end(); + }).catch(function(err) { + test.fail("promise should not be rejected (" + err + ")"); + }); + }); + + test.test(this.name + " - reject twice", function(test) { + + function fn(arg1, arg2, callback) { + test.equal(this, ctx, "function should be called with this = ctx"); + test.equal(arg1, 1, "function should be called with arg1 = 1"); + test.equal(arg2, 2, "function should be called with arg2 = 2"); + callback(arg1); + callback(arg2); + } + + var ctx = {}; + var count = 0; + + var promise = asPromise(fn, ctx, 1, 2); + promise.then(function() { + test.fail("promise should not be resolved"); + }).catch(function(err) { + test.equal(err, 1, "promise should be rejected with err = 1"); + if (++count > 1) + test.fail("promise should not be rejected twice"); + test.end(); + }); + }); + + test.test(this.name + " - reject error", function(test) { + + function fn(callback) { + test.ok(arguments.length === 1 && typeof callback === "function", "function should be called with just a callback"); + throw 3; + } + + var promise = asPromise(fn, null); + promise.then(function() { + test.fail("promise should not be resolved"); + }).catch(function(err) { + test.equal(err, 3, "promise should be rejected with err = 3"); + test.end(); + }); + }); + + test.test(this.name + " - reject and error", function(test) { + + function fn(callback) { + callback(3); + throw 4; + } + + var count = 0; + + var promise = asPromise(fn, null); + promise.then(function() { + test.fail("promise should not be resolved"); + }).catch(function(err) { + test.equal(err, 3, "promise should be rejected with err = 3"); + if (++count > 1) + test.fail("promise should not be rejected twice"); + test.end(); + }); + }); +}); diff --git a/node_modules/@protobufjs/base64/LICENSE b/node_modules/@protobufjs/base64/LICENSE new file mode 100644 index 0000000..2a2d560 --- /dev/null +++ b/node_modules/@protobufjs/base64/LICENSE @@ -0,0 +1,26 @@ +Copyright (c) 2016, Daniel Wirtz All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + +* Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. +* Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. +* Neither the name of its author, nor the names of its contributors + may be used to endorse or promote products derived from this software + without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/node_modules/@protobufjs/base64/README.md b/node_modules/@protobufjs/base64/README.md new file mode 100644 index 0000000..0e2eb33 --- /dev/null +++ b/node_modules/@protobufjs/base64/README.md @@ -0,0 +1,19 @@ +@protobufjs/base64 +================== +[![npm](https://img.shields.io/npm/v/@protobufjs/base64.svg)](https://www.npmjs.com/package/@protobufjs/base64) + +A minimal base64 implementation for number arrays. + +API +--- + +* **base64.length(string: `string`): `number`**
+ Calculates the byte length of a base64 encoded string. + +* **base64.encode(buffer: `Uint8Array`, start: `number`, end: `number`): `string`**
+ Encodes a buffer to a base64 encoded string. + +* **base64.decode(string: `string`, buffer: `Uint8Array`, offset: `number`): `number`**
+ Decodes a base64 encoded string to a buffer. + +**License:** [BSD 3-Clause License](https://opensource.org/licenses/BSD-3-Clause) diff --git a/node_modules/@protobufjs/base64/index.d.ts b/node_modules/@protobufjs/base64/index.d.ts new file mode 100644 index 0000000..16fd7db --- /dev/null +++ b/node_modules/@protobufjs/base64/index.d.ts @@ -0,0 +1,32 @@ +/** + * Calculates the byte length of a base64 encoded string. + * @param {string} string Base64 encoded string + * @returns {number} Byte length + */ +export function length(string: string): number; + +/** + * Encodes a buffer to a base64 encoded string. + * @param {Uint8Array} buffer Source buffer + * @param {number} start Source start + * @param {number} end Source end + * @returns {string} Base64 encoded string + */ +export function encode(buffer: Uint8Array, start: number, end: number): string; + +/** + * Decodes a base64 encoded string to a buffer. + * @param {string} string Source string + * @param {Uint8Array} buffer Destination buffer + * @param {number} offset Destination offset + * @returns {number} Number of bytes written + * @throws {Error} If encoding is invalid + */ +export function decode(string: string, buffer: Uint8Array, offset: number): number; + +/** + * Tests if the specified string appears to be base64 encoded. + * @param {string} string String to test + * @returns {boolean} `true` if it appears to be base64 encoded, otherwise false + */ +export function test(string: string): boolean; diff --git a/node_modules/@protobufjs/base64/index.js b/node_modules/@protobufjs/base64/index.js new file mode 100644 index 0000000..26d5443 --- /dev/null +++ b/node_modules/@protobufjs/base64/index.js @@ -0,0 +1,139 @@ +"use strict"; + +/** + * A minimal base64 implementation for number arrays. + * @memberof util + * @namespace + */ +var base64 = exports; + +/** + * Calculates the byte length of a base64 encoded string. + * @param {string} string Base64 encoded string + * @returns {number} Byte length + */ +base64.length = function length(string) { + var p = string.length; + if (!p) + return 0; + var n = 0; + while (--p % 4 > 1 && string.charAt(p) === "=") + ++n; + return Math.ceil(string.length * 3) / 4 - n; +}; + +// Base64 encoding table +var b64 = new Array(64); + +// Base64 decoding table +var s64 = new Array(123); + +// 65..90, 97..122, 48..57, 43, 47 +for (var i = 0; i < 64;) + s64[b64[i] = i < 26 ? i + 65 : i < 52 ? i + 71 : i < 62 ? i - 4 : i - 59 | 43] = i++; + +/** + * Encodes a buffer to a base64 encoded string. + * @param {Uint8Array} buffer Source buffer + * @param {number} start Source start + * @param {number} end Source end + * @returns {string} Base64 encoded string + */ +base64.encode = function encode(buffer, start, end) { + var parts = null, + chunk = []; + var i = 0, // output index + j = 0, // goto index + t; // temporary + while (start < end) { + var b = buffer[start++]; + switch (j) { + case 0: + chunk[i++] = b64[b >> 2]; + t = (b & 3) << 4; + j = 1; + break; + case 1: + chunk[i++] = b64[t | b >> 4]; + t = (b & 15) << 2; + j = 2; + break; + case 2: + chunk[i++] = b64[t | b >> 6]; + chunk[i++] = b64[b & 63]; + j = 0; + break; + } + if (i > 8191) { + (parts || (parts = [])).push(String.fromCharCode.apply(String, chunk)); + i = 0; + } + } + if (j) { + chunk[i++] = b64[t]; + chunk[i++] = 61; + if (j === 1) + chunk[i++] = 61; + } + if (parts) { + if (i) + parts.push(String.fromCharCode.apply(String, chunk.slice(0, i))); + return parts.join(""); + } + return String.fromCharCode.apply(String, chunk.slice(0, i)); +}; + +var invalidEncoding = "invalid encoding"; + +/** + * Decodes a base64 encoded string to a buffer. + * @param {string} string Source string + * @param {Uint8Array} buffer Destination buffer + * @param {number} offset Destination offset + * @returns {number} Number of bytes written + * @throws {Error} If encoding is invalid + */ +base64.decode = function decode(string, buffer, offset) { + var start = offset; + var j = 0, // goto index + t; // temporary + for (var i = 0; i < string.length;) { + var c = string.charCodeAt(i++); + if (c === 61 && j > 1) + break; + if ((c = s64[c]) === undefined) + throw Error(invalidEncoding); + switch (j) { + case 0: + t = c; + j = 1; + break; + case 1: + buffer[offset++] = t << 2 | (c & 48) >> 4; + t = c; + j = 2; + break; + case 2: + buffer[offset++] = (t & 15) << 4 | (c & 60) >> 2; + t = c; + j = 3; + break; + case 3: + buffer[offset++] = (t & 3) << 6 | c; + j = 0; + break; + } + } + if (j === 1) + throw Error(invalidEncoding); + return offset - start; +}; + +/** + * Tests if the specified string appears to be base64 encoded. + * @param {string} string String to test + * @returns {boolean} `true` if probably base64 encoded, otherwise false + */ +base64.test = function test(string) { + return /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(string); +}; diff --git a/node_modules/@protobufjs/base64/package.json b/node_modules/@protobufjs/base64/package.json new file mode 100644 index 0000000..46e71d4 --- /dev/null +++ b/node_modules/@protobufjs/base64/package.json @@ -0,0 +1,21 @@ +{ + "name": "@protobufjs/base64", + "description": "A minimal base64 implementation for number arrays.", + "version": "1.1.2", + "author": "Daniel Wirtz ", + "repository": { + "type": "git", + "url": "https://github.com/dcodeIO/protobuf.js.git" + }, + "license": "BSD-3-Clause", + "main": "index.js", + "types": "index.d.ts", + "devDependencies": { + "istanbul": "^0.4.5", + "tape": "^4.6.3" + }, + "scripts": { + "test": "tape tests/*.js", + "coverage": "istanbul cover node_modules/tape/bin/tape tests/*.js" + } +} \ No newline at end of file diff --git a/node_modules/@protobufjs/base64/tests/index.js b/node_modules/@protobufjs/base64/tests/index.js new file mode 100644 index 0000000..89828f2 --- /dev/null +++ b/node_modules/@protobufjs/base64/tests/index.js @@ -0,0 +1,46 @@ +var tape = require("tape"); + +var base64 = require(".."); + +var strings = { + "": "", + "a": "YQ==", + "ab": "YWI=", + "abcdefg": "YWJjZGVmZw==", + "abcdefgh": "YWJjZGVmZ2g=", + "abcdefghi": "YWJjZGVmZ2hp" +}; + +tape.test("base64", function(test) { + + Object.keys(strings).forEach(function(str) { + var enc = strings[str]; + + test.equal(base64.test(enc), true, "should detect '" + enc + "' to be base64 encoded"); + + var len = base64.length(enc); + test.equal(len, str.length, "should calculate '" + enc + "' as " + str.length + " bytes"); + + var buf = new Array(len); + var len2 = base64.decode(enc, buf, 0); + test.equal(len2, len, "should decode '" + enc + "' to " + len + " bytes"); + + test.equal(String.fromCharCode.apply(String, buf), str, "should decode '" + enc + "' to '" + str + "'"); + + var enc2 = base64.encode(buf, 0, buf.length); + test.equal(enc2, enc, "should encode '" + str + "' to '" + enc + "'"); + + }); + + test.throws(function() { + var buf = new Array(10); + base64.decode("YQ!", buf, 0); + }, Error, "should throw if encoding is invalid"); + + test.throws(function() { + var buf = new Array(10); + base64.decode("Y", buf, 0); + }, Error, "should throw if string is truncated"); + + test.end(); +}); diff --git a/node_modules/@protobufjs/codegen/LICENSE b/node_modules/@protobufjs/codegen/LICENSE new file mode 100644 index 0000000..2a2d560 --- /dev/null +++ b/node_modules/@protobufjs/codegen/LICENSE @@ -0,0 +1,26 @@ +Copyright (c) 2016, Daniel Wirtz All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + +* Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. +* Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. +* Neither the name of its author, nor the names of its contributors + may be used to endorse or promote products derived from this software + without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/node_modules/@protobufjs/codegen/README.md b/node_modules/@protobufjs/codegen/README.md new file mode 100644 index 0000000..0169338 --- /dev/null +++ b/node_modules/@protobufjs/codegen/README.md @@ -0,0 +1,49 @@ +@protobufjs/codegen +=================== +[![npm](https://img.shields.io/npm/v/@protobufjs/codegen.svg)](https://www.npmjs.com/package/@protobufjs/codegen) + +A minimalistic code generation utility. + +API +--- + +* **codegen([functionParams: `string[]`], [functionName: string]): `Codegen`**
+ Begins generating a function. + +* **codegen.verbose = `false`**
+ When set to true, codegen will log generated code to console. Useful for debugging. + +Invoking **codegen** returns an appender function that appends code to the function's body and returns itself: + +* **Codegen(formatString: `string`, [...formatParams: `any`]): Codegen**
+ Appends code to the function's body. The format string can contain placeholders specifying the types of inserted format parameters: + + * `%d`: Number (integer or floating point value) + * `%f`: Floating point value + * `%i`: Integer value + * `%j`: JSON.stringify'ed value + * `%s`: String value + * `%%`: Percent sign
+ +* **Codegen([scope: `Object.`]): `Function`**
+ Finishes the function and returns it. + +* **Codegen.toString([functionNameOverride: `string`]): `string`**
+ Returns the function as a string. + +Example +------- + +```js +var codegen = require("@protobufjs/codegen"); + +var add = codegen(["a", "b"], "add") // A function with parameters "a" and "b" named "add" + ("// awesome comment") // adds the line to the function's body + ("return a + b - c + %d", 1) // replaces %d with 1 and adds the line to the body + ({ c: 1 }); // adds "c" with a value of 1 to the function's scope + +console.log(add.toString()); // function add(a, b) { return a + b - c + 1 } +console.log(add(1, 2)); // calculates 1 + 2 - 1 + 1 = 3 +``` + +**License:** [BSD 3-Clause License](https://opensource.org/licenses/BSD-3-Clause) diff --git a/node_modules/@protobufjs/codegen/index.d.ts b/node_modules/@protobufjs/codegen/index.d.ts new file mode 100644 index 0000000..f7fb921 --- /dev/null +++ b/node_modules/@protobufjs/codegen/index.d.ts @@ -0,0 +1,31 @@ +export = codegen; + +/** + * Appends code to the function's body. + * @param [formatStringOrScope] Format string or, to finish the function, an object of additional scope variables, if any + * @param [formatParams] Format parameters + * @returns Itself or the generated function if finished + * @throws {Error} If format parameter counts do not match + */ +type Codegen = (formatStringOrScope?: (string|{ [k: string]: any }), ...formatParams: any[]) => (Codegen|Function); + +/** + * Begins generating a function. + * @param functionParams Function parameter names + * @param [functionName] Function name if not anonymous + * @returns Appender that appends code to the function's body + */ +declare function codegen(functionParams: string[], functionName?: string): Codegen; + +/** + * Begins generating a function. + * @param [functionName] Function name if not anonymous + * @returns Appender that appends code to the function's body + */ +declare function codegen(functionName?: string): Codegen; + +declare namespace codegen { + + /** When set to `true`, codegen will log generated code to console. Useful for debugging. */ + let verbose: boolean; +} diff --git a/node_modules/@protobufjs/codegen/index.js b/node_modules/@protobufjs/codegen/index.js new file mode 100644 index 0000000..de73f80 --- /dev/null +++ b/node_modules/@protobufjs/codegen/index.js @@ -0,0 +1,99 @@ +"use strict"; +module.exports = codegen; + +/** + * Begins generating a function. + * @memberof util + * @param {string[]} functionParams Function parameter names + * @param {string} [functionName] Function name if not anonymous + * @returns {Codegen} Appender that appends code to the function's body + */ +function codegen(functionParams, functionName) { + + /* istanbul ignore if */ + if (typeof functionParams === "string") { + functionName = functionParams; + functionParams = undefined; + } + + var body = []; + + /** + * Appends code to the function's body or finishes generation. + * @typedef Codegen + * @type {function} + * @param {string|Object.} [formatStringOrScope] Format string or, to finish the function, an object of additional scope variables, if any + * @param {...*} [formatParams] Format parameters + * @returns {Codegen|Function} Itself or the generated function if finished + * @throws {Error} If format parameter counts do not match + */ + + function Codegen(formatStringOrScope) { + // note that explicit array handling below makes this ~50% faster + + // finish the function + if (typeof formatStringOrScope !== "string") { + var source = toString(); + if (codegen.verbose) + console.log("codegen: " + source); // eslint-disable-line no-console + source = "return " + source; + if (formatStringOrScope) { + var scopeKeys = Object.keys(formatStringOrScope), + scopeParams = new Array(scopeKeys.length + 1), + scopeValues = new Array(scopeKeys.length), + scopeOffset = 0; + while (scopeOffset < scopeKeys.length) { + scopeParams[scopeOffset] = scopeKeys[scopeOffset]; + scopeValues[scopeOffset] = formatStringOrScope[scopeKeys[scopeOffset++]]; + } + scopeParams[scopeOffset] = source; + return Function.apply(null, scopeParams).apply(null, scopeValues); // eslint-disable-line no-new-func + } + return Function(source)(); // eslint-disable-line no-new-func + } + + // otherwise append to body + var formatParams = new Array(arguments.length - 1), + formatOffset = 0; + while (formatOffset < formatParams.length) + formatParams[formatOffset] = arguments[++formatOffset]; + formatOffset = 0; + formatStringOrScope = formatStringOrScope.replace(/%([%dfijs])/g, function replace($0, $1) { + var value = formatParams[formatOffset++]; + switch ($1) { + case "d": case "f": return String(Number(value)); + case "i": return String(Math.floor(value)); + case "j": return JSON.stringify(value); + case "s": return String(value); + } + return "%"; + }); + if (formatOffset !== formatParams.length) + throw Error("parameter count mismatch"); + body.push(formatStringOrScope); + return Codegen; + } + + function toString(functionNameOverride) { + return "function " + (functionNameOverride || functionName || "") + "(" + (functionParams && functionParams.join(",") || "") + "){\n " + body.join("\n ") + "\n}"; + } + + Codegen.toString = toString; + return Codegen; +} + +/** + * Begins generating a function. + * @memberof util + * @function codegen + * @param {string} [functionName] Function name if not anonymous + * @returns {Codegen} Appender that appends code to the function's body + * @variation 2 + */ + +/** + * When set to `true`, codegen will log generated code to console. Useful for debugging. + * @name util.codegen.verbose + * @type {boolean} + */ +codegen.verbose = false; diff --git a/node_modules/@protobufjs/codegen/package.json b/node_modules/@protobufjs/codegen/package.json new file mode 100644 index 0000000..92f2c4c --- /dev/null +++ b/node_modules/@protobufjs/codegen/package.json @@ -0,0 +1,13 @@ +{ + "name": "@protobufjs/codegen", + "description": "A minimalistic code generation utility.", + "version": "2.0.4", + "author": "Daniel Wirtz ", + "repository": { + "type": "git", + "url": "https://github.com/dcodeIO/protobuf.js.git" + }, + "license": "BSD-3-Clause", + "main": "index.js", + "types": "index.d.ts" +} \ No newline at end of file diff --git a/node_modules/@protobufjs/codegen/tests/index.js b/node_modules/@protobufjs/codegen/tests/index.js new file mode 100644 index 0000000..f3a3db1 --- /dev/null +++ b/node_modules/@protobufjs/codegen/tests/index.js @@ -0,0 +1,13 @@ +var codegen = require(".."); + +// new require("benchmark").Suite().add("add", function() { + +var add = codegen(["a", "b"], "add") + ("// awesome comment") + ("return a + b - c + %d", 1) + ({ c: 1 }); + +if (add(1, 2) !== 3) + throw Error("failed"); + +// }).on("cycle", function(event) { process.stdout.write(String(event.target) + "\n"); }).run(); diff --git a/node_modules/@protobufjs/eventemitter/LICENSE b/node_modules/@protobufjs/eventemitter/LICENSE new file mode 100644 index 0000000..2a2d560 --- /dev/null +++ b/node_modules/@protobufjs/eventemitter/LICENSE @@ -0,0 +1,26 @@ +Copyright (c) 2016, Daniel Wirtz All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + +* Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. +* Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. +* Neither the name of its author, nor the names of its contributors + may be used to endorse or promote products derived from this software + without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/node_modules/@protobufjs/eventemitter/README.md b/node_modules/@protobufjs/eventemitter/README.md new file mode 100644 index 0000000..998d315 --- /dev/null +++ b/node_modules/@protobufjs/eventemitter/README.md @@ -0,0 +1,22 @@ +@protobufjs/eventemitter +======================== +[![npm](https://img.shields.io/npm/v/@protobufjs/eventemitter.svg)](https://www.npmjs.com/package/@protobufjs/eventemitter) + +A minimal event emitter. + +API +--- + +* **new EventEmitter()**
+ Constructs a new event emitter instance. + +* **EventEmitter#on(evt: `string`, fn: `function`, [ctx: `Object`]): `EventEmitter`**
+ Registers an event listener. + +* **EventEmitter#off([evt: `string`], [fn: `function`]): `EventEmitter`**
+ Removes an event listener or any matching listeners if arguments are omitted. + +* **EventEmitter#emit(evt: `string`, ...args: `*`): `EventEmitter`**
+ Emits an event by calling its listeners with the specified arguments. + +**License:** [BSD 3-Clause License](https://opensource.org/licenses/BSD-3-Clause) diff --git a/node_modules/@protobufjs/eventemitter/index.d.ts b/node_modules/@protobufjs/eventemitter/index.d.ts new file mode 100644 index 0000000..4615963 --- /dev/null +++ b/node_modules/@protobufjs/eventemitter/index.d.ts @@ -0,0 +1,43 @@ +export = EventEmitter; + +/** + * Constructs a new event emitter instance. + * @classdesc A minimal event emitter. + * @memberof util + * @constructor + */ +declare class EventEmitter { + + /** + * Constructs a new event emitter instance. + * @classdesc A minimal event emitter. + * @memberof util + * @constructor + */ + constructor(); + + /** + * Registers an event listener. + * @param {string} evt Event name + * @param {function} fn Listener + * @param {*} [ctx] Listener context + * @returns {util.EventEmitter} `this` + */ + on(evt: string, fn: () => any, ctx?: any): EventEmitter; + + /** + * Removes an event listener or any matching listeners if arguments are omitted. + * @param {string} [evt] Event name. Removes all listeners if omitted. + * @param {function} [fn] Listener to remove. Removes all listeners of `evt` if omitted. + * @returns {util.EventEmitter} `this` + */ + off(evt?: string, fn?: () => any): EventEmitter; + + /** + * Emits an event by calling its listeners with the specified arguments. + * @param {string} evt Event name + * @param {...*} args Arguments + * @returns {util.EventEmitter} `this` + */ + emit(evt: string, ...args: any[]): EventEmitter; +} diff --git a/node_modules/@protobufjs/eventemitter/index.js b/node_modules/@protobufjs/eventemitter/index.js new file mode 100644 index 0000000..76ce938 --- /dev/null +++ b/node_modules/@protobufjs/eventemitter/index.js @@ -0,0 +1,76 @@ +"use strict"; +module.exports = EventEmitter; + +/** + * Constructs a new event emitter instance. + * @classdesc A minimal event emitter. + * @memberof util + * @constructor + */ +function EventEmitter() { + + /** + * Registered listeners. + * @type {Object.} + * @private + */ + this._listeners = {}; +} + +/** + * Registers an event listener. + * @param {string} evt Event name + * @param {function} fn Listener + * @param {*} [ctx] Listener context + * @returns {util.EventEmitter} `this` + */ +EventEmitter.prototype.on = function on(evt, fn, ctx) { + (this._listeners[evt] || (this._listeners[evt] = [])).push({ + fn : fn, + ctx : ctx || this + }); + return this; +}; + +/** + * Removes an event listener or any matching listeners if arguments are omitted. + * @param {string} [evt] Event name. Removes all listeners if omitted. + * @param {function} [fn] Listener to remove. Removes all listeners of `evt` if omitted. + * @returns {util.EventEmitter} `this` + */ +EventEmitter.prototype.off = function off(evt, fn) { + if (evt === undefined) + this._listeners = {}; + else { + if (fn === undefined) + this._listeners[evt] = []; + else { + var listeners = this._listeners[evt]; + for (var i = 0; i < listeners.length;) + if (listeners[i].fn === fn) + listeners.splice(i, 1); + else + ++i; + } + } + return this; +}; + +/** + * Emits an event by calling its listeners with the specified arguments. + * @param {string} evt Event name + * @param {...*} args Arguments + * @returns {util.EventEmitter} `this` + */ +EventEmitter.prototype.emit = function emit(evt) { + var listeners = this._listeners[evt]; + if (listeners) { + var args = [], + i = 1; + for (; i < arguments.length;) + args.push(arguments[i++]); + for (i = 0; i < listeners.length;) + listeners[i].fn.apply(listeners[i++].ctx, args); + } + return this; +}; diff --git a/node_modules/@protobufjs/eventemitter/package.json b/node_modules/@protobufjs/eventemitter/package.json new file mode 100644 index 0000000..1d565e6 --- /dev/null +++ b/node_modules/@protobufjs/eventemitter/package.json @@ -0,0 +1,21 @@ +{ + "name": "@protobufjs/eventemitter", + "description": "A minimal event emitter.", + "version": "1.1.0", + "author": "Daniel Wirtz ", + "repository": { + "type": "git", + "url": "https://github.com/dcodeIO/protobuf.js.git" + }, + "license": "BSD-3-Clause", + "main": "index.js", + "types": "index.d.ts", + "devDependencies": { + "istanbul": "^0.4.5", + "tape": "^4.6.3" + }, + "scripts": { + "test": "tape tests/*.js", + "coverage": "istanbul cover node_modules/tape/bin/tape tests/*.js" + } +} \ No newline at end of file diff --git a/node_modules/@protobufjs/eventemitter/tests/index.js b/node_modules/@protobufjs/eventemitter/tests/index.js new file mode 100644 index 0000000..aeee277 --- /dev/null +++ b/node_modules/@protobufjs/eventemitter/tests/index.js @@ -0,0 +1,47 @@ +var tape = require("tape"); + +var EventEmitter = require(".."); + +tape.test("eventemitter", function(test) { + + var ee = new EventEmitter(); + var fn; + var ctx = {}; + + test.doesNotThrow(function() { + ee.emit("a", 1); + ee.off(); + ee.off("a"); + ee.off("a", function() {}); + }, "should not throw if no listeners are registered"); + + test.equal(ee.on("a", function(arg1) { + test.equal(this, ctx, "should be called with this = ctx"); + test.equal(arg1, 1, "should be called with arg1 = 1"); + }, ctx), ee, "should return itself when registering events"); + ee.emit("a", 1); + + ee.off("a"); + test.same(ee._listeners, { a: [] }, "should remove all listeners of the respective event when calling off(evt)"); + + ee.off(); + test.same(ee._listeners, {}, "should remove all listeners when just calling off()"); + + ee.on("a", fn = function(arg1) { + test.equal(this, ctx, "should be called with this = ctx"); + test.equal(arg1, 1, "should be called with arg1 = 1"); + }, ctx).emit("a", 1); + + ee.off("a", fn); + test.same(ee._listeners, { a: [] }, "should remove the exact listener when calling off(evt, fn)"); + + ee.on("a", function() { + test.equal(this, ee, "should be called with this = ee"); + }).emit("a"); + + test.doesNotThrow(function() { + ee.off("a", fn); + }, "should not throw if no such listener is found"); + + test.end(); +}); diff --git a/node_modules/@protobufjs/fetch/LICENSE b/node_modules/@protobufjs/fetch/LICENSE new file mode 100644 index 0000000..2a2d560 --- /dev/null +++ b/node_modules/@protobufjs/fetch/LICENSE @@ -0,0 +1,26 @@ +Copyright (c) 2016, Daniel Wirtz All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + +* Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. +* Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. +* Neither the name of its author, nor the names of its contributors + may be used to endorse or promote products derived from this software + without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/node_modules/@protobufjs/fetch/README.md b/node_modules/@protobufjs/fetch/README.md new file mode 100644 index 0000000..11088a0 --- /dev/null +++ b/node_modules/@protobufjs/fetch/README.md @@ -0,0 +1,13 @@ +@protobufjs/fetch +================= +[![npm](https://img.shields.io/npm/v/@protobufjs/fetch.svg)](https://www.npmjs.com/package/@protobufjs/fetch) + +Fetches the contents of a file accross node and browsers. + +API +--- + +* **fetch(path: `string`, [options: { binary: boolean } ], [callback: `function(error: ?Error, [contents: string])`]): `Promise|undefined`** + Fetches the contents of a file. + +**License:** [BSD 3-Clause License](https://opensource.org/licenses/BSD-3-Clause) diff --git a/node_modules/@protobufjs/fetch/index.d.ts b/node_modules/@protobufjs/fetch/index.d.ts new file mode 100644 index 0000000..77cf9f3 --- /dev/null +++ b/node_modules/@protobufjs/fetch/index.d.ts @@ -0,0 +1,56 @@ +export = fetch; + +/** + * Node-style callback as used by {@link util.fetch}. + * @typedef FetchCallback + * @type {function} + * @param {?Error} error Error, if any, otherwise `null` + * @param {string} [contents] File contents, if there hasn't been an error + * @returns {undefined} + */ +type FetchCallback = (error: Error, contents?: string) => void; + +/** + * Options as used by {@link util.fetch}. + * @typedef FetchOptions + * @type {Object} + * @property {boolean} [binary=false] Whether expecting a binary response + * @property {boolean} [xhr=false] If `true`, forces the use of XMLHttpRequest + */ + +interface FetchOptions { + binary?: boolean; + xhr?: boolean +} + +/** + * Fetches the contents of a file. + * @memberof util + * @param {string} filename File path or url + * @param {FetchOptions} options Fetch options + * @param {FetchCallback} callback Callback function + * @returns {undefined} + */ +declare function fetch(filename: string, options: FetchOptions, callback: FetchCallback): void; + +/** + * Fetches the contents of a file. + * @name util.fetch + * @function + * @param {string} path File path or url + * @param {FetchCallback} callback Callback function + * @returns {undefined} + * @variation 2 + */ +declare function fetch(path: string, callback: FetchCallback): void; + +/** + * Fetches the contents of a file. + * @name util.fetch + * @function + * @param {string} path File path or url + * @param {FetchOptions} [options] Fetch options + * @returns {Promise} Promise + * @variation 3 + */ +declare function fetch(path: string, options?: FetchOptions): Promise<(string|Uint8Array)>; diff --git a/node_modules/@protobufjs/fetch/index.js b/node_modules/@protobufjs/fetch/index.js new file mode 100644 index 0000000..f2766f5 --- /dev/null +++ b/node_modules/@protobufjs/fetch/index.js @@ -0,0 +1,115 @@ +"use strict"; +module.exports = fetch; + +var asPromise = require("@protobufjs/aspromise"), + inquire = require("@protobufjs/inquire"); + +var fs = inquire("fs"); + +/** + * Node-style callback as used by {@link util.fetch}. + * @typedef FetchCallback + * @type {function} + * @param {?Error} error Error, if any, otherwise `null` + * @param {string} [contents] File contents, if there hasn't been an error + * @returns {undefined} + */ + +/** + * Options as used by {@link util.fetch}. + * @typedef FetchOptions + * @type {Object} + * @property {boolean} [binary=false] Whether expecting a binary response + * @property {boolean} [xhr=false] If `true`, forces the use of XMLHttpRequest + */ + +/** + * Fetches the contents of a file. + * @memberof util + * @param {string} filename File path or url + * @param {FetchOptions} options Fetch options + * @param {FetchCallback} callback Callback function + * @returns {undefined} + */ +function fetch(filename, options, callback) { + if (typeof options === "function") { + callback = options; + options = {}; + } else if (!options) + options = {}; + + if (!callback) + return asPromise(fetch, this, filename, options); // eslint-disable-line no-invalid-this + + // if a node-like filesystem is present, try it first but fall back to XHR if nothing is found. + if (!options.xhr && fs && fs.readFile) + return fs.readFile(filename, function fetchReadFileCallback(err, contents) { + return err && typeof XMLHttpRequest !== "undefined" + ? fetch.xhr(filename, options, callback) + : err + ? callback(err) + : callback(null, options.binary ? contents : contents.toString("utf8")); + }); + + // use the XHR version otherwise. + return fetch.xhr(filename, options, callback); +} + +/** + * Fetches the contents of a file. + * @name util.fetch + * @function + * @param {string} path File path or url + * @param {FetchCallback} callback Callback function + * @returns {undefined} + * @variation 2 + */ + +/** + * Fetches the contents of a file. + * @name util.fetch + * @function + * @param {string} path File path or url + * @param {FetchOptions} [options] Fetch options + * @returns {Promise} Promise + * @variation 3 + */ + +/**/ +fetch.xhr = function fetch_xhr(filename, options, callback) { + var xhr = new XMLHttpRequest(); + xhr.onreadystatechange /* works everywhere */ = function fetchOnReadyStateChange() { + + if (xhr.readyState !== 4) + return undefined; + + // local cors security errors return status 0 / empty string, too. afaik this cannot be + // reliably distinguished from an actually empty file for security reasons. feel free + // to send a pull request if you are aware of a solution. + if (xhr.status !== 0 && xhr.status !== 200) + return callback(Error("status " + xhr.status)); + + // if binary data is expected, make sure that some sort of array is returned, even if + // ArrayBuffers are not supported. the binary string fallback, however, is unsafe. + if (options.binary) { + var buffer = xhr.response; + if (!buffer) { + buffer = []; + for (var i = 0; i < xhr.responseText.length; ++i) + buffer.push(xhr.responseText.charCodeAt(i) & 255); + } + return callback(null, typeof Uint8Array !== "undefined" ? new Uint8Array(buffer) : buffer); + } + return callback(null, xhr.responseText); + }; + + if (options.binary) { + // ref: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Sending_and_Receiving_Binary_Data#Receiving_binary_data_in_older_browsers + if ("overrideMimeType" in xhr) + xhr.overrideMimeType("text/plain; charset=x-user-defined"); + xhr.responseType = "arraybuffer"; + } + + xhr.open("GET", filename); + xhr.send(); +}; diff --git a/node_modules/@protobufjs/fetch/package.json b/node_modules/@protobufjs/fetch/package.json new file mode 100644 index 0000000..10096ea --- /dev/null +++ b/node_modules/@protobufjs/fetch/package.json @@ -0,0 +1,25 @@ +{ + "name": "@protobufjs/fetch", + "description": "Fetches the contents of a file accross node and browsers.", + "version": "1.1.0", + "author": "Daniel Wirtz ", + "repository": { + "type": "git", + "url": "https://github.com/dcodeIO/protobuf.js.git" + }, + "dependencies": { + "@protobufjs/aspromise": "^1.1.1", + "@protobufjs/inquire": "^1.1.0" + }, + "license": "BSD-3-Clause", + "main": "index.js", + "types": "index.d.ts", + "devDependencies": { + "istanbul": "^0.4.5", + "tape": "^4.6.3" + }, + "scripts": { + "test": "tape tests/*.js", + "coverage": "istanbul cover node_modules/tape/bin/tape tests/*.js" + } +} \ No newline at end of file diff --git a/node_modules/@protobufjs/fetch/tests/index.js b/node_modules/@protobufjs/fetch/tests/index.js new file mode 100644 index 0000000..3cb0dae --- /dev/null +++ b/node_modules/@protobufjs/fetch/tests/index.js @@ -0,0 +1,16 @@ +var tape = require("tape"); + +var fetch = require(".."); + +tape.test("fetch", function(test) { + + if (typeof Promise !== "undefined") { + var promise = fetch("NOTFOUND"); + promise.catch(function() {}); + test.ok(promise instanceof Promise, "should return a promise if callback has been omitted"); + } + + // TODO - some way to test this properly? + + test.end(); +}); diff --git a/node_modules/@protobufjs/float/LICENSE b/node_modules/@protobufjs/float/LICENSE new file mode 100644 index 0000000..2a2d560 --- /dev/null +++ b/node_modules/@protobufjs/float/LICENSE @@ -0,0 +1,26 @@ +Copyright (c) 2016, Daniel Wirtz All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + +* Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. +* Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. +* Neither the name of its author, nor the names of its contributors + may be used to endorse or promote products derived from this software + without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/node_modules/@protobufjs/float/README.md b/node_modules/@protobufjs/float/README.md new file mode 100644 index 0000000..8947bae --- /dev/null +++ b/node_modules/@protobufjs/float/README.md @@ -0,0 +1,102 @@ +@protobufjs/float +================= +[![npm](https://img.shields.io/npm/v/@protobufjs/float.svg)](https://www.npmjs.com/package/@protobufjs/float) + +Reads / writes floats / doubles from / to buffers in both modern and ancient browsers. Fast. + +API +--- + +* **writeFloatLE(val: `number`, buf: `Uint8Array`, pos: `number`)**
+ Writes a 32 bit float to a buffer using little endian byte order. + +* **writeFloatBE(val: `number`, buf: `Uint8Array`, pos: `number`)**
+ Writes a 32 bit float to a buffer using big endian byte order. + +* **readFloatLE(buf: `Uint8Array`, pos: `number`): `number`**
+ Reads a 32 bit float from a buffer using little endian byte order. + +* **readFloatBE(buf: `Uint8Array`, pos: `number`): `number`**
+ Reads a 32 bit float from a buffer using big endian byte order. + +* **writeDoubleLE(val: `number`, buf: `Uint8Array`, pos: `number`)**
+ Writes a 64 bit double to a buffer using little endian byte order. + +* **writeDoubleBE(val: `number`, buf: `Uint8Array`, pos: `number`)**
+ Writes a 64 bit double to a buffer using big endian byte order. + +* **readDoubleLE(buf: `Uint8Array`, pos: `number`): `number`**
+ Reads a 64 bit double from a buffer using little endian byte order. + +* **readDoubleBE(buf: `Uint8Array`, pos: `number`): `number`**
+ Reads a 64 bit double from a buffer using big endian byte order. + +Performance +----------- +There is a simple benchmark included comparing raw read/write performance of this library (float), float's fallback for old browsers, the [ieee754](https://www.npmjs.com/package/ieee754) module and node's [buffer](https://nodejs.org/api/buffer.html). On an i7-2600k running node 6.9.1 it yields: + +``` +benchmarking writeFloat performance ... + +float x 42,741,625 ops/sec ±1.75% (81 runs sampled) +float (fallback) x 11,272,532 ops/sec ±1.12% (85 runs sampled) +ieee754 x 8,653,337 ops/sec ±1.18% (84 runs sampled) +buffer x 12,412,414 ops/sec ±1.41% (83 runs sampled) +buffer (noAssert) x 13,471,149 ops/sec ±1.09% (84 runs sampled) + + float was fastest + float (fallback) was 73.5% slower + ieee754 was 79.6% slower + buffer was 70.9% slower + buffer (noAssert) was 68.3% slower + +benchmarking readFloat performance ... + +float x 44,382,729 ops/sec ±1.70% (84 runs sampled) +float (fallback) x 20,925,938 ops/sec ±0.86% (87 runs sampled) +ieee754 x 17,189,009 ops/sec ±1.01% (87 runs sampled) +buffer x 10,518,437 ops/sec ±1.04% (83 runs sampled) +buffer (noAssert) x 11,031,636 ops/sec ±1.15% (87 runs sampled) + + float was fastest + float (fallback) was 52.5% slower + ieee754 was 61.0% slower + buffer was 76.1% slower + buffer (noAssert) was 75.0% slower + +benchmarking writeDouble performance ... + +float x 38,624,906 ops/sec ±0.93% (83 runs sampled) +float (fallback) x 10,457,811 ops/sec ±1.54% (85 runs sampled) +ieee754 x 7,681,130 ops/sec ±1.11% (83 runs sampled) +buffer x 12,657,876 ops/sec ±1.03% (83 runs sampled) +buffer (noAssert) x 13,372,795 ops/sec ±0.84% (85 runs sampled) + + float was fastest + float (fallback) was 73.1% slower + ieee754 was 80.1% slower + buffer was 67.3% slower + buffer (noAssert) was 65.3% slower + +benchmarking readDouble performance ... + +float x 40,527,888 ops/sec ±1.05% (84 runs sampled) +float (fallback) x 18,696,480 ops/sec ±0.84% (86 runs sampled) +ieee754 x 14,074,028 ops/sec ±1.04% (87 runs sampled) +buffer x 10,092,367 ops/sec ±1.15% (84 runs sampled) +buffer (noAssert) x 10,623,793 ops/sec ±0.96% (84 runs sampled) + + float was fastest + float (fallback) was 53.8% slower + ieee754 was 65.3% slower + buffer was 75.1% slower + buffer (noAssert) was 73.8% slower +``` + +To run it yourself: + +``` +$> npm run bench +``` + +**License:** [BSD 3-Clause License](https://opensource.org/licenses/BSD-3-Clause) diff --git a/node_modules/@protobufjs/float/bench/index.js b/node_modules/@protobufjs/float/bench/index.js new file mode 100644 index 0000000..1b3c4b8 --- /dev/null +++ b/node_modules/@protobufjs/float/bench/index.js @@ -0,0 +1,87 @@ +"use strict"; + +var float = require(".."), + ieee754 = require("ieee754"), + newSuite = require("./suite"); + +var F32 = Float32Array; +var F64 = Float64Array; +delete global.Float32Array; +delete global.Float64Array; +var floatFallback = float({}); +global.Float32Array = F32; +global.Float64Array = F64; + +var buf = new Buffer(8); + +newSuite("writeFloat") +.add("float", function() { + float.writeFloatLE(0.1, buf, 0); +}) +.add("float (fallback)", function() { + floatFallback.writeFloatLE(0.1, buf, 0); +}) +.add("ieee754", function() { + ieee754.write(buf, 0.1, 0, true, 23, 4); +}) +.add("buffer", function() { + buf.writeFloatLE(0.1, 0); +}) +.add("buffer (noAssert)", function() { + buf.writeFloatLE(0.1, 0, true); +}) +.run(); + +newSuite("readFloat") +.add("float", function() { + float.readFloatLE(buf, 0); +}) +.add("float (fallback)", function() { + floatFallback.readFloatLE(buf, 0); +}) +.add("ieee754", function() { + ieee754.read(buf, 0, true, 23, 4); +}) +.add("buffer", function() { + buf.readFloatLE(0); +}) +.add("buffer (noAssert)", function() { + buf.readFloatLE(0, true); +}) +.run(); + +newSuite("writeDouble") +.add("float", function() { + float.writeDoubleLE(0.1, buf, 0); +}) +.add("float (fallback)", function() { + floatFallback.writeDoubleLE(0.1, buf, 0); +}) +.add("ieee754", function() { + ieee754.write(buf, 0.1, 0, true, 52, 8); +}) +.add("buffer", function() { + buf.writeDoubleLE(0.1, 0); +}) +.add("buffer (noAssert)", function() { + buf.writeDoubleLE(0.1, 0, true); +}) +.run(); + +newSuite("readDouble") +.add("float", function() { + float.readDoubleLE(buf, 0); +}) +.add("float (fallback)", function() { + floatFallback.readDoubleLE(buf, 0); +}) +.add("ieee754", function() { + ieee754.read(buf, 0, true, 52, 8); +}) +.add("buffer", function() { + buf.readDoubleLE(0); +}) +.add("buffer (noAssert)", function() { + buf.readDoubleLE(0, true); +}) +.run(); diff --git a/node_modules/@protobufjs/float/bench/suite.js b/node_modules/@protobufjs/float/bench/suite.js new file mode 100644 index 0000000..3820579 --- /dev/null +++ b/node_modules/@protobufjs/float/bench/suite.js @@ -0,0 +1,46 @@ +"use strict"; +module.exports = newSuite; + +var benchmark = require("benchmark"), + chalk = require("chalk"); + +var padSize = 27; + +function newSuite(name) { + var benches = []; + return new benchmark.Suite(name) + .on("add", function(event) { + benches.push(event.target); + }) + .on("start", function() { + process.stdout.write("benchmarking " + name + " performance ...\n\n"); + }) + .on("cycle", function(event) { + process.stdout.write(String(event.target) + "\n"); + }) + .on("complete", function() { + if (benches.length > 1) { + var fastest = this.filter("fastest"), // eslint-disable-line no-invalid-this + fastestHz = getHz(fastest[0]); + process.stdout.write("\n" + chalk.white(pad(fastest[0].name, padSize)) + " was " + chalk.green("fastest") + "\n"); + benches.forEach(function(bench) { + if (fastest.indexOf(bench) === 0) + return; + var hz = hz = getHz(bench); + var percent = (1 - hz / fastestHz) * 100; + process.stdout.write(chalk.white(pad(bench.name, padSize)) + " was " + chalk.red(percent.toFixed(1) + "% slower") + "\n"); + }); + } + process.stdout.write("\n"); + }); +} + +function getHz(bench) { + return 1 / (bench.stats.mean + bench.stats.moe); +} + +function pad(str, len, l) { + while (str.length < len) + str = l ? str + " " : " " + str; + return str; +} diff --git a/node_modules/@protobufjs/float/index.d.ts b/node_modules/@protobufjs/float/index.d.ts new file mode 100644 index 0000000..ab05de3 --- /dev/null +++ b/node_modules/@protobufjs/float/index.d.ts @@ -0,0 +1,83 @@ +/** + * Writes a 32 bit float to a buffer using little endian byte order. + * @name writeFloatLE + * @function + * @param {number} val Value to write + * @param {Uint8Array} buf Target buffer + * @param {number} pos Target buffer offset + * @returns {undefined} + */ +export function writeFloatLE(val: number, buf: Uint8Array, pos: number): void; + +/** + * Writes a 32 bit float to a buffer using big endian byte order. + * @name writeFloatBE + * @function + * @param {number} val Value to write + * @param {Uint8Array} buf Target buffer + * @param {number} pos Target buffer offset + * @returns {undefined} + */ +export function writeFloatBE(val: number, buf: Uint8Array, pos: number): void; + +/** + * Reads a 32 bit float from a buffer using little endian byte order. + * @name readFloatLE + * @function + * @param {Uint8Array} buf Source buffer + * @param {number} pos Source buffer offset + * @returns {number} Value read + */ +export function readFloatLE(buf: Uint8Array, pos: number): number; + +/** + * Reads a 32 bit float from a buffer using big endian byte order. + * @name readFloatBE + * @function + * @param {Uint8Array} buf Source buffer + * @param {number} pos Source buffer offset + * @returns {number} Value read + */ +export function readFloatBE(buf: Uint8Array, pos: number): number; + +/** + * Writes a 64 bit double to a buffer using little endian byte order. + * @name writeDoubleLE + * @function + * @param {number} val Value to write + * @param {Uint8Array} buf Target buffer + * @param {number} pos Target buffer offset + * @returns {undefined} + */ +export function writeDoubleLE(val: number, buf: Uint8Array, pos: number): void; + +/** + * Writes a 64 bit double to a buffer using big endian byte order. + * @name writeDoubleBE + * @function + * @param {number} val Value to write + * @param {Uint8Array} buf Target buffer + * @param {number} pos Target buffer offset + * @returns {undefined} + */ +export function writeDoubleBE(val: number, buf: Uint8Array, pos: number): void; + +/** + * Reads a 64 bit double from a buffer using little endian byte order. + * @name readDoubleLE + * @function + * @param {Uint8Array} buf Source buffer + * @param {number} pos Source buffer offset + * @returns {number} Value read + */ +export function readDoubleLE(buf: Uint8Array, pos: number): number; + +/** + * Reads a 64 bit double from a buffer using big endian byte order. + * @name readDoubleBE + * @function + * @param {Uint8Array} buf Source buffer + * @param {number} pos Source buffer offset + * @returns {number} Value read + */ +export function readDoubleBE(buf: Uint8Array, pos: number): number; diff --git a/node_modules/@protobufjs/float/index.js b/node_modules/@protobufjs/float/index.js new file mode 100644 index 0000000..706d096 --- /dev/null +++ b/node_modules/@protobufjs/float/index.js @@ -0,0 +1,335 @@ +"use strict"; + +module.exports = factory(factory); + +/** + * Reads / writes floats / doubles from / to buffers. + * @name util.float + * @namespace + */ + +/** + * Writes a 32 bit float to a buffer using little endian byte order. + * @name util.float.writeFloatLE + * @function + * @param {number} val Value to write + * @param {Uint8Array} buf Target buffer + * @param {number} pos Target buffer offset + * @returns {undefined} + */ + +/** + * Writes a 32 bit float to a buffer using big endian byte order. + * @name util.float.writeFloatBE + * @function + * @param {number} val Value to write + * @param {Uint8Array} buf Target buffer + * @param {number} pos Target buffer offset + * @returns {undefined} + */ + +/** + * Reads a 32 bit float from a buffer using little endian byte order. + * @name util.float.readFloatLE + * @function + * @param {Uint8Array} buf Source buffer + * @param {number} pos Source buffer offset + * @returns {number} Value read + */ + +/** + * Reads a 32 bit float from a buffer using big endian byte order. + * @name util.float.readFloatBE + * @function + * @param {Uint8Array} buf Source buffer + * @param {number} pos Source buffer offset + * @returns {number} Value read + */ + +/** + * Writes a 64 bit double to a buffer using little endian byte order. + * @name util.float.writeDoubleLE + * @function + * @param {number} val Value to write + * @param {Uint8Array} buf Target buffer + * @param {number} pos Target buffer offset + * @returns {undefined} + */ + +/** + * Writes a 64 bit double to a buffer using big endian byte order. + * @name util.float.writeDoubleBE + * @function + * @param {number} val Value to write + * @param {Uint8Array} buf Target buffer + * @param {number} pos Target buffer offset + * @returns {undefined} + */ + +/** + * Reads a 64 bit double from a buffer using little endian byte order. + * @name util.float.readDoubleLE + * @function + * @param {Uint8Array} buf Source buffer + * @param {number} pos Source buffer offset + * @returns {number} Value read + */ + +/** + * Reads a 64 bit double from a buffer using big endian byte order. + * @name util.float.readDoubleBE + * @function + * @param {Uint8Array} buf Source buffer + * @param {number} pos Source buffer offset + * @returns {number} Value read + */ + +// Factory function for the purpose of node-based testing in modified global environments +function factory(exports) { + + // float: typed array + if (typeof Float32Array !== "undefined") (function() { + + var f32 = new Float32Array([ -0 ]), + f8b = new Uint8Array(f32.buffer), + le = f8b[3] === 128; + + function writeFloat_f32_cpy(val, buf, pos) { + f32[0] = val; + buf[pos ] = f8b[0]; + buf[pos + 1] = f8b[1]; + buf[pos + 2] = f8b[2]; + buf[pos + 3] = f8b[3]; + } + + function writeFloat_f32_rev(val, buf, pos) { + f32[0] = val; + buf[pos ] = f8b[3]; + buf[pos + 1] = f8b[2]; + buf[pos + 2] = f8b[1]; + buf[pos + 3] = f8b[0]; + } + + /* istanbul ignore next */ + exports.writeFloatLE = le ? writeFloat_f32_cpy : writeFloat_f32_rev; + /* istanbul ignore next */ + exports.writeFloatBE = le ? writeFloat_f32_rev : writeFloat_f32_cpy; + + function readFloat_f32_cpy(buf, pos) { + f8b[0] = buf[pos ]; + f8b[1] = buf[pos + 1]; + f8b[2] = buf[pos + 2]; + f8b[3] = buf[pos + 3]; + return f32[0]; + } + + function readFloat_f32_rev(buf, pos) { + f8b[3] = buf[pos ]; + f8b[2] = buf[pos + 1]; + f8b[1] = buf[pos + 2]; + f8b[0] = buf[pos + 3]; + return f32[0]; + } + + /* istanbul ignore next */ + exports.readFloatLE = le ? readFloat_f32_cpy : readFloat_f32_rev; + /* istanbul ignore next */ + exports.readFloatBE = le ? readFloat_f32_rev : readFloat_f32_cpy; + + // float: ieee754 + })(); else (function() { + + function writeFloat_ieee754(writeUint, val, buf, pos) { + var sign = val < 0 ? 1 : 0; + if (sign) + val = -val; + if (val === 0) + writeUint(1 / val > 0 ? /* positive */ 0 : /* negative 0 */ 2147483648, buf, pos); + else if (isNaN(val)) + writeUint(2143289344, buf, pos); + else if (val > 3.4028234663852886e+38) // +-Infinity + writeUint((sign << 31 | 2139095040) >>> 0, buf, pos); + else if (val < 1.1754943508222875e-38) // denormal + writeUint((sign << 31 | Math.round(val / 1.401298464324817e-45)) >>> 0, buf, pos); + else { + var exponent = Math.floor(Math.log(val) / Math.LN2), + mantissa = Math.round(val * Math.pow(2, -exponent) * 8388608) & 8388607; + writeUint((sign << 31 | exponent + 127 << 23 | mantissa) >>> 0, buf, pos); + } + } + + exports.writeFloatLE = writeFloat_ieee754.bind(null, writeUintLE); + exports.writeFloatBE = writeFloat_ieee754.bind(null, writeUintBE); + + function readFloat_ieee754(readUint, buf, pos) { + var uint = readUint(buf, pos), + sign = (uint >> 31) * 2 + 1, + exponent = uint >>> 23 & 255, + mantissa = uint & 8388607; + return exponent === 255 + ? mantissa + ? NaN + : sign * Infinity + : exponent === 0 // denormal + ? sign * 1.401298464324817e-45 * mantissa + : sign * Math.pow(2, exponent - 150) * (mantissa + 8388608); + } + + exports.readFloatLE = readFloat_ieee754.bind(null, readUintLE); + exports.readFloatBE = readFloat_ieee754.bind(null, readUintBE); + + })(); + + // double: typed array + if (typeof Float64Array !== "undefined") (function() { + + var f64 = new Float64Array([-0]), + f8b = new Uint8Array(f64.buffer), + le = f8b[7] === 128; + + function writeDouble_f64_cpy(val, buf, pos) { + f64[0] = val; + buf[pos ] = f8b[0]; + buf[pos + 1] = f8b[1]; + buf[pos + 2] = f8b[2]; + buf[pos + 3] = f8b[3]; + buf[pos + 4] = f8b[4]; + buf[pos + 5] = f8b[5]; + buf[pos + 6] = f8b[6]; + buf[pos + 7] = f8b[7]; + } + + function writeDouble_f64_rev(val, buf, pos) { + f64[0] = val; + buf[pos ] = f8b[7]; + buf[pos + 1] = f8b[6]; + buf[pos + 2] = f8b[5]; + buf[pos + 3] = f8b[4]; + buf[pos + 4] = f8b[3]; + buf[pos + 5] = f8b[2]; + buf[pos + 6] = f8b[1]; + buf[pos + 7] = f8b[0]; + } + + /* istanbul ignore next */ + exports.writeDoubleLE = le ? writeDouble_f64_cpy : writeDouble_f64_rev; + /* istanbul ignore next */ + exports.writeDoubleBE = le ? writeDouble_f64_rev : writeDouble_f64_cpy; + + function readDouble_f64_cpy(buf, pos) { + f8b[0] = buf[pos ]; + f8b[1] = buf[pos + 1]; + f8b[2] = buf[pos + 2]; + f8b[3] = buf[pos + 3]; + f8b[4] = buf[pos + 4]; + f8b[5] = buf[pos + 5]; + f8b[6] = buf[pos + 6]; + f8b[7] = buf[pos + 7]; + return f64[0]; + } + + function readDouble_f64_rev(buf, pos) { + f8b[7] = buf[pos ]; + f8b[6] = buf[pos + 1]; + f8b[5] = buf[pos + 2]; + f8b[4] = buf[pos + 3]; + f8b[3] = buf[pos + 4]; + f8b[2] = buf[pos + 5]; + f8b[1] = buf[pos + 6]; + f8b[0] = buf[pos + 7]; + return f64[0]; + } + + /* istanbul ignore next */ + exports.readDoubleLE = le ? readDouble_f64_cpy : readDouble_f64_rev; + /* istanbul ignore next */ + exports.readDoubleBE = le ? readDouble_f64_rev : readDouble_f64_cpy; + + // double: ieee754 + })(); else (function() { + + function writeDouble_ieee754(writeUint, off0, off1, val, buf, pos) { + var sign = val < 0 ? 1 : 0; + if (sign) + val = -val; + if (val === 0) { + writeUint(0, buf, pos + off0); + writeUint(1 / val > 0 ? /* positive */ 0 : /* negative 0 */ 2147483648, buf, pos + off1); + } else if (isNaN(val)) { + writeUint(0, buf, pos + off0); + writeUint(2146959360, buf, pos + off1); + } else if (val > 1.7976931348623157e+308) { // +-Infinity + writeUint(0, buf, pos + off0); + writeUint((sign << 31 | 2146435072) >>> 0, buf, pos + off1); + } else { + var mantissa; + if (val < 2.2250738585072014e-308) { // denormal + mantissa = val / 5e-324; + writeUint(mantissa >>> 0, buf, pos + off0); + writeUint((sign << 31 | mantissa / 4294967296) >>> 0, buf, pos + off1); + } else { + var exponent = Math.floor(Math.log(val) / Math.LN2); + if (exponent === 1024) + exponent = 1023; + mantissa = val * Math.pow(2, -exponent); + writeUint(mantissa * 4503599627370496 >>> 0, buf, pos + off0); + writeUint((sign << 31 | exponent + 1023 << 20 | mantissa * 1048576 & 1048575) >>> 0, buf, pos + off1); + } + } + } + + exports.writeDoubleLE = writeDouble_ieee754.bind(null, writeUintLE, 0, 4); + exports.writeDoubleBE = writeDouble_ieee754.bind(null, writeUintBE, 4, 0); + + function readDouble_ieee754(readUint, off0, off1, buf, pos) { + var lo = readUint(buf, pos + off0), + hi = readUint(buf, pos + off1); + var sign = (hi >> 31) * 2 + 1, + exponent = hi >>> 20 & 2047, + mantissa = 4294967296 * (hi & 1048575) + lo; + return exponent === 2047 + ? mantissa + ? NaN + : sign * Infinity + : exponent === 0 // denormal + ? sign * 5e-324 * mantissa + : sign * Math.pow(2, exponent - 1075) * (mantissa + 4503599627370496); + } + + exports.readDoubleLE = readDouble_ieee754.bind(null, readUintLE, 0, 4); + exports.readDoubleBE = readDouble_ieee754.bind(null, readUintBE, 4, 0); + + })(); + + return exports; +} + +// uint helpers + +function writeUintLE(val, buf, pos) { + buf[pos ] = val & 255; + buf[pos + 1] = val >>> 8 & 255; + buf[pos + 2] = val >>> 16 & 255; + buf[pos + 3] = val >>> 24; +} + +function writeUintBE(val, buf, pos) { + buf[pos ] = val >>> 24; + buf[pos + 1] = val >>> 16 & 255; + buf[pos + 2] = val >>> 8 & 255; + buf[pos + 3] = val & 255; +} + +function readUintLE(buf, pos) { + return (buf[pos ] + | buf[pos + 1] << 8 + | buf[pos + 2] << 16 + | buf[pos + 3] << 24) >>> 0; +} + +function readUintBE(buf, pos) { + return (buf[pos ] << 24 + | buf[pos + 1] << 16 + | buf[pos + 2] << 8 + | buf[pos + 3]) >>> 0; +} diff --git a/node_modules/@protobufjs/float/package.json b/node_modules/@protobufjs/float/package.json new file mode 100644 index 0000000..b3072f1 --- /dev/null +++ b/node_modules/@protobufjs/float/package.json @@ -0,0 +1,26 @@ +{ + "name": "@protobufjs/float", + "description": "Reads / writes floats / doubles from / to buffers in both modern and ancient browsers.", + "version": "1.0.2", + "author": "Daniel Wirtz ", + "repository": { + "type": "git", + "url": "https://github.com/dcodeIO/protobuf.js.git" + }, + "dependencies": {}, + "license": "BSD-3-Clause", + "main": "index.js", + "types": "index.d.ts", + "devDependencies": { + "benchmark": "^2.1.4", + "chalk": "^1.1.3", + "ieee754": "^1.1.8", + "istanbul": "^0.4.5", + "tape": "^4.6.3" + }, + "scripts": { + "test": "tape tests/*.js", + "coverage": "istanbul cover node_modules/tape/bin/tape tests/*.js", + "bench": "node bench" + } +} \ No newline at end of file diff --git a/node_modules/@protobufjs/float/tests/index.js b/node_modules/@protobufjs/float/tests/index.js new file mode 100644 index 0000000..324e85c --- /dev/null +++ b/node_modules/@protobufjs/float/tests/index.js @@ -0,0 +1,100 @@ +var tape = require("tape"); + +var float = require(".."); + +tape.test("float", function(test) { + + // default + test.test(test.name + " - typed array", function(test) { + runTest(float, test); + }); + + // ieee754 + test.test(test.name + " - fallback", function(test) { + var F32 = global.Float32Array, + F64 = global.Float64Array; + delete global.Float32Array; + delete global.Float64Array; + runTest(float({}), test); + global.Float32Array = F32; + global.Float64Array = F64; + }); +}); + +function runTest(float, test) { + + var common = [ + 0, + -0, + Infinity, + -Infinity, + 0.125, + 1024.5, + -4096.5, + NaN + ]; + + test.test(test.name + " - using 32 bits", function(test) { + common.concat([ + 3.4028234663852886e+38, + 1.1754943508222875e-38, + 1.1754946310819804e-39 + ]) + .forEach(function(value) { + var strval = value === 0 && 1 / value < 0 ? "-0" : value.toString(); + test.ok( + checkValue(value, 4, float.readFloatLE, float.writeFloatLE, Buffer.prototype.writeFloatLE), + "should write and read back " + strval + " (32 bit LE)" + ); + test.ok( + checkValue(value, 4, float.readFloatBE, float.writeFloatBE, Buffer.prototype.writeFloatBE), + "should write and read back " + strval + " (32 bit BE)" + ); + }); + test.end(); + }); + + test.test(test.name + " - using 64 bits", function(test) { + common.concat([ + 1.7976931348623157e+308, + 2.2250738585072014e-308, + 2.2250738585072014e-309 + ]) + .forEach(function(value) { + var strval = value === 0 && 1 / value < 0 ? "-0" : value.toString(); + test.ok( + checkValue(value, 8, float.readDoubleLE, float.writeDoubleLE, Buffer.prototype.writeDoubleLE), + "should write and read back " + strval + " (64 bit LE)" + ); + test.ok( + checkValue(value, 8, float.readDoubleBE, float.writeDoubleBE, Buffer.prototype.writeDoubleBE), + "should write and read back " + strval + " (64 bit BE)" + ); + }); + test.end(); + }); + + test.end(); +} + +function checkValue(value, size, read, write, write_comp) { + var buffer = new Buffer(size); + write(value, buffer, 0); + var value_comp = read(buffer, 0); + var strval = value === 0 && 1 / value < 0 ? "-0" : value.toString(); + if (value !== value) { + if (value_comp === value_comp) + return false; + } else if (value_comp !== value) + return false; + + var buffer_comp = new Buffer(size); + write_comp.call(buffer_comp, value, 0); + for (var i = 0; i < size; ++i) + if (buffer[i] !== buffer_comp[i]) { + console.error(">", buffer, buffer_comp); + return false; + } + + return true; +} \ No newline at end of file diff --git a/node_modules/@protobufjs/inquire/.npmignore b/node_modules/@protobufjs/inquire/.npmignore new file mode 100644 index 0000000..ce75de4 --- /dev/null +++ b/node_modules/@protobufjs/inquire/.npmignore @@ -0,0 +1,3 @@ +npm-debug.* +node_modules/ +coverage/ diff --git a/node_modules/@protobufjs/inquire/LICENSE b/node_modules/@protobufjs/inquire/LICENSE new file mode 100644 index 0000000..2a2d560 --- /dev/null +++ b/node_modules/@protobufjs/inquire/LICENSE @@ -0,0 +1,26 @@ +Copyright (c) 2016, Daniel Wirtz All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + +* Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. +* Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. +* Neither the name of its author, nor the names of its contributors + may be used to endorse or promote products derived from this software + without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/node_modules/@protobufjs/inquire/README.md b/node_modules/@protobufjs/inquire/README.md new file mode 100644 index 0000000..22f9968 --- /dev/null +++ b/node_modules/@protobufjs/inquire/README.md @@ -0,0 +1,13 @@ +@protobufjs/inquire +=================== +[![npm](https://img.shields.io/npm/v/@protobufjs/inquire.svg)](https://www.npmjs.com/package/@protobufjs/inquire) + +Requires a module only if available and hides the require call from bundlers. + +API +--- + +* **inquire(moduleName: `string`): `?Object`**
+ Requires a module only if available. + +**License:** [BSD 3-Clause License](https://opensource.org/licenses/BSD-3-Clause) diff --git a/node_modules/@protobufjs/inquire/index.d.ts b/node_modules/@protobufjs/inquire/index.d.ts new file mode 100644 index 0000000..6f9825b --- /dev/null +++ b/node_modules/@protobufjs/inquire/index.d.ts @@ -0,0 +1,9 @@ +export = inquire; + +/** + * Requires a module only if available. + * @memberof util + * @param {string} moduleName Module to require + * @returns {?Object} Required module if available and not empty, otherwise `null` + */ +declare function inquire(moduleName: string): Object; diff --git a/node_modules/@protobufjs/inquire/index.js b/node_modules/@protobufjs/inquire/index.js new file mode 100644 index 0000000..33778b5 --- /dev/null +++ b/node_modules/@protobufjs/inquire/index.js @@ -0,0 +1,17 @@ +"use strict"; +module.exports = inquire; + +/** + * Requires a module only if available. + * @memberof util + * @param {string} moduleName Module to require + * @returns {?Object} Required module if available and not empty, otherwise `null` + */ +function inquire(moduleName) { + try { + var mod = eval("quire".replace(/^/,"re"))(moduleName); // eslint-disable-line no-eval + if (mod && (mod.length || Object.keys(mod).length)) + return mod; + } catch (e) {} // eslint-disable-line no-empty + return null; +} diff --git a/node_modules/@protobufjs/inquire/package.json b/node_modules/@protobufjs/inquire/package.json new file mode 100644 index 0000000..f4b33db --- /dev/null +++ b/node_modules/@protobufjs/inquire/package.json @@ -0,0 +1,21 @@ +{ + "name": "@protobufjs/inquire", + "description": "Requires a module only if available and hides the require call from bundlers.", + "version": "1.1.0", + "author": "Daniel Wirtz ", + "repository": { + "type": "git", + "url": "https://github.com/dcodeIO/protobuf.js.git" + }, + "license": "BSD-3-Clause", + "main": "index.js", + "types": "index.d.ts", + "devDependencies": { + "istanbul": "^0.4.5", + "tape": "^4.6.3" + }, + "scripts": { + "test": "tape tests/*.js", + "coverage": "istanbul cover node_modules/tape/bin/tape tests/*.js" + } +} \ No newline at end of file diff --git a/node_modules/@protobufjs/inquire/tests/data/array.js b/node_modules/@protobufjs/inquire/tests/data/array.js new file mode 100644 index 0000000..96627c3 --- /dev/null +++ b/node_modules/@protobufjs/inquire/tests/data/array.js @@ -0,0 +1 @@ +module.exports = [1]; diff --git a/node_modules/@protobufjs/inquire/tests/data/emptyArray.js b/node_modules/@protobufjs/inquire/tests/data/emptyArray.js new file mode 100644 index 0000000..0630c8f --- /dev/null +++ b/node_modules/@protobufjs/inquire/tests/data/emptyArray.js @@ -0,0 +1 @@ +module.exports = []; diff --git a/node_modules/@protobufjs/inquire/tests/data/emptyObject.js b/node_modules/@protobufjs/inquire/tests/data/emptyObject.js new file mode 100644 index 0000000..0369aa4 --- /dev/null +++ b/node_modules/@protobufjs/inquire/tests/data/emptyObject.js @@ -0,0 +1 @@ +module.exports = {}; diff --git a/node_modules/@protobufjs/inquire/tests/data/object.js b/node_modules/@protobufjs/inquire/tests/data/object.js new file mode 100644 index 0000000..3226d44 --- /dev/null +++ b/node_modules/@protobufjs/inquire/tests/data/object.js @@ -0,0 +1 @@ +module.exports = { a: 1 }; diff --git a/node_modules/@protobufjs/inquire/tests/index.js b/node_modules/@protobufjs/inquire/tests/index.js new file mode 100644 index 0000000..7d6496f --- /dev/null +++ b/node_modules/@protobufjs/inquire/tests/index.js @@ -0,0 +1,20 @@ +var tape = require("tape"); + +var inquire = require(".."); + +tape.test("inquire", function(test) { + + test.equal(inquire("buffer").Buffer, Buffer, "should be able to require \"buffer\""); + + test.equal(inquire("%invalid"), null, "should not be able to require \"%invalid\""); + + test.equal(inquire("./tests/data/emptyObject"), null, "should return null when requiring a module exporting an empty object"); + + test.equal(inquire("./tests/data/emptyArray"), null, "should return null when requiring a module exporting an empty array"); + + test.same(inquire("./tests/data/object"), { a: 1 }, "should return the object if a non-empty object"); + + test.same(inquire("./tests/data/array"), [ 1 ], "should return the module if a non-empty array"); + + test.end(); +}); diff --git a/node_modules/@protobufjs/path/LICENSE b/node_modules/@protobufjs/path/LICENSE new file mode 100644 index 0000000..2a2d560 --- /dev/null +++ b/node_modules/@protobufjs/path/LICENSE @@ -0,0 +1,26 @@ +Copyright (c) 2016, Daniel Wirtz All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + +* Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. +* Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. +* Neither the name of its author, nor the names of its contributors + may be used to endorse or promote products derived from this software + without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/node_modules/@protobufjs/path/README.md b/node_modules/@protobufjs/path/README.md new file mode 100644 index 0000000..0e8e6bc --- /dev/null +++ b/node_modules/@protobufjs/path/README.md @@ -0,0 +1,19 @@ +@protobufjs/path +================ +[![npm](https://img.shields.io/npm/v/@protobufjs/path.svg)](https://www.npmjs.com/package/@protobufjs/path) + +A minimal path module to resolve Unix, Windows and URL paths alike. + +API +--- + +* **path.isAbsolute(path: `string`): `boolean`**
+ Tests if the specified path is absolute. + +* **path.normalize(path: `string`): `string`**
+ Normalizes the specified path. + +* **path.resolve(originPath: `string`, includePath: `string`, [alreadyNormalized=false: `boolean`]): `string`**
+ Resolves the specified include path against the specified origin path. + +**License:** [BSD 3-Clause License](https://opensource.org/licenses/BSD-3-Clause) diff --git a/node_modules/@protobufjs/path/index.d.ts b/node_modules/@protobufjs/path/index.d.ts new file mode 100644 index 0000000..567c3dc --- /dev/null +++ b/node_modules/@protobufjs/path/index.d.ts @@ -0,0 +1,22 @@ +/** + * Tests if the specified path is absolute. + * @param {string} path Path to test + * @returns {boolean} `true` if path is absolute + */ +export function isAbsolute(path: string): boolean; + +/** + * Normalizes the specified path. + * @param {string} path Path to normalize + * @returns {string} Normalized path + */ +export function normalize(path: string): string; + +/** + * Resolves the specified include path against the specified origin path. + * @param {string} originPath Path to the origin file + * @param {string} includePath Include path relative to origin path + * @param {boolean} [alreadyNormalized=false] `true` if both paths are already known to be normalized + * @returns {string} Path to the include file + */ +export function resolve(originPath: string, includePath: string, alreadyNormalized?: boolean): string; diff --git a/node_modules/@protobufjs/path/index.js b/node_modules/@protobufjs/path/index.js new file mode 100644 index 0000000..1ea7b17 --- /dev/null +++ b/node_modules/@protobufjs/path/index.js @@ -0,0 +1,65 @@ +"use strict"; + +/** + * A minimal path module to resolve Unix, Windows and URL paths alike. + * @memberof util + * @namespace + */ +var path = exports; + +var isAbsolute = +/** + * Tests if the specified path is absolute. + * @param {string} path Path to test + * @returns {boolean} `true` if path is absolute + */ +path.isAbsolute = function isAbsolute(path) { + return /^(?:\/|\w+:)/.test(path); +}; + +var normalize = +/** + * Normalizes the specified path. + * @param {string} path Path to normalize + * @returns {string} Normalized path + */ +path.normalize = function normalize(path) { + path = path.replace(/\\/g, "/") + .replace(/\/{2,}/g, "/"); + var parts = path.split("/"), + absolute = isAbsolute(path), + prefix = ""; + if (absolute) + prefix = parts.shift() + "/"; + for (var i = 0; i < parts.length;) { + if (parts[i] === "..") { + if (i > 0 && parts[i - 1] !== "..") + parts.splice(--i, 2); + else if (absolute) + parts.splice(i, 1); + else + ++i; + } else if (parts[i] === ".") + parts.splice(i, 1); + else + ++i; + } + return prefix + parts.join("/"); +}; + +/** + * Resolves the specified include path against the specified origin path. + * @param {string} originPath Path to the origin file + * @param {string} includePath Include path relative to origin path + * @param {boolean} [alreadyNormalized=false] `true` if both paths are already known to be normalized + * @returns {string} Path to the include file + */ +path.resolve = function resolve(originPath, includePath, alreadyNormalized) { + if (!alreadyNormalized) + includePath = normalize(includePath); + if (isAbsolute(includePath)) + return includePath; + if (!alreadyNormalized) + originPath = normalize(originPath); + return (originPath = originPath.replace(/(?:\/|^)[^/]+$/, "")).length ? normalize(originPath + "/" + includePath) : includePath; +}; diff --git a/node_modules/@protobufjs/path/package.json b/node_modules/@protobufjs/path/package.json new file mode 100644 index 0000000..ae0808a --- /dev/null +++ b/node_modules/@protobufjs/path/package.json @@ -0,0 +1,21 @@ +{ + "name": "@protobufjs/path", + "description": "A minimal path module to resolve Unix, Windows and URL paths alike.", + "version": "1.1.2", + "author": "Daniel Wirtz ", + "repository": { + "type": "git", + "url": "https://github.com/dcodeIO/protobuf.js.git" + }, + "license": "BSD-3-Clause", + "main": "index.js", + "types": "index.d.ts", + "devDependencies": { + "istanbul": "^0.4.5", + "tape": "^4.6.3" + }, + "scripts": { + "test": "tape tests/*.js", + "coverage": "istanbul cover node_modules/tape/bin/tape tests/*.js" + } +} \ No newline at end of file diff --git a/node_modules/@protobufjs/path/tests/index.js b/node_modules/@protobufjs/path/tests/index.js new file mode 100644 index 0000000..927736e --- /dev/null +++ b/node_modules/@protobufjs/path/tests/index.js @@ -0,0 +1,60 @@ +var tape = require("tape"); + +var path = require(".."); + +tape.test("path", function(test) { + + test.ok(path.isAbsolute("X:\\some\\path\\file.js"), "should identify absolute windows paths"); + test.ok(path.isAbsolute("/some/path/file.js"), "should identify absolute unix paths"); + + test.notOk(path.isAbsolute("some\\path\\file.js"), "should identify relative windows paths"); + test.notOk(path.isAbsolute("some/path/file.js"), "should identify relative unix paths"); + + var paths = [ + { + actual: "X:\\some\\..\\.\\path\\\\file.js", + normal: "X:/path/file.js", + resolve: { + origin: "X:/path/origin.js", + expected: "X:/path/file.js" + } + }, { + actual: "some\\..\\.\\path\\\\file.js", + normal: "path/file.js", + resolve: { + origin: "X:/path/origin.js", + expected: "X:/path/path/file.js" + } + }, { + actual: "/some/.././path//file.js", + normal: "/path/file.js", + resolve: { + origin: "/path/origin.js", + expected: "/path/file.js" + } + }, { + actual: "some/.././path//file.js", + normal: "path/file.js", + resolve: { + origin: "", + expected: "path/file.js" + } + }, { + actual: ".././path//file.js", + normal: "../path/file.js" + }, { + actual: "/.././path//file.js", + normal: "/path/file.js" + } + ]; + + paths.forEach(function(p) { + test.equal(path.normalize(p.actual), p.normal, "should normalize " + p.actual); + if (p.resolve) { + test.equal(path.resolve(p.resolve.origin, p.actual), p.resolve.expected, "should resolve " + p.actual); + test.equal(path.resolve(p.resolve.origin, p.normal, true), p.resolve.expected, "should resolve " + p.normal + " (already normalized)"); + } + }); + + test.end(); +}); diff --git a/node_modules/@protobufjs/pool/.npmignore b/node_modules/@protobufjs/pool/.npmignore new file mode 100644 index 0000000..ce75de4 --- /dev/null +++ b/node_modules/@protobufjs/pool/.npmignore @@ -0,0 +1,3 @@ +npm-debug.* +node_modules/ +coverage/ diff --git a/node_modules/@protobufjs/pool/LICENSE b/node_modules/@protobufjs/pool/LICENSE new file mode 100644 index 0000000..2a2d560 --- /dev/null +++ b/node_modules/@protobufjs/pool/LICENSE @@ -0,0 +1,26 @@ +Copyright (c) 2016, Daniel Wirtz All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + +* Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. +* Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. +* Neither the name of its author, nor the names of its contributors + may be used to endorse or promote products derived from this software + without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/node_modules/@protobufjs/pool/README.md b/node_modules/@protobufjs/pool/README.md new file mode 100644 index 0000000..3955ae0 --- /dev/null +++ b/node_modules/@protobufjs/pool/README.md @@ -0,0 +1,13 @@ +@protobufjs/pool +================ +[![npm](https://img.shields.io/npm/v/@protobufjs/pool.svg)](https://www.npmjs.com/package/@protobufjs/pool) + +A general purpose buffer pool. + +API +--- + +* **pool(alloc: `function(size: number): Uint8Array`, slice: `function(this: Uint8Array, start: number, end: number): Uint8Array`, [size=8192: `number`]): `function(size: number): Uint8Array`**
+ Creates a pooled allocator. + +**License:** [BSD 3-Clause License](https://opensource.org/licenses/BSD-3-Clause) diff --git a/node_modules/@protobufjs/pool/index.d.ts b/node_modules/@protobufjs/pool/index.d.ts new file mode 100644 index 0000000..465559c --- /dev/null +++ b/node_modules/@protobufjs/pool/index.d.ts @@ -0,0 +1,32 @@ +export = pool; + +/** + * An allocator as used by {@link util.pool}. + * @typedef PoolAllocator + * @type {function} + * @param {number} size Buffer size + * @returns {Uint8Array} Buffer + */ +type PoolAllocator = (size: number) => Uint8Array; + +/** + * A slicer as used by {@link util.pool}. + * @typedef PoolSlicer + * @type {function} + * @param {number} start Start offset + * @param {number} end End offset + * @returns {Uint8Array} Buffer slice + * @this {Uint8Array} + */ +type PoolSlicer = (this: Uint8Array, start: number, end: number) => Uint8Array; + +/** + * A general purpose buffer pool. + * @memberof util + * @function + * @param {PoolAllocator} alloc Allocator + * @param {PoolSlicer} slice Slicer + * @param {number} [size=8192] Slab size + * @returns {PoolAllocator} Pooled allocator + */ +declare function pool(alloc: PoolAllocator, slice: PoolSlicer, size?: number): PoolAllocator; diff --git a/node_modules/@protobufjs/pool/index.js b/node_modules/@protobufjs/pool/index.js new file mode 100644 index 0000000..9556f5a --- /dev/null +++ b/node_modules/@protobufjs/pool/index.js @@ -0,0 +1,48 @@ +"use strict"; +module.exports = pool; + +/** + * An allocator as used by {@link util.pool}. + * @typedef PoolAllocator + * @type {function} + * @param {number} size Buffer size + * @returns {Uint8Array} Buffer + */ + +/** + * A slicer as used by {@link util.pool}. + * @typedef PoolSlicer + * @type {function} + * @param {number} start Start offset + * @param {number} end End offset + * @returns {Uint8Array} Buffer slice + * @this {Uint8Array} + */ + +/** + * A general purpose buffer pool. + * @memberof util + * @function + * @param {PoolAllocator} alloc Allocator + * @param {PoolSlicer} slice Slicer + * @param {number} [size=8192] Slab size + * @returns {PoolAllocator} Pooled allocator + */ +function pool(alloc, slice, size) { + var SIZE = size || 8192; + var MAX = SIZE >>> 1; + var slab = null; + var offset = SIZE; + return function pool_alloc(size) { + if (size < 1 || size > MAX) + return alloc(size); + if (offset + size > SIZE) { + slab = alloc(SIZE); + offset = 0; + } + var buf = slice.call(slab, offset, offset += size); + if (offset & 7) // align to 32 bit + offset = (offset | 7) + 1; + return buf; + }; +} diff --git a/node_modules/@protobufjs/pool/package.json b/node_modules/@protobufjs/pool/package.json new file mode 100644 index 0000000..f025e03 --- /dev/null +++ b/node_modules/@protobufjs/pool/package.json @@ -0,0 +1,21 @@ +{ + "name": "@protobufjs/pool", + "description": "A general purpose buffer pool.", + "version": "1.1.0", + "author": "Daniel Wirtz ", + "repository": { + "type": "git", + "url": "https://github.com/dcodeIO/protobuf.js.git" + }, + "license": "BSD-3-Clause", + "main": "index.js", + "types": "index.d.ts", + "devDependencies": { + "istanbul": "^0.4.5", + "tape": "^4.6.3" + }, + "scripts": { + "test": "tape tests/*.js", + "coverage": "istanbul cover node_modules/tape/bin/tape tests/*.js" + } +} diff --git a/node_modules/@protobufjs/pool/tests/index.js b/node_modules/@protobufjs/pool/tests/index.js new file mode 100644 index 0000000..dc488b8 --- /dev/null +++ b/node_modules/@protobufjs/pool/tests/index.js @@ -0,0 +1,33 @@ +var tape = require("tape"); + +var pool = require(".."); + +if (typeof Uint8Array !== "undefined") +tape.test("pool", function(test) { + + var alloc = pool(function(size) { return new Uint8Array(size); }, Uint8Array.prototype.subarray); + + var buf1 = alloc(0); + test.equal(buf1.length, 0, "should allocate a buffer of size 0"); + + var buf2 = alloc(1); + test.equal(buf2.length, 1, "should allocate a buffer of size 1 (initializes slab)"); + + test.notEqual(buf2.buffer, buf1.buffer, "should not reference the same backing buffer if previous buffer had size 0"); + test.equal(buf2.byteOffset, 0, "should allocate at byteOffset 0 when using a new slab"); + + buf1 = alloc(1); + test.equal(buf1.buffer, buf2.buffer, "should reference the same backing buffer when allocating a chunk fitting into the slab"); + test.equal(buf1.byteOffset, 8, "should align slices to 32 bit and this allocate at byteOffset 8"); + + var buf3 = alloc(4097); + test.notEqual(buf3.buffer, buf2.buffer, "should not reference the same backing buffer when allocating a buffer larger than half the backing buffer's size"); + + buf2 = alloc(4096); + test.equal(buf2.buffer, buf1.buffer, "should reference the same backing buffer when allocating a buffer smaller or equal than half the backing buffer's size"); + + buf1 = alloc(4096); + test.notEqual(buf1.buffer, buf2.buffer, "should not reference the same backing buffer when the slab is exhausted (initializes new slab)"); + + test.end(); +}); \ No newline at end of file diff --git a/node_modules/@protobufjs/utf8/.npmignore b/node_modules/@protobufjs/utf8/.npmignore new file mode 100644 index 0000000..ce75de4 --- /dev/null +++ b/node_modules/@protobufjs/utf8/.npmignore @@ -0,0 +1,3 @@ +npm-debug.* +node_modules/ +coverage/ diff --git a/node_modules/@protobufjs/utf8/LICENSE b/node_modules/@protobufjs/utf8/LICENSE new file mode 100644 index 0000000..2a2d560 --- /dev/null +++ b/node_modules/@protobufjs/utf8/LICENSE @@ -0,0 +1,26 @@ +Copyright (c) 2016, Daniel Wirtz All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + +* Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. +* Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. +* Neither the name of its author, nor the names of its contributors + may be used to endorse or promote products derived from this software + without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/node_modules/@protobufjs/utf8/README.md b/node_modules/@protobufjs/utf8/README.md new file mode 100644 index 0000000..3696289 --- /dev/null +++ b/node_modules/@protobufjs/utf8/README.md @@ -0,0 +1,20 @@ +@protobufjs/utf8 +================ +[![npm](https://img.shields.io/npm/v/@protobufjs/utf8.svg)](https://www.npmjs.com/package/@protobufjs/utf8) + +A minimal UTF8 implementation for number arrays. + +API +--- + +* **utf8.length(string: `string`): `number`**
+ Calculates the UTF8 byte length of a string. + +* **utf8.read(buffer: `Uint8Array`, start: `number`, end: `number`): `string`**
+ Reads UTF8 bytes as a string. + +* **utf8.write(string: `string`, buffer: `Uint8Array`, offset: `number`): `number`**
+ Writes a string as UTF8 bytes. + + +**License:** [BSD 3-Clause License](https://opensource.org/licenses/BSD-3-Clause) diff --git a/node_modules/@protobufjs/utf8/index.d.ts b/node_modules/@protobufjs/utf8/index.d.ts new file mode 100644 index 0000000..010888c --- /dev/null +++ b/node_modules/@protobufjs/utf8/index.d.ts @@ -0,0 +1,24 @@ +/** + * Calculates the UTF8 byte length of a string. + * @param {string} string String + * @returns {number} Byte length + */ +export function length(string: string): number; + +/** + * Reads UTF8 bytes as a string. + * @param {Uint8Array} buffer Source buffer + * @param {number} start Source start + * @param {number} end Source end + * @returns {string} String read + */ +export function read(buffer: Uint8Array, start: number, end: number): string; + +/** + * Writes a string as UTF8 bytes. + * @param {string} string Source string + * @param {Uint8Array} buffer Destination buffer + * @param {number} offset Destination offset + * @returns {number} Bytes written + */ +export function write(string: string, buffer: Uint8Array, offset: number): number; diff --git a/node_modules/@protobufjs/utf8/index.js b/node_modules/@protobufjs/utf8/index.js new file mode 100644 index 0000000..e4ff8df --- /dev/null +++ b/node_modules/@protobufjs/utf8/index.js @@ -0,0 +1,105 @@ +"use strict"; + +/** + * A minimal UTF8 implementation for number arrays. + * @memberof util + * @namespace + */ +var utf8 = exports; + +/** + * Calculates the UTF8 byte length of a string. + * @param {string} string String + * @returns {number} Byte length + */ +utf8.length = function utf8_length(string) { + var len = 0, + c = 0; + for (var i = 0; i < string.length; ++i) { + c = string.charCodeAt(i); + if (c < 128) + len += 1; + else if (c < 2048) + len += 2; + else if ((c & 0xFC00) === 0xD800 && (string.charCodeAt(i + 1) & 0xFC00) === 0xDC00) { + ++i; + len += 4; + } else + len += 3; + } + return len; +}; + +/** + * Reads UTF8 bytes as a string. + * @param {Uint8Array} buffer Source buffer + * @param {number} start Source start + * @param {number} end Source end + * @returns {string} String read + */ +utf8.read = function utf8_read(buffer, start, end) { + var len = end - start; + if (len < 1) + return ""; + var parts = null, + chunk = [], + i = 0, // char offset + t; // temporary + while (start < end) { + t = buffer[start++]; + if (t < 128) + chunk[i++] = t; + else if (t > 191 && t < 224) + chunk[i++] = (t & 31) << 6 | buffer[start++] & 63; + else if (t > 239 && t < 365) { + t = ((t & 7) << 18 | (buffer[start++] & 63) << 12 | (buffer[start++] & 63) << 6 | buffer[start++] & 63) - 0x10000; + chunk[i++] = 0xD800 + (t >> 10); + chunk[i++] = 0xDC00 + (t & 1023); + } else + chunk[i++] = (t & 15) << 12 | (buffer[start++] & 63) << 6 | buffer[start++] & 63; + if (i > 8191) { + (parts || (parts = [])).push(String.fromCharCode.apply(String, chunk)); + i = 0; + } + } + if (parts) { + if (i) + parts.push(String.fromCharCode.apply(String, chunk.slice(0, i))); + return parts.join(""); + } + return String.fromCharCode.apply(String, chunk.slice(0, i)); +}; + +/** + * Writes a string as UTF8 bytes. + * @param {string} string Source string + * @param {Uint8Array} buffer Destination buffer + * @param {number} offset Destination offset + * @returns {number} Bytes written + */ +utf8.write = function utf8_write(string, buffer, offset) { + var start = offset, + c1, // character 1 + c2; // character 2 + for (var i = 0; i < string.length; ++i) { + c1 = string.charCodeAt(i); + if (c1 < 128) { + buffer[offset++] = c1; + } else if (c1 < 2048) { + buffer[offset++] = c1 >> 6 | 192; + buffer[offset++] = c1 & 63 | 128; + } else if ((c1 & 0xFC00) === 0xD800 && ((c2 = string.charCodeAt(i + 1)) & 0xFC00) === 0xDC00) { + c1 = 0x10000 + ((c1 & 0x03FF) << 10) + (c2 & 0x03FF); + ++i; + buffer[offset++] = c1 >> 18 | 240; + buffer[offset++] = c1 >> 12 & 63 | 128; + buffer[offset++] = c1 >> 6 & 63 | 128; + buffer[offset++] = c1 & 63 | 128; + } else { + buffer[offset++] = c1 >> 12 | 224; + buffer[offset++] = c1 >> 6 & 63 | 128; + buffer[offset++] = c1 & 63 | 128; + } + } + return offset - start; +}; diff --git a/node_modules/@protobufjs/utf8/package.json b/node_modules/@protobufjs/utf8/package.json new file mode 100644 index 0000000..80881c5 --- /dev/null +++ b/node_modules/@protobufjs/utf8/package.json @@ -0,0 +1,21 @@ +{ + "name": "@protobufjs/utf8", + "description": "A minimal UTF8 implementation for number arrays.", + "version": "1.1.0", + "author": "Daniel Wirtz ", + "repository": { + "type": "git", + "url": "https://github.com/dcodeIO/protobuf.js.git" + }, + "license": "BSD-3-Clause", + "main": "index.js", + "types": "index.d.ts", + "devDependencies": { + "istanbul": "^0.4.5", + "tape": "^4.6.3" + }, + "scripts": { + "test": "tape tests/*.js", + "coverage": "istanbul cover node_modules/tape/bin/tape tests/*.js" + } +} diff --git a/node_modules/@protobufjs/utf8/tests/data/utf8.txt b/node_modules/@protobufjs/utf8/tests/data/utf8.txt new file mode 100644 index 0000000..580b4c4 --- /dev/null +++ b/node_modules/@protobufjs/utf8/tests/data/utf8.txt @@ -0,0 +1,216 @@ +UTF-8 encoded sample plain-text file +‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾ + +Markus Kuhn [ˈmaʳkʊs kuːn] — 2002-07-25 CC BY + + +The ASCII compatible UTF-8 encoding used in this plain-text file +is defined in Unicode, ISO 10646-1, and RFC 2279. + + +Using Unicode/UTF-8, you can write in emails and source code things such as + +Mathematics and sciences: + + ∮ E⋅da = Q, n → ∞, ∑ f(i) = ∏ g(i), ⎧⎡⎛┌─────┐⎞⎤⎫ + ⎪⎢⎜│a²+b³ ⎟⎥⎪ + ∀x∈ℝ: ⌈x⌉ = −⌊−x⌋, α ∧ ¬β = ¬(¬α ∨ β), ⎪⎢⎜│───── ⎟⎥⎪ + ⎪⎢⎜⎷ c₈ ⎟⎥⎪ + ℕ ⊆ ℕ₀ ⊂ ℤ ⊂ ℚ ⊂ ℝ ⊂ ℂ, ⎨⎢⎜ ⎟⎥⎬ + ⎪⎢⎜ ∞ ⎟⎥⎪ + ⊥ < a ≠ b ≡ c ≤ d ≪ ⊤ ⇒ (⟦A⟧ ⇔ ⟪B⟫), ⎪⎢⎜ ⎲ ⎟⎥⎪ + ⎪⎢⎜ ⎳aⁱ-bⁱ⎟⎥⎪ + 2H₂ + O₂ ⇌ 2H₂O, R = 4.7 kΩ, ⌀ 200 mm ⎩⎣⎝i=1 ⎠⎦⎭ + +Linguistics and dictionaries: + + ði ıntəˈnæʃənəl fəˈnɛtık əsoʊsiˈeıʃn + Y [ˈʏpsilɔn], Yen [jɛn], Yoga [ˈjoːgɑ] + +APL: + + ((V⍳V)=⍳⍴V)/V←,V ⌷←⍳→⍴∆∇⊃‾⍎⍕⌈ + +Nicer typography in plain text files: + + ╔══════════════════════════════════════════╗ + ║ ║ + ║ • ‘single’ and “double” quotes ║ + ║ ║ + ║ • Curly apostrophes: “We’ve been here” ║ + ║ ║ + ║ • Latin-1 apostrophe and accents: '´` ║ + ║ ║ + ║ • ‚deutsche‘ „Anführungszeichen“ ║ + ║ ║ + ║ • †, ‡, ‰, •, 3–4, —, −5/+5, ™, … ║ + ║ ║ + ║ • ASCII safety test: 1lI|, 0OD, 8B ║ + ║ ╭─────────╮ ║ + ║ • the euro symbol: │ 14.95 € │ ║ + ║ ╰─────────╯ ║ + ╚══════════════════════════════════════════╝ + +Combining characters: + + STARGΛ̊TE SG-1, a = v̇ = r̈, a⃑ ⊥ b⃑ + +Greek (in Polytonic): + + The Greek anthem: + + Σὲ γνωρίζω ἀπὸ τὴν κόψη + τοῦ σπαθιοῦ τὴν τρομερή, + σὲ γνωρίζω ἀπὸ τὴν ὄψη + ποὺ μὲ βία μετράει τὴ γῆ. + + ᾿Απ᾿ τὰ κόκκαλα βγαλμένη + τῶν ῾Ελλήνων τὰ ἱερά + καὶ σὰν πρῶτα ἀνδρειωμένη + χαῖρε, ὦ χαῖρε, ᾿Ελευθεριά! + + From a speech of Demosthenes in the 4th century BC: + + Οὐχὶ ταὐτὰ παρίσταταί μοι γιγνώσκειν, ὦ ἄνδρες ᾿Αθηναῖοι, + ὅταν τ᾿ εἰς τὰ πράγματα ἀποβλέψω καὶ ὅταν πρὸς τοὺς + λόγους οὓς ἀκούω· τοὺς μὲν γὰρ λόγους περὶ τοῦ + τιμωρήσασθαι Φίλιππον ὁρῶ γιγνομένους, τὰ δὲ πράγματ᾿ + εἰς τοῦτο προήκοντα, ὥσθ᾿ ὅπως μὴ πεισόμεθ᾿ αὐτοὶ + πρότερον κακῶς σκέψασθαι δέον. οὐδέν οὖν ἄλλο μοι δοκοῦσιν + οἱ τὰ τοιαῦτα λέγοντες ἢ τὴν ὑπόθεσιν, περὶ ἧς βουλεύεσθαι, + οὐχὶ τὴν οὖσαν παριστάντες ὑμῖν ἁμαρτάνειν. ἐγὼ δέ, ὅτι μέν + ποτ᾿ ἐξῆν τῇ πόλει καὶ τὰ αὑτῆς ἔχειν ἀσφαλῶς καὶ Φίλιππον + τιμωρήσασθαι, καὶ μάλ᾿ ἀκριβῶς οἶδα· ἐπ᾿ ἐμοῦ γάρ, οὐ πάλαι + γέγονεν ταῦτ᾿ ἀμφότερα· νῦν μέντοι πέπεισμαι τοῦθ᾿ ἱκανὸν + προλαβεῖν ἡμῖν εἶναι τὴν πρώτην, ὅπως τοὺς συμμάχους + σώσομεν. ἐὰν γὰρ τοῦτο βεβαίως ὑπάρξῃ, τότε καὶ περὶ τοῦ + τίνα τιμωρήσεταί τις καὶ ὃν τρόπον ἐξέσται σκοπεῖν· πρὶν δὲ + τὴν ἀρχὴν ὀρθῶς ὑποθέσθαι, μάταιον ἡγοῦμαι περὶ τῆς + τελευτῆς ὁντινοῦν ποιεῖσθαι λόγον. + + Δημοσθένους, Γ´ ᾿Ολυνθιακὸς + +Georgian: + + From a Unicode conference invitation: + + გთხოვთ ახლავე გაიაროთ რეგისტრაცია Unicode-ის მეათე საერთაშორისო + კონფერენციაზე დასასწრებად, რომელიც გაიმართება 10-12 მარტს, + ქ. მაინცში, გერმანიაში. კონფერენცია შეჰკრებს ერთად მსოფლიოს + ექსპერტებს ისეთ დარგებში როგორიცაა ინტერნეტი და Unicode-ი, + ინტერნაციონალიზაცია და ლოკალიზაცია, Unicode-ის გამოყენება + ოპერაციულ სისტემებსა, და გამოყენებით პროგრამებში, შრიფტებში, + ტექსტების დამუშავებასა და მრავალენოვან კომპიუტერულ სისტემებში. + +Russian: + + From a Unicode conference invitation: + + Зарегистрируйтесь сейчас на Десятую Международную Конференцию по + Unicode, которая состоится 10-12 марта 1997 года в Майнце в Германии. + Конференция соберет широкий круг экспертов по вопросам глобального + Интернета и Unicode, локализации и интернационализации, воплощению и + применению Unicode в различных операционных системах и программных + приложениях, шрифтах, верстке и многоязычных компьютерных системах. + +Thai (UCS Level 2): + + Excerpt from a poetry on The Romance of The Three Kingdoms (a Chinese + classic 'San Gua'): + + [----------------------------|------------------------] + ๏ แผ่นดินฮั่นเสื่อมโทรมแสนสังเวช พระปกเกศกองบู๊กู้ขึ้นใหม่ + สิบสองกษัตริย์ก่อนหน้าแลถัดไป สององค์ไซร้โง่เขลาเบาปัญญา + ทรงนับถือขันทีเป็นที่พึ่ง บ้านเมืองจึงวิปริตเป็นนักหนา + โฮจิ๋นเรียกทัพทั่วหัวเมืองมา หมายจะฆ่ามดชั่วตัวสำคัญ + เหมือนขับไสไล่เสือจากเคหา รับหมาป่าเข้ามาเลยอาสัญ + ฝ่ายอ้องอุ้นยุแยกให้แตกกัน ใช้สาวนั้นเป็นชนวนชื่นชวนใจ + พลันลิฉุยกุยกีกลับก่อเหตุ ช่างอาเพศจริงหนาฟ้าร้องไห้ + ต้องรบราฆ่าฟันจนบรรลัย ฤๅหาใครค้ำชูกู้บรรลังก์ ฯ + + (The above is a two-column text. If combining characters are handled + correctly, the lines of the second column should be aligned with the + | character above.) + +Ethiopian: + + Proverbs in the Amharic language: + + ሰማይ አይታረስ ንጉሥ አይከሰስ። + ብላ ካለኝ እንደአባቴ በቆመጠኝ። + ጌጥ ያለቤቱ ቁምጥና ነው። + ደሀ በሕልሙ ቅቤ ባይጠጣ ንጣት በገደለው። + የአፍ ወለምታ በቅቤ አይታሽም። + አይጥ በበላ ዳዋ ተመታ። + ሲተረጉሙ ይደረግሙ። + ቀስ በቀስ፥ ዕንቁላል በእግሩ ይሄዳል። + ድር ቢያብር አንበሳ ያስር። + ሰው እንደቤቱ እንጅ እንደ ጉረቤቱ አይተዳደርም። + እግዜር የከፈተውን ጉሮሮ ሳይዘጋው አይድርም። + የጎረቤት ሌባ፥ ቢያዩት ይስቅ ባያዩት ያጠልቅ። + ሥራ ከመፍታት ልጄን ላፋታት። + ዓባይ ማደሪያ የለው፥ ግንድ ይዞ ይዞራል። + የእስላም አገሩ መካ የአሞራ አገሩ ዋርካ። + ተንጋሎ ቢተፉ ተመልሶ ባፉ። + ወዳጅህ ማር ቢሆን ጨርስህ አትላሰው። + እግርህን በፍራሽህ ልክ ዘርጋ። + +Runes: + + ᚻᛖ ᚳᚹᚫᚦ ᚦᚫᛏ ᚻᛖ ᛒᚢᛞᛖ ᚩᚾ ᚦᚫᛗ ᛚᚪᚾᛞᛖ ᚾᚩᚱᚦᚹᛖᚪᚱᛞᚢᛗ ᚹᛁᚦ ᚦᚪ ᚹᛖᛥᚫ + + (Old English, which transcribed into Latin reads 'He cwaeth that he + bude thaem lande northweardum with tha Westsae.' and means 'He said + that he lived in the northern land near the Western Sea.') + +Braille: + + ⡌⠁⠧⠑ ⠼⠁⠒ ⡍⠜⠇⠑⠹⠰⠎ ⡣⠕⠌ + + ⡍⠜⠇⠑⠹ ⠺⠁⠎ ⠙⠑⠁⠙⠒ ⠞⠕ ⠃⠑⠛⠔ ⠺⠊⠹⠲ ⡹⠻⠑ ⠊⠎ ⠝⠕ ⠙⠳⠃⠞ + ⠱⠁⠞⠑⠧⠻ ⠁⠃⠳⠞ ⠹⠁⠞⠲ ⡹⠑ ⠗⠑⠛⠊⠌⠻ ⠕⠋ ⠙⠊⠎ ⠃⠥⠗⠊⠁⠇ ⠺⠁⠎ + ⠎⠊⠛⠝⠫ ⠃⠹ ⠹⠑ ⠊⠇⠻⠛⠹⠍⠁⠝⠂ ⠹⠑ ⠊⠇⠻⠅⠂ ⠹⠑ ⠥⠝⠙⠻⠞⠁⠅⠻⠂ + ⠁⠝⠙ ⠹⠑ ⠡⠊⠑⠋ ⠍⠳⠗⠝⠻⠲ ⡎⠊⠗⠕⠕⠛⠑ ⠎⠊⠛⠝⠫ ⠊⠞⠲ ⡁⠝⠙ + ⡎⠊⠗⠕⠕⠛⠑⠰⠎ ⠝⠁⠍⠑ ⠺⠁⠎ ⠛⠕⠕⠙ ⠥⠏⠕⠝ ⠰⡡⠁⠝⠛⠑⠂ ⠋⠕⠗ ⠁⠝⠹⠹⠔⠛ ⠙⠑ + ⠡⠕⠎⠑ ⠞⠕ ⠏⠥⠞ ⠙⠊⠎ ⠙⠁⠝⠙ ⠞⠕⠲ + + ⡕⠇⠙ ⡍⠜⠇⠑⠹ ⠺⠁⠎ ⠁⠎ ⠙⠑⠁⠙ ⠁⠎ ⠁ ⠙⠕⠕⠗⠤⠝⠁⠊⠇⠲ + + ⡍⠔⠙⠖ ⡊ ⠙⠕⠝⠰⠞ ⠍⠑⠁⠝ ⠞⠕ ⠎⠁⠹ ⠹⠁⠞ ⡊ ⠅⠝⠪⠂ ⠕⠋ ⠍⠹ + ⠪⠝ ⠅⠝⠪⠇⠫⠛⠑⠂ ⠱⠁⠞ ⠹⠻⠑ ⠊⠎ ⠏⠜⠞⠊⠊⠥⠇⠜⠇⠹ ⠙⠑⠁⠙ ⠁⠃⠳⠞ + ⠁ ⠙⠕⠕⠗⠤⠝⠁⠊⠇⠲ ⡊ ⠍⠊⠣⠞ ⠙⠁⠧⠑ ⠃⠑⠲ ⠔⠊⠇⠔⠫⠂ ⠍⠹⠎⠑⠇⠋⠂ ⠞⠕ + ⠗⠑⠛⠜⠙ ⠁ ⠊⠕⠋⠋⠔⠤⠝⠁⠊⠇ ⠁⠎ ⠹⠑ ⠙⠑⠁⠙⠑⠌ ⠏⠊⠑⠊⠑ ⠕⠋ ⠊⠗⠕⠝⠍⠕⠝⠛⠻⠹ + ⠔ ⠹⠑ ⠞⠗⠁⠙⠑⠲ ⡃⠥⠞ ⠹⠑ ⠺⠊⠎⠙⠕⠍ ⠕⠋ ⠳⠗ ⠁⠝⠊⠑⠌⠕⠗⠎ + ⠊⠎ ⠔ ⠹⠑ ⠎⠊⠍⠊⠇⠑⠆ ⠁⠝⠙ ⠍⠹ ⠥⠝⠙⠁⠇⠇⠪⠫ ⠙⠁⠝⠙⠎ + ⠩⠁⠇⠇ ⠝⠕⠞ ⠙⠊⠌⠥⠗⠃ ⠊⠞⠂ ⠕⠗ ⠹⠑ ⡊⠳⠝⠞⠗⠹⠰⠎ ⠙⠕⠝⠑ ⠋⠕⠗⠲ ⡹⠳ + ⠺⠊⠇⠇ ⠹⠻⠑⠋⠕⠗⠑ ⠏⠻⠍⠊⠞ ⠍⠑ ⠞⠕ ⠗⠑⠏⠑⠁⠞⠂ ⠑⠍⠏⠙⠁⠞⠊⠊⠁⠇⠇⠹⠂ ⠹⠁⠞ + ⡍⠜⠇⠑⠹ ⠺⠁⠎ ⠁⠎ ⠙⠑⠁⠙ ⠁⠎ ⠁ ⠙⠕⠕⠗⠤⠝⠁⠊⠇⠲ + + (The first couple of paragraphs of "A Christmas Carol" by Dickens) + +Compact font selection example text: + + ABCDEFGHIJKLMNOPQRSTUVWXYZ /0123456789 + abcdefghijklmnopqrstuvwxyz £©µÀÆÖÞßéöÿ + –—‘“”„†•…‰™œŠŸž€ ΑΒΓΔΩαβγδω АБВГДабвгд + ∀∂∈ℝ∧∪≡∞ ↑↗↨↻⇣ ┐┼╔╘░►☺♀ fi�⑀₂ἠḂӥẄɐː⍎אԱა + +Greetings in various languages: + + Hello world, Καλημέρα κόσμε, コンニチハ + +Box drawing alignment tests: █ + ▉ + ╔══╦══╗ ┌──┬──┐ ╭──┬──╮ ╭──┬──╮ ┏━━┳━━┓ ┎┒┏┑ ╷ ╻ ┏┯┓ ┌┰┐ ▊ ╱╲╱╲╳╳╳ + ║┌─╨─┐║ │╔═╧═╗│ │╒═╪═╕│ │╓─╁─╖│ ┃┌─╂─┐┃ ┗╃╄┙ ╶┼╴╺╋╸┠┼┨ ┝╋┥ ▋ ╲╱╲╱╳╳╳ + ║│╲ ╱│║ │║ ║│ ││ │ ││ │║ ┃ ║│ ┃│ ╿ │┃ ┍╅╆┓ ╵ ╹ ┗┷┛ └┸┘ ▌ ╱╲╱╲╳╳╳ + ╠╡ ╳ ╞╣ ├╢ ╟┤ ├┼─┼─┼┤ ├╫─╂─╫┤ ┣┿╾┼╼┿┫ ┕┛┖┚ ┌┄┄┐ ╎ ┏┅┅┓ ┋ ▍ ╲╱╲╱╳╳╳ + ║│╱ ╲│║ │║ ║│ ││ │ ││ │║ ┃ ║│ ┃│ ╽ │┃ ░░▒▒▓▓██ ┊ ┆ ╎ ╏ ┇ ┋ ▎ + ║└─╥─┘║ │╚═╤═╝│ │╘═╪═╛│ │╙─╀─╜│ ┃└─╂─┘┃ ░░▒▒▓▓██ ┊ ┆ ╎ ╏ ┇ ┋ ▏ + ╚══╩══╝ └──┴──┘ ╰──┴──╯ ╰──┴──╯ ┗━━┻━━┛ ▗▄▖▛▀▜ └╌╌┘ ╎ ┗╍╍┛ ┋ ▁▂▃▄▅▆▇█ + ▝▀▘▙▄▟ + +Surrogates: + +𠜎 𠜱 𠝹 𠱓 𠱸 𠲖 𠳏 𠳕 𠴕 𠵼 𠵿 𠸎 𠸏 𠹷 𠺝 𠺢 𠻗 𠻹 𠻺 𠼭 𠼮 𠽌 𠾴 𠾼 𠿪 𡁜 𡁯 𡁵 𡁶 𡁻 𡃁 +𡃉 𡇙 𢃇 𢞵 𢫕 𢭃 𢯊 𢱑 𢱕 𢳂 𢴈 𢵌 𢵧 𢺳 𣲷 𤓓 𤶸 𤷪 𥄫 𦉘 𦟌 𦧲 𦧺 𧨾 𨅝 𨈇 𨋢 𨳊 𨳍 𨳒 𩶘 diff --git a/node_modules/@protobufjs/utf8/tests/index.js b/node_modules/@protobufjs/utf8/tests/index.js new file mode 100644 index 0000000..222cd8a --- /dev/null +++ b/node_modules/@protobufjs/utf8/tests/index.js @@ -0,0 +1,57 @@ +var tape = require("tape"); + +var utf8 = require(".."); + +var data = require("fs").readFileSync(require.resolve("./data/utf8.txt")), + dataStr = data.toString("utf8"); + +tape.test("utf8", function(test) { + + test.test(test.name + " - length", function(test) { + test.equal(utf8.length(""), 0, "should return a byte length of zero for an empty string"); + + test.equal(utf8.length(dataStr), Buffer.byteLength(dataStr), "should return the same byte length as node buffers"); + + test.end(); + }); + + test.test(test.name + " - read", function(test) { + var comp = utf8.read([], 0, 0); + test.equal(comp, "", "should decode an empty buffer to an empty string"); + + comp = utf8.read(data, 0, data.length); + test.equal(comp, data.toString("utf8"), "should decode to the same byte data as node buffers"); + + var longData = Buffer.concat([data, data, data, data]); + comp = utf8.read(longData, 0, longData.length); + test.equal(comp, longData.toString("utf8"), "should decode to the same byte data as node buffers (long)"); + + var chunkData = new Buffer(data.toString("utf8").substring(0, 8192)); + comp = utf8.read(chunkData, 0, chunkData.length); + test.equal(comp, chunkData.toString("utf8"), "should decode to the same byte data as node buffers (chunk size)"); + + test.end(); + }); + + test.test(test.name + " - write", function(test) { + var buf = new Buffer(0); + test.equal(utf8.write("", buf, 0), 0, "should encode an empty string to an empty buffer"); + + var len = utf8.length(dataStr); + buf = new Buffer(len); + test.equal(utf8.write(dataStr, buf, 0), len, "should encode to exactly " + len + " bytes"); + + test.equal(buf.length, data.length, "should encode to a buffer length equal to that of node buffers"); + + for (var i = 0; i < buf.length; ++i) { + if (buf[i] !== data[i]) { + test.fail("should encode to the same buffer data as node buffers (offset " + i + ")"); + return; + } + } + test.pass("should encode to the same buffer data as node buffers"); + + test.end(); + }); + +}); diff --git a/node_modules/@types/node/LICENSE b/node_modules/@types/node/LICENSE new file mode 100644 index 0000000..9e841e7 --- /dev/null +++ b/node_modules/@types/node/LICENSE @@ -0,0 +1,21 @@ + MIT License + + Copyright (c) Microsoft Corporation. + + Permission is hereby granted, free of charge, to any person obtaining a copy + of this software and associated documentation files (the "Software"), to deal + in the Software without restriction, including without limitation the rights + to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + copies of the Software, and to permit persons to whom the Software is + furnished to do so, subject to the following conditions: + + The above copyright notice and this permission notice shall be included in all + copies or substantial portions of the Software. + + THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + SOFTWARE diff --git a/node_modules/@types/node/README.md b/node_modules/@types/node/README.md new file mode 100644 index 0000000..e13ec5a --- /dev/null +++ b/node_modules/@types/node/README.md @@ -0,0 +1,15 @@ +# Installation +> `npm install --save @types/node` + +# Summary +This package contains type definitions for node (https://nodejs.org/). + +# Details +Files were exported from https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/node. + +### Additional Details + * Last updated: Mon, 03 Jun 2024 23:35:49 GMT + * Dependencies: [undici-types](https://npmjs.com/package/undici-types) + +# Credits +These definitions were written by [Microsoft TypeScript](https://github.com/Microsoft), [Alberto Schiabel](https://github.com/jkomyno), [Alvis HT Tang](https://github.com/alvis), [Andrew Makarov](https://github.com/r3nya), [Benjamin Toueg](https://github.com/btoueg), [Chigozirim C.](https://github.com/smac89), [David Junger](https://github.com/touffy), [Deividas Bakanas](https://github.com/DeividasBakanas), [Eugene Y. Q. Shen](https://github.com/eyqs), [Hannes Magnusson](https://github.com/Hannes-Magnusson-CK), [Huw](https://github.com/hoo29), [Kelvin Jin](https://github.com/kjin), [Klaus Meinhardt](https://github.com/ajafff), [Lishude](https://github.com/islishude), [Mariusz Wiktorczyk](https://github.com/mwiktorczyk), [Mohsen Azimi](https://github.com/mohsen1), [Nikita Galkin](https://github.com/galkin), [Parambir Singh](https://github.com/parambirs), [Sebastian Silbermann](https://github.com/eps1lon), [Thomas den Hollander](https://github.com/ThomasdenH), [Wilco Bakker](https://github.com/WilcoBakker), [wwwy3y3](https://github.com/wwwy3y3), [Samuel Ainsworth](https://github.com/samuela), [Kyle Uehlein](https://github.com/kuehlein), [Thanik Bhongbhibhat](https://github.com/bhongy), [Marcin Kopacz](https://github.com/chyzwar), [Trivikram Kamat](https://github.com/trivikr), [Junxiao Shi](https://github.com/yoursunny), [Ilia Baryshnikov](https://github.com/qwelias), [ExE Boss](https://github.com/ExE-Boss), [Piotr Błażejewicz](https://github.com/peterblazejewicz), [Anna Henningsen](https://github.com/addaleax), [Victor Perin](https://github.com/victorperin), [Yongsheng Zhang](https://github.com/ZYSzys), [NodeJS Contributors](https://github.com/NodeJS), [Linus Unnebäck](https://github.com/LinusU), [wafuwafu13](https://github.com/wafuwafu13), [Matteo Collina](https://github.com/mcollina), and [Dmitry Semigradsky](https://github.com/Semigradsky). diff --git a/node_modules/@types/node/assert.d.ts b/node_modules/@types/node/assert.d.ts new file mode 100644 index 0000000..4e465c5 --- /dev/null +++ b/node_modules/@types/node/assert.d.ts @@ -0,0 +1,1040 @@ +/** + * The `node:assert` module provides a set of assertion functions for verifying + * invariants. + * @see [source](https://github.com/nodejs/node/blob/v20.13.1/lib/assert.js) + */ +declare module "assert" { + /** + * An alias of {@link ok}. + * @since v0.5.9 + * @param value The input that is checked for being truthy. + */ + function assert(value: unknown, message?: string | Error): asserts value; + namespace assert { + /** + * Indicates the failure of an assertion. All errors thrown by the `node:assert` module will be instances of the `AssertionError` class. + */ + class AssertionError extends Error { + /** + * Set to the `actual` argument for methods such as {@link assert.strictEqual()}. + */ + actual: unknown; + /** + * Set to the `expected` argument for methods such as {@link assert.strictEqual()}. + */ + expected: unknown; + /** + * Set to the passed in operator value. + */ + operator: string; + /** + * Indicates if the message was auto-generated (`true`) or not. + */ + generatedMessage: boolean; + /** + * Value is always `ERR_ASSERTION` to show that the error is an assertion error. + */ + code: "ERR_ASSERTION"; + constructor(options?: { + /** If provided, the error message is set to this value. */ + message?: string | undefined; + /** The `actual` property on the error instance. */ + actual?: unknown | undefined; + /** The `expected` property on the error instance. */ + expected?: unknown | undefined; + /** The `operator` property on the error instance. */ + operator?: string | undefined; + /** If provided, the generated stack trace omits frames before this function. */ + // eslint-disable-next-line @typescript-eslint/ban-types + stackStartFn?: Function | undefined; + }); + } + /** + * This feature is deprecated and will be removed in a future version. + * Please consider using alternatives such as the `mock` helper function. + * @since v14.2.0, v12.19.0 + * @deprecated Deprecated + */ + class CallTracker { + /** + * The wrapper function is expected to be called exactly `exact` times. If the + * function has not been called exactly `exact` times when `tracker.verify()` is called, then `tracker.verify()` will throw an + * error. + * + * ```js + * import assert from 'node:assert'; + * + * // Creates call tracker. + * const tracker = new assert.CallTracker(); + * + * function func() {} + * + * // Returns a function that wraps func() that must be called exact times + * // before tracker.verify(). + * const callsfunc = tracker.calls(func); + * ``` + * @since v14.2.0, v12.19.0 + * @param [fn='A no-op function'] + * @param [exact=1] + * @return A function that wraps `fn`. + */ + calls(exact?: number): () => void; + calls any>(fn?: Func, exact?: number): Func; + /** + * Example: + * + * ```js + * import assert from 'node:assert'; + * + * const tracker = new assert.CallTracker(); + * + * function func() {} + * const callsfunc = tracker.calls(func); + * callsfunc(1, 2, 3); + * + * assert.deepStrictEqual(tracker.getCalls(callsfunc), + * [{ thisArg: undefined, arguments: [1, 2, 3] }]); + * ``` + * @since v18.8.0, v16.18.0 + * @return An array with all the calls to a tracked function. + */ + getCalls(fn: Function): CallTrackerCall[]; + /** + * The arrays contains information about the expected and actual number of calls of + * the functions that have not been called the expected number of times. + * + * ```js + * import assert from 'node:assert'; + * + * // Creates call tracker. + * const tracker = new assert.CallTracker(); + * + * function func() {} + * + * // Returns a function that wraps func() that must be called exact times + * // before tracker.verify(). + * const callsfunc = tracker.calls(func, 2); + * + * // Returns an array containing information on callsfunc() + * console.log(tracker.report()); + * // [ + * // { + * // message: 'Expected the func function to be executed 2 time(s) but was + * // executed 0 time(s).', + * // actual: 0, + * // expected: 2, + * // operator: 'func', + * // stack: stack trace + * // } + * // ] + * ``` + * @since v14.2.0, v12.19.0 + * @return An array of objects containing information about the wrapper functions returned by {@link tracker.calls()}. + */ + report(): CallTrackerReportInformation[]; + /** + * Reset calls of the call tracker. If a tracked function is passed as an argument, the calls will be reset for it. + * If no arguments are passed, all tracked functions will be reset. + * + * ```js + * import assert from 'node:assert'; + * + * const tracker = new assert.CallTracker(); + * + * function func() {} + * const callsfunc = tracker.calls(func); + * + * callsfunc(); + * // Tracker was called once + * assert.strictEqual(tracker.getCalls(callsfunc).length, 1); + * + * tracker.reset(callsfunc); + * assert.strictEqual(tracker.getCalls(callsfunc).length, 0); + * ``` + * @since v18.8.0, v16.18.0 + * @param fn a tracked function to reset. + */ + reset(fn?: Function): void; + /** + * Iterates through the list of functions passed to {@link tracker.calls()} and will throw an error for functions that + * have not been called the expected number of times. + * + * ```js + * import assert from 'node:assert'; + * + * // Creates call tracker. + * const tracker = new assert.CallTracker(); + * + * function func() {} + * + * // Returns a function that wraps func() that must be called exact times + * // before tracker.verify(). + * const callsfunc = tracker.calls(func, 2); + * + * callsfunc(); + * + * // Will throw an error since callsfunc() was only called once. + * tracker.verify(); + * ``` + * @since v14.2.0, v12.19.0 + */ + verify(): void; + } + interface CallTrackerCall { + thisArg: object; + arguments: unknown[]; + } + interface CallTrackerReportInformation { + message: string; + /** The actual number of times the function was called. */ + actual: number; + /** The number of times the function was expected to be called. */ + expected: number; + /** The name of the function that is wrapped. */ + operator: string; + /** A stack trace of the function. */ + stack: object; + } + type AssertPredicate = RegExp | (new() => object) | ((thrown: unknown) => boolean) | object | Error; + /** + * Throws an `AssertionError` with the provided error message or a default + * error message. If the `message` parameter is an instance of an `Error` then + * it will be thrown instead of the `AssertionError`. + * + * ```js + * import assert from 'node:assert/strict'; + * + * assert.fail(); + * // AssertionError [ERR_ASSERTION]: Failed + * + * assert.fail('boom'); + * // AssertionError [ERR_ASSERTION]: boom + * + * assert.fail(new TypeError('need array')); + * // TypeError: need array + * ``` + * + * Using `assert.fail()` with more than two arguments is possible but deprecated. + * See below for further details. + * @since v0.1.21 + * @param [message='Failed'] + */ + function fail(message?: string | Error): never; + /** @deprecated since v10.0.0 - use fail([message]) or other assert functions instead. */ + function fail( + actual: unknown, + expected: unknown, + message?: string | Error, + operator?: string, + // eslint-disable-next-line @typescript-eslint/ban-types + stackStartFn?: Function, + ): never; + /** + * Tests if `value` is truthy. It is equivalent to `assert.equal(!!value, true, message)`. + * + * If `value` is not truthy, an `AssertionError` is thrown with a `message` property set equal to the value of the `message` parameter. If the `message` parameter is `undefined`, a default + * error message is assigned. If the `message` parameter is an instance of an `Error` then it will be thrown instead of the `AssertionError`. + * If no arguments are passed in at all `message` will be set to the string:`` 'No value argument passed to `assert.ok()`' ``. + * + * Be aware that in the `repl` the error message will be different to the one + * thrown in a file! See below for further details. + * + * ```js + * import assert from 'node:assert/strict'; + * + * assert.ok(true); + * // OK + * assert.ok(1); + * // OK + * + * assert.ok(); + * // AssertionError: No value argument passed to `assert.ok()` + * + * assert.ok(false, 'it\'s false'); + * // AssertionError: it's false + * + * // In the repl: + * assert.ok(typeof 123 === 'string'); + * // AssertionError: false == true + * + * // In a file (e.g. test.js): + * assert.ok(typeof 123 === 'string'); + * // AssertionError: The expression evaluated to a falsy value: + * // + * // assert.ok(typeof 123 === 'string') + * + * assert.ok(false); + * // AssertionError: The expression evaluated to a falsy value: + * // + * // assert.ok(false) + * + * assert.ok(0); + * // AssertionError: The expression evaluated to a falsy value: + * // + * // assert.ok(0) + * ``` + * + * ```js + * import assert from 'node:assert/strict'; + * + * // Using `assert()` works the same: + * assert(0); + * // AssertionError: The expression evaluated to a falsy value: + * // + * // assert(0) + * ``` + * @since v0.1.21 + */ + function ok(value: unknown, message?: string | Error): asserts value; + /** + * **Strict assertion mode** + * + * An alias of {@link strictEqual}. + * + * **Legacy assertion mode** + * + * > Stability: 3 - Legacy: Use {@link strictEqual} instead. + * + * Tests shallow, coercive equality between the `actual` and `expected` parameters + * using the [`==` operator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Equality). `NaN` is specially handled + * and treated as being identical if both sides are `NaN`. + * + * ```js + * import assert from 'node:assert'; + * + * assert.equal(1, 1); + * // OK, 1 == 1 + * assert.equal(1, '1'); + * // OK, 1 == '1' + * assert.equal(NaN, NaN); + * // OK + * + * assert.equal(1, 2); + * // AssertionError: 1 == 2 + * assert.equal({ a: { b: 1 } }, { a: { b: 1 } }); + * // AssertionError: { a: { b: 1 } } == { a: { b: 1 } } + * ``` + * + * If the values are not equal, an `AssertionError` is thrown with a `message` property set equal to the value of the `message` parameter. If the `message` parameter is undefined, a default + * error message is assigned. If the `message` parameter is an instance of an `Error` then it will be thrown instead of the `AssertionError`. + * @since v0.1.21 + */ + function equal(actual: unknown, expected: unknown, message?: string | Error): void; + /** + * **Strict assertion mode** + * + * An alias of {@link notStrictEqual}. + * + * **Legacy assertion mode** + * + * > Stability: 3 - Legacy: Use {@link notStrictEqual} instead. + * + * Tests shallow, coercive inequality with the [`!=` operator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Inequality). `NaN` is + * specially handled and treated as being identical if both sides are `NaN`. + * + * ```js + * import assert from 'node:assert'; + * + * assert.notEqual(1, 2); + * // OK + * + * assert.notEqual(1, 1); + * // AssertionError: 1 != 1 + * + * assert.notEqual(1, '1'); + * // AssertionError: 1 != '1' + * ``` + * + * If the values are equal, an `AssertionError` is thrown with a `message` property set equal to the value of the `message` parameter. If the `message` parameter is undefined, a default error + * message is assigned. If the `message` parameter is an instance of an `Error` then it will be thrown instead of the `AssertionError`. + * @since v0.1.21 + */ + function notEqual(actual: unknown, expected: unknown, message?: string | Error): void; + /** + * **Strict assertion mode** + * + * An alias of {@link deepStrictEqual}. + * + * **Legacy assertion mode** + * + * > Stability: 3 - Legacy: Use {@link deepStrictEqual} instead. + * + * Tests for deep equality between the `actual` and `expected` parameters. Consider + * using {@link deepStrictEqual} instead. {@link deepEqual} can have + * surprising results. + * + * _Deep equality_ means that the enumerable "own" properties of child objects + * are also recursively evaluated by the following rules. + * @since v0.1.21 + */ + function deepEqual(actual: unknown, expected: unknown, message?: string | Error): void; + /** + * **Strict assertion mode** + * + * An alias of {@link notDeepStrictEqual}. + * + * **Legacy assertion mode** + * + * > Stability: 3 - Legacy: Use {@link notDeepStrictEqual} instead. + * + * Tests for any deep inequality. Opposite of {@link deepEqual}. + * + * ```js + * import assert from 'node:assert'; + * + * const obj1 = { + * a: { + * b: 1, + * }, + * }; + * const obj2 = { + * a: { + * b: 2, + * }, + * }; + * const obj3 = { + * a: { + * b: 1, + * }, + * }; + * const obj4 = { __proto__: obj1 }; + * + * assert.notDeepEqual(obj1, obj1); + * // AssertionError: { a: { b: 1 } } notDeepEqual { a: { b: 1 } } + * + * assert.notDeepEqual(obj1, obj2); + * // OK + * + * assert.notDeepEqual(obj1, obj3); + * // AssertionError: { a: { b: 1 } } notDeepEqual { a: { b: 1 } } + * + * assert.notDeepEqual(obj1, obj4); + * // OK + * ``` + * + * If the values are deeply equal, an `AssertionError` is thrown with a `message` property set equal to the value of the `message` parameter. If the `message` parameter is undefined, a default + * error message is assigned. If the `message` parameter is an instance of an `Error` then it will be thrown + * instead of the `AssertionError`. + * @since v0.1.21 + */ + function notDeepEqual(actual: unknown, expected: unknown, message?: string | Error): void; + /** + * Tests strict equality between the `actual` and `expected` parameters as + * determined by [`Object.is()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is). + * + * ```js + * import assert from 'node:assert/strict'; + * + * assert.strictEqual(1, 2); + * // AssertionError [ERR_ASSERTION]: Expected inputs to be strictly equal: + * // + * // 1 !== 2 + * + * assert.strictEqual(1, 1); + * // OK + * + * assert.strictEqual('Hello foobar', 'Hello World!'); + * // AssertionError [ERR_ASSERTION]: Expected inputs to be strictly equal: + * // + actual - expected + * // + * // + 'Hello foobar' + * // - 'Hello World!' + * // ^ + * + * const apples = 1; + * const oranges = 2; + * assert.strictEqual(apples, oranges, `apples ${apples} !== oranges ${oranges}`); + * // AssertionError [ERR_ASSERTION]: apples 1 !== oranges 2 + * + * assert.strictEqual(1, '1', new TypeError('Inputs are not identical')); + * // TypeError: Inputs are not identical + * ``` + * + * If the values are not strictly equal, an `AssertionError` is thrown with a `message` property set equal to the value of the `message` parameter. If the `message` parameter is undefined, a + * default error message is assigned. If the `message` parameter is an instance of an `Error` then it will be thrown + * instead of the `AssertionError`. + * @since v0.1.21 + */ + function strictEqual(actual: unknown, expected: T, message?: string | Error): asserts actual is T; + /** + * Tests strict inequality between the `actual` and `expected` parameters as + * determined by [`Object.is()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/is). + * + * ```js + * import assert from 'node:assert/strict'; + * + * assert.notStrictEqual(1, 2); + * // OK + * + * assert.notStrictEqual(1, 1); + * // AssertionError [ERR_ASSERTION]: Expected "actual" to be strictly unequal to: + * // + * // 1 + * + * assert.notStrictEqual(1, '1'); + * // OK + * ``` + * + * If the values are strictly equal, an `AssertionError` is thrown with a `message` property set equal to the value of the `message` parameter. If the `message` parameter is undefined, a + * default error message is assigned. If the `message` parameter is an instance of an `Error` then it will be thrown + * instead of the `AssertionError`. + * @since v0.1.21 + */ + function notStrictEqual(actual: unknown, expected: unknown, message?: string | Error): void; + /** + * Tests for deep equality between the `actual` and `expected` parameters. + * "Deep" equality means that the enumerable "own" properties of child objects + * are recursively evaluated also by the following rules. + * @since v1.2.0 + */ + function deepStrictEqual(actual: unknown, expected: T, message?: string | Error): asserts actual is T; + /** + * Tests for deep strict inequality. Opposite of {@link deepStrictEqual}. + * + * ```js + * import assert from 'node:assert/strict'; + * + * assert.notDeepStrictEqual({ a: 1 }, { a: '1' }); + * // OK + * ``` + * + * If the values are deeply and strictly equal, an `AssertionError` is thrown + * with a `message` property set equal to the value of the `message` parameter. If + * the `message` parameter is undefined, a default error message is assigned. If + * the `message` parameter is an instance of an `Error` then it will be thrown + * instead of the `AssertionError`. + * @since v1.2.0 + */ + function notDeepStrictEqual(actual: unknown, expected: unknown, message?: string | Error): void; + /** + * Expects the function `fn` to throw an error. + * + * If specified, `error` can be a [`Class`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes), + * [`RegExp`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions), a validation function, + * a validation object where each property will be tested for strict deep equality, + * or an instance of error where each property will be tested for strict deep + * equality including the non-enumerable `message` and `name` properties. When + * using an object, it is also possible to use a regular expression, when + * validating against a string property. See below for examples. + * + * If specified, `message` will be appended to the message provided by the `AssertionError` if the `fn` call fails to throw or in case the error validation + * fails. + * + * Custom validation object/error instance: + * + * ```js + * import assert from 'node:assert/strict'; + * + * const err = new TypeError('Wrong value'); + * err.code = 404; + * err.foo = 'bar'; + * err.info = { + * nested: true, + * baz: 'text', + * }; + * err.reg = /abc/i; + * + * assert.throws( + * () => { + * throw err; + * }, + * { + * name: 'TypeError', + * message: 'Wrong value', + * info: { + * nested: true, + * baz: 'text', + * }, + * // Only properties on the validation object will be tested for. + * // Using nested objects requires all properties to be present. Otherwise + * // the validation is going to fail. + * }, + * ); + * + * // Using regular expressions to validate error properties: + * assert.throws( + * () => { + * throw err; + * }, + * { + * // The `name` and `message` properties are strings and using regular + * // expressions on those will match against the string. If they fail, an + * // error is thrown. + * name: /^TypeError$/, + * message: /Wrong/, + * foo: 'bar', + * info: { + * nested: true, + * // It is not possible to use regular expressions for nested properties! + * baz: 'text', + * }, + * // The `reg` property contains a regular expression and only if the + * // validation object contains an identical regular expression, it is going + * // to pass. + * reg: /abc/i, + * }, + * ); + * + * // Fails due to the different `message` and `name` properties: + * assert.throws( + * () => { + * const otherErr = new Error('Not found'); + * // Copy all enumerable properties from `err` to `otherErr`. + * for (const [key, value] of Object.entries(err)) { + * otherErr[key] = value; + * } + * throw otherErr; + * }, + * // The error's `message` and `name` properties will also be checked when using + * // an error as validation object. + * err, + * ); + * ``` + * + * Validate instanceof using constructor: + * + * ```js + * import assert from 'node:assert/strict'; + * + * assert.throws( + * () => { + * throw new Error('Wrong value'); + * }, + * Error, + * ); + * ``` + * + * Validate error message using [`RegExp`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions): + * + * Using a regular expression runs `.toString` on the error object, and will + * therefore also include the error name. + * + * ```js + * import assert from 'node:assert/strict'; + * + * assert.throws( + * () => { + * throw new Error('Wrong value'); + * }, + * /^Error: Wrong value$/, + * ); + * ``` + * + * Custom error validation: + * + * The function must return `true` to indicate all internal validations passed. + * It will otherwise fail with an `AssertionError`. + * + * ```js + * import assert from 'node:assert/strict'; + * + * assert.throws( + * () => { + * throw new Error('Wrong value'); + * }, + * (err) => { + * assert(err instanceof Error); + * assert(/value/.test(err)); + * // Avoid returning anything from validation functions besides `true`. + * // Otherwise, it's not clear what part of the validation failed. Instead, + * // throw an error about the specific validation that failed (as done in this + * // example) and add as much helpful debugging information to that error as + * // possible. + * return true; + * }, + * 'unexpected error', + * ); + * ``` + * + * `error` cannot be a string. If a string is provided as the second + * argument, then `error` is assumed to be omitted and the string will be used for `message` instead. This can lead to easy-to-miss mistakes. Using the same + * message as the thrown error message is going to result in an `ERR_AMBIGUOUS_ARGUMENT` error. Please read the example below carefully if using + * a string as the second argument gets considered: + * + * ```js + * import assert from 'node:assert/strict'; + * + * function throwingFirst() { + * throw new Error('First'); + * } + * + * function throwingSecond() { + * throw new Error('Second'); + * } + * + * function notThrowing() {} + * + * // The second argument is a string and the input function threw an Error. + * // The first case will not throw as it does not match for the error message + * // thrown by the input function! + * assert.throws(throwingFirst, 'Second'); + * // In the next example the message has no benefit over the message from the + * // error and since it is not clear if the user intended to actually match + * // against the error message, Node.js throws an `ERR_AMBIGUOUS_ARGUMENT` error. + * assert.throws(throwingSecond, 'Second'); + * // TypeError [ERR_AMBIGUOUS_ARGUMENT] + * + * // The string is only used (as message) in case the function does not throw: + * assert.throws(notThrowing, 'Second'); + * // AssertionError [ERR_ASSERTION]: Missing expected exception: Second + * + * // If it was intended to match for the error message do this instead: + * // It does not throw because the error messages match. + * assert.throws(throwingSecond, /Second$/); + * + * // If the error message does not match, an AssertionError is thrown. + * assert.throws(throwingFirst, /Second$/); + * // AssertionError [ERR_ASSERTION] + * ``` + * + * Due to the confusing error-prone notation, avoid a string as the second + * argument. + * @since v0.1.21 + */ + function throws(block: () => unknown, message?: string | Error): void; + function throws(block: () => unknown, error: AssertPredicate, message?: string | Error): void; + /** + * Asserts that the function `fn` does not throw an error. + * + * Using `assert.doesNotThrow()` is actually not useful because there + * is no benefit in catching an error and then rethrowing it. Instead, consider + * adding a comment next to the specific code path that should not throw and keep + * error messages as expressive as possible. + * + * When `assert.doesNotThrow()` is called, it will immediately call the `fn` function. + * + * If an error is thrown and it is the same type as that specified by the `error` parameter, then an `AssertionError` is thrown. If the error is of a + * different type, or if the `error` parameter is undefined, the error is + * propagated back to the caller. + * + * If specified, `error` can be a [`Class`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes), + * [`RegExp`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions), or a validation + * function. See {@link throws} for more details. + * + * The following, for instance, will throw the `TypeError` because there is no + * matching error type in the assertion: + * + * ```js + * import assert from 'node:assert/strict'; + * + * assert.doesNotThrow( + * () => { + * throw new TypeError('Wrong value'); + * }, + * SyntaxError, + * ); + * ``` + * + * However, the following will result in an `AssertionError` with the message + * 'Got unwanted exception...': + * + * ```js + * import assert from 'node:assert/strict'; + * + * assert.doesNotThrow( + * () => { + * throw new TypeError('Wrong value'); + * }, + * TypeError, + * ); + * ``` + * + * If an `AssertionError` is thrown and a value is provided for the `message` parameter, the value of `message` will be appended to the `AssertionError` message: + * + * ```js + * import assert from 'node:assert/strict'; + * + * assert.doesNotThrow( + * () => { + * throw new TypeError('Wrong value'); + * }, + * /Wrong value/, + * 'Whoops', + * ); + * // Throws: AssertionError: Got unwanted exception: Whoops + * ``` + * @since v0.1.21 + */ + function doesNotThrow(block: () => unknown, message?: string | Error): void; + function doesNotThrow(block: () => unknown, error: AssertPredicate, message?: string | Error): void; + /** + * Throws `value` if `value` is not `undefined` or `null`. This is useful when + * testing the `error` argument in callbacks. The stack trace contains all frames + * from the error passed to `ifError()` including the potential new frames for `ifError()` itself. + * + * ```js + * import assert from 'node:assert/strict'; + * + * assert.ifError(null); + * // OK + * assert.ifError(0); + * // AssertionError [ERR_ASSERTION]: ifError got unwanted exception: 0 + * assert.ifError('error'); + * // AssertionError [ERR_ASSERTION]: ifError got unwanted exception: 'error' + * assert.ifError(new Error()); + * // AssertionError [ERR_ASSERTION]: ifError got unwanted exception: Error + * + * // Create some random error frames. + * let err; + * (function errorFrame() { + * err = new Error('test error'); + * })(); + * + * (function ifErrorFrame() { + * assert.ifError(err); + * })(); + * // AssertionError [ERR_ASSERTION]: ifError got unwanted exception: test error + * // at ifErrorFrame + * // at errorFrame + * ``` + * @since v0.1.97 + */ + function ifError(value: unknown): asserts value is null | undefined; + /** + * Awaits the `asyncFn` promise or, if `asyncFn` is a function, immediately + * calls the function and awaits the returned promise to complete. It will then + * check that the promise is rejected. + * + * If `asyncFn` is a function and it throws an error synchronously, `assert.rejects()` will return a rejected `Promise` with that error. If the + * function does not return a promise, `assert.rejects()` will return a rejected `Promise` with an [ERR_INVALID_RETURN_VALUE](https://nodejs.org/docs/latest-v20.x/api/errors.html#err_invalid_return_value) + * error. In both cases the error handler is skipped. + * + * Besides the async nature to await the completion behaves identically to {@link throws}. + * + * If specified, `error` can be a [`Class`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes), + * [`RegExp`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions), a validation function, + * an object where each property will be tested for, or an instance of error where + * each property will be tested for including the non-enumerable `message` and `name` properties. + * + * If specified, `message` will be the message provided by the `{@link AssertionError}` if the `asyncFn` fails to reject. + * + * ```js + * import assert from 'node:assert/strict'; + * + * await assert.rejects( + * async () => { + * throw new TypeError('Wrong value'); + * }, + * { + * name: 'TypeError', + * message: 'Wrong value', + * }, + * ); + * ``` + * + * ```js + * import assert from 'node:assert/strict'; + * + * await assert.rejects( + * async () => { + * throw new TypeError('Wrong value'); + * }, + * (err) => { + * assert.strictEqual(err.name, 'TypeError'); + * assert.strictEqual(err.message, 'Wrong value'); + * return true; + * }, + * ); + * ``` + * + * ```js + * import assert from 'node:assert/strict'; + * + * assert.rejects( + * Promise.reject(new Error('Wrong value')), + * Error, + * ).then(() => { + * // ... + * }); + * ``` + * + * `error` cannot be a string. If a string is provided as the second argument, then `error` is assumed to + * be omitted and the string will be used for `message` instead. This can lead to easy-to-miss mistakes. Please read the + * example in {@link throws} carefully if using a string as the second argument gets considered. + * @since v10.0.0 + */ + function rejects(block: (() => Promise) | Promise, message?: string | Error): Promise; + function rejects( + block: (() => Promise) | Promise, + error: AssertPredicate, + message?: string | Error, + ): Promise; + /** + * Awaits the `asyncFn` promise or, if `asyncFn` is a function, immediately + * calls the function and awaits the returned promise to complete. It will then + * check that the promise is not rejected. + * + * If `asyncFn` is a function and it throws an error synchronously, `assert.doesNotReject()` will return a rejected `Promise` with that error. If + * the function does not return a promise, `assert.doesNotReject()` will return a + * rejected `Promise` with an [ERR_INVALID_RETURN_VALUE](https://nodejs.org/docs/latest-v20.x/api/errors.html#err_invalid_return_value) error. In both cases + * the error handler is skipped. + * + * Using `assert.doesNotReject()` is actually not useful because there is little + * benefit in catching a rejection and then rejecting it again. Instead, consider + * adding a comment next to the specific code path that should not reject and keep + * error messages as expressive as possible. + * + * If specified, `error` can be a [`Class`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes), + * [`RegExp`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions), or a validation + * function. See {@link throws} for more details. + * + * Besides the async nature to await the completion behaves identically to {@link doesNotThrow}. + * + * ```js + * import assert from 'node:assert/strict'; + * + * await assert.doesNotReject( + * async () => { + * throw new TypeError('Wrong value'); + * }, + * SyntaxError, + * ); + * ``` + * + * ```js + * import assert from 'node:assert/strict'; + * + * assert.doesNotReject(Promise.reject(new TypeError('Wrong value'))) + * .then(() => { + * // ... + * }); + * ``` + * @since v10.0.0 + */ + function doesNotReject( + block: (() => Promise) | Promise, + message?: string | Error, + ): Promise; + function doesNotReject( + block: (() => Promise) | Promise, + error: AssertPredicate, + message?: string | Error, + ): Promise; + /** + * Expects the `string` input to match the regular expression. + * + * ```js + * import assert from 'node:assert/strict'; + * + * assert.match('I will fail', /pass/); + * // AssertionError [ERR_ASSERTION]: The input did not match the regular ... + * + * assert.match(123, /pass/); + * // AssertionError [ERR_ASSERTION]: The "string" argument must be of type string. + * + * assert.match('I will pass', /pass/); + * // OK + * ``` + * + * If the values do not match, or if the `string` argument is of another type than `string`, an `{@link AssertionError}` is thrown with a `message` property set equal + * to the value of the `message` parameter. If the `message` parameter is + * undefined, a default error message is assigned. If the `message` parameter is an + * instance of an [Error](https://nodejs.org/docs/latest-v20.x/api/errors.html#class-error) then it will be thrown instead of the `{@link AssertionError}`. + * @since v13.6.0, v12.16.0 + */ + function match(value: string, regExp: RegExp, message?: string | Error): void; + /** + * Expects the `string` input not to match the regular expression. + * + * ```js + * import assert from 'node:assert/strict'; + * + * assert.doesNotMatch('I will fail', /fail/); + * // AssertionError [ERR_ASSERTION]: The input was expected to not match the ... + * + * assert.doesNotMatch(123, /pass/); + * // AssertionError [ERR_ASSERTION]: The "string" argument must be of type string. + * + * assert.doesNotMatch('I will pass', /different/); + * // OK + * ``` + * + * If the values do match, or if the `string` argument is of another type than `string`, an `{@link AssertionError}` is thrown with a `message` property set equal + * to the value of the `message` parameter. If the `message` parameter is + * undefined, a default error message is assigned. If the `message` parameter is an + * instance of an [Error](https://nodejs.org/docs/latest-v20.x/api/errors.html#class-error) then it will be thrown instead of the `{@link AssertionError}`. + * @since v13.6.0, v12.16.0 + */ + function doesNotMatch(value: string, regExp: RegExp, message?: string | Error): void; + /** + * In strict assertion mode, non-strict methods behave like their corresponding strict methods. For example, + * {@link deepEqual} will behave like {@link deepStrictEqual}. + * + * In strict assertion mode, error messages for objects display a diff. In legacy assertion mode, error + * messages for objects display the objects, often truncated. + * + * To use strict assertion mode: + * + * ```js + * import { strict as assert } from 'node:assert';COPY + * import assert from 'node:assert/strict'; + * ``` + * + * Example error diff: + * + * ```js + * import { strict as assert } from 'node:assert'; + * + * assert.deepEqual([[[1, 2, 3]], 4, 5], [[[1, 2, '3']], 4, 5]); + * // AssertionError: Expected inputs to be strictly deep-equal: + * // + actual - expected ... Lines skipped + * // + * // [ + * // [ + * // ... + * // 2, + * // + 3 + * // - '3' + * // ], + * // ... + * // 5 + * // ] + * ``` + * + * To deactivate the colors, use the `NO_COLOR` or `NODE_DISABLE_COLORS` environment variables. This will also + * deactivate the colors in the REPL. For more on color support in terminal environments, read the tty + * `getColorDepth()` documentation. + * + * @since v15.0.0, v13.9.0, v12.16.2, v9.9.0 + */ + namespace strict { + type AssertionError = assert.AssertionError; + type AssertPredicate = assert.AssertPredicate; + type CallTrackerCall = assert.CallTrackerCall; + type CallTrackerReportInformation = assert.CallTrackerReportInformation; + } + const strict: + & Omit< + typeof assert, + | "equal" + | "notEqual" + | "deepEqual" + | "notDeepEqual" + | "ok" + | "strictEqual" + | "deepStrictEqual" + | "ifError" + | "strict" + > + & { + (value: unknown, message?: string | Error): asserts value; + equal: typeof strictEqual; + notEqual: typeof notStrictEqual; + deepEqual: typeof deepStrictEqual; + notDeepEqual: typeof notDeepStrictEqual; + // Mapped types and assertion functions are incompatible? + // TS2775: Assertions require every name in the call target + // to be declared with an explicit type annotation. + ok: typeof ok; + strictEqual: typeof strictEqual; + deepStrictEqual: typeof deepStrictEqual; + ifError: typeof ifError; + strict: typeof strict; + }; + } + export = assert; +} +declare module "node:assert" { + import assert = require("assert"); + export = assert; +} diff --git a/node_modules/@types/node/assert/strict.d.ts b/node_modules/@types/node/assert/strict.d.ts new file mode 100644 index 0000000..f333913 --- /dev/null +++ b/node_modules/@types/node/assert/strict.d.ts @@ -0,0 +1,8 @@ +declare module "assert/strict" { + import { strict } from "node:assert"; + export = strict; +} +declare module "node:assert/strict" { + import { strict } from "node:assert"; + export = strict; +} diff --git a/node_modules/@types/node/async_hooks.d.ts b/node_modules/@types/node/async_hooks.d.ts new file mode 100644 index 0000000..f5432e2 --- /dev/null +++ b/node_modules/@types/node/async_hooks.d.ts @@ -0,0 +1,541 @@ +/** + * We strongly discourage the use of the `async_hooks` API. + * Other APIs that can cover most of its use cases include: + * + * * [`AsyncLocalStorage`](https://nodejs.org/docs/latest-v20.x/api/async_context.html#class-asynclocalstorage) tracks async context + * * [`process.getActiveResourcesInfo()`](https://nodejs.org/docs/latest-v20.x/api/process.html#processgetactiveresourcesinfo) tracks active resources + * + * The `node:async_hooks` module provides an API to track asynchronous resources. + * It can be accessed using: + * + * ```js + * import async_hooks from 'node:async_hooks'; + * ``` + * @experimental + * @see [source](https://github.com/nodejs/node/blob/v20.13.1/lib/async_hooks.js) + */ +declare module "async_hooks" { + /** + * ```js + * import { executionAsyncId } from 'node:async_hooks'; + * import fs from 'node:fs'; + * + * console.log(executionAsyncId()); // 1 - bootstrap + * const path = '.'; + * fs.open(path, 'r', (err, fd) => { + * console.log(executionAsyncId()); // 6 - open() + * }); + * ``` + * + * The ID returned from `executionAsyncId()` is related to execution timing, not + * causality (which is covered by `triggerAsyncId()`): + * + * ```js + * const server = net.createServer((conn) => { + * // Returns the ID of the server, not of the new connection, because the + * // callback runs in the execution scope of the server's MakeCallback(). + * async_hooks.executionAsyncId(); + * + * }).listen(port, () => { + * // Returns the ID of a TickObject (process.nextTick()) because all + * // callbacks passed to .listen() are wrapped in a nextTick(). + * async_hooks.executionAsyncId(); + * }); + * ``` + * + * Promise contexts may not get precise `executionAsyncIds` by default. + * See the section on [promise execution tracking](https://nodejs.org/docs/latest-v20.x/api/async_hooks.html#promise-execution-tracking). + * @since v8.1.0 + * @return The `asyncId` of the current execution context. Useful to track when something calls. + */ + function executionAsyncId(): number; + /** + * Resource objects returned by `executionAsyncResource()` are most often internal + * Node.js handle objects with undocumented APIs. Using any functions or properties + * on the object is likely to crash your application and should be avoided. + * + * Using `executionAsyncResource()` in the top-level execution context will + * return an empty object as there is no handle or request object to use, + * but having an object representing the top-level can be helpful. + * + * ```js + * import { open } from 'node:fs'; + * import { executionAsyncId, executionAsyncResource } from 'node:async_hooks'; + * + * console.log(executionAsyncId(), executionAsyncResource()); // 1 {} + * open(new URL(import.meta.url), 'r', (err, fd) => { + * console.log(executionAsyncId(), executionAsyncResource()); // 7 FSReqWrap + * }); + * ``` + * + * This can be used to implement continuation local storage without the + * use of a tracking `Map` to store the metadata: + * + * ```js + * import { createServer } from 'node:http'; + * import { + * executionAsyncId, + * executionAsyncResource, + * createHook, + * } from 'async_hooks'; + * const sym = Symbol('state'); // Private symbol to avoid pollution + * + * createHook({ + * init(asyncId, type, triggerAsyncId, resource) { + * const cr = executionAsyncResource(); + * if (cr) { + * resource[sym] = cr[sym]; + * } + * }, + * }).enable(); + * + * const server = createServer((req, res) => { + * executionAsyncResource()[sym] = { state: req.url }; + * setTimeout(function() { + * res.end(JSON.stringify(executionAsyncResource()[sym])); + * }, 100); + * }).listen(3000); + * ``` + * @since v13.9.0, v12.17.0 + * @return The resource representing the current execution. Useful to store data within the resource. + */ + function executionAsyncResource(): object; + /** + * ```js + * const server = net.createServer((conn) => { + * // The resource that caused (or triggered) this callback to be called + * // was that of the new connection. Thus the return value of triggerAsyncId() + * // is the asyncId of "conn". + * async_hooks.triggerAsyncId(); + * + * }).listen(port, () => { + * // Even though all callbacks passed to .listen() are wrapped in a nextTick() + * // the callback itself exists because the call to the server's .listen() + * // was made. So the return value would be the ID of the server. + * async_hooks.triggerAsyncId(); + * }); + * ``` + * + * Promise contexts may not get valid `triggerAsyncId`s by default. See + * the section on [promise execution tracking](https://nodejs.org/docs/latest-v20.x/api/async_hooks.html#promise-execution-tracking). + * @return The ID of the resource responsible for calling the callback that is currently being executed. + */ + function triggerAsyncId(): number; + interface HookCallbacks { + /** + * Called when a class is constructed that has the possibility to emit an asynchronous event. + * @param asyncId A unique ID for the async resource + * @param type The type of the async resource + * @param triggerAsyncId The unique ID of the async resource in whose execution context this async resource was created + * @param resource Reference to the resource representing the async operation, needs to be released during destroy + */ + init?(asyncId: number, type: string, triggerAsyncId: number, resource: object): void; + /** + * When an asynchronous operation is initiated or completes a callback is called to notify the user. + * The before callback is called just before said callback is executed. + * @param asyncId the unique identifier assigned to the resource about to execute the callback. + */ + before?(asyncId: number): void; + /** + * Called immediately after the callback specified in `before` is completed. + * + * If an uncaught exception occurs during execution of the callback, then `after` will run after the `'uncaughtException'` event is emitted or a `domain`'s handler runs. + * @param asyncId the unique identifier assigned to the resource which has executed the callback. + */ + after?(asyncId: number): void; + /** + * Called when a promise has resolve() called. This may not be in the same execution id + * as the promise itself. + * @param asyncId the unique id for the promise that was resolve()d. + */ + promiseResolve?(asyncId: number): void; + /** + * Called after the resource corresponding to asyncId is destroyed + * @param asyncId a unique ID for the async resource + */ + destroy?(asyncId: number): void; + } + interface AsyncHook { + /** + * Enable the callbacks for a given AsyncHook instance. If no callbacks are provided enabling is a noop. + */ + enable(): this; + /** + * Disable the callbacks for a given AsyncHook instance from the global pool of AsyncHook callbacks to be executed. Once a hook has been disabled it will not be called again until enabled. + */ + disable(): this; + } + /** + * Registers functions to be called for different lifetime events of each async + * operation. + * + * The callbacks `init()`/`before()`/`after()`/`destroy()` are called for the + * respective asynchronous event during a resource's lifetime. + * + * All callbacks are optional. For example, if only resource cleanup needs to + * be tracked, then only the `destroy` callback needs to be passed. The + * specifics of all functions that can be passed to `callbacks` is in the `Hook Callbacks` section. + * + * ```js + * import { createHook } from 'node:async_hooks'; + * + * const asyncHook = createHook({ + * init(asyncId, type, triggerAsyncId, resource) { }, + * destroy(asyncId) { }, + * }); + * ``` + * + * The callbacks will be inherited via the prototype chain: + * + * ```js + * class MyAsyncCallbacks { + * init(asyncId, type, triggerAsyncId, resource) { } + * destroy(asyncId) {} + * } + * + * class MyAddedCallbacks extends MyAsyncCallbacks { + * before(asyncId) { } + * after(asyncId) { } + * } + * + * const asyncHook = async_hooks.createHook(new MyAddedCallbacks()); + * ``` + * + * Because promises are asynchronous resources whose lifecycle is tracked + * via the async hooks mechanism, the `init()`, `before()`, `after()`, and`destroy()` callbacks _must not_ be async functions that return promises. + * @since v8.1.0 + * @param callbacks The `Hook Callbacks` to register + * @return Instance used for disabling and enabling hooks + */ + function createHook(callbacks: HookCallbacks): AsyncHook; + interface AsyncResourceOptions { + /** + * The ID of the execution context that created this async event. + * @default executionAsyncId() + */ + triggerAsyncId?: number | undefined; + /** + * Disables automatic `emitDestroy` when the object is garbage collected. + * This usually does not need to be set (even if `emitDestroy` is called + * manually), unless the resource's `asyncId` is retrieved and the + * sensitive API's `emitDestroy` is called with it. + * @default false + */ + requireManualDestroy?: boolean | undefined; + } + /** + * The class `AsyncResource` is designed to be extended by the embedder's async + * resources. Using this, users can easily trigger the lifetime events of their + * own resources. + * + * The `init` hook will trigger when an `AsyncResource` is instantiated. + * + * The following is an overview of the `AsyncResource` API. + * + * ```js + * import { AsyncResource, executionAsyncId } from 'node:async_hooks'; + * + * // AsyncResource() is meant to be extended. Instantiating a + * // new AsyncResource() also triggers init. If triggerAsyncId is omitted then + * // async_hook.executionAsyncId() is used. + * const asyncResource = new AsyncResource( + * type, { triggerAsyncId: executionAsyncId(), requireManualDestroy: false }, + * ); + * + * // Run a function in the execution context of the resource. This will + * // * establish the context of the resource + * // * trigger the AsyncHooks before callbacks + * // * call the provided function `fn` with the supplied arguments + * // * trigger the AsyncHooks after callbacks + * // * restore the original execution context + * asyncResource.runInAsyncScope(fn, thisArg, ...args); + * + * // Call AsyncHooks destroy callbacks. + * asyncResource.emitDestroy(); + * + * // Return the unique ID assigned to the AsyncResource instance. + * asyncResource.asyncId(); + * + * // Return the trigger ID for the AsyncResource instance. + * asyncResource.triggerAsyncId(); + * ``` + */ + class AsyncResource { + /** + * AsyncResource() is meant to be extended. Instantiating a + * new AsyncResource() also triggers init. If triggerAsyncId is omitted then + * async_hook.executionAsyncId() is used. + * @param type The type of async event. + * @param triggerAsyncId The ID of the execution context that created + * this async event (default: `executionAsyncId()`), or an + * AsyncResourceOptions object (since v9.3.0) + */ + constructor(type: string, triggerAsyncId?: number | AsyncResourceOptions); + /** + * Binds the given function to the current execution context. + * @since v14.8.0, v12.19.0 + * @param fn The function to bind to the current execution context. + * @param type An optional name to associate with the underlying `AsyncResource`. + */ + static bind any, ThisArg>( + fn: Func, + type?: string, + thisArg?: ThisArg, + ): Func; + /** + * Binds the given function to execute to this `AsyncResource`'s scope. + * @since v14.8.0, v12.19.0 + * @param fn The function to bind to the current `AsyncResource`. + */ + bind any>(fn: Func): Func; + /** + * Call the provided function with the provided arguments in the execution context + * of the async resource. This will establish the context, trigger the AsyncHooks + * before callbacks, call the function, trigger the AsyncHooks after callbacks, and + * then restore the original execution context. + * @since v9.6.0 + * @param fn The function to call in the execution context of this async resource. + * @param thisArg The receiver to be used for the function call. + * @param args Optional arguments to pass to the function. + */ + runInAsyncScope( + fn: (this: This, ...args: any[]) => Result, + thisArg?: This, + ...args: any[] + ): Result; + /** + * Call all `destroy` hooks. This should only ever be called once. An error will + * be thrown if it is called more than once. This **must** be manually called. If + * the resource is left to be collected by the GC then the `destroy` hooks will + * never be called. + * @return A reference to `asyncResource`. + */ + emitDestroy(): this; + /** + * @return The unique `asyncId` assigned to the resource. + */ + asyncId(): number; + /** + * @return The same `triggerAsyncId` that is passed to the `AsyncResource` constructor. + */ + triggerAsyncId(): number; + } + /** + * This class creates stores that stay coherent through asynchronous operations. + * + * While you can create your own implementation on top of the `node:async_hooks` module, `AsyncLocalStorage` should be preferred as it is a performant and memory + * safe implementation that involves significant optimizations that are non-obvious + * to implement. + * + * The following example uses `AsyncLocalStorage` to build a simple logger + * that assigns IDs to incoming HTTP requests and includes them in messages + * logged within each request. + * + * ```js + * import http from 'node:http'; + * import { AsyncLocalStorage } from 'node:async_hooks'; + * + * const asyncLocalStorage = new AsyncLocalStorage(); + * + * function logWithId(msg) { + * const id = asyncLocalStorage.getStore(); + * console.log(`${id !== undefined ? id : '-'}:`, msg); + * } + * + * let idSeq = 0; + * http.createServer((req, res) => { + * asyncLocalStorage.run(idSeq++, () => { + * logWithId('start'); + * // Imagine any chain of async operations here + * setImmediate(() => { + * logWithId('finish'); + * res.end(); + * }); + * }); + * }).listen(8080); + * + * http.get('http://localhost:8080'); + * http.get('http://localhost:8080'); + * // Prints: + * // 0: start + * // 1: start + * // 0: finish + * // 1: finish + * ``` + * + * Each instance of `AsyncLocalStorage` maintains an independent storage context. + * Multiple instances can safely exist simultaneously without risk of interfering + * with each other's data. + * @since v13.10.0, v12.17.0 + */ + class AsyncLocalStorage { + /** + * Binds the given function to the current execution context. + * @since v19.8.0 + * @experimental + * @param fn The function to bind to the current execution context. + * @return A new function that calls `fn` within the captured execution context. + */ + static bind any>(fn: Func): Func; + /** + * Captures the current execution context and returns a function that accepts a + * function as an argument. Whenever the returned function is called, it + * calls the function passed to it within the captured context. + * + * ```js + * const asyncLocalStorage = new AsyncLocalStorage(); + * const runInAsyncScope = asyncLocalStorage.run(123, () => AsyncLocalStorage.snapshot()); + * const result = asyncLocalStorage.run(321, () => runInAsyncScope(() => asyncLocalStorage.getStore())); + * console.log(result); // returns 123 + * ``` + * + * AsyncLocalStorage.snapshot() can replace the use of AsyncResource for simple + * async context tracking purposes, for example: + * + * ```js + * class Foo { + * #runInAsyncScope = AsyncLocalStorage.snapshot(); + * + * get() { return this.#runInAsyncScope(() => asyncLocalStorage.getStore()); } + * } + * + * const foo = asyncLocalStorage.run(123, () => new Foo()); + * console.log(asyncLocalStorage.run(321, () => foo.get())); // returns 123 + * ``` + * @since v19.8.0 + * @experimental + * @return A new function with the signature `(fn: (...args) : R, ...args) : R`. + */ + static snapshot(): (fn: (...args: TArgs) => R, ...args: TArgs) => R; + /** + * Disables the instance of `AsyncLocalStorage`. All subsequent calls + * to `asyncLocalStorage.getStore()` will return `undefined` until `asyncLocalStorage.run()` or `asyncLocalStorage.enterWith()` is called again. + * + * When calling `asyncLocalStorage.disable()`, all current contexts linked to the + * instance will be exited. + * + * Calling `asyncLocalStorage.disable()` is required before the `asyncLocalStorage` can be garbage collected. This does not apply to stores + * provided by the `asyncLocalStorage`, as those objects are garbage collected + * along with the corresponding async resources. + * + * Use this method when the `asyncLocalStorage` is not in use anymore + * in the current process. + * @since v13.10.0, v12.17.0 + * @experimental + */ + disable(): void; + /** + * Returns the current store. + * If called outside of an asynchronous context initialized by + * calling `asyncLocalStorage.run()` or `asyncLocalStorage.enterWith()`, it + * returns `undefined`. + * @since v13.10.0, v12.17.0 + */ + getStore(): T | undefined; + /** + * Runs a function synchronously within a context and returns its + * return value. The store is not accessible outside of the callback function. + * The store is accessible to any asynchronous operations created within the + * callback. + * + * The optional `args` are passed to the callback function. + * + * If the callback function throws an error, the error is thrown by `run()` too. + * The stacktrace is not impacted by this call and the context is exited. + * + * Example: + * + * ```js + * const store = { id: 2 }; + * try { + * asyncLocalStorage.run(store, () => { + * asyncLocalStorage.getStore(); // Returns the store object + * setTimeout(() => { + * asyncLocalStorage.getStore(); // Returns the store object + * }, 200); + * throw new Error(); + * }); + * } catch (e) { + * asyncLocalStorage.getStore(); // Returns undefined + * // The error will be caught here + * } + * ``` + * @since v13.10.0, v12.17.0 + */ + run(store: T, callback: () => R): R; + run(store: T, callback: (...args: TArgs) => R, ...args: TArgs): R; + /** + * Runs a function synchronously outside of a context and returns its + * return value. The store is not accessible within the callback function or + * the asynchronous operations created within the callback. Any `getStore()` call done within the callback function will always return `undefined`. + * + * The optional `args` are passed to the callback function. + * + * If the callback function throws an error, the error is thrown by `exit()` too. + * The stacktrace is not impacted by this call and the context is re-entered. + * + * Example: + * + * ```js + * // Within a call to run + * try { + * asyncLocalStorage.getStore(); // Returns the store object or value + * asyncLocalStorage.exit(() => { + * asyncLocalStorage.getStore(); // Returns undefined + * throw new Error(); + * }); + * } catch (e) { + * asyncLocalStorage.getStore(); // Returns the same object or value + * // The error will be caught here + * } + * ``` + * @since v13.10.0, v12.17.0 + * @experimental + */ + exit(callback: (...args: TArgs) => R, ...args: TArgs): R; + /** + * Transitions into the context for the remainder of the current + * synchronous execution and then persists the store through any following + * asynchronous calls. + * + * Example: + * + * ```js + * const store = { id: 1 }; + * // Replaces previous store with the given store object + * asyncLocalStorage.enterWith(store); + * asyncLocalStorage.getStore(); // Returns the store object + * someAsyncOperation(() => { + * asyncLocalStorage.getStore(); // Returns the same object + * }); + * ``` + * + * This transition will continue for the _entire_ synchronous execution. + * This means that if, for example, the context is entered within an event + * handler subsequent event handlers will also run within that context unless + * specifically bound to another context with an `AsyncResource`. That is why `run()` should be preferred over `enterWith()` unless there are strong reasons + * to use the latter method. + * + * ```js + * const store = { id: 1 }; + * + * emitter.on('my-event', () => { + * asyncLocalStorage.enterWith(store); + * }); + * emitter.on('my-event', () => { + * asyncLocalStorage.getStore(); // Returns the same object + * }); + * + * asyncLocalStorage.getStore(); // Returns undefined + * emitter.emit('my-event'); + * asyncLocalStorage.getStore(); // Returns the same object + * ``` + * @since v13.11.0, v12.17.0 + * @experimental + */ + enterWith(store: T): void; + } +} +declare module "node:async_hooks" { + export * from "async_hooks"; +} diff --git a/node_modules/@types/node/buffer.d.ts b/node_modules/@types/node/buffer.d.ts new file mode 100644 index 0000000..abdf9a6 --- /dev/null +++ b/node_modules/@types/node/buffer.d.ts @@ -0,0 +1,2363 @@ +/** + * `Buffer` objects are used to represent a fixed-length sequence of bytes. Many + * Node.js APIs support `Buffer`s. + * + * The `Buffer` class is a subclass of JavaScript's [`Uint8Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array) class and + * extends it with methods that cover additional use cases. Node.js APIs accept + * plain [`Uint8Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array) s wherever `Buffer`s are supported as well. + * + * While the `Buffer` class is available within the global scope, it is still + * recommended to explicitly reference it via an import or require statement. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * // Creates a zero-filled Buffer of length 10. + * const buf1 = Buffer.alloc(10); + * + * // Creates a Buffer of length 10, + * // filled with bytes which all have the value `1`. + * const buf2 = Buffer.alloc(10, 1); + * + * // Creates an uninitialized buffer of length 10. + * // This is faster than calling Buffer.alloc() but the returned + * // Buffer instance might contain old data that needs to be + * // overwritten using fill(), write(), or other functions that fill the Buffer's + * // contents. + * const buf3 = Buffer.allocUnsafe(10); + * + * // Creates a Buffer containing the bytes [1, 2, 3]. + * const buf4 = Buffer.from([1, 2, 3]); + * + * // Creates a Buffer containing the bytes [1, 1, 1, 1] – the entries + * // are all truncated using `(value & 255)` to fit into the range 0–255. + * const buf5 = Buffer.from([257, 257.5, -255, '1']); + * + * // Creates a Buffer containing the UTF-8-encoded bytes for the string 'tést': + * // [0x74, 0xc3, 0xa9, 0x73, 0x74] (in hexadecimal notation) + * // [116, 195, 169, 115, 116] (in decimal notation) + * const buf6 = Buffer.from('tést'); + * + * // Creates a Buffer containing the Latin-1 bytes [0x74, 0xe9, 0x73, 0x74]. + * const buf7 = Buffer.from('tést', 'latin1'); + * ``` + * @see [source](https://github.com/nodejs/node/blob/v20.13.1/lib/buffer.js) + */ +declare module "buffer" { + import { BinaryLike } from "node:crypto"; + import { ReadableStream as WebReadableStream } from "node:stream/web"; + /** + * This function returns `true` if `input` contains only valid UTF-8-encoded data, + * including the case in which `input` is empty. + * + * Throws if the `input` is a detached array buffer. + * @since v19.4.0, v18.14.0 + * @param input The input to validate. + */ + export function isUtf8(input: Buffer | ArrayBuffer | NodeJS.TypedArray): boolean; + /** + * This function returns `true` if `input` contains only valid ASCII-encoded data, + * including the case in which `input` is empty. + * + * Throws if the `input` is a detached array buffer. + * @since v19.6.0, v18.15.0 + * @param input The input to validate. + */ + export function isAscii(input: Buffer | ArrayBuffer | NodeJS.TypedArray): boolean; + export const INSPECT_MAX_BYTES: number; + export const kMaxLength: number; + export const kStringMaxLength: number; + export const constants: { + MAX_LENGTH: number; + MAX_STRING_LENGTH: number; + }; + export type TranscodeEncoding = + | "ascii" + | "utf8" + | "utf-8" + | "utf16le" + | "utf-16le" + | "ucs2" + | "ucs-2" + | "latin1" + | "binary"; + /** + * Re-encodes the given `Buffer` or `Uint8Array` instance from one character + * encoding to another. Returns a new `Buffer` instance. + * + * Throws if the `fromEnc` or `toEnc` specify invalid character encodings or if + * conversion from `fromEnc` to `toEnc` is not permitted. + * + * Encodings supported by `buffer.transcode()` are: `'ascii'`, `'utf8'`, `'utf16le'`, `'ucs2'`, `'latin1'`, and `'binary'`. + * + * The transcoding process will use substitution characters if a given byte + * sequence cannot be adequately represented in the target encoding. For instance: + * + * ```js + * import { Buffer, transcode } from 'node:buffer'; + * + * const newBuf = transcode(Buffer.from('€'), 'utf8', 'ascii'); + * console.log(newBuf.toString('ascii')); + * // Prints: '?' + * ``` + * + * Because the Euro (`€`) sign is not representable in US-ASCII, it is replaced + * with `?` in the transcoded `Buffer`. + * @since v7.1.0 + * @param source A `Buffer` or `Uint8Array` instance. + * @param fromEnc The current encoding. + * @param toEnc To target encoding. + */ + export function transcode(source: Uint8Array, fromEnc: TranscodeEncoding, toEnc: TranscodeEncoding): Buffer; + export const SlowBuffer: { + /** @deprecated since v6.0.0, use `Buffer.allocUnsafeSlow()` */ + new(size: number): Buffer; + prototype: Buffer; + }; + /** + * Resolves a `'blob:nodedata:...'` an associated `Blob` object registered using + * a prior call to `URL.createObjectURL()`. + * @since v16.7.0 + * @experimental + * @param id A `'blob:nodedata:...` URL string returned by a prior call to `URL.createObjectURL()`. + */ + export function resolveObjectURL(id: string): Blob | undefined; + export { Buffer }; + /** + * @experimental + */ + export interface BlobOptions { + /** + * One of either `'transparent'` or `'native'`. When set to `'native'`, line endings in string source parts + * will be converted to the platform native line-ending as specified by `require('node:os').EOL`. + */ + endings?: "transparent" | "native"; + /** + * The Blob content-type. The intent is for `type` to convey + * the MIME media type of the data, however no validation of the type format + * is performed. + */ + type?: string | undefined; + } + /** + * A [`Blob`](https://developer.mozilla.org/en-US/docs/Web/API/Blob) encapsulates immutable, raw data that can be safely shared across + * multiple worker threads. + * @since v15.7.0, v14.18.0 + */ + export class Blob { + /** + * The total size of the `Blob` in bytes. + * @since v15.7.0, v14.18.0 + */ + readonly size: number; + /** + * The content-type of the `Blob`. + * @since v15.7.0, v14.18.0 + */ + readonly type: string; + /** + * Creates a new `Blob` object containing a concatenation of the given sources. + * + * {ArrayBuffer}, {TypedArray}, {DataView}, and {Buffer} sources are copied into + * the 'Blob' and can therefore be safely modified after the 'Blob' is created. + * + * String sources are also copied into the `Blob`. + */ + constructor(sources: Array, options?: BlobOptions); + /** + * Returns a promise that fulfills with an [ArrayBuffer](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) containing a copy of + * the `Blob` data. + * @since v15.7.0, v14.18.0 + */ + arrayBuffer(): Promise; + /** + * Creates and returns a new `Blob` containing a subset of this `Blob` objects + * data. The original `Blob` is not altered. + * @since v15.7.0, v14.18.0 + * @param start The starting index. + * @param end The ending index. + * @param type The content-type for the new `Blob` + */ + slice(start?: number, end?: number, type?: string): Blob; + /** + * Returns a promise that fulfills with the contents of the `Blob` decoded as a + * UTF-8 string. + * @since v15.7.0, v14.18.0 + */ + text(): Promise; + /** + * Returns a new `ReadableStream` that allows the content of the `Blob` to be read. + * @since v16.7.0 + */ + stream(): WebReadableStream; + } + export interface FileOptions { + /** + * One of either `'transparent'` or `'native'`. When set to `'native'`, line endings in string source parts will be + * converted to the platform native line-ending as specified by `require('node:os').EOL`. + */ + endings?: "native" | "transparent"; + /** The File content-type. */ + type?: string; + /** The last modified date of the file. `Default`: Date.now(). */ + lastModified?: number; + } + /** + * A [`File`](https://developer.mozilla.org/en-US/docs/Web/API/File) provides information about files. + * @since v19.2.0, v18.13.0 + */ + export class File extends Blob { + constructor(sources: Array, fileName: string, options?: FileOptions); + /** + * The name of the `File`. + * @since v19.2.0, v18.13.0 + */ + readonly name: string; + /** + * The last modified date of the `File`. + * @since v19.2.0, v18.13.0 + */ + readonly lastModified: number; + } + export import atob = globalThis.atob; + export import btoa = globalThis.btoa; + import { Blob as NodeBlob } from "buffer"; + // This conditional type will be the existing global Blob in a browser, or + // the copy below in a Node environment. + type __Blob = typeof globalThis extends { onmessage: any; Blob: any } ? {} : NodeBlob; + global { + namespace NodeJS { + export { BufferEncoding }; + } + // Buffer class + type BufferEncoding = + | "ascii" + | "utf8" + | "utf-8" + | "utf16le" + | "utf-16le" + | "ucs2" + | "ucs-2" + | "base64" + | "base64url" + | "latin1" + | "binary" + | "hex"; + type WithImplicitCoercion = + | T + | { + valueOf(): T; + }; + /** + * Raw data is stored in instances of the Buffer class. + * A Buffer is similar to an array of integers but corresponds to a raw memory allocation outside the V8 heap. A Buffer cannot be resized. + * Valid string encodings: 'ascii'|'utf8'|'utf16le'|'ucs2'(alias of 'utf16le')|'base64'|'base64url'|'binary'(deprecated)|'hex' + */ + interface BufferConstructor { + /** + * Allocates a new buffer containing the given {str}. + * + * @param str String to store in buffer. + * @param encoding encoding to use, optional. Default is 'utf8' + * @deprecated since v10.0.0 - Use `Buffer.from(string[, encoding])` instead. + */ + new(str: string, encoding?: BufferEncoding): Buffer; + /** + * Allocates a new buffer of {size} octets. + * + * @param size count of octets to allocate. + * @deprecated since v10.0.0 - Use `Buffer.alloc()` instead (also see `Buffer.allocUnsafe()`). + */ + new(size: number): Buffer; + /** + * Allocates a new buffer containing the given {array} of octets. + * + * @param array The octets to store. + * @deprecated since v10.0.0 - Use `Buffer.from(array)` instead. + */ + new(array: Uint8Array): Buffer; + /** + * Produces a Buffer backed by the same allocated memory as + * the given {ArrayBuffer}/{SharedArrayBuffer}. + * + * @param arrayBuffer The ArrayBuffer with which to share memory. + * @deprecated since v10.0.0 - Use `Buffer.from(arrayBuffer[, byteOffset[, length]])` instead. + */ + new(arrayBuffer: ArrayBuffer | SharedArrayBuffer): Buffer; + /** + * Allocates a new buffer containing the given {array} of octets. + * + * @param array The octets to store. + * @deprecated since v10.0.0 - Use `Buffer.from(array)` instead. + */ + new(array: readonly any[]): Buffer; + /** + * Copies the passed {buffer} data onto a new {Buffer} instance. + * + * @param buffer The buffer to copy. + * @deprecated since v10.0.0 - Use `Buffer.from(buffer)` instead. + */ + new(buffer: Buffer): Buffer; + /** + * Allocates a new `Buffer` using an `array` of bytes in the range `0` – `255`. + * Array entries outside that range will be truncated to fit into it. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * // Creates a new Buffer containing the UTF-8 bytes of the string 'buffer'. + * const buf = Buffer.from([0x62, 0x75, 0x66, 0x66, 0x65, 0x72]); + * ``` + * + * If `array` is an `Array`\-like object (that is, one with a `length` property of + * type `number`), it is treated as if it is an array, unless it is a `Buffer` or + * a `Uint8Array`. This means all other `TypedArray` variants get treated as an `Array`. To create a `Buffer` from the bytes backing a `TypedArray`, use `Buffer.copyBytesFrom()`. + * + * A `TypeError` will be thrown if `array` is not an `Array` or another type + * appropriate for `Buffer.from()` variants. + * + * `Buffer.from(array)` and `Buffer.from(string)` may also use the internal `Buffer` pool like `Buffer.allocUnsafe()` does. + * @since v5.10.0 + */ + from( + arrayBuffer: WithImplicitCoercion, + byteOffset?: number, + length?: number, + ): Buffer; + /** + * Creates a new Buffer using the passed {data} + * @param data data to create a new Buffer + */ + from(data: Uint8Array | readonly number[]): Buffer; + from(data: WithImplicitCoercion): Buffer; + /** + * Creates a new Buffer containing the given JavaScript string {str}. + * If provided, the {encoding} parameter identifies the character encoding. + * If not provided, {encoding} defaults to 'utf8'. + */ + from( + str: + | WithImplicitCoercion + | { + [Symbol.toPrimitive](hint: "string"): string; + }, + encoding?: BufferEncoding, + ): Buffer; + /** + * Creates a new Buffer using the passed {data} + * @param values to create a new Buffer + */ + of(...items: number[]): Buffer; + /** + * Returns `true` if `obj` is a `Buffer`, `false` otherwise. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * Buffer.isBuffer(Buffer.alloc(10)); // true + * Buffer.isBuffer(Buffer.from('foo')); // true + * Buffer.isBuffer('a string'); // false + * Buffer.isBuffer([]); // false + * Buffer.isBuffer(new Uint8Array(1024)); // false + * ``` + * @since v0.1.101 + */ + isBuffer(obj: any): obj is Buffer; + /** + * Returns `true` if `encoding` is the name of a supported character encoding, + * or `false` otherwise. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * console.log(Buffer.isEncoding('utf8')); + * // Prints: true + * + * console.log(Buffer.isEncoding('hex')); + * // Prints: true + * + * console.log(Buffer.isEncoding('utf/8')); + * // Prints: false + * + * console.log(Buffer.isEncoding('')); + * // Prints: false + * ``` + * @since v0.9.1 + * @param encoding A character encoding name to check. + */ + isEncoding(encoding: string): encoding is BufferEncoding; + /** + * Returns the byte length of a string when encoded using `encoding`. + * This is not the same as [`String.prototype.length`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/length), which does not account + * for the encoding that is used to convert the string into bytes. + * + * For `'base64'`, `'base64url'`, and `'hex'`, this function assumes valid input. + * For strings that contain non-base64/hex-encoded data (e.g. whitespace), the + * return value might be greater than the length of a `Buffer` created from the + * string. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const str = '\u00bd + \u00bc = \u00be'; + * + * console.log(`${str}: ${str.length} characters, ` + + * `${Buffer.byteLength(str, 'utf8')} bytes`); + * // Prints: ½ + ¼ = ¾: 9 characters, 12 bytes + * ``` + * + * When `string` is a + * `Buffer`/[`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView)/[`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/- + * Reference/Global_Objects/TypedArray)/[`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer)/[`SharedArrayBuffer`](https://develop- + * er.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer), the byte length as reported by `.byteLength`is returned. + * @since v0.1.90 + * @param string A value to calculate the length of. + * @param [encoding='utf8'] If `string` is a string, this is its encoding. + * @return The number of bytes contained within `string`. + */ + byteLength( + string: string | Buffer | NodeJS.ArrayBufferView | ArrayBuffer | SharedArrayBuffer, + encoding?: BufferEncoding, + ): number; + /** + * Returns a new `Buffer` which is the result of concatenating all the `Buffer` instances in the `list` together. + * + * If the list has no items, or if the `totalLength` is 0, then a new zero-length `Buffer` is returned. + * + * If `totalLength` is not provided, it is calculated from the `Buffer` instances + * in `list` by adding their lengths. + * + * If `totalLength` is provided, it is coerced to an unsigned integer. If the + * combined length of the `Buffer`s in `list` exceeds `totalLength`, the result is + * truncated to `totalLength`. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * // Create a single `Buffer` from a list of three `Buffer` instances. + * + * const buf1 = Buffer.alloc(10); + * const buf2 = Buffer.alloc(14); + * const buf3 = Buffer.alloc(18); + * const totalLength = buf1.length + buf2.length + buf3.length; + * + * console.log(totalLength); + * // Prints: 42 + * + * const bufA = Buffer.concat([buf1, buf2, buf3], totalLength); + * + * console.log(bufA); + * // Prints: + * console.log(bufA.length); + * // Prints: 42 + * ``` + * + * `Buffer.concat()` may also use the internal `Buffer` pool like `Buffer.allocUnsafe()` does. + * @since v0.7.11 + * @param list List of `Buffer` or {@link Uint8Array} instances to concatenate. + * @param totalLength Total length of the `Buffer` instances in `list` when concatenated. + */ + concat(list: readonly Uint8Array[], totalLength?: number): Buffer; + /** + * Copies the underlying memory of `view` into a new `Buffer`. + * + * ```js + * const u16 = new Uint16Array([0, 0xffff]); + * const buf = Buffer.copyBytesFrom(u16, 1, 1); + * u16[1] = 0; + * console.log(buf.length); // 2 + * console.log(buf[0]); // 255 + * console.log(buf[1]); // 255 + * ``` + * @since v19.8.0 + * @param view The {TypedArray} to copy. + * @param [offset=0] The starting offset within `view`. + * @param [length=view.length - offset] The number of elements from `view` to copy. + */ + copyBytesFrom(view: NodeJS.TypedArray, offset?: number, length?: number): Buffer; + /** + * Compares `buf1` to `buf2`, typically for the purpose of sorting arrays of `Buffer` instances. This is equivalent to calling `buf1.compare(buf2)`. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf1 = Buffer.from('1234'); + * const buf2 = Buffer.from('0123'); + * const arr = [buf1, buf2]; + * + * console.log(arr.sort(Buffer.compare)); + * // Prints: [ , ] + * // (This result is equal to: [buf2, buf1].) + * ``` + * @since v0.11.13 + * @return Either `-1`, `0`, or `1`, depending on the result of the comparison. See `compare` for details. + */ + compare(buf1: Uint8Array, buf2: Uint8Array): -1 | 0 | 1; + /** + * Allocates a new `Buffer` of `size` bytes. If `fill` is `undefined`, the`Buffer` will be zero-filled. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.alloc(5); + * + * console.log(buf); + * // Prints: + * ``` + * + * If `size` is larger than {@link constants.MAX_LENGTH} or smaller than 0, `ERR_OUT_OF_RANGE` is thrown. + * + * If `fill` is specified, the allocated `Buffer` will be initialized by calling `buf.fill(fill)`. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.alloc(5, 'a'); + * + * console.log(buf); + * // Prints: + * ``` + * + * If both `fill` and `encoding` are specified, the allocated `Buffer` will be + * initialized by calling `buf.fill(fill, encoding)`. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.alloc(11, 'aGVsbG8gd29ybGQ=', 'base64'); + * + * console.log(buf); + * // Prints: + * ``` + * + * Calling `Buffer.alloc()` can be measurably slower than the alternative `Buffer.allocUnsafe()` but ensures that the newly created `Buffer` instance + * contents will never contain sensitive data from previous allocations, including + * data that might not have been allocated for `Buffer`s. + * + * A `TypeError` will be thrown if `size` is not a number. + * @since v5.10.0 + * @param size The desired length of the new `Buffer`. + * @param [fill=0] A value to pre-fill the new `Buffer` with. + * @param [encoding='utf8'] If `fill` is a string, this is its encoding. + */ + alloc(size: number, fill?: string | Uint8Array | number, encoding?: BufferEncoding): Buffer; + /** + * Allocates a new `Buffer` of `size` bytes. If `size` is larger than {@link constants.MAX_LENGTH} or smaller than 0, `ERR_OUT_OF_RANGE` is thrown. + * + * The underlying memory for `Buffer` instances created in this way is _not_ + * _initialized_. The contents of the newly created `Buffer` are unknown and _may contain sensitive data_. Use `Buffer.alloc()` instead to initialize`Buffer` instances with zeroes. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(10); + * + * console.log(buf); + * // Prints (contents may vary): + * + * buf.fill(0); + * + * console.log(buf); + * // Prints: + * ``` + * + * A `TypeError` will be thrown if `size` is not a number. + * + * The `Buffer` module pre-allocates an internal `Buffer` instance of + * size `Buffer.poolSize` that is used as a pool for the fast allocation of new `Buffer` instances created using `Buffer.allocUnsafe()`, `Buffer.from(array)`, + * and `Buffer.concat()` only when `size` is less than `Buffer.poolSize >>> 1` (floor of `Buffer.poolSize` divided by two). + * + * Use of this pre-allocated internal memory pool is a key difference between + * calling `Buffer.alloc(size, fill)` vs. `Buffer.allocUnsafe(size).fill(fill)`. + * Specifically, `Buffer.alloc(size, fill)` will _never_ use the internal `Buffer`pool, while `Buffer.allocUnsafe(size).fill(fill)`_will_ use the internal`Buffer` pool if `size` is less + * than or equal to half `Buffer.poolSize`. The + * difference is subtle but can be important when an application requires the + * additional performance that `Buffer.allocUnsafe()` provides. + * @since v5.10.0 + * @param size The desired length of the new `Buffer`. + */ + allocUnsafe(size: number): Buffer; + /** + * Allocates a new `Buffer` of `size` bytes. If `size` is larger than {@link constants.MAX_LENGTH} or smaller than 0, `ERR_OUT_OF_RANGE` is thrown. A zero-length `Buffer` is created if + * `size` is 0. + * + * The underlying memory for `Buffer` instances created in this way is _not_ + * _initialized_. The contents of the newly created `Buffer` are unknown and _may contain sensitive data_. Use `buf.fill(0)` to initialize + * such `Buffer` instances with zeroes. + * + * When using `Buffer.allocUnsafe()` to allocate new `Buffer` instances, + * allocations under 4 KiB are sliced from a single pre-allocated `Buffer`. This + * allows applications to avoid the garbage collection overhead of creating many + * individually allocated `Buffer` instances. This approach improves both + * performance and memory usage by eliminating the need to track and clean up as + * many individual `ArrayBuffer` objects. + * + * However, in the case where a developer may need to retain a small chunk of + * memory from a pool for an indeterminate amount of time, it may be appropriate + * to create an un-pooled `Buffer` instance using `Buffer.allocUnsafeSlow()` and + * then copying out the relevant bits. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * // Need to keep around a few small chunks of memory. + * const store = []; + * + * socket.on('readable', () => { + * let data; + * while (null !== (data = readable.read())) { + * // Allocate for retained data. + * const sb = Buffer.allocUnsafeSlow(10); + * + * // Copy the data into the new allocation. + * data.copy(sb, 0, 0, 10); + * + * store.push(sb); + * } + * }); + * ``` + * + * A `TypeError` will be thrown if `size` is not a number. + * @since v5.12.0 + * @param size The desired length of the new `Buffer`. + */ + allocUnsafeSlow(size: number): Buffer; + /** + * This is the size (in bytes) of pre-allocated internal `Buffer` instances used + * for pooling. This value may be modified. + * @since v0.11.3 + */ + poolSize: number; + } + interface Buffer extends Uint8Array { + /** + * Writes `string` to `buf` at `offset` according to the character encoding in`encoding`. The `length` parameter is the number of bytes to write. If `buf` did + * not contain enough space to fit the entire string, only part of `string` will be + * written. However, partially encoded characters will not be written. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.alloc(256); + * + * const len = buf.write('\u00bd + \u00bc = \u00be', 0); + * + * console.log(`${len} bytes: ${buf.toString('utf8', 0, len)}`); + * // Prints: 12 bytes: ½ + ¼ = ¾ + * + * const buffer = Buffer.alloc(10); + * + * const length = buffer.write('abcd', 8); + * + * console.log(`${length} bytes: ${buffer.toString('utf8', 8, 10)}`); + * // Prints: 2 bytes : ab + * ``` + * @since v0.1.90 + * @param string String to write to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write `string`. + * @param [length=buf.length - offset] Maximum number of bytes to write (written bytes will not exceed `buf.length - offset`). + * @param [encoding='utf8'] The character encoding of `string`. + * @return Number of bytes written. + */ + write(string: string, encoding?: BufferEncoding): number; + write(string: string, offset: number, encoding?: BufferEncoding): number; + write(string: string, offset: number, length: number, encoding?: BufferEncoding): number; + /** + * Decodes `buf` to a string according to the specified character encoding in`encoding`. `start` and `end` may be passed to decode only a subset of `buf`. + * + * If `encoding` is `'utf8'` and a byte sequence in the input is not valid UTF-8, + * then each invalid byte is replaced with the replacement character `U+FFFD`. + * + * The maximum length of a string instance (in UTF-16 code units) is available + * as {@link constants.MAX_STRING_LENGTH}. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf1 = Buffer.allocUnsafe(26); + * + * for (let i = 0; i < 26; i++) { + * // 97 is the decimal ASCII value for 'a'. + * buf1[i] = i + 97; + * } + * + * console.log(buf1.toString('utf8')); + * // Prints: abcdefghijklmnopqrstuvwxyz + * console.log(buf1.toString('utf8', 0, 5)); + * // Prints: abcde + * + * const buf2 = Buffer.from('tést'); + * + * console.log(buf2.toString('hex')); + * // Prints: 74c3a97374 + * console.log(buf2.toString('utf8', 0, 3)); + * // Prints: té + * console.log(buf2.toString(undefined, 0, 3)); + * // Prints: té + * ``` + * @since v0.1.90 + * @param [encoding='utf8'] The character encoding to use. + * @param [start=0] The byte offset to start decoding at. + * @param [end=buf.length] The byte offset to stop decoding at (not inclusive). + */ + toString(encoding?: BufferEncoding, start?: number, end?: number): string; + /** + * Returns a JSON representation of `buf`. [`JSON.stringify()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify) implicitly calls + * this function when stringifying a `Buffer` instance. + * + * `Buffer.from()` accepts objects in the format returned from this method. + * In particular, `Buffer.from(buf.toJSON())` works like `Buffer.from(buf)`. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from([0x1, 0x2, 0x3, 0x4, 0x5]); + * const json = JSON.stringify(buf); + * + * console.log(json); + * // Prints: {"type":"Buffer","data":[1,2,3,4,5]} + * + * const copy = JSON.parse(json, (key, value) => { + * return value && value.type === 'Buffer' ? + * Buffer.from(value) : + * value; + * }); + * + * console.log(copy); + * // Prints: + * ``` + * @since v0.9.2 + */ + toJSON(): { + type: "Buffer"; + data: number[]; + }; + /** + * Returns `true` if both `buf` and `otherBuffer` have exactly the same bytes,`false` otherwise. Equivalent to `buf.compare(otherBuffer) === 0`. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf1 = Buffer.from('ABC'); + * const buf2 = Buffer.from('414243', 'hex'); + * const buf3 = Buffer.from('ABCD'); + * + * console.log(buf1.equals(buf2)); + * // Prints: true + * console.log(buf1.equals(buf3)); + * // Prints: false + * ``` + * @since v0.11.13 + * @param otherBuffer A `Buffer` or {@link Uint8Array} with which to compare `buf`. + */ + equals(otherBuffer: Uint8Array): boolean; + /** + * Compares `buf` with `target` and returns a number indicating whether `buf`comes before, after, or is the same as `target` in sort order. + * Comparison is based on the actual sequence of bytes in each `Buffer`. + * + * * `0` is returned if `target` is the same as `buf` + * * `1` is returned if `target` should come _before_`buf` when sorted. + * * `-1` is returned if `target` should come _after_`buf` when sorted. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf1 = Buffer.from('ABC'); + * const buf2 = Buffer.from('BCD'); + * const buf3 = Buffer.from('ABCD'); + * + * console.log(buf1.compare(buf1)); + * // Prints: 0 + * console.log(buf1.compare(buf2)); + * // Prints: -1 + * console.log(buf1.compare(buf3)); + * // Prints: -1 + * console.log(buf2.compare(buf1)); + * // Prints: 1 + * console.log(buf2.compare(buf3)); + * // Prints: 1 + * console.log([buf1, buf2, buf3].sort(Buffer.compare)); + * // Prints: [ , , ] + * // (This result is equal to: [buf1, buf3, buf2].) + * ``` + * + * The optional `targetStart`, `targetEnd`, `sourceStart`, and `sourceEnd` arguments can be used to limit the comparison to specific ranges within `target` and `buf` respectively. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf1 = Buffer.from([1, 2, 3, 4, 5, 6, 7, 8, 9]); + * const buf2 = Buffer.from([5, 6, 7, 8, 9, 1, 2, 3, 4]); + * + * console.log(buf1.compare(buf2, 5, 9, 0, 4)); + * // Prints: 0 + * console.log(buf1.compare(buf2, 0, 6, 4)); + * // Prints: -1 + * console.log(buf1.compare(buf2, 5, 6, 5)); + * // Prints: 1 + * ``` + * + * `ERR_OUT_OF_RANGE` is thrown if `targetStart < 0`, `sourceStart < 0`, `targetEnd > target.byteLength`, or `sourceEnd > source.byteLength`. + * @since v0.11.13 + * @param target A `Buffer` or {@link Uint8Array} with which to compare `buf`. + * @param [targetStart=0] The offset within `target` at which to begin comparison. + * @param [targetEnd=target.length] The offset within `target` at which to end comparison (not inclusive). + * @param [sourceStart=0] The offset within `buf` at which to begin comparison. + * @param [sourceEnd=buf.length] The offset within `buf` at which to end comparison (not inclusive). + */ + compare( + target: Uint8Array, + targetStart?: number, + targetEnd?: number, + sourceStart?: number, + sourceEnd?: number, + ): -1 | 0 | 1; + /** + * Copies data from a region of `buf` to a region in `target`, even if the `target`memory region overlaps with `buf`. + * + * [`TypedArray.prototype.set()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/set) performs the same operation, and is available + * for all TypedArrays, including Node.js `Buffer`s, although it takes + * different function arguments. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * // Create two `Buffer` instances. + * const buf1 = Buffer.allocUnsafe(26); + * const buf2 = Buffer.allocUnsafe(26).fill('!'); + * + * for (let i = 0; i < 26; i++) { + * // 97 is the decimal ASCII value for 'a'. + * buf1[i] = i + 97; + * } + * + * // Copy `buf1` bytes 16 through 19 into `buf2` starting at byte 8 of `buf2`. + * buf1.copy(buf2, 8, 16, 20); + * // This is equivalent to: + * // buf2.set(buf1.subarray(16, 20), 8); + * + * console.log(buf2.toString('ascii', 0, 25)); + * // Prints: !!!!!!!!qrst!!!!!!!!!!!!! + * ``` + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * // Create a `Buffer` and copy data from one region to an overlapping region + * // within the same `Buffer`. + * + * const buf = Buffer.allocUnsafe(26); + * + * for (let i = 0; i < 26; i++) { + * // 97 is the decimal ASCII value for 'a'. + * buf[i] = i + 97; + * } + * + * buf.copy(buf, 0, 4, 10); + * + * console.log(buf.toString()); + * // Prints: efghijghijklmnopqrstuvwxyz + * ``` + * @since v0.1.90 + * @param target A `Buffer` or {@link Uint8Array} to copy into. + * @param [targetStart=0] The offset within `target` at which to begin writing. + * @param [sourceStart=0] The offset within `buf` from which to begin copying. + * @param [sourceEnd=buf.length] The offset within `buf` at which to stop copying (not inclusive). + * @return The number of bytes copied. + */ + copy(target: Uint8Array, targetStart?: number, sourceStart?: number, sourceEnd?: number): number; + /** + * Returns a new `Buffer` that references the same memory as the original, but + * offset and cropped by the `start` and `end` indices. + * + * This method is not compatible with the `Uint8Array.prototype.slice()`, + * which is a superclass of `Buffer`. To copy the slice, use`Uint8Array.prototype.slice()`. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from('buffer'); + * + * const copiedBuf = Uint8Array.prototype.slice.call(buf); + * copiedBuf[0]++; + * console.log(copiedBuf.toString()); + * // Prints: cuffer + * + * console.log(buf.toString()); + * // Prints: buffer + * + * // With buf.slice(), the original buffer is modified. + * const notReallyCopiedBuf = buf.slice(); + * notReallyCopiedBuf[0]++; + * console.log(notReallyCopiedBuf.toString()); + * // Prints: cuffer + * console.log(buf.toString()); + * // Also prints: cuffer (!) + * ``` + * @since v0.3.0 + * @deprecated Use `subarray` instead. + * @param [start=0] Where the new `Buffer` will start. + * @param [end=buf.length] Where the new `Buffer` will end (not inclusive). + */ + slice(start?: number, end?: number): Buffer; + /** + * Returns a new `Buffer` that references the same memory as the original, but + * offset and cropped by the `start` and `end` indices. + * + * Specifying `end` greater than `buf.length` will return the same result as + * that of `end` equal to `buf.length`. + * + * This method is inherited from [`TypedArray.prototype.subarray()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/subarray). + * + * Modifying the new `Buffer` slice will modify the memory in the original `Buffer`because the allocated memory of the two objects overlap. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * // Create a `Buffer` with the ASCII alphabet, take a slice, and modify one byte + * // from the original `Buffer`. + * + * const buf1 = Buffer.allocUnsafe(26); + * + * for (let i = 0; i < 26; i++) { + * // 97 is the decimal ASCII value for 'a'. + * buf1[i] = i + 97; + * } + * + * const buf2 = buf1.subarray(0, 3); + * + * console.log(buf2.toString('ascii', 0, buf2.length)); + * // Prints: abc + * + * buf1[0] = 33; + * + * console.log(buf2.toString('ascii', 0, buf2.length)); + * // Prints: !bc + * ``` + * + * Specifying negative indexes causes the slice to be generated relative to the + * end of `buf` rather than the beginning. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from('buffer'); + * + * console.log(buf.subarray(-6, -1).toString()); + * // Prints: buffe + * // (Equivalent to buf.subarray(0, 5).) + * + * console.log(buf.subarray(-6, -2).toString()); + * // Prints: buff + * // (Equivalent to buf.subarray(0, 4).) + * + * console.log(buf.subarray(-5, -2).toString()); + * // Prints: uff + * // (Equivalent to buf.subarray(1, 4).) + * ``` + * @since v3.0.0 + * @param [start=0] Where the new `Buffer` will start. + * @param [end=buf.length] Where the new `Buffer` will end (not inclusive). + */ + subarray(start?: number, end?: number): Buffer; + /** + * Writes `value` to `buf` at the specified `offset` as big-endian. + * + * `value` is interpreted and written as a two's complement signed integer. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(8); + * + * buf.writeBigInt64BE(0x0102030405060708n, 0); + * + * console.log(buf); + * // Prints: + * ``` + * @since v12.0.0, v10.20.0 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy: `0 <= offset <= buf.length - 8`. + * @return `offset` plus the number of bytes written. + */ + writeBigInt64BE(value: bigint, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as little-endian. + * + * `value` is interpreted and written as a two's complement signed integer. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(8); + * + * buf.writeBigInt64LE(0x0102030405060708n, 0); + * + * console.log(buf); + * // Prints: + * ``` + * @since v12.0.0, v10.20.0 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy: `0 <= offset <= buf.length - 8`. + * @return `offset` plus the number of bytes written. + */ + writeBigInt64LE(value: bigint, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as big-endian. + * + * This function is also available under the `writeBigUint64BE` alias. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(8); + * + * buf.writeBigUInt64BE(0xdecafafecacefaden, 0); + * + * console.log(buf); + * // Prints: + * ``` + * @since v12.0.0, v10.20.0 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy: `0 <= offset <= buf.length - 8`. + * @return `offset` plus the number of bytes written. + */ + writeBigUInt64BE(value: bigint, offset?: number): number; + /** + * @alias Buffer.writeBigUInt64BE + * @since v14.10.0, v12.19.0 + */ + writeBigUint64BE(value: bigint, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as little-endian + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(8); + * + * buf.writeBigUInt64LE(0xdecafafecacefaden, 0); + * + * console.log(buf); + * // Prints: + * ``` + * + * This function is also available under the `writeBigUint64LE` alias. + * @since v12.0.0, v10.20.0 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy: `0 <= offset <= buf.length - 8`. + * @return `offset` plus the number of bytes written. + */ + writeBigUInt64LE(value: bigint, offset?: number): number; + /** + * @alias Buffer.writeBigUInt64LE + * @since v14.10.0, v12.19.0 + */ + writeBigUint64LE(value: bigint, offset?: number): number; + /** + * Writes `byteLength` bytes of `value` to `buf` at the specified `offset`as little-endian. Supports up to 48 bits of accuracy. Behavior is undefined + * when `value` is anything other than an unsigned integer. + * + * This function is also available under the `writeUintLE` alias. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(6); + * + * buf.writeUIntLE(0x1234567890ab, 0, 6); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.5.5 + * @param value Number to be written to `buf`. + * @param offset Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - byteLength`. + * @param byteLength Number of bytes to write. Must satisfy `0 < byteLength <= 6`. + * @return `offset` plus the number of bytes written. + */ + writeUIntLE(value: number, offset: number, byteLength: number): number; + /** + * @alias Buffer.writeUIntLE + * @since v14.9.0, v12.19.0 + */ + writeUintLE(value: number, offset: number, byteLength: number): number; + /** + * Writes `byteLength` bytes of `value` to `buf` at the specified `offset`as big-endian. Supports up to 48 bits of accuracy. Behavior is undefined + * when `value` is anything other than an unsigned integer. + * + * This function is also available under the `writeUintBE` alias. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(6); + * + * buf.writeUIntBE(0x1234567890ab, 0, 6); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.5.5 + * @param value Number to be written to `buf`. + * @param offset Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - byteLength`. + * @param byteLength Number of bytes to write. Must satisfy `0 < byteLength <= 6`. + * @return `offset` plus the number of bytes written. + */ + writeUIntBE(value: number, offset: number, byteLength: number): number; + /** + * @alias Buffer.writeUIntBE + * @since v14.9.0, v12.19.0 + */ + writeUintBE(value: number, offset: number, byteLength: number): number; + /** + * Writes `byteLength` bytes of `value` to `buf` at the specified `offset`as little-endian. Supports up to 48 bits of accuracy. Behavior is undefined + * when `value` is anything other than a signed integer. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(6); + * + * buf.writeIntLE(0x1234567890ab, 0, 6); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.11.15 + * @param value Number to be written to `buf`. + * @param offset Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - byteLength`. + * @param byteLength Number of bytes to write. Must satisfy `0 < byteLength <= 6`. + * @return `offset` plus the number of bytes written. + */ + writeIntLE(value: number, offset: number, byteLength: number): number; + /** + * Writes `byteLength` bytes of `value` to `buf` at the specified `offset`as big-endian. Supports up to 48 bits of accuracy. Behavior is undefined when`value` is anything other than a + * signed integer. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(6); + * + * buf.writeIntBE(0x1234567890ab, 0, 6); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.11.15 + * @param value Number to be written to `buf`. + * @param offset Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - byteLength`. + * @param byteLength Number of bytes to write. Must satisfy `0 < byteLength <= 6`. + * @return `offset` plus the number of bytes written. + */ + writeIntBE(value: number, offset: number, byteLength: number): number; + /** + * Reads an unsigned, big-endian 64-bit integer from `buf` at the specified`offset`. + * + * This function is also available under the `readBigUint64BE` alias. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from([0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff]); + * + * console.log(buf.readBigUInt64BE(0)); + * // Prints: 4294967295n + * ``` + * @since v12.0.0, v10.20.0 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy: `0 <= offset <= buf.length - 8`. + */ + readBigUInt64BE(offset?: number): bigint; + /** + * @alias Buffer.readBigUInt64BE + * @since v14.10.0, v12.19.0 + */ + readBigUint64BE(offset?: number): bigint; + /** + * Reads an unsigned, little-endian 64-bit integer from `buf` at the specified`offset`. + * + * This function is also available under the `readBigUint64LE` alias. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from([0x00, 0x00, 0x00, 0x00, 0xff, 0xff, 0xff, 0xff]); + * + * console.log(buf.readBigUInt64LE(0)); + * // Prints: 18446744069414584320n + * ``` + * @since v12.0.0, v10.20.0 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy: `0 <= offset <= buf.length - 8`. + */ + readBigUInt64LE(offset?: number): bigint; + /** + * @alias Buffer.readBigUInt64LE + * @since v14.10.0, v12.19.0 + */ + readBigUint64LE(offset?: number): bigint; + /** + * Reads a signed, big-endian 64-bit integer from `buf` at the specified `offset`. + * + * Integers read from a `Buffer` are interpreted as two's complement signed + * values. + * @since v12.0.0, v10.20.0 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy: `0 <= offset <= buf.length - 8`. + */ + readBigInt64BE(offset?: number): bigint; + /** + * Reads a signed, little-endian 64-bit integer from `buf` at the specified`offset`. + * + * Integers read from a `Buffer` are interpreted as two's complement signed + * values. + * @since v12.0.0, v10.20.0 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy: `0 <= offset <= buf.length - 8`. + */ + readBigInt64LE(offset?: number): bigint; + /** + * Reads `byteLength` number of bytes from `buf` at the specified `offset` and interprets the result as an unsigned, little-endian integer supporting + * up to 48 bits of accuracy. + * + * This function is also available under the `readUintLE` alias. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from([0x12, 0x34, 0x56, 0x78, 0x90, 0xab]); + * + * console.log(buf.readUIntLE(0, 6).toString(16)); + * // Prints: ab9078563412 + * ``` + * @since v0.11.15 + * @param offset Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - byteLength`. + * @param byteLength Number of bytes to read. Must satisfy `0 < byteLength <= 6`. + */ + readUIntLE(offset: number, byteLength: number): number; + /** + * @alias Buffer.readUIntLE + * @since v14.9.0, v12.19.0 + */ + readUintLE(offset: number, byteLength: number): number; + /** + * Reads `byteLength` number of bytes from `buf` at the specified `offset` and interprets the result as an unsigned big-endian integer supporting + * up to 48 bits of accuracy. + * + * This function is also available under the `readUintBE` alias. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from([0x12, 0x34, 0x56, 0x78, 0x90, 0xab]); + * + * console.log(buf.readUIntBE(0, 6).toString(16)); + * // Prints: 1234567890ab + * console.log(buf.readUIntBE(1, 6).toString(16)); + * // Throws ERR_OUT_OF_RANGE. + * ``` + * @since v0.11.15 + * @param offset Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - byteLength`. + * @param byteLength Number of bytes to read. Must satisfy `0 < byteLength <= 6`. + */ + readUIntBE(offset: number, byteLength: number): number; + /** + * @alias Buffer.readUIntBE + * @since v14.9.0, v12.19.0 + */ + readUintBE(offset: number, byteLength: number): number; + /** + * Reads `byteLength` number of bytes from `buf` at the specified `offset` and interprets the result as a little-endian, two's complement signed value + * supporting up to 48 bits of accuracy. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from([0x12, 0x34, 0x56, 0x78, 0x90, 0xab]); + * + * console.log(buf.readIntLE(0, 6).toString(16)); + * // Prints: -546f87a9cbee + * ``` + * @since v0.11.15 + * @param offset Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - byteLength`. + * @param byteLength Number of bytes to read. Must satisfy `0 < byteLength <= 6`. + */ + readIntLE(offset: number, byteLength: number): number; + /** + * Reads `byteLength` number of bytes from `buf` at the specified `offset` and interprets the result as a big-endian, two's complement signed value + * supporting up to 48 bits of accuracy. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from([0x12, 0x34, 0x56, 0x78, 0x90, 0xab]); + * + * console.log(buf.readIntBE(0, 6).toString(16)); + * // Prints: 1234567890ab + * console.log(buf.readIntBE(1, 6).toString(16)); + * // Throws ERR_OUT_OF_RANGE. + * console.log(buf.readIntBE(1, 0).toString(16)); + * // Throws ERR_OUT_OF_RANGE. + * ``` + * @since v0.11.15 + * @param offset Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - byteLength`. + * @param byteLength Number of bytes to read. Must satisfy `0 < byteLength <= 6`. + */ + readIntBE(offset: number, byteLength: number): number; + /** + * Reads an unsigned 8-bit integer from `buf` at the specified `offset`. + * + * This function is also available under the `readUint8` alias. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from([1, -2]); + * + * console.log(buf.readUInt8(0)); + * // Prints: 1 + * console.log(buf.readUInt8(1)); + * // Prints: 254 + * console.log(buf.readUInt8(2)); + * // Throws ERR_OUT_OF_RANGE. + * ``` + * @since v0.5.0 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 1`. + */ + readUInt8(offset?: number): number; + /** + * @alias Buffer.readUInt8 + * @since v14.9.0, v12.19.0 + */ + readUint8(offset?: number): number; + /** + * Reads an unsigned, little-endian 16-bit integer from `buf` at the specified `offset`. + * + * This function is also available under the `readUint16LE` alias. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from([0x12, 0x34, 0x56]); + * + * console.log(buf.readUInt16LE(0).toString(16)); + * // Prints: 3412 + * console.log(buf.readUInt16LE(1).toString(16)); + * // Prints: 5634 + * console.log(buf.readUInt16LE(2).toString(16)); + * // Throws ERR_OUT_OF_RANGE. + * ``` + * @since v0.5.5 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 2`. + */ + readUInt16LE(offset?: number): number; + /** + * @alias Buffer.readUInt16LE + * @since v14.9.0, v12.19.0 + */ + readUint16LE(offset?: number): number; + /** + * Reads an unsigned, big-endian 16-bit integer from `buf` at the specified`offset`. + * + * This function is also available under the `readUint16BE` alias. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from([0x12, 0x34, 0x56]); + * + * console.log(buf.readUInt16BE(0).toString(16)); + * // Prints: 1234 + * console.log(buf.readUInt16BE(1).toString(16)); + * // Prints: 3456 + * ``` + * @since v0.5.5 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 2`. + */ + readUInt16BE(offset?: number): number; + /** + * @alias Buffer.readUInt16BE + * @since v14.9.0, v12.19.0 + */ + readUint16BE(offset?: number): number; + /** + * Reads an unsigned, little-endian 32-bit integer from `buf` at the specified`offset`. + * + * This function is also available under the `readUint32LE` alias. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from([0x12, 0x34, 0x56, 0x78]); + * + * console.log(buf.readUInt32LE(0).toString(16)); + * // Prints: 78563412 + * console.log(buf.readUInt32LE(1).toString(16)); + * // Throws ERR_OUT_OF_RANGE. + * ``` + * @since v0.5.5 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 4`. + */ + readUInt32LE(offset?: number): number; + /** + * @alias Buffer.readUInt32LE + * @since v14.9.0, v12.19.0 + */ + readUint32LE(offset?: number): number; + /** + * Reads an unsigned, big-endian 32-bit integer from `buf` at the specified`offset`. + * + * This function is also available under the `readUint32BE` alias. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from([0x12, 0x34, 0x56, 0x78]); + * + * console.log(buf.readUInt32BE(0).toString(16)); + * // Prints: 12345678 + * ``` + * @since v0.5.5 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 4`. + */ + readUInt32BE(offset?: number): number; + /** + * @alias Buffer.readUInt32BE + * @since v14.9.0, v12.19.0 + */ + readUint32BE(offset?: number): number; + /** + * Reads a signed 8-bit integer from `buf` at the specified `offset`. + * + * Integers read from a `Buffer` are interpreted as two's complement signed values. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from([-1, 5]); + * + * console.log(buf.readInt8(0)); + * // Prints: -1 + * console.log(buf.readInt8(1)); + * // Prints: 5 + * console.log(buf.readInt8(2)); + * // Throws ERR_OUT_OF_RANGE. + * ``` + * @since v0.5.0 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 1`. + */ + readInt8(offset?: number): number; + /** + * Reads a signed, little-endian 16-bit integer from `buf` at the specified`offset`. + * + * Integers read from a `Buffer` are interpreted as two's complement signed values. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from([0, 5]); + * + * console.log(buf.readInt16LE(0)); + * // Prints: 1280 + * console.log(buf.readInt16LE(1)); + * // Throws ERR_OUT_OF_RANGE. + * ``` + * @since v0.5.5 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 2`. + */ + readInt16LE(offset?: number): number; + /** + * Reads a signed, big-endian 16-bit integer from `buf` at the specified `offset`. + * + * Integers read from a `Buffer` are interpreted as two's complement signed values. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from([0, 5]); + * + * console.log(buf.readInt16BE(0)); + * // Prints: 5 + * ``` + * @since v0.5.5 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 2`. + */ + readInt16BE(offset?: number): number; + /** + * Reads a signed, little-endian 32-bit integer from `buf` at the specified`offset`. + * + * Integers read from a `Buffer` are interpreted as two's complement signed values. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from([0, 0, 0, 5]); + * + * console.log(buf.readInt32LE(0)); + * // Prints: 83886080 + * console.log(buf.readInt32LE(1)); + * // Throws ERR_OUT_OF_RANGE. + * ``` + * @since v0.5.5 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 4`. + */ + readInt32LE(offset?: number): number; + /** + * Reads a signed, big-endian 32-bit integer from `buf` at the specified `offset`. + * + * Integers read from a `Buffer` are interpreted as two's complement signed values. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from([0, 0, 0, 5]); + * + * console.log(buf.readInt32BE(0)); + * // Prints: 5 + * ``` + * @since v0.5.5 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 4`. + */ + readInt32BE(offset?: number): number; + /** + * Reads a 32-bit, little-endian float from `buf` at the specified `offset`. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from([1, 2, 3, 4]); + * + * console.log(buf.readFloatLE(0)); + * // Prints: 1.539989614439558e-36 + * console.log(buf.readFloatLE(1)); + * // Throws ERR_OUT_OF_RANGE. + * ``` + * @since v0.11.15 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 4`. + */ + readFloatLE(offset?: number): number; + /** + * Reads a 32-bit, big-endian float from `buf` at the specified `offset`. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from([1, 2, 3, 4]); + * + * console.log(buf.readFloatBE(0)); + * // Prints: 2.387939260590663e-38 + * ``` + * @since v0.11.15 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 4`. + */ + readFloatBE(offset?: number): number; + /** + * Reads a 64-bit, little-endian double from `buf` at the specified `offset`. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from([1, 2, 3, 4, 5, 6, 7, 8]); + * + * console.log(buf.readDoubleLE(0)); + * // Prints: 5.447603722011605e-270 + * console.log(buf.readDoubleLE(1)); + * // Throws ERR_OUT_OF_RANGE. + * ``` + * @since v0.11.15 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 8`. + */ + readDoubleLE(offset?: number): number; + /** + * Reads a 64-bit, big-endian double from `buf` at the specified `offset`. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from([1, 2, 3, 4, 5, 6, 7, 8]); + * + * console.log(buf.readDoubleBE(0)); + * // Prints: 8.20788039913184e-304 + * ``` + * @since v0.11.15 + * @param [offset=0] Number of bytes to skip before starting to read. Must satisfy `0 <= offset <= buf.length - 8`. + */ + readDoubleBE(offset?: number): number; + reverse(): this; + /** + * Interprets `buf` as an array of unsigned 16-bit integers and swaps the + * byte order _in-place_. Throws `ERR_INVALID_BUFFER_SIZE` if `buf.length` is not a multiple of 2. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf1 = Buffer.from([0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8]); + * + * console.log(buf1); + * // Prints: + * + * buf1.swap16(); + * + * console.log(buf1); + * // Prints: + * + * const buf2 = Buffer.from([0x1, 0x2, 0x3]); + * + * buf2.swap16(); + * // Throws ERR_INVALID_BUFFER_SIZE. + * ``` + * + * One convenient use of `buf.swap16()` is to perform a fast in-place conversion + * between UTF-16 little-endian and UTF-16 big-endian: + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from('This is little-endian UTF-16', 'utf16le'); + * buf.swap16(); // Convert to big-endian UTF-16 text. + * ``` + * @since v5.10.0 + * @return A reference to `buf`. + */ + swap16(): Buffer; + /** + * Interprets `buf` as an array of unsigned 32-bit integers and swaps the + * byte order _in-place_. Throws `ERR_INVALID_BUFFER_SIZE` if `buf.length` is not a multiple of 4. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf1 = Buffer.from([0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8]); + * + * console.log(buf1); + * // Prints: + * + * buf1.swap32(); + * + * console.log(buf1); + * // Prints: + * + * const buf2 = Buffer.from([0x1, 0x2, 0x3]); + * + * buf2.swap32(); + * // Throws ERR_INVALID_BUFFER_SIZE. + * ``` + * @since v5.10.0 + * @return A reference to `buf`. + */ + swap32(): Buffer; + /** + * Interprets `buf` as an array of 64-bit numbers and swaps byte order _in-place_. + * Throws `ERR_INVALID_BUFFER_SIZE` if `buf.length` is not a multiple of 8. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf1 = Buffer.from([0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8]); + * + * console.log(buf1); + * // Prints: + * + * buf1.swap64(); + * + * console.log(buf1); + * // Prints: + * + * const buf2 = Buffer.from([0x1, 0x2, 0x3]); + * + * buf2.swap64(); + * // Throws ERR_INVALID_BUFFER_SIZE. + * ``` + * @since v6.3.0 + * @return A reference to `buf`. + */ + swap64(): Buffer; + /** + * Writes `value` to `buf` at the specified `offset`. `value` must be a + * valid unsigned 8-bit integer. Behavior is undefined when `value` is anything + * other than an unsigned 8-bit integer. + * + * This function is also available under the `writeUint8` alias. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(4); + * + * buf.writeUInt8(0x3, 0); + * buf.writeUInt8(0x4, 1); + * buf.writeUInt8(0x23, 2); + * buf.writeUInt8(0x42, 3); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.5.0 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 1`. + * @return `offset` plus the number of bytes written. + */ + writeUInt8(value: number, offset?: number): number; + /** + * @alias Buffer.writeUInt8 + * @since v14.9.0, v12.19.0 + */ + writeUint8(value: number, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as little-endian. The `value` must be a valid unsigned 16-bit integer. Behavior is undefined when `value` is + * anything other than an unsigned 16-bit integer. + * + * This function is also available under the `writeUint16LE` alias. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(4); + * + * buf.writeUInt16LE(0xdead, 0); + * buf.writeUInt16LE(0xbeef, 2); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.5.5 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 2`. + * @return `offset` plus the number of bytes written. + */ + writeUInt16LE(value: number, offset?: number): number; + /** + * @alias Buffer.writeUInt16LE + * @since v14.9.0, v12.19.0 + */ + writeUint16LE(value: number, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as big-endian. The `value` must be a valid unsigned 16-bit integer. Behavior is undefined when `value`is anything other than an + * unsigned 16-bit integer. + * + * This function is also available under the `writeUint16BE` alias. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(4); + * + * buf.writeUInt16BE(0xdead, 0); + * buf.writeUInt16BE(0xbeef, 2); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.5.5 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 2`. + * @return `offset` plus the number of bytes written. + */ + writeUInt16BE(value: number, offset?: number): number; + /** + * @alias Buffer.writeUInt16BE + * @since v14.9.0, v12.19.0 + */ + writeUint16BE(value: number, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as little-endian. The `value` must be a valid unsigned 32-bit integer. Behavior is undefined when `value` is + * anything other than an unsigned 32-bit integer. + * + * This function is also available under the `writeUint32LE` alias. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(4); + * + * buf.writeUInt32LE(0xfeedface, 0); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.5.5 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 4`. + * @return `offset` plus the number of bytes written. + */ + writeUInt32LE(value: number, offset?: number): number; + /** + * @alias Buffer.writeUInt32LE + * @since v14.9.0, v12.19.0 + */ + writeUint32LE(value: number, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as big-endian. The `value` must be a valid unsigned 32-bit integer. Behavior is undefined when `value`is anything other than an + * unsigned 32-bit integer. + * + * This function is also available under the `writeUint32BE` alias. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(4); + * + * buf.writeUInt32BE(0xfeedface, 0); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.5.5 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 4`. + * @return `offset` plus the number of bytes written. + */ + writeUInt32BE(value: number, offset?: number): number; + /** + * @alias Buffer.writeUInt32BE + * @since v14.9.0, v12.19.0 + */ + writeUint32BE(value: number, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset`. `value` must be a valid + * signed 8-bit integer. Behavior is undefined when `value` is anything other than + * a signed 8-bit integer. + * + * `value` is interpreted and written as a two's complement signed integer. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(2); + * + * buf.writeInt8(2, 0); + * buf.writeInt8(-2, 1); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.5.0 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 1`. + * @return `offset` plus the number of bytes written. + */ + writeInt8(value: number, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as little-endian. The `value` must be a valid signed 16-bit integer. Behavior is undefined when `value` is + * anything other than a signed 16-bit integer. + * + * The `value` is interpreted and written as a two's complement signed integer. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(2); + * + * buf.writeInt16LE(0x0304, 0); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.5.5 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 2`. + * @return `offset` plus the number of bytes written. + */ + writeInt16LE(value: number, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as big-endian. The `value` must be a valid signed 16-bit integer. Behavior is undefined when `value` is + * anything other than a signed 16-bit integer. + * + * The `value` is interpreted and written as a two's complement signed integer. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(2); + * + * buf.writeInt16BE(0x0102, 0); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.5.5 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 2`. + * @return `offset` plus the number of bytes written. + */ + writeInt16BE(value: number, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as little-endian. The `value` must be a valid signed 32-bit integer. Behavior is undefined when `value` is + * anything other than a signed 32-bit integer. + * + * The `value` is interpreted and written as a two's complement signed integer. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(4); + * + * buf.writeInt32LE(0x05060708, 0); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.5.5 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 4`. + * @return `offset` plus the number of bytes written. + */ + writeInt32LE(value: number, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as big-endian. The `value` must be a valid signed 32-bit integer. Behavior is undefined when `value` is + * anything other than a signed 32-bit integer. + * + * The `value` is interpreted and written as a two's complement signed integer. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(4); + * + * buf.writeInt32BE(0x01020304, 0); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.5.5 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 4`. + * @return `offset` plus the number of bytes written. + */ + writeInt32BE(value: number, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as little-endian. Behavior is + * undefined when `value` is anything other than a JavaScript number. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(4); + * + * buf.writeFloatLE(0xcafebabe, 0); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.11.15 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 4`. + * @return `offset` plus the number of bytes written. + */ + writeFloatLE(value: number, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as big-endian. Behavior is + * undefined when `value` is anything other than a JavaScript number. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(4); + * + * buf.writeFloatBE(0xcafebabe, 0); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.11.15 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 4`. + * @return `offset` plus the number of bytes written. + */ + writeFloatBE(value: number, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as little-endian. The `value` must be a JavaScript number. Behavior is undefined when `value` is anything + * other than a JavaScript number. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(8); + * + * buf.writeDoubleLE(123.456, 0); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.11.15 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 8`. + * @return `offset` plus the number of bytes written. + */ + writeDoubleLE(value: number, offset?: number): number; + /** + * Writes `value` to `buf` at the specified `offset` as big-endian. The `value` must be a JavaScript number. Behavior is undefined when `value` is anything + * other than a JavaScript number. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(8); + * + * buf.writeDoubleBE(123.456, 0); + * + * console.log(buf); + * // Prints: + * ``` + * @since v0.11.15 + * @param value Number to be written to `buf`. + * @param [offset=0] Number of bytes to skip before starting to write. Must satisfy `0 <= offset <= buf.length - 8`. + * @return `offset` plus the number of bytes written. + */ + writeDoubleBE(value: number, offset?: number): number; + /** + * Fills `buf` with the specified `value`. If the `offset` and `end` are not given, + * the entire `buf` will be filled: + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * // Fill a `Buffer` with the ASCII character 'h'. + * + * const b = Buffer.allocUnsafe(50).fill('h'); + * + * console.log(b.toString()); + * // Prints: hhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh + * + * // Fill a buffer with empty string + * const c = Buffer.allocUnsafe(5).fill(''); + * + * console.log(c.fill('')); + * // Prints: + * ``` + * + * `value` is coerced to a `uint32` value if it is not a string, `Buffer`, or + * integer. If the resulting integer is greater than `255` (decimal), `buf` will be + * filled with `value & 255`. + * + * If the final write of a `fill()` operation falls on a multi-byte character, + * then only the bytes of that character that fit into `buf` are written: + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * // Fill a `Buffer` with character that takes up two bytes in UTF-8. + * + * console.log(Buffer.allocUnsafe(5).fill('\u0222')); + * // Prints: + * ``` + * + * If `value` contains invalid characters, it is truncated; if no valid + * fill data remains, an exception is thrown: + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.allocUnsafe(5); + * + * console.log(buf.fill('a')); + * // Prints: + * console.log(buf.fill('aazz', 'hex')); + * // Prints: + * console.log(buf.fill('zz', 'hex')); + * // Throws an exception. + * ``` + * @since v0.5.0 + * @param value The value with which to fill `buf`. Empty value (string, Uint8Array, Buffer) is coerced to `0`. + * @param [offset=0] Number of bytes to skip before starting to fill `buf`. + * @param [end=buf.length] Where to stop filling `buf` (not inclusive). + * @param [encoding='utf8'] The encoding for `value` if `value` is a string. + * @return A reference to `buf`. + */ + fill(value: string | Uint8Array | number, offset?: number, end?: number, encoding?: BufferEncoding): this; + /** + * If `value` is: + * + * * a string, `value` is interpreted according to the character encoding in `encoding`. + * * a `Buffer` or [`Uint8Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array), `value` will be used in its entirety. + * To compare a partial `Buffer`, use `buf.subarray`. + * * a number, `value` will be interpreted as an unsigned 8-bit integer + * value between `0` and `255`. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from('this is a buffer'); + * + * console.log(buf.indexOf('this')); + * // Prints: 0 + * console.log(buf.indexOf('is')); + * // Prints: 2 + * console.log(buf.indexOf(Buffer.from('a buffer'))); + * // Prints: 8 + * console.log(buf.indexOf(97)); + * // Prints: 8 (97 is the decimal ASCII value for 'a') + * console.log(buf.indexOf(Buffer.from('a buffer example'))); + * // Prints: -1 + * console.log(buf.indexOf(Buffer.from('a buffer example').slice(0, 8))); + * // Prints: 8 + * + * const utf16Buffer = Buffer.from('\u039a\u0391\u03a3\u03a3\u0395', 'utf16le'); + * + * console.log(utf16Buffer.indexOf('\u03a3', 0, 'utf16le')); + * // Prints: 4 + * console.log(utf16Buffer.indexOf('\u03a3', -4, 'utf16le')); + * // Prints: 6 + * ``` + * + * If `value` is not a string, number, or `Buffer`, this method will throw a `TypeError`. If `value` is a number, it will be coerced to a valid byte value, + * an integer between 0 and 255. + * + * If `byteOffset` is not a number, it will be coerced to a number. If the result + * of coercion is `NaN` or `0`, then the entire buffer will be searched. This + * behavior matches [`String.prototype.indexOf()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/indexOf). + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const b = Buffer.from('abcdef'); + * + * // Passing a value that's a number, but not a valid byte. + * // Prints: 2, equivalent to searching for 99 or 'c'. + * console.log(b.indexOf(99.9)); + * console.log(b.indexOf(256 + 99)); + * + * // Passing a byteOffset that coerces to NaN or 0. + * // Prints: 1, searching the whole buffer. + * console.log(b.indexOf('b', undefined)); + * console.log(b.indexOf('b', {})); + * console.log(b.indexOf('b', null)); + * console.log(b.indexOf('b', [])); + * ``` + * + * If `value` is an empty string or empty `Buffer` and `byteOffset` is less + * than `buf.length`, `byteOffset` will be returned. If `value` is empty and`byteOffset` is at least `buf.length`, `buf.length` will be returned. + * @since v1.5.0 + * @param value What to search for. + * @param [byteOffset=0] Where to begin searching in `buf`. If negative, then offset is calculated from the end of `buf`. + * @param [encoding='utf8'] If `value` is a string, this is the encoding used to determine the binary representation of the string that will be searched for in `buf`. + * @return The index of the first occurrence of `value` in `buf`, or `-1` if `buf` does not contain `value`. + */ + indexOf(value: string | number | Uint8Array, byteOffset?: number, encoding?: BufferEncoding): number; + /** + * Identical to `buf.indexOf()`, except the last occurrence of `value` is found + * rather than the first occurrence. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from('this buffer is a buffer'); + * + * console.log(buf.lastIndexOf('this')); + * // Prints: 0 + * console.log(buf.lastIndexOf('buffer')); + * // Prints: 17 + * console.log(buf.lastIndexOf(Buffer.from('buffer'))); + * // Prints: 17 + * console.log(buf.lastIndexOf(97)); + * // Prints: 15 (97 is the decimal ASCII value for 'a') + * console.log(buf.lastIndexOf(Buffer.from('yolo'))); + * // Prints: -1 + * console.log(buf.lastIndexOf('buffer', 5)); + * // Prints: 5 + * console.log(buf.lastIndexOf('buffer', 4)); + * // Prints: -1 + * + * const utf16Buffer = Buffer.from('\u039a\u0391\u03a3\u03a3\u0395', 'utf16le'); + * + * console.log(utf16Buffer.lastIndexOf('\u03a3', undefined, 'utf16le')); + * // Prints: 6 + * console.log(utf16Buffer.lastIndexOf('\u03a3', -5, 'utf16le')); + * // Prints: 4 + * ``` + * + * If `value` is not a string, number, or `Buffer`, this method will throw a `TypeError`. If `value` is a number, it will be coerced to a valid byte value, + * an integer between 0 and 255. + * + * If `byteOffset` is not a number, it will be coerced to a number. Any arguments + * that coerce to `NaN`, like `{}` or `undefined`, will search the whole buffer. + * This behavior matches [`String.prototype.lastIndexOf()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/lastIndexOf). + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const b = Buffer.from('abcdef'); + * + * // Passing a value that's a number, but not a valid byte. + * // Prints: 2, equivalent to searching for 99 or 'c'. + * console.log(b.lastIndexOf(99.9)); + * console.log(b.lastIndexOf(256 + 99)); + * + * // Passing a byteOffset that coerces to NaN. + * // Prints: 1, searching the whole buffer. + * console.log(b.lastIndexOf('b', undefined)); + * console.log(b.lastIndexOf('b', {})); + * + * // Passing a byteOffset that coerces to 0. + * // Prints: -1, equivalent to passing 0. + * console.log(b.lastIndexOf('b', null)); + * console.log(b.lastIndexOf('b', [])); + * ``` + * + * If `value` is an empty string or empty `Buffer`, `byteOffset` will be returned. + * @since v6.0.0 + * @param value What to search for. + * @param [byteOffset=buf.length - 1] Where to begin searching in `buf`. If negative, then offset is calculated from the end of `buf`. + * @param [encoding='utf8'] If `value` is a string, this is the encoding used to determine the binary representation of the string that will be searched for in `buf`. + * @return The index of the last occurrence of `value` in `buf`, or `-1` if `buf` does not contain `value`. + */ + lastIndexOf(value: string | number | Uint8Array, byteOffset?: number, encoding?: BufferEncoding): number; + /** + * Creates and returns an [iterator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols) of `[index, byte]` pairs from the contents + * of `buf`. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * // Log the entire contents of a `Buffer`. + * + * const buf = Buffer.from('buffer'); + * + * for (const pair of buf.entries()) { + * console.log(pair); + * } + * // Prints: + * // [0, 98] + * // [1, 117] + * // [2, 102] + * // [3, 102] + * // [4, 101] + * // [5, 114] + * ``` + * @since v1.1.0 + */ + entries(): IterableIterator<[number, number]>; + /** + * Equivalent to `buf.indexOf() !== -1`. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from('this is a buffer'); + * + * console.log(buf.includes('this')); + * // Prints: true + * console.log(buf.includes('is')); + * // Prints: true + * console.log(buf.includes(Buffer.from('a buffer'))); + * // Prints: true + * console.log(buf.includes(97)); + * // Prints: true (97 is the decimal ASCII value for 'a') + * console.log(buf.includes(Buffer.from('a buffer example'))); + * // Prints: false + * console.log(buf.includes(Buffer.from('a buffer example').slice(0, 8))); + * // Prints: true + * console.log(buf.includes('this', 4)); + * // Prints: false + * ``` + * @since v5.3.0 + * @param value What to search for. + * @param [byteOffset=0] Where to begin searching in `buf`. If negative, then offset is calculated from the end of `buf`. + * @param [encoding='utf8'] If `value` is a string, this is its encoding. + * @return `true` if `value` was found in `buf`, `false` otherwise. + */ + includes(value: string | number | Buffer, byteOffset?: number, encoding?: BufferEncoding): boolean; + /** + * Creates and returns an [iterator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols) of `buf` keys (indices). + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from('buffer'); + * + * for (const key of buf.keys()) { + * console.log(key); + * } + * // Prints: + * // 0 + * // 1 + * // 2 + * // 3 + * // 4 + * // 5 + * ``` + * @since v1.1.0 + */ + keys(): IterableIterator; + /** + * Creates and returns an [iterator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols) for `buf` values (bytes). This function is + * called automatically when a `Buffer` is used in a `for..of` statement. + * + * ```js + * import { Buffer } from 'node:buffer'; + * + * const buf = Buffer.from('buffer'); + * + * for (const value of buf.values()) { + * console.log(value); + * } + * // Prints: + * // 98 + * // 117 + * // 102 + * // 102 + * // 101 + * // 114 + * + * for (const value of buf) { + * console.log(value); + * } + * // Prints: + * // 98 + * // 117 + * // 102 + * // 102 + * // 101 + * // 114 + * ``` + * @since v1.1.0 + */ + values(): IterableIterator; + } + var Buffer: BufferConstructor; + /** + * Decodes a string of Base64-encoded data into bytes, and encodes those bytes + * into a string using Latin-1 (ISO-8859-1). + * + * The `data` may be any JavaScript-value that can be coerced into a string. + * + * **This function is only provided for compatibility with legacy web platform APIs** + * **and should never be used in new code, because they use strings to represent** + * **binary data and predate the introduction of typed arrays in JavaScript.** + * **For code running using Node.js APIs, converting between base64-encoded strings** + * **and binary data should be performed using `Buffer.from(str, 'base64')` and `buf.toString('base64')`.** + * @since v15.13.0, v14.17.0 + * @legacy Use `Buffer.from(data, 'base64')` instead. + * @param data The Base64-encoded input string. + */ + function atob(data: string): string; + /** + * Decodes a string into bytes using Latin-1 (ISO-8859), and encodes those bytes + * into a string using Base64. + * + * The `data` may be any JavaScript-value that can be coerced into a string. + * + * **This function is only provided for compatibility with legacy web platform APIs** + * **and should never be used in new code, because they use strings to represent** + * **binary data and predate the introduction of typed arrays in JavaScript.** + * **For code running using Node.js APIs, converting between base64-encoded strings** + * **and binary data should be performed using `Buffer.from(str, 'base64')` and `buf.toString('base64')`.** + * @since v15.13.0, v14.17.0 + * @legacy Use `buf.toString('base64')` instead. + * @param data An ASCII (Latin1) string. + */ + function btoa(data: string): string; + interface Blob extends __Blob {} + /** + * `Blob` class is a global reference for `require('node:buffer').Blob` + * https://nodejs.org/api/buffer.html#class-blob + * @since v18.0.0 + */ + var Blob: typeof globalThis extends { + onmessage: any; + Blob: infer T; + } ? T + : typeof NodeBlob; + } +} +declare module "node:buffer" { + export * from "buffer"; +} diff --git a/node_modules/@types/node/child_process.d.ts b/node_modules/@types/node/child_process.d.ts new file mode 100644 index 0000000..91458be --- /dev/null +++ b/node_modules/@types/node/child_process.d.ts @@ -0,0 +1,1544 @@ +/** + * The `node:child_process` module provides the ability to spawn subprocesses in + * a manner that is similar, but not identical, to [`popen(3)`](http://man7.org/linux/man-pages/man3/popen.3.html). This capability + * is primarily provided by the {@link spawn} function: + * + * ```js + * const { spawn } = require('node:child_process'); + * const ls = spawn('ls', ['-lh', '/usr']); + * + * ls.stdout.on('data', (data) => { + * console.log(`stdout: ${data}`); + * }); + * + * ls.stderr.on('data', (data) => { + * console.error(`stderr: ${data}`); + * }); + * + * ls.on('close', (code) => { + * console.log(`child process exited with code ${code}`); + * }); + * ``` + * + * By default, pipes for `stdin`, `stdout`, and `stderr` are established between + * the parent Node.js process and the spawned subprocess. These pipes have + * limited (and platform-specific) capacity. If the subprocess writes to + * stdout in excess of that limit without the output being captured, the + * subprocess blocks waiting for the pipe buffer to accept more data. This is + * identical to the behavior of pipes in the shell. Use the `{ stdio: 'ignore' }` option if the output will not be consumed. + * + * The command lookup is performed using the `options.env.PATH` environment + * variable if `env` is in the `options` object. Otherwise, `process.env.PATH` is + * used. If `options.env` is set without `PATH`, lookup on Unix is performed + * on a default search path search of `/usr/bin:/bin` (see your operating system's + * manual for execvpe/execvp), on Windows the current processes environment + * variable `PATH` is used. + * + * On Windows, environment variables are case-insensitive. Node.js + * lexicographically sorts the `env` keys and uses the first one that + * case-insensitively matches. Only first (in lexicographic order) entry will be + * passed to the subprocess. This might lead to issues on Windows when passing + * objects to the `env` option that have multiple variants of the same key, such as `PATH` and `Path`. + * + * The {@link spawn} method spawns the child process asynchronously, + * without blocking the Node.js event loop. The {@link spawnSync} function provides equivalent functionality in a synchronous manner that blocks + * the event loop until the spawned process either exits or is terminated. + * + * For convenience, the `node:child_process` module provides a handful of + * synchronous and asynchronous alternatives to {@link spawn} and {@link spawnSync}. Each of these alternatives are implemented on + * top of {@link spawn} or {@link spawnSync}. + * + * * {@link exec}: spawns a shell and runs a command within that + * shell, passing the `stdout` and `stderr` to a callback function when + * complete. + * * {@link execFile}: similar to {@link exec} except + * that it spawns the command directly without first spawning a shell by + * default. + * * {@link fork}: spawns a new Node.js process and invokes a + * specified module with an IPC communication channel established that allows + * sending messages between parent and child. + * * {@link execSync}: a synchronous version of {@link exec} that will block the Node.js event loop. + * * {@link execFileSync}: a synchronous version of {@link execFile} that will block the Node.js event loop. + * + * For certain use cases, such as automating shell scripts, the `synchronous counterparts` may be more convenient. In many cases, however, + * the synchronous methods can have significant impact on performance due to + * stalling the event loop while spawned processes complete. + * @see [source](https://github.com/nodejs/node/blob/v20.13.1/lib/child_process.js) + */ +declare module "child_process" { + import { ObjectEncodingOptions } from "node:fs"; + import { Abortable, EventEmitter } from "node:events"; + import * as dgram from "node:dgram"; + import * as net from "node:net"; + import { Pipe, Readable, Stream, Writable } from "node:stream"; + import { URL } from "node:url"; + type Serializable = string | object | number | boolean | bigint; + type SendHandle = net.Socket | net.Server | dgram.Socket | undefined; + /** + * Instances of the `ChildProcess` represent spawned child processes. + * + * Instances of `ChildProcess` are not intended to be created directly. Rather, + * use the {@link spawn}, {@link exec},{@link execFile}, or {@link fork} methods to create + * instances of `ChildProcess`. + * @since v2.2.0 + */ + class ChildProcess extends EventEmitter { + /** + * A `Writable Stream` that represents the child process's `stdin`. + * + * If a child process waits to read all of its input, the child will not continue + * until this stream has been closed via `end()`. + * + * If the child was spawned with `stdio[0]` set to anything other than `'pipe'`, + * then this will be `null`. + * + * `subprocess.stdin` is an alias for `subprocess.stdio[0]`. Both properties will + * refer to the same value. + * + * The `subprocess.stdin` property can be `null` or `undefined` if the child process could not be successfully spawned. + * @since v0.1.90 + */ + stdin: Writable | null; + /** + * A `Readable Stream` that represents the child process's `stdout`. + * + * If the child was spawned with `stdio[1]` set to anything other than `'pipe'`, + * then this will be `null`. + * + * `subprocess.stdout` is an alias for `subprocess.stdio[1]`. Both properties will + * refer to the same value. + * + * ```js + * const { spawn } = require('node:child_process'); + * + * const subprocess = spawn('ls'); + * + * subprocess.stdout.on('data', (data) => { + * console.log(`Received chunk ${data}`); + * }); + * ``` + * + * The `subprocess.stdout` property can be `null` or `undefined` if the child process could not be successfully spawned. + * @since v0.1.90 + */ + stdout: Readable | null; + /** + * A `Readable Stream` that represents the child process's `stderr`. + * + * If the child was spawned with `stdio[2]` set to anything other than `'pipe'`, + * then this will be `null`. + * + * `subprocess.stderr` is an alias for `subprocess.stdio[2]`. Both properties will + * refer to the same value. + * + * The `subprocess.stderr` property can be `null` or `undefined` if the child process could not be successfully spawned. + * @since v0.1.90 + */ + stderr: Readable | null; + /** + * The `subprocess.channel` property is a reference to the child's IPC channel. If + * no IPC channel exists, this property is `undefined`. + * @since v7.1.0 + */ + readonly channel?: Pipe | null | undefined; + /** + * A sparse array of pipes to the child process, corresponding with positions in + * the `stdio` option passed to {@link spawn} that have been set + * to the value `'pipe'`. `subprocess.stdio[0]`, `subprocess.stdio[1]`, and `subprocess.stdio[2]` are also available as `subprocess.stdin`, `subprocess.stdout`, and `subprocess.stderr`, + * respectively. + * + * In the following example, only the child's fd `1` (stdout) is configured as a + * pipe, so only the parent's `subprocess.stdio[1]` is a stream, all other values + * in the array are `null`. + * + * ```js + * const assert = require('node:assert'); + * const fs = require('node:fs'); + * const child_process = require('node:child_process'); + * + * const subprocess = child_process.spawn('ls', { + * stdio: [ + * 0, // Use parent's stdin for child. + * 'pipe', // Pipe child's stdout to parent. + * fs.openSync('err.out', 'w'), // Direct child's stderr to a file. + * ], + * }); + * + * assert.strictEqual(subprocess.stdio[0], null); + * assert.strictEqual(subprocess.stdio[0], subprocess.stdin); + * + * assert(subprocess.stdout); + * assert.strictEqual(subprocess.stdio[1], subprocess.stdout); + * + * assert.strictEqual(subprocess.stdio[2], null); + * assert.strictEqual(subprocess.stdio[2], subprocess.stderr); + * ``` + * + * The `subprocess.stdio` property can be `undefined` if the child process could + * not be successfully spawned. + * @since v0.7.10 + */ + readonly stdio: [ + Writable | null, + // stdin + Readable | null, + // stdout + Readable | null, + // stderr + Readable | Writable | null | undefined, + // extra + Readable | Writable | null | undefined, // extra + ]; + /** + * The `subprocess.killed` property indicates whether the child process + * successfully received a signal from `subprocess.kill()`. The `killed` property + * does not indicate that the child process has been terminated. + * @since v0.5.10 + */ + readonly killed: boolean; + /** + * Returns the process identifier (PID) of the child process. If the child process + * fails to spawn due to errors, then the value is `undefined` and `error` is + * emitted. + * + * ```js + * const { spawn } = require('node:child_process'); + * const grep = spawn('grep', ['ssh']); + * + * console.log(`Spawned child pid: ${grep.pid}`); + * grep.stdin.end(); + * ``` + * @since v0.1.90 + */ + readonly pid?: number | undefined; + /** + * The `subprocess.connected` property indicates whether it is still possible to + * send and receive messages from a child process. When `subprocess.connected` is `false`, it is no longer possible to send or receive messages. + * @since v0.7.2 + */ + readonly connected: boolean; + /** + * The `subprocess.exitCode` property indicates the exit code of the child process. + * If the child process is still running, the field will be `null`. + */ + readonly exitCode: number | null; + /** + * The `subprocess.signalCode` property indicates the signal received by + * the child process if any, else `null`. + */ + readonly signalCode: NodeJS.Signals | null; + /** + * The `subprocess.spawnargs` property represents the full list of command-line + * arguments the child process was launched with. + */ + readonly spawnargs: string[]; + /** + * The `subprocess.spawnfile` property indicates the executable file name of + * the child process that is launched. + * + * For {@link fork}, its value will be equal to `process.execPath`. + * For {@link spawn}, its value will be the name of + * the executable file. + * For {@link exec}, its value will be the name of the shell + * in which the child process is launched. + */ + readonly spawnfile: string; + /** + * The `subprocess.kill()` method sends a signal to the child process. If no + * argument is given, the process will be sent the `'SIGTERM'` signal. See [`signal(7)`](http://man7.org/linux/man-pages/man7/signal.7.html) for a list of available signals. This function + * returns `true` if [`kill(2)`](http://man7.org/linux/man-pages/man2/kill.2.html) succeeds, and `false` otherwise. + * + * ```js + * const { spawn } = require('node:child_process'); + * const grep = spawn('grep', ['ssh']); + * + * grep.on('close', (code, signal) => { + * console.log( + * `child process terminated due to receipt of signal ${signal}`); + * }); + * + * // Send SIGHUP to process. + * grep.kill('SIGHUP'); + * ``` + * + * The `ChildProcess` object may emit an `'error'` event if the signal + * cannot be delivered. Sending a signal to a child process that has already exited + * is not an error but may have unforeseen consequences. Specifically, if the + * process identifier (PID) has been reassigned to another process, the signal will + * be delivered to that process instead which can have unexpected results. + * + * While the function is called `kill`, the signal delivered to the child process + * may not actually terminate the process. + * + * See [`kill(2)`](http://man7.org/linux/man-pages/man2/kill.2.html) for reference. + * + * On Windows, where POSIX signals do not exist, the `signal` argument will be + * ignored, and the process will be killed forcefully and abruptly (similar to `'SIGKILL'`). + * See `Signal Events` for more details. + * + * On Linux, child processes of child processes will not be terminated + * when attempting to kill their parent. This is likely to happen when running a + * new process in a shell or with the use of the `shell` option of `ChildProcess`: + * + * ```js + * 'use strict'; + * const { spawn } = require('node:child_process'); + * + * const subprocess = spawn( + * 'sh', + * [ + * '-c', + * `node -e "setInterval(() => { + * console.log(process.pid, 'is alive') + * }, 500);"`, + * ], { + * stdio: ['inherit', 'inherit', 'inherit'], + * }, + * ); + * + * setTimeout(() => { + * subprocess.kill(); // Does not terminate the Node.js process in the shell. + * }, 2000); + * ``` + * @since v0.1.90 + */ + kill(signal?: NodeJS.Signals | number): boolean; + /** + * Calls {@link ChildProcess.kill} with `'SIGTERM'`. + * @since v20.5.0 + */ + [Symbol.dispose](): void; + /** + * When an IPC channel has been established between the parent and child ( + * i.e. when using {@link fork}), the `subprocess.send()` method can + * be used to send messages to the child process. When the child process is a + * Node.js instance, these messages can be received via the `'message'` event. + * + * The message goes through serialization and parsing. The resulting + * message might not be the same as what is originally sent. + * + * For example, in the parent script: + * + * ```js + * const cp = require('node:child_process'); + * const n = cp.fork(`${__dirname}/sub.js`); + * + * n.on('message', (m) => { + * console.log('PARENT got message:', m); + * }); + * + * // Causes the child to print: CHILD got message: { hello: 'world' } + * n.send({ hello: 'world' }); + * ``` + * + * And then the child script, `'sub.js'` might look like this: + * + * ```js + * process.on('message', (m) => { + * console.log('CHILD got message:', m); + * }); + * + * // Causes the parent to print: PARENT got message: { foo: 'bar', baz: null } + * process.send({ foo: 'bar', baz: NaN }); + * ``` + * + * Child Node.js processes will have a `process.send()` method of their own + * that allows the child to send messages back to the parent. + * + * There is a special case when sending a `{cmd: 'NODE_foo'}` message. Messages + * containing a `NODE_` prefix in the `cmd` property are reserved for use within + * Node.js core and will not be emitted in the child's `'message'` event. Rather, such messages are emitted using the `'internalMessage'` event and are consumed internally by Node.js. + * Applications should avoid using such messages or listening for `'internalMessage'` events as it is subject to change without notice. + * + * The optional `sendHandle` argument that may be passed to `subprocess.send()` is + * for passing a TCP server or socket object to the child process. The child will + * receive the object as the second argument passed to the callback function + * registered on the `'message'` event. Any data that is received and buffered in + * the socket will not be sent to the child. Sending IPC sockets is not supported on Windows. + * + * The optional `callback` is a function that is invoked after the message is + * sent but before the child may have received it. The function is called with a + * single argument: `null` on success, or an `Error` object on failure. + * + * If no `callback` function is provided and the message cannot be sent, an `'error'` event will be emitted by the `ChildProcess` object. This can + * happen, for instance, when the child process has already exited. + * + * `subprocess.send()` will return `false` if the channel has closed or when the + * backlog of unsent messages exceeds a threshold that makes it unwise to send + * more. Otherwise, the method returns `true`. The `callback` function can be + * used to implement flow control. + * + * #### Example: sending a server object + * + * The `sendHandle` argument can be used, for instance, to pass the handle of + * a TCP server object to the child process as illustrated in the example below: + * + * ```js + * const subprocess = require('node:child_process').fork('subprocess.js'); + * + * // Open up the server object and send the handle. + * const server = require('node:net').createServer(); + * server.on('connection', (socket) => { + * socket.end('handled by parent'); + * }); + * server.listen(1337, () => { + * subprocess.send('server', server); + * }); + * ``` + * + * The child would then receive the server object as: + * + * ```js + * process.on('message', (m, server) => { + * if (m === 'server') { + * server.on('connection', (socket) => { + * socket.end('handled by child'); + * }); + * } + * }); + * ``` + * + * Once the server is now shared between the parent and child, some connections + * can be handled by the parent and some by the child. + * + * While the example above uses a server created using the `node:net` module, `node:dgram` module servers use exactly the same workflow with the exceptions of + * listening on a `'message'` event instead of `'connection'` and using `server.bind()` instead of `server.listen()`. This is, however, only + * supported on Unix platforms. + * + * #### Example: sending a socket object + * + * Similarly, the `sendHandler` argument can be used to pass the handle of a + * socket to the child process. The example below spawns two children that each + * handle connections with "normal" or "special" priority: + * + * ```js + * const { fork } = require('node:child_process'); + * const normal = fork('subprocess.js', ['normal']); + * const special = fork('subprocess.js', ['special']); + * + * // Open up the server and send sockets to child. Use pauseOnConnect to prevent + * // the sockets from being read before they are sent to the child process. + * const server = require('node:net').createServer({ pauseOnConnect: true }); + * server.on('connection', (socket) => { + * + * // If this is special priority... + * if (socket.remoteAddress === '74.125.127.100') { + * special.send('socket', socket); + * return; + * } + * // This is normal priority. + * normal.send('socket', socket); + * }); + * server.listen(1337); + * ``` + * + * The `subprocess.js` would receive the socket handle as the second argument + * passed to the event callback function: + * + * ```js + * process.on('message', (m, socket) => { + * if (m === 'socket') { + * if (socket) { + * // Check that the client socket exists. + * // It is possible for the socket to be closed between the time it is + * // sent and the time it is received in the child process. + * socket.end(`Request handled with ${process.argv[2]} priority`); + * } + * } + * }); + * ``` + * + * Do not use `.maxConnections` on a socket that has been passed to a subprocess. + * The parent cannot track when the socket is destroyed. + * + * Any `'message'` handlers in the subprocess should verify that `socket` exists, + * as the connection may have been closed during the time it takes to send the + * connection to the child. + * @since v0.5.9 + * @param sendHandle `undefined`, or a [`net.Socket`](https://nodejs.org/docs/latest-v20.x/api/net.html#class-netsocket), [`net.Server`](https://nodejs.org/docs/latest-v20.x/api/net.html#class-netserver), or [`dgram.Socket`](https://nodejs.org/docs/latest-v20.x/api/dgram.html#class-dgramsocket) object. + * @param options The `options` argument, if present, is an object used to parameterize the sending of certain types of handles. `options` supports the following properties: + */ + send(message: Serializable, callback?: (error: Error | null) => void): boolean; + send(message: Serializable, sendHandle?: SendHandle, callback?: (error: Error | null) => void): boolean; + send( + message: Serializable, + sendHandle?: SendHandle, + options?: MessageOptions, + callback?: (error: Error | null) => void, + ): boolean; + /** + * Closes the IPC channel between parent and child, allowing the child to exit + * gracefully once there are no other connections keeping it alive. After calling + * this method the `subprocess.connected` and `process.connected` properties in + * both the parent and child (respectively) will be set to `false`, and it will be + * no longer possible to pass messages between the processes. + * + * The `'disconnect'` event will be emitted when there are no messages in the + * process of being received. This will most often be triggered immediately after + * calling `subprocess.disconnect()`. + * + * When the child process is a Node.js instance (e.g. spawned using {@link fork}), the `process.disconnect()` method can be invoked + * within the child process to close the IPC channel as well. + * @since v0.7.2 + */ + disconnect(): void; + /** + * By default, the parent will wait for the detached child to exit. To prevent the + * parent from waiting for a given `subprocess` to exit, use the `subprocess.unref()` method. Doing so will cause the parent's event loop to not + * include the child in its reference count, allowing the parent to exit + * independently of the child, unless there is an established IPC channel between + * the child and the parent. + * + * ```js + * const { spawn } = require('node:child_process'); + * + * const subprocess = spawn(process.argv[0], ['child_program.js'], { + * detached: true, + * stdio: 'ignore', + * }); + * + * subprocess.unref(); + * ``` + * @since v0.7.10 + */ + unref(): void; + /** + * Calling `subprocess.ref()` after making a call to `subprocess.unref()` will + * restore the removed reference count for the child process, forcing the parent + * to wait for the child to exit before exiting itself. + * + * ```js + * const { spawn } = require('node:child_process'); + * + * const subprocess = spawn(process.argv[0], ['child_program.js'], { + * detached: true, + * stdio: 'ignore', + * }); + * + * subprocess.unref(); + * subprocess.ref(); + * ``` + * @since v0.7.10 + */ + ref(): void; + /** + * events.EventEmitter + * 1. close + * 2. disconnect + * 3. error + * 4. exit + * 5. message + * 6. spawn + */ + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "close", listener: (code: number | null, signal: NodeJS.Signals | null) => void): this; + addListener(event: "disconnect", listener: () => void): this; + addListener(event: "error", listener: (err: Error) => void): this; + addListener(event: "exit", listener: (code: number | null, signal: NodeJS.Signals | null) => void): this; + addListener(event: "message", listener: (message: Serializable, sendHandle: SendHandle) => void): this; + addListener(event: "spawn", listener: () => void): this; + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: "close", code: number | null, signal: NodeJS.Signals | null): boolean; + emit(event: "disconnect"): boolean; + emit(event: "error", err: Error): boolean; + emit(event: "exit", code: number | null, signal: NodeJS.Signals | null): boolean; + emit(event: "message", message: Serializable, sendHandle: SendHandle): boolean; + emit(event: "spawn", listener: () => void): boolean; + on(event: string, listener: (...args: any[]) => void): this; + on(event: "close", listener: (code: number | null, signal: NodeJS.Signals | null) => void): this; + on(event: "disconnect", listener: () => void): this; + on(event: "error", listener: (err: Error) => void): this; + on(event: "exit", listener: (code: number | null, signal: NodeJS.Signals | null) => void): this; + on(event: "message", listener: (message: Serializable, sendHandle: SendHandle) => void): this; + on(event: "spawn", listener: () => void): this; + once(event: string, listener: (...args: any[]) => void): this; + once(event: "close", listener: (code: number | null, signal: NodeJS.Signals | null) => void): this; + once(event: "disconnect", listener: () => void): this; + once(event: "error", listener: (err: Error) => void): this; + once(event: "exit", listener: (code: number | null, signal: NodeJS.Signals | null) => void): this; + once(event: "message", listener: (message: Serializable, sendHandle: SendHandle) => void): this; + once(event: "spawn", listener: () => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "close", listener: (code: number | null, signal: NodeJS.Signals | null) => void): this; + prependListener(event: "disconnect", listener: () => void): this; + prependListener(event: "error", listener: (err: Error) => void): this; + prependListener(event: "exit", listener: (code: number | null, signal: NodeJS.Signals | null) => void): this; + prependListener(event: "message", listener: (message: Serializable, sendHandle: SendHandle) => void): this; + prependListener(event: "spawn", listener: () => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener( + event: "close", + listener: (code: number | null, signal: NodeJS.Signals | null) => void, + ): this; + prependOnceListener(event: "disconnect", listener: () => void): this; + prependOnceListener(event: "error", listener: (err: Error) => void): this; + prependOnceListener( + event: "exit", + listener: (code: number | null, signal: NodeJS.Signals | null) => void, + ): this; + prependOnceListener(event: "message", listener: (message: Serializable, sendHandle: SendHandle) => void): this; + prependOnceListener(event: "spawn", listener: () => void): this; + } + // return this object when stdio option is undefined or not specified + interface ChildProcessWithoutNullStreams extends ChildProcess { + stdin: Writable; + stdout: Readable; + stderr: Readable; + readonly stdio: [ + Writable, + Readable, + Readable, + // stderr + Readable | Writable | null | undefined, + // extra, no modification + Readable | Writable | null | undefined, // extra, no modification + ]; + } + // return this object when stdio option is a tuple of 3 + interface ChildProcessByStdio + extends ChildProcess + { + stdin: I; + stdout: O; + stderr: E; + readonly stdio: [ + I, + O, + E, + Readable | Writable | null | undefined, + // extra, no modification + Readable | Writable | null | undefined, // extra, no modification + ]; + } + interface MessageOptions { + keepOpen?: boolean | undefined; + } + type IOType = "overlapped" | "pipe" | "ignore" | "inherit"; + type StdioOptions = IOType | Array; + type SerializationType = "json" | "advanced"; + interface MessagingOptions extends Abortable { + /** + * Specify the kind of serialization used for sending messages between processes. + * @default 'json' + */ + serialization?: SerializationType | undefined; + /** + * The signal value to be used when the spawned process will be killed by the abort signal. + * @default 'SIGTERM' + */ + killSignal?: NodeJS.Signals | number | undefined; + /** + * In milliseconds the maximum amount of time the process is allowed to run. + */ + timeout?: number | undefined; + } + interface ProcessEnvOptions { + uid?: number | undefined; + gid?: number | undefined; + cwd?: string | URL | undefined; + env?: NodeJS.ProcessEnv | undefined; + } + interface CommonOptions extends ProcessEnvOptions { + /** + * @default false + */ + windowsHide?: boolean | undefined; + /** + * @default 0 + */ + timeout?: number | undefined; + } + interface CommonSpawnOptions extends CommonOptions, MessagingOptions, Abortable { + argv0?: string | undefined; + /** + * Can be set to 'pipe', 'inherit', 'overlapped', or 'ignore', or an array of these strings. + * If passed as an array, the first element is used for `stdin`, the second for + * `stdout`, and the third for `stderr`. A fourth element can be used to + * specify the `stdio` behavior beyond the standard streams. See + * {@link ChildProcess.stdio} for more information. + * + * @default 'pipe' + */ + stdio?: StdioOptions | undefined; + shell?: boolean | string | undefined; + windowsVerbatimArguments?: boolean | undefined; + } + interface SpawnOptions extends CommonSpawnOptions { + detached?: boolean | undefined; + } + interface SpawnOptionsWithoutStdio extends SpawnOptions { + stdio?: StdioPipeNamed | StdioPipe[] | undefined; + } + type StdioNull = "inherit" | "ignore" | Stream; + type StdioPipeNamed = "pipe" | "overlapped"; + type StdioPipe = undefined | null | StdioPipeNamed; + interface SpawnOptionsWithStdioTuple< + Stdin extends StdioNull | StdioPipe, + Stdout extends StdioNull | StdioPipe, + Stderr extends StdioNull | StdioPipe, + > extends SpawnOptions { + stdio: [Stdin, Stdout, Stderr]; + } + /** + * The `child_process.spawn()` method spawns a new process using the given `command`, with command-line arguments in `args`. If omitted, `args` defaults + * to an empty array. + * + * **If the `shell` option is enabled, do not pass unsanitized user input to this** + * **function. Any input containing shell metacharacters may be used to trigger** + * **arbitrary command execution.** + * + * A third argument may be used to specify additional options, with these defaults: + * + * ```js + * const defaults = { + * cwd: undefined, + * env: process.env, + * }; + * ``` + * + * Use `cwd` to specify the working directory from which the process is spawned. + * If not given, the default is to inherit the current working directory. If given, + * but the path does not exist, the child process emits an `ENOENT` error + * and exits immediately. `ENOENT` is also emitted when the command + * does not exist. + * + * Use `env` to specify environment variables that will be visible to the new + * process, the default is `process.env`. + * + * `undefined` values in `env` will be ignored. + * + * Example of running `ls -lh /usr`, capturing `stdout`, `stderr`, and the + * exit code: + * + * ```js + * const { spawn } = require('node:child_process'); + * const ls = spawn('ls', ['-lh', '/usr']); + * + * ls.stdout.on('data', (data) => { + * console.log(`stdout: ${data}`); + * }); + * + * ls.stderr.on('data', (data) => { + * console.error(`stderr: ${data}`); + * }); + * + * ls.on('close', (code) => { + * console.log(`child process exited with code ${code}`); + * }); + * ``` + * + * Example: A very elaborate way to run `ps ax | grep ssh` + * + * ```js + * const { spawn } = require('node:child_process'); + * const ps = spawn('ps', ['ax']); + * const grep = spawn('grep', ['ssh']); + * + * ps.stdout.on('data', (data) => { + * grep.stdin.write(data); + * }); + * + * ps.stderr.on('data', (data) => { + * console.error(`ps stderr: ${data}`); + * }); + * + * ps.on('close', (code) => { + * if (code !== 0) { + * console.log(`ps process exited with code ${code}`); + * } + * grep.stdin.end(); + * }); + * + * grep.stdout.on('data', (data) => { + * console.log(data.toString()); + * }); + * + * grep.stderr.on('data', (data) => { + * console.error(`grep stderr: ${data}`); + * }); + * + * grep.on('close', (code) => { + * if (code !== 0) { + * console.log(`grep process exited with code ${code}`); + * } + * }); + * ``` + * + * Example of checking for failed `spawn`: + * + * ```js + * const { spawn } = require('node:child_process'); + * const subprocess = spawn('bad_command'); + * + * subprocess.on('error', (err) => { + * console.error('Failed to start subprocess.'); + * }); + * ``` + * + * Certain platforms (macOS, Linux) will use the value of `argv[0]` for the process + * title while others (Windows, SunOS) will use `command`. + * + * Node.js overwrites `argv[0]` with `process.execPath` on startup, so `process.argv[0]` in a Node.js child process will not match the `argv0` parameter passed to `spawn` from the parent. Retrieve + * it with the `process.argv0` property instead. + * + * If the `signal` option is enabled, calling `.abort()` on the corresponding `AbortController` is similar to calling `.kill()` on the child process except + * the error passed to the callback will be an `AbortError`: + * + * ```js + * const { spawn } = require('node:child_process'); + * const controller = new AbortController(); + * const { signal } = controller; + * const grep = spawn('grep', ['ssh'], { signal }); + * grep.on('error', (err) => { + * // This will be called with err being an AbortError if the controller aborts + * }); + * controller.abort(); // Stops the child process + * ``` + * @since v0.1.90 + * @param command The command to run. + * @param args List of string arguments. + */ + function spawn(command: string, options?: SpawnOptionsWithoutStdio): ChildProcessWithoutNullStreams; + function spawn( + command: string, + options: SpawnOptionsWithStdioTuple, + ): ChildProcessByStdio; + function spawn( + command: string, + options: SpawnOptionsWithStdioTuple, + ): ChildProcessByStdio; + function spawn( + command: string, + options: SpawnOptionsWithStdioTuple, + ): ChildProcessByStdio; + function spawn( + command: string, + options: SpawnOptionsWithStdioTuple, + ): ChildProcessByStdio; + function spawn( + command: string, + options: SpawnOptionsWithStdioTuple, + ): ChildProcessByStdio; + function spawn( + command: string, + options: SpawnOptionsWithStdioTuple, + ): ChildProcessByStdio; + function spawn( + command: string, + options: SpawnOptionsWithStdioTuple, + ): ChildProcessByStdio; + function spawn( + command: string, + options: SpawnOptionsWithStdioTuple, + ): ChildProcessByStdio; + function spawn(command: string, options: SpawnOptions): ChildProcess; + // overloads of spawn with 'args' + function spawn( + command: string, + args?: readonly string[], + options?: SpawnOptionsWithoutStdio, + ): ChildProcessWithoutNullStreams; + function spawn( + command: string, + args: readonly string[], + options: SpawnOptionsWithStdioTuple, + ): ChildProcessByStdio; + function spawn( + command: string, + args: readonly string[], + options: SpawnOptionsWithStdioTuple, + ): ChildProcessByStdio; + function spawn( + command: string, + args: readonly string[], + options: SpawnOptionsWithStdioTuple, + ): ChildProcessByStdio; + function spawn( + command: string, + args: readonly string[], + options: SpawnOptionsWithStdioTuple, + ): ChildProcessByStdio; + function spawn( + command: string, + args: readonly string[], + options: SpawnOptionsWithStdioTuple, + ): ChildProcessByStdio; + function spawn( + command: string, + args: readonly string[], + options: SpawnOptionsWithStdioTuple, + ): ChildProcessByStdio; + function spawn( + command: string, + args: readonly string[], + options: SpawnOptionsWithStdioTuple, + ): ChildProcessByStdio; + function spawn( + command: string, + args: readonly string[], + options: SpawnOptionsWithStdioTuple, + ): ChildProcessByStdio; + function spawn(command: string, args: readonly string[], options: SpawnOptions): ChildProcess; + interface ExecOptions extends CommonOptions { + shell?: string | undefined; + signal?: AbortSignal | undefined; + maxBuffer?: number | undefined; + killSignal?: NodeJS.Signals | number | undefined; + } + interface ExecOptionsWithStringEncoding extends ExecOptions { + encoding: BufferEncoding; + } + interface ExecOptionsWithBufferEncoding extends ExecOptions { + encoding: BufferEncoding | null; // specify `null`. + } + interface ExecException extends Error { + cmd?: string | undefined; + killed?: boolean | undefined; + code?: number | undefined; + signal?: NodeJS.Signals | undefined; + stdout?: string; + stderr?: string; + } + /** + * Spawns a shell then executes the `command` within that shell, buffering any + * generated output. The `command` string passed to the exec function is processed + * directly by the shell and special characters (vary based on [shell](https://en.wikipedia.org/wiki/List_of_command-line_interpreters)) + * need to be dealt with accordingly: + * + * ```js + * const { exec } = require('node:child_process'); + * + * exec('"/path/to/test file/test.sh" arg1 arg2'); + * // Double quotes are used so that the space in the path is not interpreted as + * // a delimiter of multiple arguments. + * + * exec('echo "The \\$HOME variable is $HOME"'); + * // The $HOME variable is escaped in the first instance, but not in the second. + * ``` + * + * **Never pass unsanitized user input to this function. Any input containing shell** + * **metacharacters may be used to trigger arbitrary command execution.** + * + * If a `callback` function is provided, it is called with the arguments `(error, stdout, stderr)`. On success, `error` will be `null`. On error, `error` will be an instance of `Error`. The + * `error.code` property will be + * the exit code of the process. By convention, any exit code other than `0` indicates an error. `error.signal` will be the signal that terminated the + * process. + * + * The `stdout` and `stderr` arguments passed to the callback will contain the + * stdout and stderr output of the child process. By default, Node.js will decode + * the output as UTF-8 and pass strings to the callback. The `encoding` option + * can be used to specify the character encoding used to decode the stdout and + * stderr output. If `encoding` is `'buffer'`, or an unrecognized character + * encoding, `Buffer` objects will be passed to the callback instead. + * + * ```js + * const { exec } = require('node:child_process'); + * exec('cat *.js missing_file | wc -l', (error, stdout, stderr) => { + * if (error) { + * console.error(`exec error: ${error}`); + * return; + * } + * console.log(`stdout: ${stdout}`); + * console.error(`stderr: ${stderr}`); + * }); + * ``` + * + * If `timeout` is greater than `0`, the parent will send the signal + * identified by the `killSignal` property (the default is `'SIGTERM'`) if the + * child runs longer than `timeout` milliseconds. + * + * Unlike the [`exec(3)`](http://man7.org/linux/man-pages/man3/exec.3.html) POSIX system call, `child_process.exec()` does not replace + * the existing process and uses a shell to execute the command. + * + * If this method is invoked as its `util.promisify()` ed version, it returns + * a `Promise` for an `Object` with `stdout` and `stderr` properties. The returned `ChildProcess` instance is attached to the `Promise` as a `child` property. In + * case of an error (including any error resulting in an exit code other than 0), a + * rejected promise is returned, with the same `error` object given in the + * callback, but with two additional properties `stdout` and `stderr`. + * + * ```js + * const util = require('node:util'); + * const exec = util.promisify(require('node:child_process').exec); + * + * async function lsExample() { + * const { stdout, stderr } = await exec('ls'); + * console.log('stdout:', stdout); + * console.error('stderr:', stderr); + * } + * lsExample(); + * ``` + * + * If the `signal` option is enabled, calling `.abort()` on the corresponding `AbortController` is similar to calling `.kill()` on the child process except + * the error passed to the callback will be an `AbortError`: + * + * ```js + * const { exec } = require('node:child_process'); + * const controller = new AbortController(); + * const { signal } = controller; + * const child = exec('grep ssh', { signal }, (error) => { + * console.error(error); // an AbortError + * }); + * controller.abort(); + * ``` + * @since v0.1.90 + * @param command The command to run, with space-separated arguments. + * @param callback called with the output when process terminates. + */ + function exec( + command: string, + callback?: (error: ExecException | null, stdout: string, stderr: string) => void, + ): ChildProcess; + // `options` with `"buffer"` or `null` for `encoding` means stdout/stderr are definitely `Buffer`. + function exec( + command: string, + options: { + encoding: "buffer" | null; + } & ExecOptions, + callback?: (error: ExecException | null, stdout: Buffer, stderr: Buffer) => void, + ): ChildProcess; + // `options` with well known `encoding` means stdout/stderr are definitely `string`. + function exec( + command: string, + options: { + encoding: BufferEncoding; + } & ExecOptions, + callback?: (error: ExecException | null, stdout: string, stderr: string) => void, + ): ChildProcess; + // `options` with an `encoding` whose type is `string` means stdout/stderr could either be `Buffer` or `string`. + // There is no guarantee the `encoding` is unknown as `string` is a superset of `BufferEncoding`. + function exec( + command: string, + options: { + encoding: BufferEncoding; + } & ExecOptions, + callback?: (error: ExecException | null, stdout: string | Buffer, stderr: string | Buffer) => void, + ): ChildProcess; + // `options` without an `encoding` means stdout/stderr are definitely `string`. + function exec( + command: string, + options: ExecOptions, + callback?: (error: ExecException | null, stdout: string, stderr: string) => void, + ): ChildProcess; + // fallback if nothing else matches. Worst case is always `string | Buffer`. + function exec( + command: string, + options: (ObjectEncodingOptions & ExecOptions) | undefined | null, + callback?: (error: ExecException | null, stdout: string | Buffer, stderr: string | Buffer) => void, + ): ChildProcess; + interface PromiseWithChild extends Promise { + child: ChildProcess; + } + namespace exec { + function __promisify__(command: string): PromiseWithChild<{ + stdout: string; + stderr: string; + }>; + function __promisify__( + command: string, + options: { + encoding: "buffer" | null; + } & ExecOptions, + ): PromiseWithChild<{ + stdout: Buffer; + stderr: Buffer; + }>; + function __promisify__( + command: string, + options: { + encoding: BufferEncoding; + } & ExecOptions, + ): PromiseWithChild<{ + stdout: string; + stderr: string; + }>; + function __promisify__( + command: string, + options: ExecOptions, + ): PromiseWithChild<{ + stdout: string; + stderr: string; + }>; + function __promisify__( + command: string, + options?: (ObjectEncodingOptions & ExecOptions) | null, + ): PromiseWithChild<{ + stdout: string | Buffer; + stderr: string | Buffer; + }>; + } + interface ExecFileOptions extends CommonOptions, Abortable { + maxBuffer?: number | undefined; + killSignal?: NodeJS.Signals | number | undefined; + windowsVerbatimArguments?: boolean | undefined; + shell?: boolean | string | undefined; + signal?: AbortSignal | undefined; + } + interface ExecFileOptionsWithStringEncoding extends ExecFileOptions { + encoding: BufferEncoding; + } + interface ExecFileOptionsWithBufferEncoding extends ExecFileOptions { + encoding: "buffer" | null; + } + interface ExecFileOptionsWithOtherEncoding extends ExecFileOptions { + encoding: BufferEncoding; + } + type ExecFileException = + & Omit + & Omit + & { code?: string | number | undefined | null }; + /** + * The `child_process.execFile()` function is similar to {@link exec} except that it does not spawn a shell by default. Rather, the specified + * executable `file` is spawned directly as a new process making it slightly more + * efficient than {@link exec}. + * + * The same options as {@link exec} are supported. Since a shell is + * not spawned, behaviors such as I/O redirection and file globbing are not + * supported. + * + * ```js + * const { execFile } = require('node:child_process'); + * const child = execFile('node', ['--version'], (error, stdout, stderr) => { + * if (error) { + * throw error; + * } + * console.log(stdout); + * }); + * ``` + * + * The `stdout` and `stderr` arguments passed to the callback will contain the + * stdout and stderr output of the child process. By default, Node.js will decode + * the output as UTF-8 and pass strings to the callback. The `encoding` option + * can be used to specify the character encoding used to decode the stdout and + * stderr output. If `encoding` is `'buffer'`, or an unrecognized character + * encoding, `Buffer` objects will be passed to the callback instead. + * + * If this method is invoked as its `util.promisify()` ed version, it returns + * a `Promise` for an `Object` with `stdout` and `stderr` properties. The returned `ChildProcess` instance is attached to the `Promise` as a `child` property. In + * case of an error (including any error resulting in an exit code other than 0), a + * rejected promise is returned, with the same `error` object given in the + * callback, but with two additional properties `stdout` and `stderr`. + * + * ```js + * const util = require('node:util'); + * const execFile = util.promisify(require('node:child_process').execFile); + * async function getVersion() { + * const { stdout } = await execFile('node', ['--version']); + * console.log(stdout); + * } + * getVersion(); + * ``` + * + * **If the `shell` option is enabled, do not pass unsanitized user input to this** + * **function. Any input containing shell metacharacters may be used to trigger** + * **arbitrary command execution.** + * + * If the `signal` option is enabled, calling `.abort()` on the corresponding `AbortController` is similar to calling `.kill()` on the child process except + * the error passed to the callback will be an `AbortError`: + * + * ```js + * const { execFile } = require('node:child_process'); + * const controller = new AbortController(); + * const { signal } = controller; + * const child = execFile('node', ['--version'], { signal }, (error) => { + * console.error(error); // an AbortError + * }); + * controller.abort(); + * ``` + * @since v0.1.91 + * @param file The name or path of the executable file to run. + * @param args List of string arguments. + * @param callback Called with the output when process terminates. + */ + function execFile(file: string): ChildProcess; + function execFile( + file: string, + options: (ObjectEncodingOptions & ExecFileOptions) | undefined | null, + ): ChildProcess; + function execFile(file: string, args?: readonly string[] | null): ChildProcess; + function execFile( + file: string, + args: readonly string[] | undefined | null, + options: (ObjectEncodingOptions & ExecFileOptions) | undefined | null, + ): ChildProcess; + // no `options` definitely means stdout/stderr are `string`. + function execFile( + file: string, + callback: (error: ExecFileException | null, stdout: string, stderr: string) => void, + ): ChildProcess; + function execFile( + file: string, + args: readonly string[] | undefined | null, + callback: (error: ExecFileException | null, stdout: string, stderr: string) => void, + ): ChildProcess; + // `options` with `"buffer"` or `null` for `encoding` means stdout/stderr are definitely `Buffer`. + function execFile( + file: string, + options: ExecFileOptionsWithBufferEncoding, + callback: (error: ExecFileException | null, stdout: Buffer, stderr: Buffer) => void, + ): ChildProcess; + function execFile( + file: string, + args: readonly string[] | undefined | null, + options: ExecFileOptionsWithBufferEncoding, + callback: (error: ExecFileException | null, stdout: Buffer, stderr: Buffer) => void, + ): ChildProcess; + // `options` with well known `encoding` means stdout/stderr are definitely `string`. + function execFile( + file: string, + options: ExecFileOptionsWithStringEncoding, + callback: (error: ExecFileException | null, stdout: string, stderr: string) => void, + ): ChildProcess; + function execFile( + file: string, + args: readonly string[] | undefined | null, + options: ExecFileOptionsWithStringEncoding, + callback: (error: ExecFileException | null, stdout: string, stderr: string) => void, + ): ChildProcess; + // `options` with an `encoding` whose type is `string` means stdout/stderr could either be `Buffer` or `string`. + // There is no guarantee the `encoding` is unknown as `string` is a superset of `BufferEncoding`. + function execFile( + file: string, + options: ExecFileOptionsWithOtherEncoding, + callback: (error: ExecFileException | null, stdout: string | Buffer, stderr: string | Buffer) => void, + ): ChildProcess; + function execFile( + file: string, + args: readonly string[] | undefined | null, + options: ExecFileOptionsWithOtherEncoding, + callback: (error: ExecFileException | null, stdout: string | Buffer, stderr: string | Buffer) => void, + ): ChildProcess; + // `options` without an `encoding` means stdout/stderr are definitely `string`. + function execFile( + file: string, + options: ExecFileOptions, + callback: (error: ExecFileException | null, stdout: string, stderr: string) => void, + ): ChildProcess; + function execFile( + file: string, + args: readonly string[] | undefined | null, + options: ExecFileOptions, + callback: (error: ExecFileException | null, stdout: string, stderr: string) => void, + ): ChildProcess; + // fallback if nothing else matches. Worst case is always `string | Buffer`. + function execFile( + file: string, + options: (ObjectEncodingOptions & ExecFileOptions) | undefined | null, + callback: + | ((error: ExecFileException | null, stdout: string | Buffer, stderr: string | Buffer) => void) + | undefined + | null, + ): ChildProcess; + function execFile( + file: string, + args: readonly string[] | undefined | null, + options: (ObjectEncodingOptions & ExecFileOptions) | undefined | null, + callback: + | ((error: ExecFileException | null, stdout: string | Buffer, stderr: string | Buffer) => void) + | undefined + | null, + ): ChildProcess; + namespace execFile { + function __promisify__(file: string): PromiseWithChild<{ + stdout: string; + stderr: string; + }>; + function __promisify__( + file: string, + args: readonly string[] | undefined | null, + ): PromiseWithChild<{ + stdout: string; + stderr: string; + }>; + function __promisify__( + file: string, + options: ExecFileOptionsWithBufferEncoding, + ): PromiseWithChild<{ + stdout: Buffer; + stderr: Buffer; + }>; + function __promisify__( + file: string, + args: readonly string[] | undefined | null, + options: ExecFileOptionsWithBufferEncoding, + ): PromiseWithChild<{ + stdout: Buffer; + stderr: Buffer; + }>; + function __promisify__( + file: string, + options: ExecFileOptionsWithStringEncoding, + ): PromiseWithChild<{ + stdout: string; + stderr: string; + }>; + function __promisify__( + file: string, + args: readonly string[] | undefined | null, + options: ExecFileOptionsWithStringEncoding, + ): PromiseWithChild<{ + stdout: string; + stderr: string; + }>; + function __promisify__( + file: string, + options: ExecFileOptionsWithOtherEncoding, + ): PromiseWithChild<{ + stdout: string | Buffer; + stderr: string | Buffer; + }>; + function __promisify__( + file: string, + args: readonly string[] | undefined | null, + options: ExecFileOptionsWithOtherEncoding, + ): PromiseWithChild<{ + stdout: string | Buffer; + stderr: string | Buffer; + }>; + function __promisify__( + file: string, + options: ExecFileOptions, + ): PromiseWithChild<{ + stdout: string; + stderr: string; + }>; + function __promisify__( + file: string, + args: readonly string[] | undefined | null, + options: ExecFileOptions, + ): PromiseWithChild<{ + stdout: string; + stderr: string; + }>; + function __promisify__( + file: string, + options: (ObjectEncodingOptions & ExecFileOptions) | undefined | null, + ): PromiseWithChild<{ + stdout: string | Buffer; + stderr: string | Buffer; + }>; + function __promisify__( + file: string, + args: readonly string[] | undefined | null, + options: (ObjectEncodingOptions & ExecFileOptions) | undefined | null, + ): PromiseWithChild<{ + stdout: string | Buffer; + stderr: string | Buffer; + }>; + } + interface ForkOptions extends ProcessEnvOptions, MessagingOptions, Abortable { + execPath?: string | undefined; + execArgv?: string[] | undefined; + silent?: boolean | undefined; + /** + * Can be set to 'pipe', 'inherit', 'overlapped', or 'ignore', or an array of these strings. + * If passed as an array, the first element is used for `stdin`, the second for + * `stdout`, and the third for `stderr`. A fourth element can be used to + * specify the `stdio` behavior beyond the standard streams. See + * {@link ChildProcess.stdio} for more information. + * + * @default 'pipe' + */ + stdio?: StdioOptions | undefined; + detached?: boolean | undefined; + windowsVerbatimArguments?: boolean | undefined; + } + /** + * The `child_process.fork()` method is a special case of {@link spawn} used specifically to spawn new Node.js processes. + * Like {@link spawn}, a `ChildProcess` object is returned. The + * returned `ChildProcess` will have an additional communication channel + * built-in that allows messages to be passed back and forth between the parent and + * child. See `subprocess.send()` for details. + * + * Keep in mind that spawned Node.js child processes are + * independent of the parent with exception of the IPC communication channel + * that is established between the two. Each process has its own memory, with + * their own V8 instances. Because of the additional resource allocations + * required, spawning a large number of child Node.js processes is not + * recommended. + * + * By default, `child_process.fork()` will spawn new Node.js instances using the `process.execPath` of the parent process. The `execPath` property in the `options` object allows for an alternative + * execution path to be used. + * + * Node.js processes launched with a custom `execPath` will communicate with the + * parent process using the file descriptor (fd) identified using the + * environment variable `NODE_CHANNEL_FD` on the child process. + * + * Unlike the [`fork(2)`](http://man7.org/linux/man-pages/man2/fork.2.html) POSIX system call, `child_process.fork()` does not clone the + * current process. + * + * The `shell` option available in {@link spawn} is not supported by `child_process.fork()` and will be ignored if set. + * + * If the `signal` option is enabled, calling `.abort()` on the corresponding `AbortController` is similar to calling `.kill()` on the child process except + * the error passed to the callback will be an `AbortError`: + * + * ```js + * if (process.argv[2] === 'child') { + * setTimeout(() => { + * console.log(`Hello from ${process.argv[2]}!`); + * }, 1_000); + * } else { + * const { fork } = require('node:child_process'); + * const controller = new AbortController(); + * const { signal } = controller; + * const child = fork(__filename, ['child'], { signal }); + * child.on('error', (err) => { + * // This will be called with err being an AbortError if the controller aborts + * }); + * controller.abort(); // Stops the child process + * } + * ``` + * @since v0.5.0 + * @param modulePath The module to run in the child. + * @param args List of string arguments. + */ + function fork(modulePath: string, options?: ForkOptions): ChildProcess; + function fork(modulePath: string, args?: readonly string[], options?: ForkOptions): ChildProcess; + interface SpawnSyncOptions extends CommonSpawnOptions { + input?: string | NodeJS.ArrayBufferView | undefined; + maxBuffer?: number | undefined; + encoding?: BufferEncoding | "buffer" | null | undefined; + } + interface SpawnSyncOptionsWithStringEncoding extends SpawnSyncOptions { + encoding: BufferEncoding; + } + interface SpawnSyncOptionsWithBufferEncoding extends SpawnSyncOptions { + encoding?: "buffer" | null | undefined; + } + interface SpawnSyncReturns { + pid: number; + output: Array; + stdout: T; + stderr: T; + status: number | null; + signal: NodeJS.Signals | null; + error?: Error | undefined; + } + /** + * The `child_process.spawnSync()` method is generally identical to {@link spawn} with the exception that the function will not return + * until the child process has fully closed. When a timeout has been encountered + * and `killSignal` is sent, the method won't return until the process has + * completely exited. If the process intercepts and handles the `SIGTERM` signal + * and doesn't exit, the parent process will wait until the child process has + * exited. + * + * **If the `shell` option is enabled, do not pass unsanitized user input to this** + * **function. Any input containing shell metacharacters may be used to trigger** + * **arbitrary command execution.** + * @since v0.11.12 + * @param command The command to run. + * @param args List of string arguments. + */ + function spawnSync(command: string): SpawnSyncReturns; + function spawnSync(command: string, options: SpawnSyncOptionsWithStringEncoding): SpawnSyncReturns; + function spawnSync(command: string, options: SpawnSyncOptionsWithBufferEncoding): SpawnSyncReturns; + function spawnSync(command: string, options?: SpawnSyncOptions): SpawnSyncReturns; + function spawnSync(command: string, args: readonly string[]): SpawnSyncReturns; + function spawnSync( + command: string, + args: readonly string[], + options: SpawnSyncOptionsWithStringEncoding, + ): SpawnSyncReturns; + function spawnSync( + command: string, + args: readonly string[], + options: SpawnSyncOptionsWithBufferEncoding, + ): SpawnSyncReturns; + function spawnSync( + command: string, + args?: readonly string[], + options?: SpawnSyncOptions, + ): SpawnSyncReturns; + interface CommonExecOptions extends CommonOptions { + input?: string | NodeJS.ArrayBufferView | undefined; + /** + * Can be set to 'pipe', 'inherit, or 'ignore', or an array of these strings. + * If passed as an array, the first element is used for `stdin`, the second for + * `stdout`, and the third for `stderr`. A fourth element can be used to + * specify the `stdio` behavior beyond the standard streams. See + * {@link ChildProcess.stdio} for more information. + * + * @default 'pipe' + */ + stdio?: StdioOptions | undefined; + killSignal?: NodeJS.Signals | number | undefined; + maxBuffer?: number | undefined; + encoding?: BufferEncoding | "buffer" | null | undefined; + } + interface ExecSyncOptions extends CommonExecOptions { + shell?: string | undefined; + } + interface ExecSyncOptionsWithStringEncoding extends ExecSyncOptions { + encoding: BufferEncoding; + } + interface ExecSyncOptionsWithBufferEncoding extends ExecSyncOptions { + encoding?: "buffer" | null | undefined; + } + /** + * The `child_process.execSync()` method is generally identical to {@link exec} with the exception that the method will not return + * until the child process has fully closed. When a timeout has been encountered + * and `killSignal` is sent, the method won't return until the process has + * completely exited. If the child process intercepts and handles the `SIGTERM` signal and doesn't exit, the parent process will wait until the child process + * has exited. + * + * If the process times out or has a non-zero exit code, this method will throw. + * The `Error` object will contain the entire result from {@link spawnSync}. + * + * **Never pass unsanitized user input to this function. Any input containing shell** + * **metacharacters may be used to trigger arbitrary command execution.** + * @since v0.11.12 + * @param command The command to run. + * @return The stdout from the command. + */ + function execSync(command: string): Buffer; + function execSync(command: string, options: ExecSyncOptionsWithStringEncoding): string; + function execSync(command: string, options: ExecSyncOptionsWithBufferEncoding): Buffer; + function execSync(command: string, options?: ExecSyncOptions): string | Buffer; + interface ExecFileSyncOptions extends CommonExecOptions { + shell?: boolean | string | undefined; + } + interface ExecFileSyncOptionsWithStringEncoding extends ExecFileSyncOptions { + encoding: BufferEncoding; + } + interface ExecFileSyncOptionsWithBufferEncoding extends ExecFileSyncOptions { + encoding?: "buffer" | null; // specify `null`. + } + /** + * The `child_process.execFileSync()` method is generally identical to {@link execFile} with the exception that the method will not + * return until the child process has fully closed. When a timeout has been + * encountered and `killSignal` is sent, the method won't return until the process + * has completely exited. + * + * If the child process intercepts and handles the `SIGTERM` signal and + * does not exit, the parent process will still wait until the child process has + * exited. + * + * If the process times out or has a non-zero exit code, this method will throw an `Error` that will include the full result of the underlying {@link spawnSync}. + * + * **If the `shell` option is enabled, do not pass unsanitized user input to this** + * **function. Any input containing shell metacharacters may be used to trigger** + * **arbitrary command execution.** + * @since v0.11.12 + * @param file The name or path of the executable file to run. + * @param args List of string arguments. + * @return The stdout from the command. + */ + function execFileSync(file: string): Buffer; + function execFileSync(file: string, options: ExecFileSyncOptionsWithStringEncoding): string; + function execFileSync(file: string, options: ExecFileSyncOptionsWithBufferEncoding): Buffer; + function execFileSync(file: string, options?: ExecFileSyncOptions): string | Buffer; + function execFileSync(file: string, args: readonly string[]): Buffer; + function execFileSync( + file: string, + args: readonly string[], + options: ExecFileSyncOptionsWithStringEncoding, + ): string; + function execFileSync( + file: string, + args: readonly string[], + options: ExecFileSyncOptionsWithBufferEncoding, + ): Buffer; + function execFileSync(file: string, args?: readonly string[], options?: ExecFileSyncOptions): string | Buffer; +} +declare module "node:child_process" { + export * from "child_process"; +} diff --git a/node_modules/@types/node/cluster.d.ts b/node_modules/@types/node/cluster.d.ts new file mode 100644 index 0000000..7711927 --- /dev/null +++ b/node_modules/@types/node/cluster.d.ts @@ -0,0 +1,578 @@ +/** + * Clusters of Node.js processes can be used to run multiple instances of Node.js + * that can distribute workloads among their application threads. When process isolation + * is not needed, use the [`worker_threads`](https://nodejs.org/docs/latest-v20.x/api/worker_threads.html) + * module instead, which allows running multiple application threads within a single Node.js instance. + * + * The cluster module allows easy creation of child processes that all share + * server ports. + * + * ```js + * import cluster from 'node:cluster'; + * import http from 'node:http'; + * import { availableParallelism } from 'node:os'; + * import process from 'node:process'; + * + * const numCPUs = availableParallelism(); + * + * if (cluster.isPrimary) { + * console.log(`Primary ${process.pid} is running`); + * + * // Fork workers. + * for (let i = 0; i < numCPUs; i++) { + * cluster.fork(); + * } + * + * cluster.on('exit', (worker, code, signal) => { + * console.log(`worker ${worker.process.pid} died`); + * }); + * } else { + * // Workers can share any TCP connection + * // In this case it is an HTTP server + * http.createServer((req, res) => { + * res.writeHead(200); + * res.end('hello world\n'); + * }).listen(8000); + * + * console.log(`Worker ${process.pid} started`); + * } + * ``` + * + * Running Node.js will now share port 8000 between the workers: + * + * ```console + * $ node server.js + * Primary 3596 is running + * Worker 4324 started + * Worker 4520 started + * Worker 6056 started + * Worker 5644 started + * ``` + * + * On Windows, it is not yet possible to set up a named pipe server in a worker. + * @see [source](https://github.com/nodejs/node/blob/v20.13.1/lib/cluster.js) + */ +declare module "cluster" { + import * as child from "node:child_process"; + import EventEmitter = require("node:events"); + import * as net from "node:net"; + type SerializationType = "json" | "advanced"; + export interface ClusterSettings { + /** + * List of string arguments passed to the Node.js executable. + * @default process.execArgv + */ + execArgv?: string[] | undefined; + /** + * File path to worker file. + * @default process.argv[1] + */ + exec?: string | undefined; + /** + * String arguments passed to worker. + * @default process.argv.slice(2) + */ + args?: string[] | undefined; + /** + * Whether or not to send output to parent's stdio. + * @default false + */ + silent?: boolean | undefined; + /** + * Configures the stdio of forked processes. Because the cluster module relies on IPC to function, this configuration must + * contain an `'ipc'` entry. When this option is provided, it overrides `silent`. See [`child_prcess.spawn()`](https://nodejs.org/docs/latest-v20.x/api/child_process.html#child_processspawncommand-args-options)'s + * [`stdio`](https://nodejs.org/docs/latest-v20.x/api/child_process.html#optionsstdio). + */ + stdio?: any[] | undefined; + /** + * Sets the user identity of the process. (See [`setuid(2)`](https://man7.org/linux/man-pages/man2/setuid.2.html).) + */ + uid?: number | undefined; + /** + * Sets the group identity of the process. (See [`setgid(2)`](https://man7.org/linux/man-pages/man2/setgid.2.html).) + */ + gid?: number | undefined; + /** + * Sets inspector port of worker. This can be a number, or a function that takes no arguments and returns a number. + * By default each worker gets its own port, incremented from the primary's `process.debugPort`. + */ + inspectPort?: number | (() => number) | undefined; + /** + * Specify the kind of serialization used for sending messages between processes. Possible values are `'json'` and `'advanced'`. + * See [Advanced serialization for `child_process`](https://nodejs.org/docs/latest-v20.x/api/child_process.html#advanced-serialization) for more details. + * @default false + */ + serialization?: SerializationType | undefined; + /** + * Current working directory of the worker process. + * @default undefined (inherits from parent process) + */ + cwd?: string | undefined; + /** + * Hide the forked processes console window that would normally be created on Windows systems. + * @default false + */ + windowsHide?: boolean | undefined; + } + export interface Address { + address: string; + port: number; + /** + * The `addressType` is one of: + * + * * `4` (TCPv4) + * * `6` (TCPv6) + * * `-1` (Unix domain socket) + * * `'udp4'` or `'udp6'` (UDPv4 or UDPv6) + */ + addressType: 4 | 6 | -1 | "udp4" | "udp6"; + } + /** + * A `Worker` object contains all public information and method about a worker. + * In the primary it can be obtained using `cluster.workers`. In a worker + * it can be obtained using `cluster.worker`. + * @since v0.7.0 + */ + export class Worker extends EventEmitter { + /** + * Each new worker is given its own unique id, this id is stored in the `id`. + * + * While a worker is alive, this is the key that indexes it in `cluster.workers`. + * @since v0.8.0 + */ + id: number; + /** + * All workers are created using [`child_process.fork()`](https://nodejs.org/docs/latest-v20.x/api/child_process.html#child_processforkmodulepath-args-options), the returned object + * from this function is stored as `.process`. In a worker, the global `process` is stored. + * + * See: [Child Process module](https://nodejs.org/docs/latest-v20.x/api/child_process.html#child_processforkmodulepath-args-options). + * + * Workers will call `process.exit(0)` if the `'disconnect'` event occurs + * on `process` and `.exitedAfterDisconnect` is not `true`. This protects against + * accidental disconnection. + * @since v0.7.0 + */ + process: child.ChildProcess; + /** + * Send a message to a worker or primary, optionally with a handle. + * + * In the primary, this sends a message to a specific worker. It is identical to [`ChildProcess.send()`](https://nodejs.org/docs/latest-v20.x/api/child_process.html#subprocesssendmessage-sendhandle-options-callback). + * + * In a worker, this sends a message to the primary. It is identical to `process.send()`. + * + * This example will echo back all messages from the primary: + * + * ```js + * if (cluster.isPrimary) { + * const worker = cluster.fork(); + * worker.send('hi there'); + * + * } else if (cluster.isWorker) { + * process.on('message', (msg) => { + * process.send(msg); + * }); + * } + * ``` + * @since v0.7.0 + * @param options The `options` argument, if present, is an object used to parameterize the sending of certain types of handles. + */ + send(message: child.Serializable, callback?: (error: Error | null) => void): boolean; + send( + message: child.Serializable, + sendHandle: child.SendHandle, + callback?: (error: Error | null) => void, + ): boolean; + send( + message: child.Serializable, + sendHandle: child.SendHandle, + options?: child.MessageOptions, + callback?: (error: Error | null) => void, + ): boolean; + /** + * This function will kill the worker. In the primary worker, it does this by + * disconnecting the `worker.process`, and once disconnected, killing with `signal`. In the worker, it does it by killing the process with `signal`. + * + * The `kill()` function kills the worker process without waiting for a graceful + * disconnect, it has the same behavior as `worker.process.kill()`. + * + * This method is aliased as `worker.destroy()` for backwards compatibility. + * + * In a worker, `process.kill()` exists, but it is not this function; + * it is [`kill()`](https://nodejs.org/docs/latest-v20.x/api/process.html#processkillpid-signal). + * @since v0.9.12 + * @param [signal='SIGTERM'] Name of the kill signal to send to the worker process. + */ + kill(signal?: string): void; + destroy(signal?: string): void; + /** + * In a worker, this function will close all servers, wait for the `'close'` event + * on those servers, and then disconnect the IPC channel. + * + * In the primary, an internal message is sent to the worker causing it to call `.disconnect()` on itself. + * + * Causes `.exitedAfterDisconnect` to be set. + * + * After a server is closed, it will no longer accept new connections, + * but connections may be accepted by any other listening worker. Existing + * connections will be allowed to close as usual. When no more connections exist, + * see `server.close()`, the IPC channel to the worker will close allowing it + * to die gracefully. + * + * The above applies _only_ to server connections, client connections are not + * automatically closed by workers, and disconnect does not wait for them to close + * before exiting. + * + * In a worker, `process.disconnect` exists, but it is not this function; + * it is `disconnect()`. + * + * Because long living server connections may block workers from disconnecting, it + * may be useful to send a message, so application specific actions may be taken to + * close them. It also may be useful to implement a timeout, killing a worker if + * the `'disconnect'` event has not been emitted after some time. + * + * ```js + * if (cluster.isPrimary) { + * const worker = cluster.fork(); + * let timeout; + * + * worker.on('listening', (address) => { + * worker.send('shutdown'); + * worker.disconnect(); + * timeout = setTimeout(() => { + * worker.kill(); + * }, 2000); + * }); + * + * worker.on('disconnect', () => { + * clearTimeout(timeout); + * }); + * + * } else if (cluster.isWorker) { + * const net = require('node:net'); + * const server = net.createServer((socket) => { + * // Connections never end + * }); + * + * server.listen(8000); + * + * process.on('message', (msg) => { + * if (msg === 'shutdown') { + * // Initiate graceful close of any connections to server + * } + * }); + * } + * ``` + * @since v0.7.7 + * @return A reference to `worker`. + */ + disconnect(): void; + /** + * This function returns `true` if the worker is connected to its primary via its + * IPC channel, `false` otherwise. A worker is connected to its primary after it + * has been created. It is disconnected after the `'disconnect'` event is emitted. + * @since v0.11.14 + */ + isConnected(): boolean; + /** + * This function returns `true` if the worker's process has terminated (either + * because of exiting or being signaled). Otherwise, it returns `false`. + * + * ```js + * import cluster from 'node:cluster'; + * import http from 'node:http'; + * import { availableParallelism } from 'node:os'; + * import process from 'node:process'; + * + * const numCPUs = availableParallelism(); + * + * if (cluster.isPrimary) { + * console.log(`Primary ${process.pid} is running`); + * + * // Fork workers. + * for (let i = 0; i < numCPUs; i++) { + * cluster.fork(); + * } + * + * cluster.on('fork', (worker) => { + * console.log('worker is dead:', worker.isDead()); + * }); + * + * cluster.on('exit', (worker, code, signal) => { + * console.log('worker is dead:', worker.isDead()); + * }); + * } else { + * // Workers can share any TCP connection. In this case, it is an HTTP server. + * http.createServer((req, res) => { + * res.writeHead(200); + * res.end(`Current process\n ${process.pid}`); + * process.kill(process.pid); + * }).listen(8000); + * } + * ``` + * @since v0.11.14 + */ + isDead(): boolean; + /** + * This property is `true` if the worker exited due to `.disconnect()`. + * If the worker exited any other way, it is `false`. If the + * worker has not exited, it is `undefined`. + * + * The boolean `worker.exitedAfterDisconnect` allows distinguishing between + * voluntary and accidental exit, the primary may choose not to respawn a worker + * based on this value. + * + * ```js + * cluster.on('exit', (worker, code, signal) => { + * if (worker.exitedAfterDisconnect === true) { + * console.log('Oh, it was just voluntary – no need to worry'); + * } + * }); + * + * // kill worker + * worker.kill(); + * ``` + * @since v6.0.0 + */ + exitedAfterDisconnect: boolean; + /** + * events.EventEmitter + * 1. disconnect + * 2. error + * 3. exit + * 4. listening + * 5. message + * 6. online + */ + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "disconnect", listener: () => void): this; + addListener(event: "error", listener: (error: Error) => void): this; + addListener(event: "exit", listener: (code: number, signal: string) => void): this; + addListener(event: "listening", listener: (address: Address) => void): this; + addListener(event: "message", listener: (message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. + addListener(event: "online", listener: () => void): this; + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: "disconnect"): boolean; + emit(event: "error", error: Error): boolean; + emit(event: "exit", code: number, signal: string): boolean; + emit(event: "listening", address: Address): boolean; + emit(event: "message", message: any, handle: net.Socket | net.Server): boolean; + emit(event: "online"): boolean; + on(event: string, listener: (...args: any[]) => void): this; + on(event: "disconnect", listener: () => void): this; + on(event: "error", listener: (error: Error) => void): this; + on(event: "exit", listener: (code: number, signal: string) => void): this; + on(event: "listening", listener: (address: Address) => void): this; + on(event: "message", listener: (message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. + on(event: "online", listener: () => void): this; + once(event: string, listener: (...args: any[]) => void): this; + once(event: "disconnect", listener: () => void): this; + once(event: "error", listener: (error: Error) => void): this; + once(event: "exit", listener: (code: number, signal: string) => void): this; + once(event: "listening", listener: (address: Address) => void): this; + once(event: "message", listener: (message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. + once(event: "online", listener: () => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "disconnect", listener: () => void): this; + prependListener(event: "error", listener: (error: Error) => void): this; + prependListener(event: "exit", listener: (code: number, signal: string) => void): this; + prependListener(event: "listening", listener: (address: Address) => void): this; + prependListener(event: "message", listener: (message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. + prependListener(event: "online", listener: () => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "disconnect", listener: () => void): this; + prependOnceListener(event: "error", listener: (error: Error) => void): this; + prependOnceListener(event: "exit", listener: (code: number, signal: string) => void): this; + prependOnceListener(event: "listening", listener: (address: Address) => void): this; + prependOnceListener(event: "message", listener: (message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. + prependOnceListener(event: "online", listener: () => void): this; + } + export interface Cluster extends EventEmitter { + disconnect(callback?: () => void): void; + /** + * Spawn a new worker process. + * + * This can only be called from the primary process. + * @param env Key/value pairs to add to worker process environment. + * @since v0.6.0 + */ + fork(env?: any): Worker; + /** @deprecated since v16.0.0 - use isPrimary. */ + readonly isMaster: boolean; + /** + * True if the process is a primary. This is determined by the `process.env.NODE_UNIQUE_ID`. If `process.env.NODE_UNIQUE_ID` + * is undefined, then `isPrimary` is `true`. + * @since v16.0.0 + */ + readonly isPrimary: boolean; + /** + * True if the process is not a primary (it is the negation of `cluster.isPrimary`). + * @since v0.6.0 + */ + readonly isWorker: boolean; + /** + * The scheduling policy, either `cluster.SCHED_RR` for round-robin or `cluster.SCHED_NONE` to leave it to the operating system. This is a + * global setting and effectively frozen once either the first worker is spawned, or [`.setupPrimary()`](https://nodejs.org/docs/latest-v20.x/api/cluster.html#clustersetupprimarysettings) + * is called, whichever comes first. + * + * `SCHED_RR` is the default on all operating systems except Windows. Windows will change to `SCHED_RR` once libuv is able to effectively distribute + * IOCP handles without incurring a large performance hit. + * + * `cluster.schedulingPolicy` can also be set through the `NODE_CLUSTER_SCHED_POLICY` environment variable. Valid values are `'rr'` and `'none'`. + * @since v0.11.2 + */ + schedulingPolicy: number; + /** + * After calling [`.setupPrimary()`](https://nodejs.org/docs/latest-v20.x/api/cluster.html#clustersetupprimarysettings) + * (or [`.fork()`](https://nodejs.org/docs/latest-v20.x/api/cluster.html#clusterforkenv)) this settings object will contain + * the settings, including the default values. + * + * This object is not intended to be changed or set manually. + * @since v0.7.1 + */ + readonly settings: ClusterSettings; + /** @deprecated since v16.0.0 - use [`.setupPrimary()`](https://nodejs.org/docs/latest-v20.x/api/cluster.html#clustersetupprimarysettings) instead. */ + setupMaster(settings?: ClusterSettings): void; + /** + * `setupPrimary` is used to change the default 'fork' behavior. Once called, the settings will be present in `cluster.settings`. + * + * Any settings changes only affect future calls to [`.fork()`](https://nodejs.org/docs/latest-v20.x/api/cluster.html#clusterforkenv) + * and have no effect on workers that are already running. + * + * The only attribute of a worker that cannot be set via `.setupPrimary()` is the `env` passed to + * [`.fork()`](https://nodejs.org/docs/latest-v20.x/api/cluster.html#clusterforkenv). + * + * The defaults above apply to the first call only; the defaults for later calls are the current values at the time of + * `cluster.setupPrimary()` is called. + * + * ```js + * import cluster from 'node:cluster'; + * + * cluster.setupPrimary({ + * exec: 'worker.js', + * args: ['--use', 'https'], + * silent: true, + * }); + * cluster.fork(); // https worker + * cluster.setupPrimary({ + * exec: 'worker.js', + * args: ['--use', 'http'], + * }); + * cluster.fork(); // http worker + * ``` + * + * This can only be called from the primary process. + * @since v16.0.0 + */ + setupPrimary(settings?: ClusterSettings): void; + /** + * A reference to the current worker object. Not available in the primary process. + * + * ```js + * import cluster from 'node:cluster'; + * + * if (cluster.isPrimary) { + * console.log('I am primary'); + * cluster.fork(); + * cluster.fork(); + * } else if (cluster.isWorker) { + * console.log(`I am worker #${cluster.worker.id}`); + * } + * ``` + * @since v0.7.0 + */ + readonly worker?: Worker | undefined; + /** + * A hash that stores the active worker objects, keyed by `id` field. This makes it easy to loop through all the workers. It is only available in the primary process. + * + * A worker is removed from `cluster.workers` after the worker has disconnected _and_ exited. The order between these two events cannot be determined in advance. However, it + * is guaranteed that the removal from the `cluster.workers` list happens before the last `'disconnect'` or `'exit'` event is emitted. + * + * ```js + * import cluster from 'node:cluster'; + * + * for (const worker of Object.values(cluster.workers)) { + * worker.send('big announcement to all workers'); + * } + * ``` + * @since v0.7.0 + */ + readonly workers?: NodeJS.Dict | undefined; + readonly SCHED_NONE: number; + readonly SCHED_RR: number; + /** + * events.EventEmitter + * 1. disconnect + * 2. exit + * 3. fork + * 4. listening + * 5. message + * 6. online + * 7. setup + */ + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "disconnect", listener: (worker: Worker) => void): this; + addListener(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): this; + addListener(event: "fork", listener: (worker: Worker) => void): this; + addListener(event: "listening", listener: (worker: Worker, address: Address) => void): this; + addListener( + event: "message", + listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void, + ): this; // the handle is a net.Socket or net.Server object, or undefined. + addListener(event: "online", listener: (worker: Worker) => void): this; + addListener(event: "setup", listener: (settings: ClusterSettings) => void): this; + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: "disconnect", worker: Worker): boolean; + emit(event: "exit", worker: Worker, code: number, signal: string): boolean; + emit(event: "fork", worker: Worker): boolean; + emit(event: "listening", worker: Worker, address: Address): boolean; + emit(event: "message", worker: Worker, message: any, handle: net.Socket | net.Server): boolean; + emit(event: "online", worker: Worker): boolean; + emit(event: "setup", settings: ClusterSettings): boolean; + on(event: string, listener: (...args: any[]) => void): this; + on(event: "disconnect", listener: (worker: Worker) => void): this; + on(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): this; + on(event: "fork", listener: (worker: Worker) => void): this; + on(event: "listening", listener: (worker: Worker, address: Address) => void): this; + on(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. + on(event: "online", listener: (worker: Worker) => void): this; + on(event: "setup", listener: (settings: ClusterSettings) => void): this; + once(event: string, listener: (...args: any[]) => void): this; + once(event: "disconnect", listener: (worker: Worker) => void): this; + once(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): this; + once(event: "fork", listener: (worker: Worker) => void): this; + once(event: "listening", listener: (worker: Worker, address: Address) => void): this; + once(event: "message", listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void): this; // the handle is a net.Socket or net.Server object, or undefined. + once(event: "online", listener: (worker: Worker) => void): this; + once(event: "setup", listener: (settings: ClusterSettings) => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "disconnect", listener: (worker: Worker) => void): this; + prependListener(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): this; + prependListener(event: "fork", listener: (worker: Worker) => void): this; + prependListener(event: "listening", listener: (worker: Worker, address: Address) => void): this; + // the handle is a net.Socket or net.Server object, or undefined. + prependListener( + event: "message", + listener: (worker: Worker, message: any, handle?: net.Socket | net.Server) => void, + ): this; + prependListener(event: "online", listener: (worker: Worker) => void): this; + prependListener(event: "setup", listener: (settings: ClusterSettings) => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "disconnect", listener: (worker: Worker) => void): this; + prependOnceListener(event: "exit", listener: (worker: Worker, code: number, signal: string) => void): this; + prependOnceListener(event: "fork", listener: (worker: Worker) => void): this; + prependOnceListener(event: "listening", listener: (worker: Worker, address: Address) => void): this; + // the handle is a net.Socket or net.Server object, or undefined. + prependOnceListener( + event: "message", + listener: (worker: Worker, message: any, handle: net.Socket | net.Server) => void, + ): this; + prependOnceListener(event: "online", listener: (worker: Worker) => void): this; + prependOnceListener(event: "setup", listener: (settings: ClusterSettings) => void): this; + } + const cluster: Cluster; + export default cluster; +} +declare module "node:cluster" { + export * from "cluster"; + export { default as default } from "cluster"; +} diff --git a/node_modules/@types/node/console.d.ts b/node_modules/@types/node/console.d.ts new file mode 100644 index 0000000..3d1a6c2 --- /dev/null +++ b/node_modules/@types/node/console.d.ts @@ -0,0 +1,452 @@ +/** + * The `node:console` module provides a simple debugging console that is similar to + * the JavaScript console mechanism provided by web browsers. + * + * The module exports two specific components: + * + * * A `Console` class with methods such as `console.log()`, `console.error()`, and `console.warn()` that can be used to write to any Node.js stream. + * * A global `console` instance configured to write to [`process.stdout`](https://nodejs.org/docs/latest-v20.x/api/process.html#processstdout) and + * [`process.stderr`](https://nodejs.org/docs/latest-v20.x/api/process.html#processstderr). The global `console` can be used without calling `require('node:console')`. + * + * _**Warning**_: The global console object's methods are neither consistently + * synchronous like the browser APIs they resemble, nor are they consistently + * asynchronous like all other Node.js streams. See the [`note on process I/O`](https://nodejs.org/docs/latest-v20.x/api/process.html#a-note-on-process-io) for + * more information. + * + * Example using the global `console`: + * + * ```js + * console.log('hello world'); + * // Prints: hello world, to stdout + * console.log('hello %s', 'world'); + * // Prints: hello world, to stdout + * console.error(new Error('Whoops, something bad happened')); + * // Prints error message and stack trace to stderr: + * // Error: Whoops, something bad happened + * // at [eval]:5:15 + * // at Script.runInThisContext (node:vm:132:18) + * // at Object.runInThisContext (node:vm:309:38) + * // at node:internal/process/execution:77:19 + * // at [eval]-wrapper:6:22 + * // at evalScript (node:internal/process/execution:76:60) + * // at node:internal/main/eval_string:23:3 + * + * const name = 'Will Robinson'; + * console.warn(`Danger ${name}! Danger!`); + * // Prints: Danger Will Robinson! Danger!, to stderr + * ``` + * + * Example using the `Console` class: + * + * ```js + * const out = getStreamSomehow(); + * const err = getStreamSomehow(); + * const myConsole = new console.Console(out, err); + * + * myConsole.log('hello world'); + * // Prints: hello world, to out + * myConsole.log('hello %s', 'world'); + * // Prints: hello world, to out + * myConsole.error(new Error('Whoops, something bad happened')); + * // Prints: [Error: Whoops, something bad happened], to err + * + * const name = 'Will Robinson'; + * myConsole.warn(`Danger ${name}! Danger!`); + * // Prints: Danger Will Robinson! Danger!, to err + * ``` + * @see [source](https://github.com/nodejs/node/blob/v20.13.1/lib/console.js) + */ +declare module "console" { + import console = require("node:console"); + export = console; +} +declare module "node:console" { + import { InspectOptions } from "node:util"; + global { + // This needs to be global to avoid TS2403 in case lib.dom.d.ts is present in the same build + interface Console { + Console: console.ConsoleConstructor; + /** + * `console.assert()` writes a message if `value` is [falsy](https://developer.mozilla.org/en-US/docs/Glossary/Falsy) or omitted. It only + * writes a message and does not otherwise affect execution. The output always + * starts with `"Assertion failed"`. If provided, `message` is formatted using + * [`util.format()`](https://nodejs.org/docs/latest-v20.x/api/util.html#utilformatformat-args). + * + * If `value` is [truthy](https://developer.mozilla.org/en-US/docs/Glossary/Truthy), nothing happens. + * + * ```js + * console.assert(true, 'does nothing'); + * + * console.assert(false, 'Whoops %s work', 'didn\'t'); + * // Assertion failed: Whoops didn't work + * + * console.assert(); + * // Assertion failed + * ``` + * @since v0.1.101 + * @param value The value tested for being truthy. + * @param message All arguments besides `value` are used as error message. + */ + assert(value: any, message?: string, ...optionalParams: any[]): void; + /** + * When `stdout` is a TTY, calling `console.clear()` will attempt to clear the + * TTY. When `stdout` is not a TTY, this method does nothing. + * + * The specific operation of `console.clear()` can vary across operating systems + * and terminal types. For most Linux operating systems, `console.clear()` operates similarly to the `clear` shell command. On Windows, `console.clear()` will clear only the output in the + * current terminal viewport for the Node.js + * binary. + * @since v8.3.0 + */ + clear(): void; + /** + * Maintains an internal counter specific to `label` and outputs to `stdout` the + * number of times `console.count()` has been called with the given `label`. + * + * ```js + * > console.count() + * default: 1 + * undefined + * > console.count('default') + * default: 2 + * undefined + * > console.count('abc') + * abc: 1 + * undefined + * > console.count('xyz') + * xyz: 1 + * undefined + * > console.count('abc') + * abc: 2 + * undefined + * > console.count() + * default: 3 + * undefined + * > + * ``` + * @since v8.3.0 + * @param [label='default'] The display label for the counter. + */ + count(label?: string): void; + /** + * Resets the internal counter specific to `label`. + * + * ```js + * > console.count('abc'); + * abc: 1 + * undefined + * > console.countReset('abc'); + * undefined + * > console.count('abc'); + * abc: 1 + * undefined + * > + * ``` + * @since v8.3.0 + * @param [label='default'] The display label for the counter. + */ + countReset(label?: string): void; + /** + * The `console.debug()` function is an alias for {@link log}. + * @since v8.0.0 + */ + debug(message?: any, ...optionalParams: any[]): void; + /** + * Uses [`util.inspect()`](https://nodejs.org/docs/latest-v20.x/api/util.html#utilinspectobject-options) on `obj` and prints the resulting string to `stdout`. + * This function bypasses any custom `inspect()` function defined on `obj`. + * @since v0.1.101 + */ + dir(obj: any, options?: InspectOptions): void; + /** + * This method calls `console.log()` passing it the arguments received. + * This method does not produce any XML formatting. + * @since v8.0.0 + */ + dirxml(...data: any[]): void; + /** + * Prints to `stderr` with newline. Multiple arguments can be passed, with the + * first used as the primary message and all additional used as substitution + * values similar to [`printf(3)`](http://man7.org/linux/man-pages/man3/printf.3.html) + * (the arguments are all passed to [`util.format()`](https://nodejs.org/docs/latest-v20.x/api/util.html#utilformatformat-args)). + * + * ```js + * const code = 5; + * console.error('error #%d', code); + * // Prints: error #5, to stderr + * console.error('error', code); + * // Prints: error 5, to stderr + * ``` + * + * If formatting elements (e.g. `%d`) are not found in the first string then + * [`util.inspect()`](https://nodejs.org/docs/latest-v20.x/api/util.html#utilinspectobject-options) is called on each argument and the + * resulting string values are concatenated. See [`util.format()`](https://nodejs.org/docs/latest-v20.x/api/util.html#utilformatformat-args) + * for more information. + * @since v0.1.100 + */ + error(message?: any, ...optionalParams: any[]): void; + /** + * Increases indentation of subsequent lines by spaces for `groupIndentation` length. + * + * If one or more `label`s are provided, those are printed first without the + * additional indentation. + * @since v8.5.0 + */ + group(...label: any[]): void; + /** + * An alias for {@link group}. + * @since v8.5.0 + */ + groupCollapsed(...label: any[]): void; + /** + * Decreases indentation of subsequent lines by spaces for `groupIndentation` length. + * @since v8.5.0 + */ + groupEnd(): void; + /** + * The `console.info()` function is an alias for {@link log}. + * @since v0.1.100 + */ + info(message?: any, ...optionalParams: any[]): void; + /** + * Prints to `stdout` with newline. Multiple arguments can be passed, with the + * first used as the primary message and all additional used as substitution + * values similar to [`printf(3)`](http://man7.org/linux/man-pages/man3/printf.3.html) + * (the arguments are all passed to [`util.format()`](https://nodejs.org/docs/latest-v20.x/api/util.html#utilformatformat-args)). + * + * ```js + * const count = 5; + * console.log('count: %d', count); + * // Prints: count: 5, to stdout + * console.log('count:', count); + * // Prints: count: 5, to stdout + * ``` + * + * See [`util.format()`](https://nodejs.org/docs/latest-v20.x/api/util.html#utilformatformat-args) for more information. + * @since v0.1.100 + */ + log(message?: any, ...optionalParams: any[]): void; + /** + * Try to construct a table with the columns of the properties of `tabularData` (or use `properties`) and rows of `tabularData` and log it. Falls back to just + * logging the argument if it can't be parsed as tabular. + * + * ```js + * // These can't be parsed as tabular data + * console.table(Symbol()); + * // Symbol() + * + * console.table(undefined); + * // undefined + * + * console.table([{ a: 1, b: 'Y' }, { a: 'Z', b: 2 }]); + * // ┌─────────┬─────┬─────┐ + * // │ (index) │ a │ b │ + * // ├─────────┼─────┼─────┤ + * // │ 0 │ 1 │ 'Y' │ + * // │ 1 │ 'Z' │ 2 │ + * // └─────────┴─────┴─────┘ + * + * console.table([{ a: 1, b: 'Y' }, { a: 'Z', b: 2 }], ['a']); + * // ┌─────────┬─────┐ + * // │ (index) │ a │ + * // ├─────────┼─────┤ + * // │ 0 │ 1 │ + * // │ 1 │ 'Z' │ + * // └─────────┴─────┘ + * ``` + * @since v10.0.0 + * @param properties Alternate properties for constructing the table. + */ + table(tabularData: any, properties?: readonly string[]): void; + /** + * Starts a timer that can be used to compute the duration of an operation. Timers + * are identified by a unique `label`. Use the same `label` when calling {@link timeEnd} to stop the timer and output the elapsed time in + * suitable time units to `stdout`. For example, if the elapsed + * time is 3869ms, `console.timeEnd()` displays "3.869s". + * @since v0.1.104 + * @param [label='default'] + */ + time(label?: string): void; + /** + * Stops a timer that was previously started by calling {@link time} and + * prints the result to `stdout`: + * + * ```js + * console.time('bunch-of-stuff'); + * // Do a bunch of stuff. + * console.timeEnd('bunch-of-stuff'); + * // Prints: bunch-of-stuff: 225.438ms + * ``` + * @since v0.1.104 + * @param [label='default'] + */ + timeEnd(label?: string): void; + /** + * For a timer that was previously started by calling {@link time}, prints + * the elapsed time and other `data` arguments to `stdout`: + * + * ```js + * console.time('process'); + * const value = expensiveProcess1(); // Returns 42 + * console.timeLog('process', value); + * // Prints "process: 365.227ms 42". + * doExpensiveProcess2(value); + * console.timeEnd('process'); + * ``` + * @since v10.7.0 + * @param [label='default'] + */ + timeLog(label?: string, ...data: any[]): void; + /** + * Prints to `stderr` the string `'Trace: '`, followed by the [`util.format()`](https://nodejs.org/docs/latest-v20.x/api/util.html#utilformatformat-args) + * formatted message and stack trace to the current position in the code. + * + * ```js + * console.trace('Show me'); + * // Prints: (stack trace will vary based on where trace is called) + * // Trace: Show me + * // at repl:2:9 + * // at REPLServer.defaultEval (repl.js:248:27) + * // at bound (domain.js:287:14) + * // at REPLServer.runBound [as eval] (domain.js:300:12) + * // at REPLServer. (repl.js:412:12) + * // at emitOne (events.js:82:20) + * // at REPLServer.emit (events.js:169:7) + * // at REPLServer.Interface._onLine (readline.js:210:10) + * // at REPLServer.Interface._line (readline.js:549:8) + * // at REPLServer.Interface._ttyWrite (readline.js:826:14) + * ``` + * @since v0.1.104 + */ + trace(message?: any, ...optionalParams: any[]): void; + /** + * The `console.warn()` function is an alias for {@link error}. + * @since v0.1.100 + */ + warn(message?: any, ...optionalParams: any[]): void; + // --- Inspector mode only --- + /** + * This method does not display anything unless used in the inspector. The `console.profile()` + * method starts a JavaScript CPU profile with an optional label until {@link profileEnd} + * is called. The profile is then added to the Profile panel of the inspector. + * + * ```js + * console.profile('MyLabel'); + * // Some code + * console.profileEnd('MyLabel'); + * // Adds the profile 'MyLabel' to the Profiles panel of the inspector. + * ``` + * @since v8.0.0 + */ + profile(label?: string): void; + /** + * This method does not display anything unless used in the inspector. Stops the current + * JavaScript CPU profiling session if one has been started and prints the report to the + * Profiles panel of the inspector. See {@link profile} for an example. + * + * If this method is called without a label, the most recently started profile is stopped. + * @since v8.0.0 + */ + profileEnd(label?: string): void; + /** + * This method does not display anything unless used in the inspector. The `console.timeStamp()` + * method adds an event with the label `'label'` to the Timeline panel of the inspector. + * @since v8.0.0 + */ + timeStamp(label?: string): void; + } + /** + * The `console` module provides a simple debugging console that is similar to the + * JavaScript console mechanism provided by web browsers. + * + * The module exports two specific components: + * + * * A `Console` class with methods such as `console.log()`, `console.error()` and `console.warn()` that can be used to write to any Node.js stream. + * * A global `console` instance configured to write to [`process.stdout`](https://nodejs.org/docs/latest-v20.x/api/process.html#processstdout) and + * [`process.stderr`](https://nodejs.org/docs/latest-v20.x/api/process.html#processstderr). The global `console` can be used without calling `require('console')`. + * + * _**Warning**_: The global console object's methods are neither consistently + * synchronous like the browser APIs they resemble, nor are they consistently + * asynchronous like all other Node.js streams. See the [`note on process I/O`](https://nodejs.org/docs/latest-v20.x/api/process.html#a-note-on-process-io) for + * more information. + * + * Example using the global `console`: + * + * ```js + * console.log('hello world'); + * // Prints: hello world, to stdout + * console.log('hello %s', 'world'); + * // Prints: hello world, to stdout + * console.error(new Error('Whoops, something bad happened')); + * // Prints error message and stack trace to stderr: + * // Error: Whoops, something bad happened + * // at [eval]:5:15 + * // at Script.runInThisContext (node:vm:132:18) + * // at Object.runInThisContext (node:vm:309:38) + * // at node:internal/process/execution:77:19 + * // at [eval]-wrapper:6:22 + * // at evalScript (node:internal/process/execution:76:60) + * // at node:internal/main/eval_string:23:3 + * + * const name = 'Will Robinson'; + * console.warn(`Danger ${name}! Danger!`); + * // Prints: Danger Will Robinson! Danger!, to stderr + * ``` + * + * Example using the `Console` class: + * + * ```js + * const out = getStreamSomehow(); + * const err = getStreamSomehow(); + * const myConsole = new console.Console(out, err); + * + * myConsole.log('hello world'); + * // Prints: hello world, to out + * myConsole.log('hello %s', 'world'); + * // Prints: hello world, to out + * myConsole.error(new Error('Whoops, something bad happened')); + * // Prints: [Error: Whoops, something bad happened], to err + * + * const name = 'Will Robinson'; + * myConsole.warn(`Danger ${name}! Danger!`); + * // Prints: Danger Will Robinson! Danger!, to err + * ``` + * @see [source](https://github.com/nodejs/node/blob/v20.11.1/lib/console.js) + */ + namespace console { + interface ConsoleConstructorOptions { + stdout: NodeJS.WritableStream; + stderr?: NodeJS.WritableStream | undefined; + /** + * Ignore errors when writing to the underlying streams. + * @default true + */ + ignoreErrors?: boolean | undefined; + /** + * Set color support for this `Console` instance. Setting to true enables coloring while inspecting + * values. Setting to `false` disables coloring while inspecting values. Setting to `'auto'` makes color + * support depend on the value of the `isTTY` property and the value returned by `getColorDepth()` on the + * respective stream. This option can not be used, if `inspectOptions.colors` is set as well. + * @default auto + */ + colorMode?: boolean | "auto" | undefined; + /** + * Specifies options that are passed along to + * [`util.inspect()`](https://nodejs.org/docs/latest-v20.x/api/util.html#utilinspectobject-options). + */ + inspectOptions?: InspectOptions | undefined; + /** + * Set group indentation. + * @default 2 + */ + groupIndentation?: number | undefined; + } + interface ConsoleConstructor { + prototype: Console; + new(stdout: NodeJS.WritableStream, stderr?: NodeJS.WritableStream, ignoreErrors?: boolean): Console; + new(options: ConsoleConstructorOptions): Console; + } + } + var console: Console; + } + export = globalThis.console; +} diff --git a/node_modules/@types/node/constants.d.ts b/node_modules/@types/node/constants.d.ts new file mode 100644 index 0000000..c3ac2b8 --- /dev/null +++ b/node_modules/@types/node/constants.d.ts @@ -0,0 +1,19 @@ +/** @deprecated since v6.3.0 - use constants property exposed by the relevant module instead. */ +declare module "constants" { + import { constants as osConstants, SignalConstants } from "node:os"; + import { constants as cryptoConstants } from "node:crypto"; + import { constants as fsConstants } from "node:fs"; + + const exp: + & typeof osConstants.errno + & typeof osConstants.priority + & SignalConstants + & typeof cryptoConstants + & typeof fsConstants; + export = exp; +} + +declare module "node:constants" { + import constants = require("constants"); + export = constants; +} diff --git a/node_modules/@types/node/crypto.d.ts b/node_modules/@types/node/crypto.d.ts new file mode 100644 index 0000000..5173dbf --- /dev/null +++ b/node_modules/@types/node/crypto.d.ts @@ -0,0 +1,4523 @@ +/** + * The `node:crypto` module provides cryptographic functionality that includes a + * set of wrappers for OpenSSL's hash, HMAC, cipher, decipher, sign, and verify + * functions. + * + * ```js + * const { createHmac } = await import('node:crypto'); + * + * const secret = 'abcdefg'; + * const hash = createHmac('sha256', secret) + * .update('I love cupcakes') + * .digest('hex'); + * console.log(hash); + * // Prints: + * // c0fa1bc00531bd78ef38c628449c5102aeabd49b5dc3a2a516ea6ea959d6658e + * ``` + * @see [source](https://github.com/nodejs/node/blob/v20.13.1/lib/crypto.js) + */ +declare module "crypto" { + import * as stream from "node:stream"; + import { PeerCertificate } from "node:tls"; + /** + * SPKAC is a Certificate Signing Request mechanism originally implemented by + * Netscape and was specified formally as part of HTML5's `keygen` element. + * + * `` is deprecated since [HTML 5.2](https://www.w3.org/TR/html52/changes.html#features-removed) and new projects + * should not use this element anymore. + * + * The `node:crypto` module provides the `Certificate` class for working with SPKAC + * data. The most common usage is handling output generated by the HTML5 `` element. Node.js uses [OpenSSL's SPKAC + * implementation](https://www.openssl.org/docs/man3.0/man1/openssl-spkac.html) internally. + * @since v0.11.8 + */ + class Certificate { + /** + * ```js + * const { Certificate } = await import('node:crypto'); + * const spkac = getSpkacSomehow(); + * const challenge = Certificate.exportChallenge(spkac); + * console.log(challenge.toString('utf8')); + * // Prints: the challenge as a UTF8 string + * ``` + * @since v9.0.0 + * @param encoding The `encoding` of the `spkac` string. + * @return The challenge component of the `spkac` data structure, which includes a public key and a challenge. + */ + static exportChallenge(spkac: BinaryLike): Buffer; + /** + * ```js + * const { Certificate } = await import('node:crypto'); + * const spkac = getSpkacSomehow(); + * const publicKey = Certificate.exportPublicKey(spkac); + * console.log(publicKey); + * // Prints: the public key as + * ``` + * @since v9.0.0 + * @param encoding The `encoding` of the `spkac` string. + * @return The public key component of the `spkac` data structure, which includes a public key and a challenge. + */ + static exportPublicKey(spkac: BinaryLike, encoding?: string): Buffer; + /** + * ```js + * import { Buffer } from 'node:buffer'; + * const { Certificate } = await import('node:crypto'); + * + * const spkac = getSpkacSomehow(); + * console.log(Certificate.verifySpkac(Buffer.from(spkac))); + * // Prints: true or false + * ``` + * @since v9.0.0 + * @param encoding The `encoding` of the `spkac` string. + * @return `true` if the given `spkac` data structure is valid, `false` otherwise. + */ + static verifySpkac(spkac: NodeJS.ArrayBufferView): boolean; + /** + * @deprecated + * @param spkac + * @returns The challenge component of the `spkac` data structure, + * which includes a public key and a challenge. + */ + exportChallenge(spkac: BinaryLike): Buffer; + /** + * @deprecated + * @param spkac + * @param encoding The encoding of the spkac string. + * @returns The public key component of the `spkac` data structure, + * which includes a public key and a challenge. + */ + exportPublicKey(spkac: BinaryLike, encoding?: string): Buffer; + /** + * @deprecated + * @param spkac + * @returns `true` if the given `spkac` data structure is valid, + * `false` otherwise. + */ + verifySpkac(spkac: NodeJS.ArrayBufferView): boolean; + } + namespace constants { + // https://nodejs.org/dist/latest-v20.x/docs/api/crypto.html#crypto-constants + const OPENSSL_VERSION_NUMBER: number; + /** Applies multiple bug workarounds within OpenSSL. See https://www.openssl.org/docs/man1.0.2/ssl/SSL_CTX_set_options.html for detail. */ + const SSL_OP_ALL: number; + /** Instructs OpenSSL to allow a non-[EC]DHE-based key exchange mode for TLS v1.3 */ + const SSL_OP_ALLOW_NO_DHE_KEX: number; + /** Allows legacy insecure renegotiation between OpenSSL and unpatched clients or servers. See https://www.openssl.org/docs/man1.0.2/ssl/SSL_CTX_set_options.html. */ + const SSL_OP_ALLOW_UNSAFE_LEGACY_RENEGOTIATION: number; + /** Attempts to use the server's preferences instead of the client's when selecting a cipher. See https://www.openssl.org/docs/man1.0.2/ssl/SSL_CTX_set_options.html. */ + const SSL_OP_CIPHER_SERVER_PREFERENCE: number; + /** Instructs OpenSSL to use Cisco's version identifier of DTLS_BAD_VER. */ + const SSL_OP_CISCO_ANYCONNECT: number; + /** Instructs OpenSSL to turn on cookie exchange. */ + const SSL_OP_COOKIE_EXCHANGE: number; + /** Instructs OpenSSL to add server-hello extension from an early version of the cryptopro draft. */ + const SSL_OP_CRYPTOPRO_TLSEXT_BUG: number; + /** Instructs OpenSSL to disable a SSL 3.0/TLS 1.0 vulnerability workaround added in OpenSSL 0.9.6d. */ + const SSL_OP_DONT_INSERT_EMPTY_FRAGMENTS: number; + /** Allows initial connection to servers that do not support RI. */ + const SSL_OP_LEGACY_SERVER_CONNECT: number; + /** Instructs OpenSSL to disable support for SSL/TLS compression. */ + const SSL_OP_NO_COMPRESSION: number; + /** Instructs OpenSSL to disable encrypt-then-MAC. */ + const SSL_OP_NO_ENCRYPT_THEN_MAC: number; + const SSL_OP_NO_QUERY_MTU: number; + /** Instructs OpenSSL to disable renegotiation. */ + const SSL_OP_NO_RENEGOTIATION: number; + /** Instructs OpenSSL to always start a new session when performing renegotiation. */ + const SSL_OP_NO_SESSION_RESUMPTION_ON_RENEGOTIATION: number; + /** Instructs OpenSSL to turn off SSL v2 */ + const SSL_OP_NO_SSLv2: number; + /** Instructs OpenSSL to turn off SSL v3 */ + const SSL_OP_NO_SSLv3: number; + /** Instructs OpenSSL to disable use of RFC4507bis tickets. */ + const SSL_OP_NO_TICKET: number; + /** Instructs OpenSSL to turn off TLS v1 */ + const SSL_OP_NO_TLSv1: number; + /** Instructs OpenSSL to turn off TLS v1.1 */ + const SSL_OP_NO_TLSv1_1: number; + /** Instructs OpenSSL to turn off TLS v1.2 */ + const SSL_OP_NO_TLSv1_2: number; + /** Instructs OpenSSL to turn off TLS v1.3 */ + const SSL_OP_NO_TLSv1_3: number; + /** Instructs OpenSSL server to prioritize ChaCha20-Poly1305 when the client does. This option has no effect if `SSL_OP_CIPHER_SERVER_PREFERENCE` is not enabled. */ + const SSL_OP_PRIORITIZE_CHACHA: number; + /** Instructs OpenSSL to disable version rollback attack detection. */ + const SSL_OP_TLS_ROLLBACK_BUG: number; + const ENGINE_METHOD_RSA: number; + const ENGINE_METHOD_DSA: number; + const ENGINE_METHOD_DH: number; + const ENGINE_METHOD_RAND: number; + const ENGINE_METHOD_EC: number; + const ENGINE_METHOD_CIPHERS: number; + const ENGINE_METHOD_DIGESTS: number; + const ENGINE_METHOD_PKEY_METHS: number; + const ENGINE_METHOD_PKEY_ASN1_METHS: number; + const ENGINE_METHOD_ALL: number; + const ENGINE_METHOD_NONE: number; + const DH_CHECK_P_NOT_SAFE_PRIME: number; + const DH_CHECK_P_NOT_PRIME: number; + const DH_UNABLE_TO_CHECK_GENERATOR: number; + const DH_NOT_SUITABLE_GENERATOR: number; + const RSA_PKCS1_PADDING: number; + const RSA_SSLV23_PADDING: number; + const RSA_NO_PADDING: number; + const RSA_PKCS1_OAEP_PADDING: number; + const RSA_X931_PADDING: number; + const RSA_PKCS1_PSS_PADDING: number; + /** Sets the salt length for RSA_PKCS1_PSS_PADDING to the digest size when signing or verifying. */ + const RSA_PSS_SALTLEN_DIGEST: number; + /** Sets the salt length for RSA_PKCS1_PSS_PADDING to the maximum permissible value when signing data. */ + const RSA_PSS_SALTLEN_MAX_SIGN: number; + /** Causes the salt length for RSA_PKCS1_PSS_PADDING to be determined automatically when verifying a signature. */ + const RSA_PSS_SALTLEN_AUTO: number; + const POINT_CONVERSION_COMPRESSED: number; + const POINT_CONVERSION_UNCOMPRESSED: number; + const POINT_CONVERSION_HYBRID: number; + /** Specifies the built-in default cipher list used by Node.js (colon-separated values). */ + const defaultCoreCipherList: string; + /** Specifies the active default cipher list used by the current Node.js process (colon-separated values). */ + const defaultCipherList: string; + } + interface HashOptions extends stream.TransformOptions { + /** + * For XOF hash functions such as `shake256`, the + * outputLength option can be used to specify the desired output length in bytes. + */ + outputLength?: number | undefined; + } + /** @deprecated since v10.0.0 */ + const fips: boolean; + /** + * Creates and returns a `Hash` object that can be used to generate hash digests + * using the given `algorithm`. Optional `options` argument controls stream + * behavior. For XOF hash functions such as `'shake256'`, the `outputLength` option + * can be used to specify the desired output length in bytes. + * + * The `algorithm` is dependent on the available algorithms supported by the + * version of OpenSSL on the platform. Examples are `'sha256'`, `'sha512'`, etc. + * On recent releases of OpenSSL, `openssl list -digest-algorithms` will + * display the available digest algorithms. + * + * Example: generating the sha256 sum of a file + * + * ```js + * import { + * createReadStream, + * } from 'node:fs'; + * import { argv } from 'node:process'; + * const { + * createHash, + * } = await import('node:crypto'); + * + * const filename = argv[2]; + * + * const hash = createHash('sha256'); + * + * const input = createReadStream(filename); + * input.on('readable', () => { + * // Only one element is going to be produced by the + * // hash stream. + * const data = input.read(); + * if (data) + * hash.update(data); + * else { + * console.log(`${hash.digest('hex')} ${filename}`); + * } + * }); + * ``` + * @since v0.1.92 + * @param options `stream.transform` options + */ + function createHash(algorithm: string, options?: HashOptions): Hash; + /** + * Creates and returns an `Hmac` object that uses the given `algorithm` and `key`. + * Optional `options` argument controls stream behavior. + * + * The `algorithm` is dependent on the available algorithms supported by the + * version of OpenSSL on the platform. Examples are `'sha256'`, `'sha512'`, etc. + * On recent releases of OpenSSL, `openssl list -digest-algorithms` will + * display the available digest algorithms. + * + * The `key` is the HMAC key used to generate the cryptographic HMAC hash. If it is + * a `KeyObject`, its type must be `secret`. If it is a string, please consider `caveats when using strings as inputs to cryptographic APIs`. If it was + * obtained from a cryptographically secure source of entropy, such as {@link randomBytes} or {@link generateKey}, its length should not + * exceed the block size of `algorithm` (e.g., 512 bits for SHA-256). + * + * Example: generating the sha256 HMAC of a file + * + * ```js + * import { + * createReadStream, + * } from 'node:fs'; + * import { argv } from 'node:process'; + * const { + * createHmac, + * } = await import('node:crypto'); + * + * const filename = argv[2]; + * + * const hmac = createHmac('sha256', 'a secret'); + * + * const input = createReadStream(filename); + * input.on('readable', () => { + * // Only one element is going to be produced by the + * // hash stream. + * const data = input.read(); + * if (data) + * hmac.update(data); + * else { + * console.log(`${hmac.digest('hex')} ${filename}`); + * } + * }); + * ``` + * @since v0.1.94 + * @param options `stream.transform` options + */ + function createHmac(algorithm: string, key: BinaryLike | KeyObject, options?: stream.TransformOptions): Hmac; + // https://nodejs.org/api/buffer.html#buffer_buffers_and_character_encodings + type BinaryToTextEncoding = "base64" | "base64url" | "hex" | "binary"; + type CharacterEncoding = "utf8" | "utf-8" | "utf16le" | "utf-16le" | "latin1"; + type LegacyCharacterEncoding = "ascii" | "binary" | "ucs2" | "ucs-2"; + type Encoding = BinaryToTextEncoding | CharacterEncoding | LegacyCharacterEncoding; + type ECDHKeyFormat = "compressed" | "uncompressed" | "hybrid"; + /** + * The `Hash` class is a utility for creating hash digests of data. It can be + * used in one of two ways: + * + * * As a `stream` that is both readable and writable, where data is written + * to produce a computed hash digest on the readable side, or + * * Using the `hash.update()` and `hash.digest()` methods to produce the + * computed hash. + * + * The {@link createHash} method is used to create `Hash` instances. `Hash`objects are not to be created directly using the `new` keyword. + * + * Example: Using `Hash` objects as streams: + * + * ```js + * const { + * createHash, + * } = await import('node:crypto'); + * + * const hash = createHash('sha256'); + * + * hash.on('readable', () => { + * // Only one element is going to be produced by the + * // hash stream. + * const data = hash.read(); + * if (data) { + * console.log(data.toString('hex')); + * // Prints: + * // 6a2da20943931e9834fc12cfe5bb47bbd9ae43489a30726962b576f4e3993e50 + * } + * }); + * + * hash.write('some data to hash'); + * hash.end(); + * ``` + * + * Example: Using `Hash` and piped streams: + * + * ```js + * import { createReadStream } from 'node:fs'; + * import { stdout } from 'node:process'; + * const { createHash } = await import('node:crypto'); + * + * const hash = createHash('sha256'); + * + * const input = createReadStream('test.js'); + * input.pipe(hash).setEncoding('hex').pipe(stdout); + * ``` + * + * Example: Using the `hash.update()` and `hash.digest()` methods: + * + * ```js + * const { + * createHash, + * } = await import('node:crypto'); + * + * const hash = createHash('sha256'); + * + * hash.update('some data to hash'); + * console.log(hash.digest('hex')); + * // Prints: + * // 6a2da20943931e9834fc12cfe5bb47bbd9ae43489a30726962b576f4e3993e50 + * ``` + * @since v0.1.92 + */ + class Hash extends stream.Transform { + private constructor(); + /** + * Creates a new `Hash` object that contains a deep copy of the internal state + * of the current `Hash` object. + * + * The optional `options` argument controls stream behavior. For XOF hash + * functions such as `'shake256'`, the `outputLength` option can be used to + * specify the desired output length in bytes. + * + * An error is thrown when an attempt is made to copy the `Hash` object after + * its `hash.digest()` method has been called. + * + * ```js + * // Calculate a rolling hash. + * const { + * createHash, + * } = await import('node:crypto'); + * + * const hash = createHash('sha256'); + * + * hash.update('one'); + * console.log(hash.copy().digest('hex')); + * + * hash.update('two'); + * console.log(hash.copy().digest('hex')); + * + * hash.update('three'); + * console.log(hash.copy().digest('hex')); + * + * // Etc. + * ``` + * @since v13.1.0 + * @param options `stream.transform` options + */ + copy(options?: HashOptions): Hash; + /** + * Updates the hash content with the given `data`, the encoding of which + * is given in `inputEncoding`. + * If `encoding` is not provided, and the `data` is a string, an + * encoding of `'utf8'` is enforced. If `data` is a `Buffer`, `TypedArray`, or`DataView`, then `inputEncoding` is ignored. + * + * This can be called many times with new data as it is streamed. + * @since v0.1.92 + * @param inputEncoding The `encoding` of the `data` string. + */ + update(data: BinaryLike): Hash; + update(data: string, inputEncoding: Encoding): Hash; + /** + * Calculates the digest of all of the data passed to be hashed (using the `hash.update()` method). + * If `encoding` is provided a string will be returned; otherwise + * a `Buffer` is returned. + * + * The `Hash` object can not be used again after `hash.digest()` method has been + * called. Multiple calls will cause an error to be thrown. + * @since v0.1.92 + * @param encoding The `encoding` of the return value. + */ + digest(): Buffer; + digest(encoding: BinaryToTextEncoding): string; + } + /** + * The `Hmac` class is a utility for creating cryptographic HMAC digests. It can + * be used in one of two ways: + * + * * As a `stream` that is both readable and writable, where data is written + * to produce a computed HMAC digest on the readable side, or + * * Using the `hmac.update()` and `hmac.digest()` methods to produce the + * computed HMAC digest. + * + * The {@link createHmac} method is used to create `Hmac` instances. `Hmac`objects are not to be created directly using the `new` keyword. + * + * Example: Using `Hmac` objects as streams: + * + * ```js + * const { + * createHmac, + * } = await import('node:crypto'); + * + * const hmac = createHmac('sha256', 'a secret'); + * + * hmac.on('readable', () => { + * // Only one element is going to be produced by the + * // hash stream. + * const data = hmac.read(); + * if (data) { + * console.log(data.toString('hex')); + * // Prints: + * // 7fd04df92f636fd450bc841c9418e5825c17f33ad9c87c518115a45971f7f77e + * } + * }); + * + * hmac.write('some data to hash'); + * hmac.end(); + * ``` + * + * Example: Using `Hmac` and piped streams: + * + * ```js + * import { createReadStream } from 'node:fs'; + * import { stdout } from 'node:process'; + * const { + * createHmac, + * } = await import('node:crypto'); + * + * const hmac = createHmac('sha256', 'a secret'); + * + * const input = createReadStream('test.js'); + * input.pipe(hmac).pipe(stdout); + * ``` + * + * Example: Using the `hmac.update()` and `hmac.digest()` methods: + * + * ```js + * const { + * createHmac, + * } = await import('node:crypto'); + * + * const hmac = createHmac('sha256', 'a secret'); + * + * hmac.update('some data to hash'); + * console.log(hmac.digest('hex')); + * // Prints: + * // 7fd04df92f636fd450bc841c9418e5825c17f33ad9c87c518115a45971f7f77e + * ``` + * @since v0.1.94 + * @deprecated Since v20.13.0 Calling `Hmac` class directly with `Hmac()` or `new Hmac()` is deprecated due to being internals, not intended for public use. Please use the {@link createHmac} method to create Hmac instances. + */ + class Hmac extends stream.Transform { + private constructor(); + /** + * Updates the `Hmac` content with the given `data`, the encoding of which + * is given in `inputEncoding`. + * If `encoding` is not provided, and the `data` is a string, an + * encoding of `'utf8'` is enforced. If `data` is a `Buffer`, `TypedArray`, or`DataView`, then `inputEncoding` is ignored. + * + * This can be called many times with new data as it is streamed. + * @since v0.1.94 + * @param inputEncoding The `encoding` of the `data` string. + */ + update(data: BinaryLike): Hmac; + update(data: string, inputEncoding: Encoding): Hmac; + /** + * Calculates the HMAC digest of all of the data passed using `hmac.update()`. + * If `encoding` is + * provided a string is returned; otherwise a `Buffer` is returned; + * + * The `Hmac` object can not be used again after `hmac.digest()` has been + * called. Multiple calls to `hmac.digest()` will result in an error being thrown. + * @since v0.1.94 + * @param encoding The `encoding` of the return value. + */ + digest(): Buffer; + digest(encoding: BinaryToTextEncoding): string; + } + type KeyObjectType = "secret" | "public" | "private"; + interface KeyExportOptions { + type: "pkcs1" | "spki" | "pkcs8" | "sec1"; + format: T; + cipher?: string | undefined; + passphrase?: string | Buffer | undefined; + } + interface JwkKeyExportOptions { + format: "jwk"; + } + interface JsonWebKey { + crv?: string | undefined; + d?: string | undefined; + dp?: string | undefined; + dq?: string | undefined; + e?: string | undefined; + k?: string | undefined; + kty?: string | undefined; + n?: string | undefined; + p?: string | undefined; + q?: string | undefined; + qi?: string | undefined; + x?: string | undefined; + y?: string | undefined; + [key: string]: unknown; + } + interface AsymmetricKeyDetails { + /** + * Key size in bits (RSA, DSA). + */ + modulusLength?: number | undefined; + /** + * Public exponent (RSA). + */ + publicExponent?: bigint | undefined; + /** + * Name of the message digest (RSA-PSS). + */ + hashAlgorithm?: string | undefined; + /** + * Name of the message digest used by MGF1 (RSA-PSS). + */ + mgf1HashAlgorithm?: string | undefined; + /** + * Minimal salt length in bytes (RSA-PSS). + */ + saltLength?: number | undefined; + /** + * Size of q in bits (DSA). + */ + divisorLength?: number | undefined; + /** + * Name of the curve (EC). + */ + namedCurve?: string | undefined; + } + /** + * Node.js uses a `KeyObject` class to represent a symmetric or asymmetric key, + * and each kind of key exposes different functions. The {@link createSecretKey}, {@link createPublicKey} and {@link createPrivateKey} methods are used to create `KeyObject`instances. `KeyObject` + * objects are not to be created directly using the `new`keyword. + * + * Most applications should consider using the new `KeyObject` API instead of + * passing keys as strings or `Buffer`s due to improved security features. + * + * `KeyObject` instances can be passed to other threads via `postMessage()`. + * The receiver obtains a cloned `KeyObject`, and the `KeyObject` does not need to + * be listed in the `transferList` argument. + * @since v11.6.0 + */ + class KeyObject { + private constructor(); + /** + * Example: Converting a `CryptoKey` instance to a `KeyObject`: + * + * ```js + * const { KeyObject } = await import('node:crypto'); + * const { subtle } = globalThis.crypto; + * + * const key = await subtle.generateKey({ + * name: 'HMAC', + * hash: 'SHA-256', + * length: 256, + * }, true, ['sign', 'verify']); + * + * const keyObject = KeyObject.from(key); + * console.log(keyObject.symmetricKeySize); + * // Prints: 32 (symmetric key size in bytes) + * ``` + * @since v15.0.0 + */ + static from(key: webcrypto.CryptoKey): KeyObject; + /** + * For asymmetric keys, this property represents the type of the key. Supported key + * types are: + * + * * `'rsa'` (OID 1.2.840.113549.1.1.1) + * * `'rsa-pss'` (OID 1.2.840.113549.1.1.10) + * * `'dsa'` (OID 1.2.840.10040.4.1) + * * `'ec'` (OID 1.2.840.10045.2.1) + * * `'x25519'` (OID 1.3.101.110) + * * `'x448'` (OID 1.3.101.111) + * * `'ed25519'` (OID 1.3.101.112) + * * `'ed448'` (OID 1.3.101.113) + * * `'dh'` (OID 1.2.840.113549.1.3.1) + * + * This property is `undefined` for unrecognized `KeyObject` types and symmetric + * keys. + * @since v11.6.0 + */ + asymmetricKeyType?: KeyType | undefined; + /** + * For asymmetric keys, this property represents the size of the embedded key in + * bytes. This property is `undefined` for symmetric keys. + */ + asymmetricKeySize?: number | undefined; + /** + * This property exists only on asymmetric keys. Depending on the type of the key, + * this object contains information about the key. None of the information obtained + * through this property can be used to uniquely identify a key or to compromise + * the security of the key. + * + * For RSA-PSS keys, if the key material contains a `RSASSA-PSS-params` sequence, + * the `hashAlgorithm`, `mgf1HashAlgorithm`, and `saltLength` properties will be + * set. + * + * Other key details might be exposed via this API using additional attributes. + * @since v15.7.0 + */ + asymmetricKeyDetails?: AsymmetricKeyDetails | undefined; + /** + * For symmetric keys, the following encoding options can be used: + * + * For public keys, the following encoding options can be used: + * + * For private keys, the following encoding options can be used: + * + * The result type depends on the selected encoding format, when PEM the + * result is a string, when DER it will be a buffer containing the data + * encoded as DER, when [JWK](https://tools.ietf.org/html/rfc7517) it will be an object. + * + * When [JWK](https://tools.ietf.org/html/rfc7517) encoding format was selected, all other encoding options are + * ignored. + * + * PKCS#1, SEC1, and PKCS#8 type keys can be encrypted by using a combination of + * the `cipher` and `format` options. The PKCS#8 `type` can be used with any`format` to encrypt any key algorithm (RSA, EC, or DH) by specifying a`cipher`. PKCS#1 and SEC1 can only be + * encrypted by specifying a `cipher`when the PEM `format` is used. For maximum compatibility, use PKCS#8 for + * encrypted private keys. Since PKCS#8 defines its own + * encryption mechanism, PEM-level encryption is not supported when encrypting + * a PKCS#8 key. See [RFC 5208](https://www.rfc-editor.org/rfc/rfc5208.txt) for PKCS#8 encryption and [RFC 1421](https://www.rfc-editor.org/rfc/rfc1421.txt) for + * PKCS#1 and SEC1 encryption. + * @since v11.6.0 + */ + export(options: KeyExportOptions<"pem">): string | Buffer; + export(options?: KeyExportOptions<"der">): Buffer; + export(options?: JwkKeyExportOptions): JsonWebKey; + /** + * Returns `true` or `false` depending on whether the keys have exactly the same + * type, value, and parameters. This method is not [constant time](https://en.wikipedia.org/wiki/Timing_attack). + * @since v17.7.0, v16.15.0 + * @param otherKeyObject A `KeyObject` with which to compare `keyObject`. + */ + equals(otherKeyObject: KeyObject): boolean; + /** + * For secret keys, this property represents the size of the key in bytes. This + * property is `undefined` for asymmetric keys. + * @since v11.6.0 + */ + symmetricKeySize?: number | undefined; + /** + * Depending on the type of this `KeyObject`, this property is either`'secret'` for secret (symmetric) keys, `'public'` for public (asymmetric) keys + * or `'private'` for private (asymmetric) keys. + * @since v11.6.0 + */ + type: KeyObjectType; + } + type CipherCCMTypes = "aes-128-ccm" | "aes-192-ccm" | "aes-256-ccm" | "chacha20-poly1305"; + type CipherGCMTypes = "aes-128-gcm" | "aes-192-gcm" | "aes-256-gcm"; + type CipherOCBTypes = "aes-128-ocb" | "aes-192-ocb" | "aes-256-ocb"; + type BinaryLike = string | NodeJS.ArrayBufferView; + type CipherKey = BinaryLike | KeyObject; + interface CipherCCMOptions extends stream.TransformOptions { + authTagLength: number; + } + interface CipherGCMOptions extends stream.TransformOptions { + authTagLength?: number | undefined; + } + interface CipherOCBOptions extends stream.TransformOptions { + authTagLength: number; + } + /** + * Creates and returns a `Cipher` object that uses the given `algorithm` and `password`. + * + * The `options` argument controls stream behavior and is optional except when a + * cipher in CCM or OCB mode (e.g. `'aes-128-ccm'`) is used. In that case, the`authTagLength` option is required and specifies the length of the + * authentication tag in bytes, see `CCM mode`. In GCM mode, the `authTagLength`option is not required but can be used to set the length of the authentication + * tag that will be returned by `getAuthTag()` and defaults to 16 bytes. + * For `chacha20-poly1305`, the `authTagLength` option defaults to 16 bytes. + * + * The `algorithm` is dependent on OpenSSL, examples are `'aes192'`, etc. On + * recent OpenSSL releases, `openssl list -cipher-algorithms` will + * display the available cipher algorithms. + * + * The `password` is used to derive the cipher key and initialization vector (IV). + * The value must be either a `'latin1'` encoded string, a `Buffer`, a`TypedArray`, or a `DataView`. + * + * **This function is semantically insecure for all** + * **supported ciphers and fatally flawed for ciphers in counter mode (such as CTR,** + * **GCM, or CCM).** + * + * The implementation of `crypto.createCipher()` derives keys using the OpenSSL + * function [`EVP_BytesToKey`](https://www.openssl.org/docs/man3.0/man3/EVP_BytesToKey.html) with the digest algorithm set to MD5, one + * iteration, and no salt. The lack of salt allows dictionary attacks as the same + * password always creates the same key. The low iteration count and + * non-cryptographically secure hash algorithm allow passwords to be tested very + * rapidly. + * + * In line with OpenSSL's recommendation to use a more modern algorithm instead of [`EVP_BytesToKey`](https://www.openssl.org/docs/man3.0/man3/EVP_BytesToKey.html) it is recommended that + * developers derive a key and IV on + * their own using {@link scrypt} and to use {@link createCipheriv} to create the `Cipher` object. Users should not use ciphers with counter mode + * (e.g. CTR, GCM, or CCM) in `crypto.createCipher()`. A warning is emitted when + * they are used in order to avoid the risk of IV reuse that causes + * vulnerabilities. For the case when IV is reused in GCM, see [Nonce-Disrespecting Adversaries](https://github.com/nonce-disrespect/nonce-disrespect) for details. + * @since v0.1.94 + * @deprecated Since v10.0.0 - Use {@link createCipheriv} instead. + * @param options `stream.transform` options + */ + function createCipher(algorithm: CipherCCMTypes, password: BinaryLike, options: CipherCCMOptions): CipherCCM; + /** @deprecated since v10.0.0 use `createCipheriv()` */ + function createCipher(algorithm: CipherGCMTypes, password: BinaryLike, options?: CipherGCMOptions): CipherGCM; + /** @deprecated since v10.0.0 use `createCipheriv()` */ + function createCipher(algorithm: string, password: BinaryLike, options?: stream.TransformOptions): Cipher; + /** + * Creates and returns a `Cipher` object, with the given `algorithm`, `key` and + * initialization vector (`iv`). + * + * The `options` argument controls stream behavior and is optional except when a + * cipher in CCM or OCB mode (e.g. `'aes-128-ccm'`) is used. In that case, the`authTagLength` option is required and specifies the length of the + * authentication tag in bytes, see `CCM mode`. In GCM mode, the `authTagLength`option is not required but can be used to set the length of the authentication + * tag that will be returned by `getAuthTag()` and defaults to 16 bytes. + * For `chacha20-poly1305`, the `authTagLength` option defaults to 16 bytes. + * + * The `algorithm` is dependent on OpenSSL, examples are `'aes192'`, etc. On + * recent OpenSSL releases, `openssl list -cipher-algorithms` will + * display the available cipher algorithms. + * + * The `key` is the raw key used by the `algorithm` and `iv` is an [initialization vector](https://en.wikipedia.org/wiki/Initialization_vector). Both arguments must be `'utf8'` encoded + * strings,`Buffers`, `TypedArray`, or `DataView`s. The `key` may optionally be + * a `KeyObject` of type `secret`. If the cipher does not need + * an initialization vector, `iv` may be `null`. + * + * When passing strings for `key` or `iv`, please consider `caveats when using strings as inputs to cryptographic APIs`. + * + * Initialization vectors should be unpredictable and unique; ideally, they will be + * cryptographically random. They do not have to be secret: IVs are typically just + * added to ciphertext messages unencrypted. It may sound contradictory that + * something has to be unpredictable and unique, but does not have to be secret; + * remember that an attacker must not be able to predict ahead of time what a + * given IV will be. + * @since v0.1.94 + * @param options `stream.transform` options + */ + function createCipheriv( + algorithm: CipherCCMTypes, + key: CipherKey, + iv: BinaryLike, + options: CipherCCMOptions, + ): CipherCCM; + function createCipheriv( + algorithm: CipherOCBTypes, + key: CipherKey, + iv: BinaryLike, + options: CipherOCBOptions, + ): CipherOCB; + function createCipheriv( + algorithm: CipherGCMTypes, + key: CipherKey, + iv: BinaryLike, + options?: CipherGCMOptions, + ): CipherGCM; + function createCipheriv( + algorithm: string, + key: CipherKey, + iv: BinaryLike | null, + options?: stream.TransformOptions, + ): Cipher; + /** + * Instances of the `Cipher` class are used to encrypt data. The class can be + * used in one of two ways: + * + * * As a `stream` that is both readable and writable, where plain unencrypted + * data is written to produce encrypted data on the readable side, or + * * Using the `cipher.update()` and `cipher.final()` methods to produce + * the encrypted data. + * + * The {@link createCipher} or {@link createCipheriv} methods are + * used to create `Cipher` instances. `Cipher` objects are not to be created + * directly using the `new` keyword. + * + * Example: Using `Cipher` objects as streams: + * + * ```js + * const { + * scrypt, + * randomFill, + * createCipheriv, + * } = await import('node:crypto'); + * + * const algorithm = 'aes-192-cbc'; + * const password = 'Password used to generate key'; + * + * // First, we'll generate the key. The key length is dependent on the algorithm. + * // In this case for aes192, it is 24 bytes (192 bits). + * scrypt(password, 'salt', 24, (err, key) => { + * if (err) throw err; + * // Then, we'll generate a random initialization vector + * randomFill(new Uint8Array(16), (err, iv) => { + * if (err) throw err; + * + * // Once we have the key and iv, we can create and use the cipher... + * const cipher = createCipheriv(algorithm, key, iv); + * + * let encrypted = ''; + * cipher.setEncoding('hex'); + * + * cipher.on('data', (chunk) => encrypted += chunk); + * cipher.on('end', () => console.log(encrypted)); + * + * cipher.write('some clear text data'); + * cipher.end(); + * }); + * }); + * ``` + * + * Example: Using `Cipher` and piped streams: + * + * ```js + * import { + * createReadStream, + * createWriteStream, + * } from 'node:fs'; + * + * import { + * pipeline, + * } from 'node:stream'; + * + * const { + * scrypt, + * randomFill, + * createCipheriv, + * } = await import('node:crypto'); + * + * const algorithm = 'aes-192-cbc'; + * const password = 'Password used to generate key'; + * + * // First, we'll generate the key. The key length is dependent on the algorithm. + * // In this case for aes192, it is 24 bytes (192 bits). + * scrypt(password, 'salt', 24, (err, key) => { + * if (err) throw err; + * // Then, we'll generate a random initialization vector + * randomFill(new Uint8Array(16), (err, iv) => { + * if (err) throw err; + * + * const cipher = createCipheriv(algorithm, key, iv); + * + * const input = createReadStream('test.js'); + * const output = createWriteStream('test.enc'); + * + * pipeline(input, cipher, output, (err) => { + * if (err) throw err; + * }); + * }); + * }); + * ``` + * + * Example: Using the `cipher.update()` and `cipher.final()` methods: + * + * ```js + * const { + * scrypt, + * randomFill, + * createCipheriv, + * } = await import('node:crypto'); + * + * const algorithm = 'aes-192-cbc'; + * const password = 'Password used to generate key'; + * + * // First, we'll generate the key. The key length is dependent on the algorithm. + * // In this case for aes192, it is 24 bytes (192 bits). + * scrypt(password, 'salt', 24, (err, key) => { + * if (err) throw err; + * // Then, we'll generate a random initialization vector + * randomFill(new Uint8Array(16), (err, iv) => { + * if (err) throw err; + * + * const cipher = createCipheriv(algorithm, key, iv); + * + * let encrypted = cipher.update('some clear text data', 'utf8', 'hex'); + * encrypted += cipher.final('hex'); + * console.log(encrypted); + * }); + * }); + * ``` + * @since v0.1.94 + */ + class Cipher extends stream.Transform { + private constructor(); + /** + * Updates the cipher with `data`. If the `inputEncoding` argument is given, + * the `data`argument is a string using the specified encoding. If the `inputEncoding`argument is not given, `data` must be a `Buffer`, `TypedArray`, or `DataView`. If `data` is a `Buffer`, + * `TypedArray`, or `DataView`, then `inputEncoding` is ignored. + * + * The `outputEncoding` specifies the output format of the enciphered + * data. If the `outputEncoding`is specified, a string using the specified encoding is returned. If no`outputEncoding` is provided, a `Buffer` is returned. + * + * The `cipher.update()` method can be called multiple times with new data until `cipher.final()` is called. Calling `cipher.update()` after `cipher.final()` will result in an error being + * thrown. + * @since v0.1.94 + * @param inputEncoding The `encoding` of the data. + * @param outputEncoding The `encoding` of the return value. + */ + update(data: BinaryLike): Buffer; + update(data: string, inputEncoding: Encoding): Buffer; + update(data: NodeJS.ArrayBufferView, inputEncoding: undefined, outputEncoding: Encoding): string; + update(data: string, inputEncoding: Encoding | undefined, outputEncoding: Encoding): string; + /** + * Once the `cipher.final()` method has been called, the `Cipher` object can no + * longer be used to encrypt data. Attempts to call `cipher.final()` more than + * once will result in an error being thrown. + * @since v0.1.94 + * @param outputEncoding The `encoding` of the return value. + * @return Any remaining enciphered contents. If `outputEncoding` is specified, a string is returned. If an `outputEncoding` is not provided, a {@link Buffer} is returned. + */ + final(): Buffer; + final(outputEncoding: BufferEncoding): string; + /** + * When using block encryption algorithms, the `Cipher` class will automatically + * add padding to the input data to the appropriate block size. To disable the + * default padding call `cipher.setAutoPadding(false)`. + * + * When `autoPadding` is `false`, the length of the entire input data must be a + * multiple of the cipher's block size or `cipher.final()` will throw an error. + * Disabling automatic padding is useful for non-standard padding, for instance + * using `0x0` instead of PKCS padding. + * + * The `cipher.setAutoPadding()` method must be called before `cipher.final()`. + * @since v0.7.1 + * @param [autoPadding=true] + * @return for method chaining. + */ + setAutoPadding(autoPadding?: boolean): this; + } + interface CipherCCM extends Cipher { + setAAD( + buffer: NodeJS.ArrayBufferView, + options: { + plaintextLength: number; + }, + ): this; + getAuthTag(): Buffer; + } + interface CipherGCM extends Cipher { + setAAD( + buffer: NodeJS.ArrayBufferView, + options?: { + plaintextLength: number; + }, + ): this; + getAuthTag(): Buffer; + } + interface CipherOCB extends Cipher { + setAAD( + buffer: NodeJS.ArrayBufferView, + options?: { + plaintextLength: number; + }, + ): this; + getAuthTag(): Buffer; + } + /** + * Creates and returns a `Decipher` object that uses the given `algorithm` and `password` (key). + * + * The `options` argument controls stream behavior and is optional except when a + * cipher in CCM or OCB mode (e.g. `'aes-128-ccm'`) is used. In that case, the `authTagLength` option is required and specifies the length of the + * authentication tag in bytes, see `CCM mode`. + * For `chacha20-poly1305`, the `authTagLength` option defaults to 16 bytes. + * + * **This function is semantically insecure for all** + * **supported ciphers and fatally flawed for ciphers in counter mode (such as CTR,** + * **GCM, or CCM).** + * + * The implementation of `crypto.createDecipher()` derives keys using the OpenSSL + * function [`EVP_BytesToKey`](https://www.openssl.org/docs/man3.0/man3/EVP_BytesToKey.html) with the digest algorithm set to MD5, one + * iteration, and no salt. The lack of salt allows dictionary attacks as the same + * password always creates the same key. The low iteration count and + * non-cryptographically secure hash algorithm allow passwords to be tested very + * rapidly. + * + * In line with OpenSSL's recommendation to use a more modern algorithm instead of [`EVP_BytesToKey`](https://www.openssl.org/docs/man3.0/man3/EVP_BytesToKey.html) it is recommended that + * developers derive a key and IV on + * their own using {@link scrypt} and to use {@link createDecipheriv} to create the `Decipher` object. + * @since v0.1.94 + * @deprecated Since v10.0.0 - Use {@link createDecipheriv} instead. + * @param options `stream.transform` options + */ + function createDecipher(algorithm: CipherCCMTypes, password: BinaryLike, options: CipherCCMOptions): DecipherCCM; + /** @deprecated since v10.0.0 use `createDecipheriv()` */ + function createDecipher(algorithm: CipherGCMTypes, password: BinaryLike, options?: CipherGCMOptions): DecipherGCM; + /** @deprecated since v10.0.0 use `createDecipheriv()` */ + function createDecipher(algorithm: string, password: BinaryLike, options?: stream.TransformOptions): Decipher; + /** + * Creates and returns a `Decipher` object that uses the given `algorithm`, `key` and initialization vector (`iv`). + * + * The `options` argument controls stream behavior and is optional except when a + * cipher in CCM or OCB mode (e.g. `'aes-128-ccm'`) is used. In that case, the `authTagLength` option is required and specifies the length of the + * authentication tag in bytes, see `CCM mode`. In GCM mode, the `authTagLength` option is not required but can be used to restrict accepted authentication tags + * to those with the specified length. + * For `chacha20-poly1305`, the `authTagLength` option defaults to 16 bytes. + * + * The `algorithm` is dependent on OpenSSL, examples are `'aes192'`, etc. On + * recent OpenSSL releases, `openssl list -cipher-algorithms` will + * display the available cipher algorithms. + * + * The `key` is the raw key used by the `algorithm` and `iv` is an [initialization vector](https://en.wikipedia.org/wiki/Initialization_vector). Both arguments must be `'utf8'` encoded + * strings,`Buffers`, `TypedArray`, or `DataView`s. The `key` may optionally be + * a `KeyObject` of type `secret`. If the cipher does not need + * an initialization vector, `iv` may be `null`. + * + * When passing strings for `key` or `iv`, please consider `caveats when using strings as inputs to cryptographic APIs`. + * + * Initialization vectors should be unpredictable and unique; ideally, they will be + * cryptographically random. They do not have to be secret: IVs are typically just + * added to ciphertext messages unencrypted. It may sound contradictory that + * something has to be unpredictable and unique, but does not have to be secret; + * remember that an attacker must not be able to predict ahead of time what a given + * IV will be. + * @since v0.1.94 + * @param options `stream.transform` options + */ + function createDecipheriv( + algorithm: CipherCCMTypes, + key: CipherKey, + iv: BinaryLike, + options: CipherCCMOptions, + ): DecipherCCM; + function createDecipheriv( + algorithm: CipherOCBTypes, + key: CipherKey, + iv: BinaryLike, + options: CipherOCBOptions, + ): DecipherOCB; + function createDecipheriv( + algorithm: CipherGCMTypes, + key: CipherKey, + iv: BinaryLike, + options?: CipherGCMOptions, + ): DecipherGCM; + function createDecipheriv( + algorithm: string, + key: CipherKey, + iv: BinaryLike | null, + options?: stream.TransformOptions, + ): Decipher; + /** + * Instances of the `Decipher` class are used to decrypt data. The class can be + * used in one of two ways: + * + * * As a `stream` that is both readable and writable, where plain encrypted + * data is written to produce unencrypted data on the readable side, or + * * Using the `decipher.update()` and `decipher.final()` methods to + * produce the unencrypted data. + * + * The {@link createDecipher} or {@link createDecipheriv} methods are + * used to create `Decipher` instances. `Decipher` objects are not to be created + * directly using the `new` keyword. + * + * Example: Using `Decipher` objects as streams: + * + * ```js + * import { Buffer } from 'node:buffer'; + * const { + * scryptSync, + * createDecipheriv, + * } = await import('node:crypto'); + * + * const algorithm = 'aes-192-cbc'; + * const password = 'Password used to generate key'; + * // Key length is dependent on the algorithm. In this case for aes192, it is + * // 24 bytes (192 bits). + * // Use the async `crypto.scrypt()` instead. + * const key = scryptSync(password, 'salt', 24); + * // The IV is usually passed along with the ciphertext. + * const iv = Buffer.alloc(16, 0); // Initialization vector. + * + * const decipher = createDecipheriv(algorithm, key, iv); + * + * let decrypted = ''; + * decipher.on('readable', () => { + * let chunk; + * while (null !== (chunk = decipher.read())) { + * decrypted += chunk.toString('utf8'); + * } + * }); + * decipher.on('end', () => { + * console.log(decrypted); + * // Prints: some clear text data + * }); + * + * // Encrypted with same algorithm, key and iv. + * const encrypted = + * 'e5f79c5915c02171eec6b212d5520d44480993d7d622a7c4c2da32f6efda0ffa'; + * decipher.write(encrypted, 'hex'); + * decipher.end(); + * ``` + * + * Example: Using `Decipher` and piped streams: + * + * ```js + * import { + * createReadStream, + * createWriteStream, + * } from 'node:fs'; + * import { Buffer } from 'node:buffer'; + * const { + * scryptSync, + * createDecipheriv, + * } = await import('node:crypto'); + * + * const algorithm = 'aes-192-cbc'; + * const password = 'Password used to generate key'; + * // Use the async `crypto.scrypt()` instead. + * const key = scryptSync(password, 'salt', 24); + * // The IV is usually passed along with the ciphertext. + * const iv = Buffer.alloc(16, 0); // Initialization vector. + * + * const decipher = createDecipheriv(algorithm, key, iv); + * + * const input = createReadStream('test.enc'); + * const output = createWriteStream('test.js'); + * + * input.pipe(decipher).pipe(output); + * ``` + * + * Example: Using the `decipher.update()` and `decipher.final()` methods: + * + * ```js + * import { Buffer } from 'node:buffer'; + * const { + * scryptSync, + * createDecipheriv, + * } = await import('node:crypto'); + * + * const algorithm = 'aes-192-cbc'; + * const password = 'Password used to generate key'; + * // Use the async `crypto.scrypt()` instead. + * const key = scryptSync(password, 'salt', 24); + * // The IV is usually passed along with the ciphertext. + * const iv = Buffer.alloc(16, 0); // Initialization vector. + * + * const decipher = createDecipheriv(algorithm, key, iv); + * + * // Encrypted using same algorithm, key and iv. + * const encrypted = + * 'e5f79c5915c02171eec6b212d5520d44480993d7d622a7c4c2da32f6efda0ffa'; + * let decrypted = decipher.update(encrypted, 'hex', 'utf8'); + * decrypted += decipher.final('utf8'); + * console.log(decrypted); + * // Prints: some clear text data + * ``` + * @since v0.1.94 + */ + class Decipher extends stream.Transform { + private constructor(); + /** + * Updates the decipher with `data`. If the `inputEncoding` argument is given, + * the `data` argument is a string using the specified encoding. If the `inputEncoding` argument is not given, `data` must be a `Buffer`. If `data` is a `Buffer` then `inputEncoding` is + * ignored. + * + * The `outputEncoding` specifies the output format of the enciphered + * data. If the `outputEncoding` is specified, a string using the specified encoding is returned. If no `outputEncoding` is provided, a `Buffer` is returned. + * + * The `decipher.update()` method can be called multiple times with new data until `decipher.final()` is called. Calling `decipher.update()` after `decipher.final()` will result in an error + * being thrown. + * @since v0.1.94 + * @param inputEncoding The `encoding` of the `data` string. + * @param outputEncoding The `encoding` of the return value. + */ + update(data: NodeJS.ArrayBufferView): Buffer; + update(data: string, inputEncoding: Encoding): Buffer; + update(data: NodeJS.ArrayBufferView, inputEncoding: undefined, outputEncoding: Encoding): string; + update(data: string, inputEncoding: Encoding | undefined, outputEncoding: Encoding): string; + /** + * Once the `decipher.final()` method has been called, the `Decipher` object can + * no longer be used to decrypt data. Attempts to call `decipher.final()` more + * than once will result in an error being thrown. + * @since v0.1.94 + * @param outputEncoding The `encoding` of the return value. + * @return Any remaining deciphered contents. If `outputEncoding` is specified, a string is returned. If an `outputEncoding` is not provided, a {@link Buffer} is returned. + */ + final(): Buffer; + final(outputEncoding: BufferEncoding): string; + /** + * When data has been encrypted without standard block padding, calling `decipher.setAutoPadding(false)` will disable automatic padding to prevent `decipher.final()` from checking for and + * removing padding. + * + * Turning auto padding off will only work if the input data's length is a + * multiple of the ciphers block size. + * + * The `decipher.setAutoPadding()` method must be called before `decipher.final()`. + * @since v0.7.1 + * @param [autoPadding=true] + * @return for method chaining. + */ + setAutoPadding(auto_padding?: boolean): this; + } + interface DecipherCCM extends Decipher { + setAuthTag(buffer: NodeJS.ArrayBufferView): this; + setAAD( + buffer: NodeJS.ArrayBufferView, + options: { + plaintextLength: number; + }, + ): this; + } + interface DecipherGCM extends Decipher { + setAuthTag(buffer: NodeJS.ArrayBufferView): this; + setAAD( + buffer: NodeJS.ArrayBufferView, + options?: { + plaintextLength: number; + }, + ): this; + } + interface DecipherOCB extends Decipher { + setAuthTag(buffer: NodeJS.ArrayBufferView): this; + setAAD( + buffer: NodeJS.ArrayBufferView, + options?: { + plaintextLength: number; + }, + ): this; + } + interface PrivateKeyInput { + key: string | Buffer; + format?: KeyFormat | undefined; + type?: "pkcs1" | "pkcs8" | "sec1" | undefined; + passphrase?: string | Buffer | undefined; + encoding?: string | undefined; + } + interface PublicKeyInput { + key: string | Buffer; + format?: KeyFormat | undefined; + type?: "pkcs1" | "spki" | undefined; + encoding?: string | undefined; + } + /** + * Asynchronously generates a new random secret key of the given `length`. The `type` will determine which validations will be performed on the `length`. + * + * ```js + * const { + * generateKey, + * } = await import('node:crypto'); + * + * generateKey('hmac', { length: 512 }, (err, key) => { + * if (err) throw err; + * console.log(key.export().toString('hex')); // 46e..........620 + * }); + * ``` + * + * The size of a generated HMAC key should not exceed the block size of the + * underlying hash function. See {@link createHmac} for more information. + * @since v15.0.0 + * @param type The intended use of the generated secret key. Currently accepted values are `'hmac'` and `'aes'`. + */ + function generateKey( + type: "hmac" | "aes", + options: { + length: number; + }, + callback: (err: Error | null, key: KeyObject) => void, + ): void; + /** + * Synchronously generates a new random secret key of the given `length`. The `type` will determine which validations will be performed on the `length`. + * + * ```js + * const { + * generateKeySync, + * } = await import('node:crypto'); + * + * const key = generateKeySync('hmac', { length: 512 }); + * console.log(key.export().toString('hex')); // e89..........41e + * ``` + * + * The size of a generated HMAC key should not exceed the block size of the + * underlying hash function. See {@link createHmac} for more information. + * @since v15.0.0 + * @param type The intended use of the generated secret key. Currently accepted values are `'hmac'` and `'aes'`. + */ + function generateKeySync( + type: "hmac" | "aes", + options: { + length: number; + }, + ): KeyObject; + interface JsonWebKeyInput { + key: JsonWebKey; + format: "jwk"; + } + /** + * Creates and returns a new key object containing a private key. If `key` is a + * string or `Buffer`, `format` is assumed to be `'pem'`; otherwise, `key` must be an object with the properties described above. + * + * If the private key is encrypted, a `passphrase` must be specified. The length + * of the passphrase is limited to 1024 bytes. + * @since v11.6.0 + */ + function createPrivateKey(key: PrivateKeyInput | string | Buffer | JsonWebKeyInput): KeyObject; + /** + * Creates and returns a new key object containing a public key. If `key` is a + * string or `Buffer`, `format` is assumed to be `'pem'`; if `key` is a `KeyObject` with type `'private'`, the public key is derived from the given private key; + * otherwise, `key` must be an object with the properties described above. + * + * If the format is `'pem'`, the `'key'` may also be an X.509 certificate. + * + * Because public keys can be derived from private keys, a private key may be + * passed instead of a public key. In that case, this function behaves as if {@link createPrivateKey} had been called, except that the type of the + * returned `KeyObject` will be `'public'` and that the private key cannot be + * extracted from the returned `KeyObject`. Similarly, if a `KeyObject` with type `'private'` is given, a new `KeyObject` with type `'public'` will be returned + * and it will be impossible to extract the private key from the returned object. + * @since v11.6.0 + */ + function createPublicKey(key: PublicKeyInput | string | Buffer | KeyObject | JsonWebKeyInput): KeyObject; + /** + * Creates and returns a new key object containing a secret key for symmetric + * encryption or `Hmac`. + * @since v11.6.0 + * @param encoding The string encoding when `key` is a string. + */ + function createSecretKey(key: NodeJS.ArrayBufferView): KeyObject; + function createSecretKey(key: string, encoding: BufferEncoding): KeyObject; + /** + * Creates and returns a `Sign` object that uses the given `algorithm`. Use {@link getHashes} to obtain the names of the available digest algorithms. + * Optional `options` argument controls the `stream.Writable` behavior. + * + * In some cases, a `Sign` instance can be created using the name of a signature + * algorithm, such as `'RSA-SHA256'`, instead of a digest algorithm. This will use + * the corresponding digest algorithm. This does not work for all signature + * algorithms, such as `'ecdsa-with-SHA256'`, so it is best to always use digest + * algorithm names. + * @since v0.1.92 + * @param options `stream.Writable` options + */ + function createSign(algorithm: string, options?: stream.WritableOptions): Sign; + type DSAEncoding = "der" | "ieee-p1363"; + interface SigningOptions { + /** + * @see crypto.constants.RSA_PKCS1_PADDING + */ + padding?: number | undefined; + saltLength?: number | undefined; + dsaEncoding?: DSAEncoding | undefined; + } + interface SignPrivateKeyInput extends PrivateKeyInput, SigningOptions {} + interface SignKeyObjectInput extends SigningOptions { + key: KeyObject; + } + interface VerifyPublicKeyInput extends PublicKeyInput, SigningOptions {} + interface VerifyKeyObjectInput extends SigningOptions { + key: KeyObject; + } + interface VerifyJsonWebKeyInput extends JsonWebKeyInput, SigningOptions {} + type KeyLike = string | Buffer | KeyObject; + /** + * The `Sign` class is a utility for generating signatures. It can be used in one + * of two ways: + * + * * As a writable `stream`, where data to be signed is written and the `sign.sign()` method is used to generate and return the signature, or + * * Using the `sign.update()` and `sign.sign()` methods to produce the + * signature. + * + * The {@link createSign} method is used to create `Sign` instances. The + * argument is the string name of the hash function to use. `Sign` objects are not + * to be created directly using the `new` keyword. + * + * Example: Using `Sign` and `Verify` objects as streams: + * + * ```js + * const { + * generateKeyPairSync, + * createSign, + * createVerify, + * } = await import('node:crypto'); + * + * const { privateKey, publicKey } = generateKeyPairSync('ec', { + * namedCurve: 'sect239k1', + * }); + * + * const sign = createSign('SHA256'); + * sign.write('some data to sign'); + * sign.end(); + * const signature = sign.sign(privateKey, 'hex'); + * + * const verify = createVerify('SHA256'); + * verify.write('some data to sign'); + * verify.end(); + * console.log(verify.verify(publicKey, signature, 'hex')); + * // Prints: true + * ``` + * + * Example: Using the `sign.update()` and `verify.update()` methods: + * + * ```js + * const { + * generateKeyPairSync, + * createSign, + * createVerify, + * } = await import('node:crypto'); + * + * const { privateKey, publicKey } = generateKeyPairSync('rsa', { + * modulusLength: 2048, + * }); + * + * const sign = createSign('SHA256'); + * sign.update('some data to sign'); + * sign.end(); + * const signature = sign.sign(privateKey); + * + * const verify = createVerify('SHA256'); + * verify.update('some data to sign'); + * verify.end(); + * console.log(verify.verify(publicKey, signature)); + * // Prints: true + * ``` + * @since v0.1.92 + */ + class Sign extends stream.Writable { + private constructor(); + /** + * Updates the `Sign` content with the given `data`, the encoding of which + * is given in `inputEncoding`. + * If `encoding` is not provided, and the `data` is a string, an + * encoding of `'utf8'` is enforced. If `data` is a `Buffer`, `TypedArray`, or`DataView`, then `inputEncoding` is ignored. + * + * This can be called many times with new data as it is streamed. + * @since v0.1.92 + * @param inputEncoding The `encoding` of the `data` string. + */ + update(data: BinaryLike): this; + update(data: string, inputEncoding: Encoding): this; + /** + * Calculates the signature on all the data passed through using either `sign.update()` or `sign.write()`. + * + * If `privateKey` is not a `KeyObject`, this function behaves as if `privateKey` had been passed to {@link createPrivateKey}. If it is an + * object, the following additional properties can be passed: + * + * If `outputEncoding` is provided a string is returned; otherwise a `Buffer` is returned. + * + * The `Sign` object can not be again used after `sign.sign()` method has been + * called. Multiple calls to `sign.sign()` will result in an error being thrown. + * @since v0.1.92 + */ + sign(privateKey: KeyLike | SignKeyObjectInput | SignPrivateKeyInput): Buffer; + sign( + privateKey: KeyLike | SignKeyObjectInput | SignPrivateKeyInput, + outputFormat: BinaryToTextEncoding, + ): string; + } + /** + * Creates and returns a `Verify` object that uses the given algorithm. + * Use {@link getHashes} to obtain an array of names of the available + * signing algorithms. Optional `options` argument controls the `stream.Writable` behavior. + * + * In some cases, a `Verify` instance can be created using the name of a signature + * algorithm, such as `'RSA-SHA256'`, instead of a digest algorithm. This will use + * the corresponding digest algorithm. This does not work for all signature + * algorithms, such as `'ecdsa-with-SHA256'`, so it is best to always use digest + * algorithm names. + * @since v0.1.92 + * @param options `stream.Writable` options + */ + function createVerify(algorithm: string, options?: stream.WritableOptions): Verify; + /** + * The `Verify` class is a utility for verifying signatures. It can be used in one + * of two ways: + * + * * As a writable `stream` where written data is used to validate against the + * supplied signature, or + * * Using the `verify.update()` and `verify.verify()` methods to verify + * the signature. + * + * The {@link createVerify} method is used to create `Verify` instances. `Verify` objects are not to be created directly using the `new` keyword. + * + * See `Sign` for examples. + * @since v0.1.92 + */ + class Verify extends stream.Writable { + private constructor(); + /** + * Updates the `Verify` content with the given `data`, the encoding of which + * is given in `inputEncoding`. + * If `inputEncoding` is not provided, and the `data` is a string, an + * encoding of `'utf8'` is enforced. If `data` is a `Buffer`, `TypedArray`, or `DataView`, then `inputEncoding` is ignored. + * + * This can be called many times with new data as it is streamed. + * @since v0.1.92 + * @param inputEncoding The `encoding` of the `data` string. + */ + update(data: BinaryLike): Verify; + update(data: string, inputEncoding: Encoding): Verify; + /** + * Verifies the provided data using the given `object` and `signature`. + * + * If `object` is not a `KeyObject`, this function behaves as if `object` had been passed to {@link createPublicKey}. If it is an + * object, the following additional properties can be passed: + * + * The `signature` argument is the previously calculated signature for the data, in + * the `signatureEncoding`. + * If a `signatureEncoding` is specified, the `signature` is expected to be a + * string; otherwise `signature` is expected to be a `Buffer`, `TypedArray`, or `DataView`. + * + * The `verify` object can not be used again after `verify.verify()` has been + * called. Multiple calls to `verify.verify()` will result in an error being + * thrown. + * + * Because public keys can be derived from private keys, a private key may + * be passed instead of a public key. + * @since v0.1.92 + */ + verify( + object: KeyLike | VerifyKeyObjectInput | VerifyPublicKeyInput | VerifyJsonWebKeyInput, + signature: NodeJS.ArrayBufferView, + ): boolean; + verify( + object: KeyLike | VerifyKeyObjectInput | VerifyPublicKeyInput | VerifyJsonWebKeyInput, + signature: string, + signature_format?: BinaryToTextEncoding, + ): boolean; + } + /** + * Creates a `DiffieHellman` key exchange object using the supplied `prime` and an + * optional specific `generator`. + * + * The `generator` argument can be a number, string, or `Buffer`. If `generator` is not specified, the value `2` is used. + * + * If `primeEncoding` is specified, `prime` is expected to be a string; otherwise + * a `Buffer`, `TypedArray`, or `DataView` is expected. + * + * If `generatorEncoding` is specified, `generator` is expected to be a string; + * otherwise a number, `Buffer`, `TypedArray`, or `DataView` is expected. + * @since v0.11.12 + * @param primeEncoding The `encoding` of the `prime` string. + * @param [generator=2] + * @param generatorEncoding The `encoding` of the `generator` string. + */ + function createDiffieHellman(primeLength: number, generator?: number): DiffieHellman; + function createDiffieHellman( + prime: ArrayBuffer | NodeJS.ArrayBufferView, + generator?: number | ArrayBuffer | NodeJS.ArrayBufferView, + ): DiffieHellman; + function createDiffieHellman( + prime: ArrayBuffer | NodeJS.ArrayBufferView, + generator: string, + generatorEncoding: BinaryToTextEncoding, + ): DiffieHellman; + function createDiffieHellman( + prime: string, + primeEncoding: BinaryToTextEncoding, + generator?: number | ArrayBuffer | NodeJS.ArrayBufferView, + ): DiffieHellman; + function createDiffieHellman( + prime: string, + primeEncoding: BinaryToTextEncoding, + generator: string, + generatorEncoding: BinaryToTextEncoding, + ): DiffieHellman; + /** + * The `DiffieHellman` class is a utility for creating Diffie-Hellman key + * exchanges. + * + * Instances of the `DiffieHellman` class can be created using the {@link createDiffieHellman} function. + * + * ```js + * import assert from 'node:assert'; + * + * const { + * createDiffieHellman, + * } = await import('node:crypto'); + * + * // Generate Alice's keys... + * const alice = createDiffieHellman(2048); + * const aliceKey = alice.generateKeys(); + * + * // Generate Bob's keys... + * const bob = createDiffieHellman(alice.getPrime(), alice.getGenerator()); + * const bobKey = bob.generateKeys(); + * + * // Exchange and generate the secret... + * const aliceSecret = alice.computeSecret(bobKey); + * const bobSecret = bob.computeSecret(aliceKey); + * + * // OK + * assert.strictEqual(aliceSecret.toString('hex'), bobSecret.toString('hex')); + * ``` + * @since v0.5.0 + */ + class DiffieHellman { + private constructor(); + /** + * Generates private and public Diffie-Hellman key values unless they have been + * generated or computed already, and returns + * the public key in the specified `encoding`. This key should be + * transferred to the other party. + * If `encoding` is provided a string is returned; otherwise a `Buffer` is returned. + * + * This function is a thin wrapper around [`DH_generate_key()`](https://www.openssl.org/docs/man3.0/man3/DH_generate_key.html). In particular, + * once a private key has been generated or set, calling this function only updates + * the public key but does not generate a new private key. + * @since v0.5.0 + * @param encoding The `encoding` of the return value. + */ + generateKeys(): Buffer; + generateKeys(encoding: BinaryToTextEncoding): string; + /** + * Computes the shared secret using `otherPublicKey` as the other + * party's public key and returns the computed shared secret. The supplied + * key is interpreted using the specified `inputEncoding`, and secret is + * encoded using specified `outputEncoding`. + * If the `inputEncoding` is not + * provided, `otherPublicKey` is expected to be a `Buffer`, `TypedArray`, or `DataView`. + * + * If `outputEncoding` is given a string is returned; otherwise, a `Buffer` is returned. + * @since v0.5.0 + * @param inputEncoding The `encoding` of an `otherPublicKey` string. + * @param outputEncoding The `encoding` of the return value. + */ + computeSecret(otherPublicKey: NodeJS.ArrayBufferView, inputEncoding?: null, outputEncoding?: null): Buffer; + computeSecret(otherPublicKey: string, inputEncoding: BinaryToTextEncoding, outputEncoding?: null): Buffer; + computeSecret( + otherPublicKey: NodeJS.ArrayBufferView, + inputEncoding: null, + outputEncoding: BinaryToTextEncoding, + ): string; + computeSecret( + otherPublicKey: string, + inputEncoding: BinaryToTextEncoding, + outputEncoding: BinaryToTextEncoding, + ): string; + /** + * Returns the Diffie-Hellman prime in the specified `encoding`. + * If `encoding` is provided a string is + * returned; otherwise a `Buffer` is returned. + * @since v0.5.0 + * @param encoding The `encoding` of the return value. + */ + getPrime(): Buffer; + getPrime(encoding: BinaryToTextEncoding): string; + /** + * Returns the Diffie-Hellman generator in the specified `encoding`. + * If `encoding` is provided a string is + * returned; otherwise a `Buffer` is returned. + * @since v0.5.0 + * @param encoding The `encoding` of the return value. + */ + getGenerator(): Buffer; + getGenerator(encoding: BinaryToTextEncoding): string; + /** + * Returns the Diffie-Hellman public key in the specified `encoding`. + * If `encoding` is provided a + * string is returned; otherwise a `Buffer` is returned. + * @since v0.5.0 + * @param encoding The `encoding` of the return value. + */ + getPublicKey(): Buffer; + getPublicKey(encoding: BinaryToTextEncoding): string; + /** + * Returns the Diffie-Hellman private key in the specified `encoding`. + * If `encoding` is provided a + * string is returned; otherwise a `Buffer` is returned. + * @since v0.5.0 + * @param encoding The `encoding` of the return value. + */ + getPrivateKey(): Buffer; + getPrivateKey(encoding: BinaryToTextEncoding): string; + /** + * Sets the Diffie-Hellman public key. If the `encoding` argument is provided, `publicKey` is expected + * to be a string. If no `encoding` is provided, `publicKey` is expected + * to be a `Buffer`, `TypedArray`, or `DataView`. + * @since v0.5.0 + * @param encoding The `encoding` of the `publicKey` string. + */ + setPublicKey(publicKey: NodeJS.ArrayBufferView): void; + setPublicKey(publicKey: string, encoding: BufferEncoding): void; + /** + * Sets the Diffie-Hellman private key. If the `encoding` argument is provided,`privateKey` is expected + * to be a string. If no `encoding` is provided, `privateKey` is expected + * to be a `Buffer`, `TypedArray`, or `DataView`. + * + * This function does not automatically compute the associated public key. Either `diffieHellman.setPublicKey()` or `diffieHellman.generateKeys()` can be + * used to manually provide the public key or to automatically derive it. + * @since v0.5.0 + * @param encoding The `encoding` of the `privateKey` string. + */ + setPrivateKey(privateKey: NodeJS.ArrayBufferView): void; + setPrivateKey(privateKey: string, encoding: BufferEncoding): void; + /** + * A bit field containing any warnings and/or errors resulting from a check + * performed during initialization of the `DiffieHellman` object. + * + * The following values are valid for this property (as defined in `node:constants` module): + * + * * `DH_CHECK_P_NOT_SAFE_PRIME` + * * `DH_CHECK_P_NOT_PRIME` + * * `DH_UNABLE_TO_CHECK_GENERATOR` + * * `DH_NOT_SUITABLE_GENERATOR` + * @since v0.11.12 + */ + verifyError: number; + } + /** + * The `DiffieHellmanGroup` class takes a well-known modp group as its argument. + * It works the same as `DiffieHellman`, except that it does not allow changing its keys after creation. + * In other words, it does not implement `setPublicKey()` or `setPrivateKey()` methods. + * + * ```js + * const { createDiffieHellmanGroup } = await import('node:crypto'); + * const dh = createDiffieHellmanGroup('modp1'); + * ``` + * The name (e.g. `'modp1'`) is taken from [RFC 2412](https://www.rfc-editor.org/rfc/rfc2412.txt) (modp1 and 2) and [RFC 3526](https://www.rfc-editor.org/rfc/rfc3526.txt): + * ```bash + * $ perl -ne 'print "$1\n" if /"(modp\d+)"/' src/node_crypto_groups.h + * modp1 # 768 bits + * modp2 # 1024 bits + * modp5 # 1536 bits + * modp14 # 2048 bits + * modp15 # etc. + * modp16 + * modp17 + * modp18 + * ``` + * @since v0.7.5 + */ + const DiffieHellmanGroup: DiffieHellmanGroupConstructor; + interface DiffieHellmanGroupConstructor { + new(name: string): DiffieHellmanGroup; + (name: string): DiffieHellmanGroup; + readonly prototype: DiffieHellmanGroup; + } + type DiffieHellmanGroup = Omit; + /** + * Creates a predefined `DiffieHellmanGroup` key exchange object. The + * supported groups are listed in the documentation for `DiffieHellmanGroup`. + * + * The returned object mimics the interface of objects created by {@link createDiffieHellman}, but will not allow changing + * the keys (with `diffieHellman.setPublicKey()`, for example). The + * advantage of using this method is that the parties do not have to + * generate nor exchange a group modulus beforehand, saving both processor + * and communication time. + * + * Example (obtaining a shared secret): + * + * ```js + * const { + * getDiffieHellman, + * } = await import('node:crypto'); + * const alice = getDiffieHellman('modp14'); + * const bob = getDiffieHellman('modp14'); + * + * alice.generateKeys(); + * bob.generateKeys(); + * + * const aliceSecret = alice.computeSecret(bob.getPublicKey(), null, 'hex'); + * const bobSecret = bob.computeSecret(alice.getPublicKey(), null, 'hex'); + * + * // aliceSecret and bobSecret should be the same + * console.log(aliceSecret === bobSecret); + * ``` + * @since v0.7.5 + */ + function getDiffieHellman(groupName: string): DiffieHellmanGroup; + /** + * An alias for {@link getDiffieHellman} + * @since v0.9.3 + */ + function createDiffieHellmanGroup(name: string): DiffieHellmanGroup; + /** + * Provides an asynchronous Password-Based Key Derivation Function 2 (PBKDF2) + * implementation. A selected HMAC digest algorithm specified by `digest` is + * applied to derive a key of the requested byte length (`keylen`) from the `password`, `salt` and `iterations`. + * + * The supplied `callback` function is called with two arguments: `err` and `derivedKey`. If an error occurs while deriving the key, `err` will be set; + * otherwise `err` will be `null`. By default, the successfully generated `derivedKey` will be passed to the callback as a `Buffer`. An error will be + * thrown if any of the input arguments specify invalid values or types. + * + * The `iterations` argument must be a number set as high as possible. The + * higher the number of iterations, the more secure the derived key will be, + * but will take a longer amount of time to complete. + * + * The `salt` should be as unique as possible. It is recommended that a salt is + * random and at least 16 bytes long. See [NIST SP 800-132](https://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-132.pdf) for details. + * + * When passing strings for `password` or `salt`, please consider `caveats when using strings as inputs to cryptographic APIs`. + * + * ```js + * const { + * pbkdf2, + * } = await import('node:crypto'); + * + * pbkdf2('secret', 'salt', 100000, 64, 'sha512', (err, derivedKey) => { + * if (err) throw err; + * console.log(derivedKey.toString('hex')); // '3745e48...08d59ae' + * }); + * ``` + * + * An array of supported digest functions can be retrieved using {@link getHashes}. + * + * This API uses libuv's threadpool, which can have surprising and + * negative performance implications for some applications; see the `UV_THREADPOOL_SIZE` documentation for more information. + * @since v0.5.5 + */ + function pbkdf2( + password: BinaryLike, + salt: BinaryLike, + iterations: number, + keylen: number, + digest: string, + callback: (err: Error | null, derivedKey: Buffer) => void, + ): void; + /** + * Provides a synchronous Password-Based Key Derivation Function 2 (PBKDF2) + * implementation. A selected HMAC digest algorithm specified by `digest` is + * applied to derive a key of the requested byte length (`keylen`) from the `password`, `salt` and `iterations`. + * + * If an error occurs an `Error` will be thrown, otherwise the derived key will be + * returned as a `Buffer`. + * + * The `iterations` argument must be a number set as high as possible. The + * higher the number of iterations, the more secure the derived key will be, + * but will take a longer amount of time to complete. + * + * The `salt` should be as unique as possible. It is recommended that a salt is + * random and at least 16 bytes long. See [NIST SP 800-132](https://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-132.pdf) for details. + * + * When passing strings for `password` or `salt`, please consider `caveats when using strings as inputs to cryptographic APIs`. + * + * ```js + * const { + * pbkdf2Sync, + * } = await import('node:crypto'); + * + * const key = pbkdf2Sync('secret', 'salt', 100000, 64, 'sha512'); + * console.log(key.toString('hex')); // '3745e48...08d59ae' + * ``` + * + * An array of supported digest functions can be retrieved using {@link getHashes}. + * @since v0.9.3 + */ + function pbkdf2Sync( + password: BinaryLike, + salt: BinaryLike, + iterations: number, + keylen: number, + digest: string, + ): Buffer; + /** + * Generates cryptographically strong pseudorandom data. The `size` argument + * is a number indicating the number of bytes to generate. + * + * If a `callback` function is provided, the bytes are generated asynchronously + * and the `callback` function is invoked with two arguments: `err` and `buf`. + * If an error occurs, `err` will be an `Error` object; otherwise it is `null`. The `buf` argument is a `Buffer` containing the generated bytes. + * + * ```js + * // Asynchronous + * const { + * randomBytes, + * } = await import('node:crypto'); + * + * randomBytes(256, (err, buf) => { + * if (err) throw err; + * console.log(`${buf.length} bytes of random data: ${buf.toString('hex')}`); + * }); + * ``` + * + * If the `callback` function is not provided, the random bytes are generated + * synchronously and returned as a `Buffer`. An error will be thrown if + * there is a problem generating the bytes. + * + * ```js + * // Synchronous + * const { + * randomBytes, + * } = await import('node:crypto'); + * + * const buf = randomBytes(256); + * console.log( + * `${buf.length} bytes of random data: ${buf.toString('hex')}`); + * ``` + * + * The `crypto.randomBytes()` method will not complete until there is + * sufficient entropy available. + * This should normally never take longer than a few milliseconds. The only time + * when generating the random bytes may conceivably block for a longer period of + * time is right after boot, when the whole system is still low on entropy. + * + * This API uses libuv's threadpool, which can have surprising and + * negative performance implications for some applications; see the `UV_THREADPOOL_SIZE` documentation for more information. + * + * The asynchronous version of `crypto.randomBytes()` is carried out in a single + * threadpool request. To minimize threadpool task length variation, partition + * large `randomBytes` requests when doing so as part of fulfilling a client + * request. + * @since v0.5.8 + * @param size The number of bytes to generate. The `size` must not be larger than `2**31 - 1`. + * @return if the `callback` function is not provided. + */ + function randomBytes(size: number): Buffer; + function randomBytes(size: number, callback: (err: Error | null, buf: Buffer) => void): void; + function pseudoRandomBytes(size: number): Buffer; + function pseudoRandomBytes(size: number, callback: (err: Error | null, buf: Buffer) => void): void; + /** + * Return a random integer `n` such that `min <= n < max`. This + * implementation avoids [modulo bias](https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle#Modulo_bias). + * + * The range (`max - min`) must be less than 2**48. `min` and `max` must + * be [safe integers](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/isSafeInteger). + * + * If the `callback` function is not provided, the random integer is + * generated synchronously. + * + * ```js + * // Asynchronous + * const { + * randomInt, + * } = await import('node:crypto'); + * + * randomInt(3, (err, n) => { + * if (err) throw err; + * console.log(`Random number chosen from (0, 1, 2): ${n}`); + * }); + * ``` + * + * ```js + * // Synchronous + * const { + * randomInt, + * } = await import('node:crypto'); + * + * const n = randomInt(3); + * console.log(`Random number chosen from (0, 1, 2): ${n}`); + * ``` + * + * ```js + * // With `min` argument + * const { + * randomInt, + * } = await import('node:crypto'); + * + * const n = randomInt(1, 7); + * console.log(`The dice rolled: ${n}`); + * ``` + * @since v14.10.0, v12.19.0 + * @param [min=0] Start of random range (inclusive). + * @param max End of random range (exclusive). + * @param callback `function(err, n) {}`. + */ + function randomInt(max: number): number; + function randomInt(min: number, max: number): number; + function randomInt(max: number, callback: (err: Error | null, value: number) => void): void; + function randomInt(min: number, max: number, callback: (err: Error | null, value: number) => void): void; + /** + * Synchronous version of {@link randomFill}. + * + * ```js + * import { Buffer } from 'node:buffer'; + * const { randomFillSync } = await import('node:crypto'); + * + * const buf = Buffer.alloc(10); + * console.log(randomFillSync(buf).toString('hex')); + * + * randomFillSync(buf, 5); + * console.log(buf.toString('hex')); + * + * // The above is equivalent to the following: + * randomFillSync(buf, 5, 5); + * console.log(buf.toString('hex')); + * ``` + * + * Any `ArrayBuffer`, `TypedArray` or `DataView` instance may be passed as`buffer`. + * + * ```js + * import { Buffer } from 'node:buffer'; + * const { randomFillSync } = await import('node:crypto'); + * + * const a = new Uint32Array(10); + * console.log(Buffer.from(randomFillSync(a).buffer, + * a.byteOffset, a.byteLength).toString('hex')); + * + * const b = new DataView(new ArrayBuffer(10)); + * console.log(Buffer.from(randomFillSync(b).buffer, + * b.byteOffset, b.byteLength).toString('hex')); + * + * const c = new ArrayBuffer(10); + * console.log(Buffer.from(randomFillSync(c)).toString('hex')); + * ``` + * @since v7.10.0, v6.13.0 + * @param buffer Must be supplied. The size of the provided `buffer` must not be larger than `2**31 - 1`. + * @param [offset=0] + * @param [size=buffer.length - offset] + * @return The object passed as `buffer` argument. + */ + function randomFillSync(buffer: T, offset?: number, size?: number): T; + /** + * This function is similar to {@link randomBytes} but requires the first + * argument to be a `Buffer` that will be filled. It also + * requires that a callback is passed in. + * + * If the `callback` function is not provided, an error will be thrown. + * + * ```js + * import { Buffer } from 'node:buffer'; + * const { randomFill } = await import('node:crypto'); + * + * const buf = Buffer.alloc(10); + * randomFill(buf, (err, buf) => { + * if (err) throw err; + * console.log(buf.toString('hex')); + * }); + * + * randomFill(buf, 5, (err, buf) => { + * if (err) throw err; + * console.log(buf.toString('hex')); + * }); + * + * // The above is equivalent to the following: + * randomFill(buf, 5, 5, (err, buf) => { + * if (err) throw err; + * console.log(buf.toString('hex')); + * }); + * ``` + * + * Any `ArrayBuffer`, `TypedArray`, or `DataView` instance may be passed as `buffer`. + * + * While this includes instances of `Float32Array` and `Float64Array`, this + * function should not be used to generate random floating-point numbers. The + * result may contain `+Infinity`, `-Infinity`, and `NaN`, and even if the array + * contains finite numbers only, they are not drawn from a uniform random + * distribution and have no meaningful lower or upper bounds. + * + * ```js + * import { Buffer } from 'node:buffer'; + * const { randomFill } = await import('node:crypto'); + * + * const a = new Uint32Array(10); + * randomFill(a, (err, buf) => { + * if (err) throw err; + * console.log(Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength) + * .toString('hex')); + * }); + * + * const b = new DataView(new ArrayBuffer(10)); + * randomFill(b, (err, buf) => { + * if (err) throw err; + * console.log(Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength) + * .toString('hex')); + * }); + * + * const c = new ArrayBuffer(10); + * randomFill(c, (err, buf) => { + * if (err) throw err; + * console.log(Buffer.from(buf).toString('hex')); + * }); + * ``` + * + * This API uses libuv's threadpool, which can have surprising and + * negative performance implications for some applications; see the `UV_THREADPOOL_SIZE` documentation for more information. + * + * The asynchronous version of `crypto.randomFill()` is carried out in a single + * threadpool request. To minimize threadpool task length variation, partition + * large `randomFill` requests when doing so as part of fulfilling a client + * request. + * @since v7.10.0, v6.13.0 + * @param buffer Must be supplied. The size of the provided `buffer` must not be larger than `2**31 - 1`. + * @param [offset=0] + * @param [size=buffer.length - offset] + * @param callback `function(err, buf) {}`. + */ + function randomFill( + buffer: T, + callback: (err: Error | null, buf: T) => void, + ): void; + function randomFill( + buffer: T, + offset: number, + callback: (err: Error | null, buf: T) => void, + ): void; + function randomFill( + buffer: T, + offset: number, + size: number, + callback: (err: Error | null, buf: T) => void, + ): void; + interface ScryptOptions { + cost?: number | undefined; + blockSize?: number | undefined; + parallelization?: number | undefined; + N?: number | undefined; + r?: number | undefined; + p?: number | undefined; + maxmem?: number | undefined; + } + /** + * Provides an asynchronous [scrypt](https://en.wikipedia.org/wiki/Scrypt) implementation. Scrypt is a password-based + * key derivation function that is designed to be expensive computationally and + * memory-wise in order to make brute-force attacks unrewarding. + * + * The `salt` should be as unique as possible. It is recommended that a salt is + * random and at least 16 bytes long. See [NIST SP 800-132](https://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-132.pdf) for details. + * + * When passing strings for `password` or `salt`, please consider `caveats when using strings as inputs to cryptographic APIs`. + * + * The `callback` function is called with two arguments: `err` and `derivedKey`. `err` is an exception object when key derivation fails, otherwise `err` is `null`. `derivedKey` is passed to the + * callback as a `Buffer`. + * + * An exception is thrown when any of the input arguments specify invalid values + * or types. + * + * ```js + * const { + * scrypt, + * } = await import('node:crypto'); + * + * // Using the factory defaults. + * scrypt('password', 'salt', 64, (err, derivedKey) => { + * if (err) throw err; + * console.log(derivedKey.toString('hex')); // '3745e48...08d59ae' + * }); + * // Using a custom N parameter. Must be a power of two. + * scrypt('password', 'salt', 64, { N: 1024 }, (err, derivedKey) => { + * if (err) throw err; + * console.log(derivedKey.toString('hex')); // '3745e48...aa39b34' + * }); + * ``` + * @since v10.5.0 + */ + function scrypt( + password: BinaryLike, + salt: BinaryLike, + keylen: number, + callback: (err: Error | null, derivedKey: Buffer) => void, + ): void; + function scrypt( + password: BinaryLike, + salt: BinaryLike, + keylen: number, + options: ScryptOptions, + callback: (err: Error | null, derivedKey: Buffer) => void, + ): void; + /** + * Provides a synchronous [scrypt](https://en.wikipedia.org/wiki/Scrypt) implementation. Scrypt is a password-based + * key derivation function that is designed to be expensive computationally and + * memory-wise in order to make brute-force attacks unrewarding. + * + * The `salt` should be as unique as possible. It is recommended that a salt is + * random and at least 16 bytes long. See [NIST SP 800-132](https://nvlpubs.nist.gov/nistpubs/Legacy/SP/nistspecialpublication800-132.pdf) for details. + * + * When passing strings for `password` or `salt`, please consider `caveats when using strings as inputs to cryptographic APIs`. + * + * An exception is thrown when key derivation fails, otherwise the derived key is + * returned as a `Buffer`. + * + * An exception is thrown when any of the input arguments specify invalid values + * or types. + * + * ```js + * const { + * scryptSync, + * } = await import('node:crypto'); + * // Using the factory defaults. + * + * const key1 = scryptSync('password', 'salt', 64); + * console.log(key1.toString('hex')); // '3745e48...08d59ae' + * // Using a custom N parameter. Must be a power of two. + * const key2 = scryptSync('password', 'salt', 64, { N: 1024 }); + * console.log(key2.toString('hex')); // '3745e48...aa39b34' + * ``` + * @since v10.5.0 + */ + function scryptSync(password: BinaryLike, salt: BinaryLike, keylen: number, options?: ScryptOptions): Buffer; + interface RsaPublicKey { + key: KeyLike; + padding?: number | undefined; + } + interface RsaPrivateKey { + key: KeyLike; + passphrase?: string | undefined; + /** + * @default 'sha1' + */ + oaepHash?: string | undefined; + oaepLabel?: NodeJS.TypedArray | undefined; + padding?: number | undefined; + } + /** + * Encrypts the content of `buffer` with `key` and returns a new `Buffer` with encrypted content. The returned data can be decrypted using + * the corresponding private key, for example using {@link privateDecrypt}. + * + * If `key` is not a `KeyObject`, this function behaves as if `key` had been passed to {@link createPublicKey}. If it is an + * object, the `padding` property can be passed. Otherwise, this function uses `RSA_PKCS1_OAEP_PADDING`. + * + * Because RSA public keys can be derived from private keys, a private key may + * be passed instead of a public key. + * @since v0.11.14 + */ + function publicEncrypt(key: RsaPublicKey | RsaPrivateKey | KeyLike, buffer: NodeJS.ArrayBufferView): Buffer; + /** + * Decrypts `buffer` with `key`.`buffer` was previously encrypted using + * the corresponding private key, for example using {@link privateEncrypt}. + * + * If `key` is not a `KeyObject`, this function behaves as if `key` had been passed to {@link createPublicKey}. If it is an + * object, the `padding` property can be passed. Otherwise, this function uses `RSA_PKCS1_PADDING`. + * + * Because RSA public keys can be derived from private keys, a private key may + * be passed instead of a public key. + * @since v1.1.0 + */ + function publicDecrypt(key: RsaPublicKey | RsaPrivateKey | KeyLike, buffer: NodeJS.ArrayBufferView): Buffer; + /** + * Decrypts `buffer` with `privateKey`. `buffer` was previously encrypted using + * the corresponding public key, for example using {@link publicEncrypt}. + * + * If `privateKey` is not a `KeyObject`, this function behaves as if `privateKey` had been passed to {@link createPrivateKey}. If it is an + * object, the `padding` property can be passed. Otherwise, this function uses `RSA_PKCS1_OAEP_PADDING`. + * @since v0.11.14 + */ + function privateDecrypt(privateKey: RsaPrivateKey | KeyLike, buffer: NodeJS.ArrayBufferView): Buffer; + /** + * Encrypts `buffer` with `privateKey`. The returned data can be decrypted using + * the corresponding public key, for example using {@link publicDecrypt}. + * + * If `privateKey` is not a `KeyObject`, this function behaves as if `privateKey` had been passed to {@link createPrivateKey}. If it is an + * object, the `padding` property can be passed. Otherwise, this function uses `RSA_PKCS1_PADDING`. + * @since v1.1.0 + */ + function privateEncrypt(privateKey: RsaPrivateKey | KeyLike, buffer: NodeJS.ArrayBufferView): Buffer; + /** + * ```js + * const { + * getCiphers, + * } = await import('node:crypto'); + * + * console.log(getCiphers()); // ['aes-128-cbc', 'aes-128-ccm', ...] + * ``` + * @since v0.9.3 + * @return An array with the names of the supported cipher algorithms. + */ + function getCiphers(): string[]; + /** + * ```js + * const { + * getCurves, + * } = await import('node:crypto'); + * + * console.log(getCurves()); // ['Oakley-EC2N-3', 'Oakley-EC2N-4', ...] + * ``` + * @since v2.3.0 + * @return An array with the names of the supported elliptic curves. + */ + function getCurves(): string[]; + /** + * @since v10.0.0 + * @return `1` if and only if a FIPS compliant crypto provider is currently in use, `0` otherwise. A future semver-major release may change the return type of this API to a {boolean}. + */ + function getFips(): 1 | 0; + /** + * Enables the FIPS compliant crypto provider in a FIPS-enabled Node.js build. + * Throws an error if FIPS mode is not available. + * @since v10.0.0 + * @param bool `true` to enable FIPS mode. + */ + function setFips(bool: boolean): void; + /** + * ```js + * const { + * getHashes, + * } = await import('node:crypto'); + * + * console.log(getHashes()); // ['DSA', 'DSA-SHA', 'DSA-SHA1', ...] + * ``` + * @since v0.9.3 + * @return An array of the names of the supported hash algorithms, such as `'RSA-SHA256'`. Hash algorithms are also called "digest" algorithms. + */ + function getHashes(): string[]; + /** + * The `ECDH` class is a utility for creating Elliptic Curve Diffie-Hellman (ECDH) + * key exchanges. + * + * Instances of the `ECDH` class can be created using the {@link createECDH} function. + * + * ```js + * import assert from 'node:assert'; + * + * const { + * createECDH, + * } = await import('node:crypto'); + * + * // Generate Alice's keys... + * const alice = createECDH('secp521r1'); + * const aliceKey = alice.generateKeys(); + * + * // Generate Bob's keys... + * const bob = createECDH('secp521r1'); + * const bobKey = bob.generateKeys(); + * + * // Exchange and generate the secret... + * const aliceSecret = alice.computeSecret(bobKey); + * const bobSecret = bob.computeSecret(aliceKey); + * + * assert.strictEqual(aliceSecret.toString('hex'), bobSecret.toString('hex')); + * // OK + * ``` + * @since v0.11.14 + */ + class ECDH { + private constructor(); + /** + * Converts the EC Diffie-Hellman public key specified by `key` and `curve` to the + * format specified by `format`. The `format` argument specifies point encoding + * and can be `'compressed'`, `'uncompressed'` or `'hybrid'`. The supplied key is + * interpreted using the specified `inputEncoding`, and the returned key is encoded + * using the specified `outputEncoding`. + * + * Use {@link getCurves} to obtain a list of available curve names. + * On recent OpenSSL releases, `openssl ecparam -list_curves` will also display + * the name and description of each available elliptic curve. + * + * If `format` is not specified the point will be returned in `'uncompressed'` format. + * + * If the `inputEncoding` is not provided, `key` is expected to be a `Buffer`, `TypedArray`, or `DataView`. + * + * Example (uncompressing a key): + * + * ```js + * const { + * createECDH, + * ECDH, + * } = await import('node:crypto'); + * + * const ecdh = createECDH('secp256k1'); + * ecdh.generateKeys(); + * + * const compressedKey = ecdh.getPublicKey('hex', 'compressed'); + * + * const uncompressedKey = ECDH.convertKey(compressedKey, + * 'secp256k1', + * 'hex', + * 'hex', + * 'uncompressed'); + * + * // The converted key and the uncompressed public key should be the same + * console.log(uncompressedKey === ecdh.getPublicKey('hex')); + * ``` + * @since v10.0.0 + * @param inputEncoding The `encoding` of the `key` string. + * @param outputEncoding The `encoding` of the return value. + * @param [format='uncompressed'] + */ + static convertKey( + key: BinaryLike, + curve: string, + inputEncoding?: BinaryToTextEncoding, + outputEncoding?: "latin1" | "hex" | "base64" | "base64url", + format?: "uncompressed" | "compressed" | "hybrid", + ): Buffer | string; + /** + * Generates private and public EC Diffie-Hellman key values, and returns + * the public key in the specified `format` and `encoding`. This key should be + * transferred to the other party. + * + * The `format` argument specifies point encoding and can be `'compressed'` or `'uncompressed'`. If `format` is not specified, the point will be returned in`'uncompressed'` format. + * + * If `encoding` is provided a string is returned; otherwise a `Buffer` is returned. + * @since v0.11.14 + * @param encoding The `encoding` of the return value. + * @param [format='uncompressed'] + */ + generateKeys(): Buffer; + generateKeys(encoding: BinaryToTextEncoding, format?: ECDHKeyFormat): string; + /** + * Computes the shared secret using `otherPublicKey` as the other + * party's public key and returns the computed shared secret. The supplied + * key is interpreted using specified `inputEncoding`, and the returned secret + * is encoded using the specified `outputEncoding`. + * If the `inputEncoding` is not + * provided, `otherPublicKey` is expected to be a `Buffer`, `TypedArray`, or `DataView`. + * + * If `outputEncoding` is given a string will be returned; otherwise a `Buffer` is returned. + * + * `ecdh.computeSecret` will throw an`ERR_CRYPTO_ECDH_INVALID_PUBLIC_KEY` error when `otherPublicKey` lies outside of the elliptic curve. Since `otherPublicKey` is + * usually supplied from a remote user over an insecure network, + * be sure to handle this exception accordingly. + * @since v0.11.14 + * @param inputEncoding The `encoding` of the `otherPublicKey` string. + * @param outputEncoding The `encoding` of the return value. + */ + computeSecret(otherPublicKey: NodeJS.ArrayBufferView): Buffer; + computeSecret(otherPublicKey: string, inputEncoding: BinaryToTextEncoding): Buffer; + computeSecret(otherPublicKey: NodeJS.ArrayBufferView, outputEncoding: BinaryToTextEncoding): string; + computeSecret( + otherPublicKey: string, + inputEncoding: BinaryToTextEncoding, + outputEncoding: BinaryToTextEncoding, + ): string; + /** + * If `encoding` is specified, a string is returned; otherwise a `Buffer` is + * returned. + * @since v0.11.14 + * @param encoding The `encoding` of the return value. + * @return The EC Diffie-Hellman in the specified `encoding`. + */ + getPrivateKey(): Buffer; + getPrivateKey(encoding: BinaryToTextEncoding): string; + /** + * The `format` argument specifies point encoding and can be `'compressed'` or `'uncompressed'`. If `format` is not specified the point will be returned in`'uncompressed'` format. + * + * If `encoding` is specified, a string is returned; otherwise a `Buffer` is + * returned. + * @since v0.11.14 + * @param encoding The `encoding` of the return value. + * @param [format='uncompressed'] + * @return The EC Diffie-Hellman public key in the specified `encoding` and `format`. + */ + getPublicKey(encoding?: null, format?: ECDHKeyFormat): Buffer; + getPublicKey(encoding: BinaryToTextEncoding, format?: ECDHKeyFormat): string; + /** + * Sets the EC Diffie-Hellman private key. + * If `encoding` is provided, `privateKey` is expected + * to be a string; otherwise `privateKey` is expected to be a `Buffer`, `TypedArray`, or `DataView`. + * + * If `privateKey` is not valid for the curve specified when the `ECDH` object was + * created, an error is thrown. Upon setting the private key, the associated + * public point (key) is also generated and set in the `ECDH` object. + * @since v0.11.14 + * @param encoding The `encoding` of the `privateKey` string. + */ + setPrivateKey(privateKey: NodeJS.ArrayBufferView): void; + setPrivateKey(privateKey: string, encoding: BinaryToTextEncoding): void; + } + /** + * Creates an Elliptic Curve Diffie-Hellman (`ECDH`) key exchange object using a + * predefined curve specified by the `curveName` string. Use {@link getCurves} to obtain a list of available curve names. On recent + * OpenSSL releases, `openssl ecparam -list_curves` will also display the name + * and description of each available elliptic curve. + * @since v0.11.14 + */ + function createECDH(curveName: string): ECDH; + /** + * This function compares the underlying bytes that represent the given `ArrayBuffer`, `TypedArray`, or `DataView` instances using a constant-time + * algorithm. + * + * This function does not leak timing information that + * would allow an attacker to guess one of the values. This is suitable for + * comparing HMAC digests or secret values like authentication cookies or [capability urls](https://www.w3.org/TR/capability-urls/). + * + * `a` and `b` must both be `Buffer`s, `TypedArray`s, or `DataView`s, and they + * must have the same byte length. An error is thrown if `a` and `b` have + * different byte lengths. + * + * If at least one of `a` and `b` is a `TypedArray` with more than one byte per + * entry, such as `Uint16Array`, the result will be computed using the platform + * byte order. + * + * **When both of the inputs are `Float32Array`s or `Float64Array`s, this function might return unexpected results due to IEEE 754** + * **encoding of floating-point numbers. In particular, neither `x === y` nor `Object.is(x, y)` implies that the byte representations of two floating-point** + * **numbers `x` and `y` are equal.** + * + * Use of `crypto.timingSafeEqual` does not guarantee that the _surrounding_ code + * is timing-safe. Care should be taken to ensure that the surrounding code does + * not introduce timing vulnerabilities. + * @since v6.6.0 + */ + function timingSafeEqual(a: NodeJS.ArrayBufferView, b: NodeJS.ArrayBufferView): boolean; + type KeyType = "rsa" | "rsa-pss" | "dsa" | "ec" | "ed25519" | "ed448" | "x25519" | "x448"; + type KeyFormat = "pem" | "der" | "jwk"; + interface BasePrivateKeyEncodingOptions { + format: T; + cipher?: string | undefined; + passphrase?: string | undefined; + } + interface KeyPairKeyObjectResult { + publicKey: KeyObject; + privateKey: KeyObject; + } + interface ED25519KeyPairKeyObjectOptions {} + interface ED448KeyPairKeyObjectOptions {} + interface X25519KeyPairKeyObjectOptions {} + interface X448KeyPairKeyObjectOptions {} + interface ECKeyPairKeyObjectOptions { + /** + * Name of the curve to use + */ + namedCurve: string; + /** + * Must be `'named'` or `'explicit'`. Default: `'named'`. + */ + paramEncoding?: "explicit" | "named" | undefined; + } + interface RSAKeyPairKeyObjectOptions { + /** + * Key size in bits + */ + modulusLength: number; + /** + * Public exponent + * @default 0x10001 + */ + publicExponent?: number | undefined; + } + interface RSAPSSKeyPairKeyObjectOptions { + /** + * Key size in bits + */ + modulusLength: number; + /** + * Public exponent + * @default 0x10001 + */ + publicExponent?: number | undefined; + /** + * Name of the message digest + */ + hashAlgorithm?: string; + /** + * Name of the message digest used by MGF1 + */ + mgf1HashAlgorithm?: string; + /** + * Minimal salt length in bytes + */ + saltLength?: string; + } + interface DSAKeyPairKeyObjectOptions { + /** + * Key size in bits + */ + modulusLength: number; + /** + * Size of q in bits + */ + divisorLength: number; + } + interface RSAKeyPairOptions { + /** + * Key size in bits + */ + modulusLength: number; + /** + * Public exponent + * @default 0x10001 + */ + publicExponent?: number | undefined; + publicKeyEncoding: { + type: "pkcs1" | "spki"; + format: PubF; + }; + privateKeyEncoding: BasePrivateKeyEncodingOptions & { + type: "pkcs1" | "pkcs8"; + }; + } + interface RSAPSSKeyPairOptions { + /** + * Key size in bits + */ + modulusLength: number; + /** + * Public exponent + * @default 0x10001 + */ + publicExponent?: number | undefined; + /** + * Name of the message digest + */ + hashAlgorithm?: string; + /** + * Name of the message digest used by MGF1 + */ + mgf1HashAlgorithm?: string; + /** + * Minimal salt length in bytes + */ + saltLength?: string; + publicKeyEncoding: { + type: "spki"; + format: PubF; + }; + privateKeyEncoding: BasePrivateKeyEncodingOptions & { + type: "pkcs8"; + }; + } + interface DSAKeyPairOptions { + /** + * Key size in bits + */ + modulusLength: number; + /** + * Size of q in bits + */ + divisorLength: number; + publicKeyEncoding: { + type: "spki"; + format: PubF; + }; + privateKeyEncoding: BasePrivateKeyEncodingOptions & { + type: "pkcs8"; + }; + } + interface ECKeyPairOptions extends ECKeyPairKeyObjectOptions { + publicKeyEncoding: { + type: "pkcs1" | "spki"; + format: PubF; + }; + privateKeyEncoding: BasePrivateKeyEncodingOptions & { + type: "sec1" | "pkcs8"; + }; + } + interface ED25519KeyPairOptions { + publicKeyEncoding: { + type: "spki"; + format: PubF; + }; + privateKeyEncoding: BasePrivateKeyEncodingOptions & { + type: "pkcs8"; + }; + } + interface ED448KeyPairOptions { + publicKeyEncoding: { + type: "spki"; + format: PubF; + }; + privateKeyEncoding: BasePrivateKeyEncodingOptions & { + type: "pkcs8"; + }; + } + interface X25519KeyPairOptions { + publicKeyEncoding: { + type: "spki"; + format: PubF; + }; + privateKeyEncoding: BasePrivateKeyEncodingOptions & { + type: "pkcs8"; + }; + } + interface X448KeyPairOptions { + publicKeyEncoding: { + type: "spki"; + format: PubF; + }; + privateKeyEncoding: BasePrivateKeyEncodingOptions & { + type: "pkcs8"; + }; + } + interface KeyPairSyncResult { + publicKey: T1; + privateKey: T2; + } + /** + * Generates a new asymmetric key pair of the given `type`. RSA, RSA-PSS, DSA, EC, + * Ed25519, Ed448, X25519, X448, and DH are currently supported. + * + * If a `publicKeyEncoding` or `privateKeyEncoding` was specified, this function + * behaves as if `keyObject.export()` had been called on its result. Otherwise, + * the respective part of the key is returned as a `KeyObject`. + * + * When encoding public keys, it is recommended to use `'spki'`. When encoding + * private keys, it is recommended to use `'pkcs8'` with a strong passphrase, + * and to keep the passphrase confidential. + * + * ```js + * const { + * generateKeyPairSync, + * } = await import('node:crypto'); + * + * const { + * publicKey, + * privateKey, + * } = generateKeyPairSync('rsa', { + * modulusLength: 4096, + * publicKeyEncoding: { + * type: 'spki', + * format: 'pem', + * }, + * privateKeyEncoding: { + * type: 'pkcs8', + * format: 'pem', + * cipher: 'aes-256-cbc', + * passphrase: 'top secret', + * }, + * }); + * ``` + * + * The return value `{ publicKey, privateKey }` represents the generated key pair. + * When PEM encoding was selected, the respective key will be a string, otherwise + * it will be a buffer containing the data encoded as DER. + * @since v10.12.0 + * @param type Must be `'rsa'`, `'rsa-pss'`, `'dsa'`, `'ec'`, `'ed25519'`, `'ed448'`, `'x25519'`, `'x448'`, or `'dh'`. + */ + function generateKeyPairSync( + type: "rsa", + options: RSAKeyPairOptions<"pem", "pem">, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: "rsa", + options: RSAKeyPairOptions<"pem", "der">, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: "rsa", + options: RSAKeyPairOptions<"der", "pem">, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: "rsa", + options: RSAKeyPairOptions<"der", "der">, + ): KeyPairSyncResult; + function generateKeyPairSync(type: "rsa", options: RSAKeyPairKeyObjectOptions): KeyPairKeyObjectResult; + function generateKeyPairSync( + type: "rsa-pss", + options: RSAPSSKeyPairOptions<"pem", "pem">, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: "rsa-pss", + options: RSAPSSKeyPairOptions<"pem", "der">, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: "rsa-pss", + options: RSAPSSKeyPairOptions<"der", "pem">, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: "rsa-pss", + options: RSAPSSKeyPairOptions<"der", "der">, + ): KeyPairSyncResult; + function generateKeyPairSync(type: "rsa-pss", options: RSAPSSKeyPairKeyObjectOptions): KeyPairKeyObjectResult; + function generateKeyPairSync( + type: "dsa", + options: DSAKeyPairOptions<"pem", "pem">, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: "dsa", + options: DSAKeyPairOptions<"pem", "der">, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: "dsa", + options: DSAKeyPairOptions<"der", "pem">, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: "dsa", + options: DSAKeyPairOptions<"der", "der">, + ): KeyPairSyncResult; + function generateKeyPairSync(type: "dsa", options: DSAKeyPairKeyObjectOptions): KeyPairKeyObjectResult; + function generateKeyPairSync( + type: "ec", + options: ECKeyPairOptions<"pem", "pem">, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: "ec", + options: ECKeyPairOptions<"pem", "der">, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: "ec", + options: ECKeyPairOptions<"der", "pem">, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: "ec", + options: ECKeyPairOptions<"der", "der">, + ): KeyPairSyncResult; + function generateKeyPairSync(type: "ec", options: ECKeyPairKeyObjectOptions): KeyPairKeyObjectResult; + function generateKeyPairSync( + type: "ed25519", + options: ED25519KeyPairOptions<"pem", "pem">, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: "ed25519", + options: ED25519KeyPairOptions<"pem", "der">, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: "ed25519", + options: ED25519KeyPairOptions<"der", "pem">, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: "ed25519", + options: ED25519KeyPairOptions<"der", "der">, + ): KeyPairSyncResult; + function generateKeyPairSync(type: "ed25519", options?: ED25519KeyPairKeyObjectOptions): KeyPairKeyObjectResult; + function generateKeyPairSync( + type: "ed448", + options: ED448KeyPairOptions<"pem", "pem">, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: "ed448", + options: ED448KeyPairOptions<"pem", "der">, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: "ed448", + options: ED448KeyPairOptions<"der", "pem">, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: "ed448", + options: ED448KeyPairOptions<"der", "der">, + ): KeyPairSyncResult; + function generateKeyPairSync(type: "ed448", options?: ED448KeyPairKeyObjectOptions): KeyPairKeyObjectResult; + function generateKeyPairSync( + type: "x25519", + options: X25519KeyPairOptions<"pem", "pem">, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: "x25519", + options: X25519KeyPairOptions<"pem", "der">, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: "x25519", + options: X25519KeyPairOptions<"der", "pem">, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: "x25519", + options: X25519KeyPairOptions<"der", "der">, + ): KeyPairSyncResult; + function generateKeyPairSync(type: "x25519", options?: X25519KeyPairKeyObjectOptions): KeyPairKeyObjectResult; + function generateKeyPairSync( + type: "x448", + options: X448KeyPairOptions<"pem", "pem">, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: "x448", + options: X448KeyPairOptions<"pem", "der">, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: "x448", + options: X448KeyPairOptions<"der", "pem">, + ): KeyPairSyncResult; + function generateKeyPairSync( + type: "x448", + options: X448KeyPairOptions<"der", "der">, + ): KeyPairSyncResult; + function generateKeyPairSync(type: "x448", options?: X448KeyPairKeyObjectOptions): KeyPairKeyObjectResult; + /** + * Generates a new asymmetric key pair of the given `type`. RSA, RSA-PSS, DSA, EC, + * Ed25519, Ed448, X25519, X448, and DH are currently supported. + * + * If a `publicKeyEncoding` or `privateKeyEncoding` was specified, this function + * behaves as if `keyObject.export()` had been called on its result. Otherwise, + * the respective part of the key is returned as a `KeyObject`. + * + * It is recommended to encode public keys as `'spki'` and private keys as `'pkcs8'` with encryption for long-term storage: + * + * ```js + * const { + * generateKeyPair, + * } = await import('node:crypto'); + * + * generateKeyPair('rsa', { + * modulusLength: 4096, + * publicKeyEncoding: { + * type: 'spki', + * format: 'pem', + * }, + * privateKeyEncoding: { + * type: 'pkcs8', + * format: 'pem', + * cipher: 'aes-256-cbc', + * passphrase: 'top secret', + * }, + * }, (err, publicKey, privateKey) => { + * // Handle errors and use the generated key pair. + * }); + * ``` + * + * On completion, `callback` will be called with `err` set to `undefined` and `publicKey` / `privateKey` representing the generated key pair. + * + * If this method is invoked as its `util.promisify()` ed version, it returns + * a `Promise` for an `Object` with `publicKey` and `privateKey` properties. + * @since v10.12.0 + * @param type Must be `'rsa'`, `'rsa-pss'`, `'dsa'`, `'ec'`, `'ed25519'`, `'ed448'`, `'x25519'`, `'x448'`, or `'dh'`. + */ + function generateKeyPair( + type: "rsa", + options: RSAKeyPairOptions<"pem", "pem">, + callback: (err: Error | null, publicKey: string, privateKey: string) => void, + ): void; + function generateKeyPair( + type: "rsa", + options: RSAKeyPairOptions<"pem", "der">, + callback: (err: Error | null, publicKey: string, privateKey: Buffer) => void, + ): void; + function generateKeyPair( + type: "rsa", + options: RSAKeyPairOptions<"der", "pem">, + callback: (err: Error | null, publicKey: Buffer, privateKey: string) => void, + ): void; + function generateKeyPair( + type: "rsa", + options: RSAKeyPairOptions<"der", "der">, + callback: (err: Error | null, publicKey: Buffer, privateKey: Buffer) => void, + ): void; + function generateKeyPair( + type: "rsa", + options: RSAKeyPairKeyObjectOptions, + callback: (err: Error | null, publicKey: KeyObject, privateKey: KeyObject) => void, + ): void; + function generateKeyPair( + type: "rsa-pss", + options: RSAPSSKeyPairOptions<"pem", "pem">, + callback: (err: Error | null, publicKey: string, privateKey: string) => void, + ): void; + function generateKeyPair( + type: "rsa-pss", + options: RSAPSSKeyPairOptions<"pem", "der">, + callback: (err: Error | null, publicKey: string, privateKey: Buffer) => void, + ): void; + function generateKeyPair( + type: "rsa-pss", + options: RSAPSSKeyPairOptions<"der", "pem">, + callback: (err: Error | null, publicKey: Buffer, privateKey: string) => void, + ): void; + function generateKeyPair( + type: "rsa-pss", + options: RSAPSSKeyPairOptions<"der", "der">, + callback: (err: Error | null, publicKey: Buffer, privateKey: Buffer) => void, + ): void; + function generateKeyPair( + type: "rsa-pss", + options: RSAPSSKeyPairKeyObjectOptions, + callback: (err: Error | null, publicKey: KeyObject, privateKey: KeyObject) => void, + ): void; + function generateKeyPair( + type: "dsa", + options: DSAKeyPairOptions<"pem", "pem">, + callback: (err: Error | null, publicKey: string, privateKey: string) => void, + ): void; + function generateKeyPair( + type: "dsa", + options: DSAKeyPairOptions<"pem", "der">, + callback: (err: Error | null, publicKey: string, privateKey: Buffer) => void, + ): void; + function generateKeyPair( + type: "dsa", + options: DSAKeyPairOptions<"der", "pem">, + callback: (err: Error | null, publicKey: Buffer, privateKey: string) => void, + ): void; + function generateKeyPair( + type: "dsa", + options: DSAKeyPairOptions<"der", "der">, + callback: (err: Error | null, publicKey: Buffer, privateKey: Buffer) => void, + ): void; + function generateKeyPair( + type: "dsa", + options: DSAKeyPairKeyObjectOptions, + callback: (err: Error | null, publicKey: KeyObject, privateKey: KeyObject) => void, + ): void; + function generateKeyPair( + type: "ec", + options: ECKeyPairOptions<"pem", "pem">, + callback: (err: Error | null, publicKey: string, privateKey: string) => void, + ): void; + function generateKeyPair( + type: "ec", + options: ECKeyPairOptions<"pem", "der">, + callback: (err: Error | null, publicKey: string, privateKey: Buffer) => void, + ): void; + function generateKeyPair( + type: "ec", + options: ECKeyPairOptions<"der", "pem">, + callback: (err: Error | null, publicKey: Buffer, privateKey: string) => void, + ): void; + function generateKeyPair( + type: "ec", + options: ECKeyPairOptions<"der", "der">, + callback: (err: Error | null, publicKey: Buffer, privateKey: Buffer) => void, + ): void; + function generateKeyPair( + type: "ec", + options: ECKeyPairKeyObjectOptions, + callback: (err: Error | null, publicKey: KeyObject, privateKey: KeyObject) => void, + ): void; + function generateKeyPair( + type: "ed25519", + options: ED25519KeyPairOptions<"pem", "pem">, + callback: (err: Error | null, publicKey: string, privateKey: string) => void, + ): void; + function generateKeyPair( + type: "ed25519", + options: ED25519KeyPairOptions<"pem", "der">, + callback: (err: Error | null, publicKey: string, privateKey: Buffer) => void, + ): void; + function generateKeyPair( + type: "ed25519", + options: ED25519KeyPairOptions<"der", "pem">, + callback: (err: Error | null, publicKey: Buffer, privateKey: string) => void, + ): void; + function generateKeyPair( + type: "ed25519", + options: ED25519KeyPairOptions<"der", "der">, + callback: (err: Error | null, publicKey: Buffer, privateKey: Buffer) => void, + ): void; + function generateKeyPair( + type: "ed25519", + options: ED25519KeyPairKeyObjectOptions | undefined, + callback: (err: Error | null, publicKey: KeyObject, privateKey: KeyObject) => void, + ): void; + function generateKeyPair( + type: "ed448", + options: ED448KeyPairOptions<"pem", "pem">, + callback: (err: Error | null, publicKey: string, privateKey: string) => void, + ): void; + function generateKeyPair( + type: "ed448", + options: ED448KeyPairOptions<"pem", "der">, + callback: (err: Error | null, publicKey: string, privateKey: Buffer) => void, + ): void; + function generateKeyPair( + type: "ed448", + options: ED448KeyPairOptions<"der", "pem">, + callback: (err: Error | null, publicKey: Buffer, privateKey: string) => void, + ): void; + function generateKeyPair( + type: "ed448", + options: ED448KeyPairOptions<"der", "der">, + callback: (err: Error | null, publicKey: Buffer, privateKey: Buffer) => void, + ): void; + function generateKeyPair( + type: "ed448", + options: ED448KeyPairKeyObjectOptions | undefined, + callback: (err: Error | null, publicKey: KeyObject, privateKey: KeyObject) => void, + ): void; + function generateKeyPair( + type: "x25519", + options: X25519KeyPairOptions<"pem", "pem">, + callback: (err: Error | null, publicKey: string, privateKey: string) => void, + ): void; + function generateKeyPair( + type: "x25519", + options: X25519KeyPairOptions<"pem", "der">, + callback: (err: Error | null, publicKey: string, privateKey: Buffer) => void, + ): void; + function generateKeyPair( + type: "x25519", + options: X25519KeyPairOptions<"der", "pem">, + callback: (err: Error | null, publicKey: Buffer, privateKey: string) => void, + ): void; + function generateKeyPair( + type: "x25519", + options: X25519KeyPairOptions<"der", "der">, + callback: (err: Error | null, publicKey: Buffer, privateKey: Buffer) => void, + ): void; + function generateKeyPair( + type: "x25519", + options: X25519KeyPairKeyObjectOptions | undefined, + callback: (err: Error | null, publicKey: KeyObject, privateKey: KeyObject) => void, + ): void; + function generateKeyPair( + type: "x448", + options: X448KeyPairOptions<"pem", "pem">, + callback: (err: Error | null, publicKey: string, privateKey: string) => void, + ): void; + function generateKeyPair( + type: "x448", + options: X448KeyPairOptions<"pem", "der">, + callback: (err: Error | null, publicKey: string, privateKey: Buffer) => void, + ): void; + function generateKeyPair( + type: "x448", + options: X448KeyPairOptions<"der", "pem">, + callback: (err: Error | null, publicKey: Buffer, privateKey: string) => void, + ): void; + function generateKeyPair( + type: "x448", + options: X448KeyPairOptions<"der", "der">, + callback: (err: Error | null, publicKey: Buffer, privateKey: Buffer) => void, + ): void; + function generateKeyPair( + type: "x448", + options: X448KeyPairKeyObjectOptions | undefined, + callback: (err: Error | null, publicKey: KeyObject, privateKey: KeyObject) => void, + ): void; + namespace generateKeyPair { + function __promisify__( + type: "rsa", + options: RSAKeyPairOptions<"pem", "pem">, + ): Promise<{ + publicKey: string; + privateKey: string; + }>; + function __promisify__( + type: "rsa", + options: RSAKeyPairOptions<"pem", "der">, + ): Promise<{ + publicKey: string; + privateKey: Buffer; + }>; + function __promisify__( + type: "rsa", + options: RSAKeyPairOptions<"der", "pem">, + ): Promise<{ + publicKey: Buffer; + privateKey: string; + }>; + function __promisify__( + type: "rsa", + options: RSAKeyPairOptions<"der", "der">, + ): Promise<{ + publicKey: Buffer; + privateKey: Buffer; + }>; + function __promisify__(type: "rsa", options: RSAKeyPairKeyObjectOptions): Promise; + function __promisify__( + type: "rsa-pss", + options: RSAPSSKeyPairOptions<"pem", "pem">, + ): Promise<{ + publicKey: string; + privateKey: string; + }>; + function __promisify__( + type: "rsa-pss", + options: RSAPSSKeyPairOptions<"pem", "der">, + ): Promise<{ + publicKey: string; + privateKey: Buffer; + }>; + function __promisify__( + type: "rsa-pss", + options: RSAPSSKeyPairOptions<"der", "pem">, + ): Promise<{ + publicKey: Buffer; + privateKey: string; + }>; + function __promisify__( + type: "rsa-pss", + options: RSAPSSKeyPairOptions<"der", "der">, + ): Promise<{ + publicKey: Buffer; + privateKey: Buffer; + }>; + function __promisify__( + type: "rsa-pss", + options: RSAPSSKeyPairKeyObjectOptions, + ): Promise; + function __promisify__( + type: "dsa", + options: DSAKeyPairOptions<"pem", "pem">, + ): Promise<{ + publicKey: string; + privateKey: string; + }>; + function __promisify__( + type: "dsa", + options: DSAKeyPairOptions<"pem", "der">, + ): Promise<{ + publicKey: string; + privateKey: Buffer; + }>; + function __promisify__( + type: "dsa", + options: DSAKeyPairOptions<"der", "pem">, + ): Promise<{ + publicKey: Buffer; + privateKey: string; + }>; + function __promisify__( + type: "dsa", + options: DSAKeyPairOptions<"der", "der">, + ): Promise<{ + publicKey: Buffer; + privateKey: Buffer; + }>; + function __promisify__(type: "dsa", options: DSAKeyPairKeyObjectOptions): Promise; + function __promisify__( + type: "ec", + options: ECKeyPairOptions<"pem", "pem">, + ): Promise<{ + publicKey: string; + privateKey: string; + }>; + function __promisify__( + type: "ec", + options: ECKeyPairOptions<"pem", "der">, + ): Promise<{ + publicKey: string; + privateKey: Buffer; + }>; + function __promisify__( + type: "ec", + options: ECKeyPairOptions<"der", "pem">, + ): Promise<{ + publicKey: Buffer; + privateKey: string; + }>; + function __promisify__( + type: "ec", + options: ECKeyPairOptions<"der", "der">, + ): Promise<{ + publicKey: Buffer; + privateKey: Buffer; + }>; + function __promisify__(type: "ec", options: ECKeyPairKeyObjectOptions): Promise; + function __promisify__( + type: "ed25519", + options: ED25519KeyPairOptions<"pem", "pem">, + ): Promise<{ + publicKey: string; + privateKey: string; + }>; + function __promisify__( + type: "ed25519", + options: ED25519KeyPairOptions<"pem", "der">, + ): Promise<{ + publicKey: string; + privateKey: Buffer; + }>; + function __promisify__( + type: "ed25519", + options: ED25519KeyPairOptions<"der", "pem">, + ): Promise<{ + publicKey: Buffer; + privateKey: string; + }>; + function __promisify__( + type: "ed25519", + options: ED25519KeyPairOptions<"der", "der">, + ): Promise<{ + publicKey: Buffer; + privateKey: Buffer; + }>; + function __promisify__( + type: "ed25519", + options?: ED25519KeyPairKeyObjectOptions, + ): Promise; + function __promisify__( + type: "ed448", + options: ED448KeyPairOptions<"pem", "pem">, + ): Promise<{ + publicKey: string; + privateKey: string; + }>; + function __promisify__( + type: "ed448", + options: ED448KeyPairOptions<"pem", "der">, + ): Promise<{ + publicKey: string; + privateKey: Buffer; + }>; + function __promisify__( + type: "ed448", + options: ED448KeyPairOptions<"der", "pem">, + ): Promise<{ + publicKey: Buffer; + privateKey: string; + }>; + function __promisify__( + type: "ed448", + options: ED448KeyPairOptions<"der", "der">, + ): Promise<{ + publicKey: Buffer; + privateKey: Buffer; + }>; + function __promisify__(type: "ed448", options?: ED448KeyPairKeyObjectOptions): Promise; + function __promisify__( + type: "x25519", + options: X25519KeyPairOptions<"pem", "pem">, + ): Promise<{ + publicKey: string; + privateKey: string; + }>; + function __promisify__( + type: "x25519", + options: X25519KeyPairOptions<"pem", "der">, + ): Promise<{ + publicKey: string; + privateKey: Buffer; + }>; + function __promisify__( + type: "x25519", + options: X25519KeyPairOptions<"der", "pem">, + ): Promise<{ + publicKey: Buffer; + privateKey: string; + }>; + function __promisify__( + type: "x25519", + options: X25519KeyPairOptions<"der", "der">, + ): Promise<{ + publicKey: Buffer; + privateKey: Buffer; + }>; + function __promisify__( + type: "x25519", + options?: X25519KeyPairKeyObjectOptions, + ): Promise; + function __promisify__( + type: "x448", + options: X448KeyPairOptions<"pem", "pem">, + ): Promise<{ + publicKey: string; + privateKey: string; + }>; + function __promisify__( + type: "x448", + options: X448KeyPairOptions<"pem", "der">, + ): Promise<{ + publicKey: string; + privateKey: Buffer; + }>; + function __promisify__( + type: "x448", + options: X448KeyPairOptions<"der", "pem">, + ): Promise<{ + publicKey: Buffer; + privateKey: string; + }>; + function __promisify__( + type: "x448", + options: X448KeyPairOptions<"der", "der">, + ): Promise<{ + publicKey: Buffer; + privateKey: Buffer; + }>; + function __promisify__(type: "x448", options?: X448KeyPairKeyObjectOptions): Promise; + } + /** + * Calculates and returns the signature for `data` using the given private key and + * algorithm. If `algorithm` is `null` or `undefined`, then the algorithm is + * dependent upon the key type (especially Ed25519 and Ed448). + * + * If `key` is not a `KeyObject`, this function behaves as if `key` had been + * passed to {@link createPrivateKey}. If it is an object, the following + * additional properties can be passed: + * + * If the `callback` function is provided this function uses libuv's threadpool. + * @since v12.0.0 + */ + function sign( + algorithm: string | null | undefined, + data: NodeJS.ArrayBufferView, + key: KeyLike | SignKeyObjectInput | SignPrivateKeyInput, + ): Buffer; + function sign( + algorithm: string | null | undefined, + data: NodeJS.ArrayBufferView, + key: KeyLike | SignKeyObjectInput | SignPrivateKeyInput, + callback: (error: Error | null, data: Buffer) => void, + ): void; + /** + * Verifies the given signature for `data` using the given key and algorithm. If `algorithm` is `null` or `undefined`, then the algorithm is dependent upon the + * key type (especially Ed25519 and Ed448). + * + * If `key` is not a `KeyObject`, this function behaves as if `key` had been + * passed to {@link createPublicKey}. If it is an object, the following + * additional properties can be passed: + * + * The `signature` argument is the previously calculated signature for the `data`. + * + * Because public keys can be derived from private keys, a private key or a public + * key may be passed for `key`. + * + * If the `callback` function is provided this function uses libuv's threadpool. + * @since v12.0.0 + */ + function verify( + algorithm: string | null | undefined, + data: NodeJS.ArrayBufferView, + key: KeyLike | VerifyKeyObjectInput | VerifyPublicKeyInput | VerifyJsonWebKeyInput, + signature: NodeJS.ArrayBufferView, + ): boolean; + function verify( + algorithm: string | null | undefined, + data: NodeJS.ArrayBufferView, + key: KeyLike | VerifyKeyObjectInput | VerifyPublicKeyInput | VerifyJsonWebKeyInput, + signature: NodeJS.ArrayBufferView, + callback: (error: Error | null, result: boolean) => void, + ): void; + /** + * Computes the Diffie-Hellman secret based on a `privateKey` and a `publicKey`. + * Both keys must have the same `asymmetricKeyType`, which must be one of `'dh'` (for Diffie-Hellman), `'ec'` (for ECDH), `'x448'`, or `'x25519'` (for ECDH-ES). + * @since v13.9.0, v12.17.0 + */ + function diffieHellman(options: { privateKey: KeyObject; publicKey: KeyObject }): Buffer; + /** + * A utility for creating one-shot hash digests of data. It can be faster than the object-based `crypto.createHash()` when hashing a smaller amount of data + * (<= 5MB) that's readily available. If the data can be big or if it is streamed, it's still recommended to use `crypto.createHash()` instead. The `algorithm` + * is dependent on the available algorithms supported by the version of OpenSSL on the platform. Examples are `'sha256'`, `'sha512'`, etc. On recent releases + * of OpenSSL, `openssl list -digest-algorithms` will display the available digest algorithms. + * + * Example: + * + * ```js + * const crypto = require('node:crypto'); + * const { Buffer } = require('node:buffer'); + * + * // Hashing a string and return the result as a hex-encoded string. + * const string = 'Node.js'; + * // 10b3493287f831e81a438811a1ffba01f8cec4b7 + * console.log(crypto.hash('sha1', string)); + * + * // Encode a base64-encoded string into a Buffer, hash it and return + * // the result as a buffer. + * const base64 = 'Tm9kZS5qcw=='; + * // + * console.log(crypto.hash('sha1', Buffer.from(base64, 'base64'), 'buffer')); + * ``` + * @since v21.7.0, v20.12.0 + * @param data When `data` is a string, it will be encoded as UTF-8 before being hashed. If a different input encoding is desired for a string input, user + * could encode the string into a `TypedArray` using either `TextEncoder` or `Buffer.from()` and passing the encoded `TypedArray` into this API instead. + * @param [outputEncoding='hex'] [Encoding](https://nodejs.org/docs/latest-v20.x/api/buffer.html#buffers-and-character-encodings) used to encode the returned digest. + */ + function hash(algorithm: string, data: BinaryLike, outputEncoding?: BinaryToTextEncoding): string; + function hash(algorithm: string, data: BinaryLike, outputEncoding: "buffer"): Buffer; + function hash( + algorithm: string, + data: BinaryLike, + outputEncoding?: BinaryToTextEncoding | "buffer", + ): string | Buffer; + type CipherMode = "cbc" | "ccm" | "cfb" | "ctr" | "ecb" | "gcm" | "ocb" | "ofb" | "stream" | "wrap" | "xts"; + interface CipherInfoOptions { + /** + * A test key length. + */ + keyLength?: number | undefined; + /** + * A test IV length. + */ + ivLength?: number | undefined; + } + interface CipherInfo { + /** + * The name of the cipher. + */ + name: string; + /** + * The nid of the cipher. + */ + nid: number; + /** + * The block size of the cipher in bytes. + * This property is omitted when mode is 'stream'. + */ + blockSize?: number | undefined; + /** + * The expected or default initialization vector length in bytes. + * This property is omitted if the cipher does not use an initialization vector. + */ + ivLength?: number | undefined; + /** + * The expected or default key length in bytes. + */ + keyLength: number; + /** + * The cipher mode. + */ + mode: CipherMode; + } + /** + * Returns information about a given cipher. + * + * Some ciphers accept variable length keys and initialization vectors. By default, + * the `crypto.getCipherInfo()` method will return the default values for these + * ciphers. To test if a given key length or iv length is acceptable for given + * cipher, use the `keyLength` and `ivLength` options. If the given values are + * unacceptable, `undefined` will be returned. + * @since v15.0.0 + * @param nameOrNid The name or nid of the cipher to query. + */ + function getCipherInfo(nameOrNid: string | number, options?: CipherInfoOptions): CipherInfo | undefined; + /** + * HKDF is a simple key derivation function defined in RFC 5869\. The given `ikm`, `salt` and `info` are used with the `digest` to derive a key of `keylen` bytes. + * + * The supplied `callback` function is called with two arguments: `err` and `derivedKey`. If an errors occurs while deriving the key, `err` will be set; + * otherwise `err` will be `null`. The successfully generated `derivedKey` will + * be passed to the callback as an [ArrayBuffer](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer). An error will be thrown if any + * of the input arguments specify invalid values or types. + * + * ```js + * import { Buffer } from 'node:buffer'; + * const { + * hkdf, + * } = await import('node:crypto'); + * + * hkdf('sha512', 'key', 'salt', 'info', 64, (err, derivedKey) => { + * if (err) throw err; + * console.log(Buffer.from(derivedKey).toString('hex')); // '24156e2...5391653' + * }); + * ``` + * @since v15.0.0 + * @param digest The digest algorithm to use. + * @param ikm The input keying material. Must be provided but can be zero-length. + * @param salt The salt value. Must be provided but can be zero-length. + * @param info Additional info value. Must be provided but can be zero-length, and cannot be more than 1024 bytes. + * @param keylen The length of the key to generate. Must be greater than 0. The maximum allowable value is `255` times the number of bytes produced by the selected digest function (e.g. `sha512` + * generates 64-byte hashes, making the maximum HKDF output 16320 bytes). + */ + function hkdf( + digest: string, + irm: BinaryLike | KeyObject, + salt: BinaryLike, + info: BinaryLike, + keylen: number, + callback: (err: Error | null, derivedKey: ArrayBuffer) => void, + ): void; + /** + * Provides a synchronous HKDF key derivation function as defined in RFC 5869\. The + * given `ikm`, `salt` and `info` are used with the `digest` to derive a key of `keylen` bytes. + * + * The successfully generated `derivedKey` will be returned as an [ArrayBuffer](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer). + * + * An error will be thrown if any of the input arguments specify invalid values or + * types, or if the derived key cannot be generated. + * + * ```js + * import { Buffer } from 'node:buffer'; + * const { + * hkdfSync, + * } = await import('node:crypto'); + * + * const derivedKey = hkdfSync('sha512', 'key', 'salt', 'info', 64); + * console.log(Buffer.from(derivedKey).toString('hex')); // '24156e2...5391653' + * ``` + * @since v15.0.0 + * @param digest The digest algorithm to use. + * @param ikm The input keying material. Must be provided but can be zero-length. + * @param salt The salt value. Must be provided but can be zero-length. + * @param info Additional info value. Must be provided but can be zero-length, and cannot be more than 1024 bytes. + * @param keylen The length of the key to generate. Must be greater than 0. The maximum allowable value is `255` times the number of bytes produced by the selected digest function (e.g. `sha512` + * generates 64-byte hashes, making the maximum HKDF output 16320 bytes). + */ + function hkdfSync( + digest: string, + ikm: BinaryLike | KeyObject, + salt: BinaryLike, + info: BinaryLike, + keylen: number, + ): ArrayBuffer; + interface SecureHeapUsage { + /** + * The total allocated secure heap size as specified using the `--secure-heap=n` command-line flag. + */ + total: number; + /** + * The minimum allocation from the secure heap as specified using the `--secure-heap-min` command-line flag. + */ + min: number; + /** + * The total number of bytes currently allocated from the secure heap. + */ + used: number; + /** + * The calculated ratio of `used` to `total` allocated bytes. + */ + utilization: number; + } + /** + * @since v15.6.0 + */ + function secureHeapUsed(): SecureHeapUsage; + interface RandomUUIDOptions { + /** + * By default, to improve performance, + * Node.js will pre-emptively generate and persistently cache enough + * random data to generate up to 128 random UUIDs. To generate a UUID + * without using the cache, set `disableEntropyCache` to `true`. + * + * @default `false` + */ + disableEntropyCache?: boolean | undefined; + } + type UUID = `${string}-${string}-${string}-${string}-${string}`; + /** + * Generates a random [RFC 4122](https://www.rfc-editor.org/rfc/rfc4122.txt) version 4 UUID. The UUID is generated using a + * cryptographic pseudorandom number generator. + * @since v15.6.0, v14.17.0 + */ + function randomUUID(options?: RandomUUIDOptions): UUID; + interface X509CheckOptions { + /** + * @default 'always' + */ + subject?: "always" | "default" | "never"; + /** + * @default true + */ + wildcards?: boolean; + /** + * @default true + */ + partialWildcards?: boolean; + /** + * @default false + */ + multiLabelWildcards?: boolean; + /** + * @default false + */ + singleLabelSubdomains?: boolean; + } + /** + * Encapsulates an X509 certificate and provides read-only access to + * its information. + * + * ```js + * const { X509Certificate } = await import('node:crypto'); + * + * const x509 = new X509Certificate('{... pem encoded cert ...}'); + * + * console.log(x509.subject); + * ``` + * @since v15.6.0 + */ + class X509Certificate { + /** + * Will be \`true\` if this is a Certificate Authority (CA) certificate. + * @since v15.6.0 + */ + readonly ca: boolean; + /** + * The SHA-1 fingerprint of this certificate. + * + * Because SHA-1 is cryptographically broken and because the security of SHA-1 is + * significantly worse than that of algorithms that are commonly used to sign + * certificates, consider using `x509.fingerprint256` instead. + * @since v15.6.0 + */ + readonly fingerprint: string; + /** + * The SHA-256 fingerprint of this certificate. + * @since v15.6.0 + */ + readonly fingerprint256: string; + /** + * The SHA-512 fingerprint of this certificate. + * + * Because computing the SHA-256 fingerprint is usually faster and because it is + * only half the size of the SHA-512 fingerprint, `x509.fingerprint256` may be + * a better choice. While SHA-512 presumably provides a higher level of security in + * general, the security of SHA-256 matches that of most algorithms that are + * commonly used to sign certificates. + * @since v17.2.0, v16.14.0 + */ + readonly fingerprint512: string; + /** + * The complete subject of this certificate. + * @since v15.6.0 + */ + readonly subject: string; + /** + * The subject alternative name specified for this certificate. + * + * This is a comma-separated list of subject alternative names. Each entry begins + * with a string identifying the kind of the subject alternative name followed by + * a colon and the value associated with the entry. + * + * Earlier versions of Node.js incorrectly assumed that it is safe to split this + * property at the two-character sequence `', '` (see [CVE-2021-44532](https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2021-44532)). However, + * both malicious and legitimate certificates can contain subject alternative names + * that include this sequence when represented as a string. + * + * After the prefix denoting the type of the entry, the remainder of each entry + * might be enclosed in quotes to indicate that the value is a JSON string literal. + * For backward compatibility, Node.js only uses JSON string literals within this + * property when necessary to avoid ambiguity. Third-party code should be prepared + * to handle both possible entry formats. + * @since v15.6.0 + */ + readonly subjectAltName: string | undefined; + /** + * A textual representation of the certificate's authority information access + * extension. + * + * This is a line feed separated list of access descriptions. Each line begins with + * the access method and the kind of the access location, followed by a colon and + * the value associated with the access location. + * + * After the prefix denoting the access method and the kind of the access location, + * the remainder of each line might be enclosed in quotes to indicate that the + * value is a JSON string literal. For backward compatibility, Node.js only uses + * JSON string literals within this property when necessary to avoid ambiguity. + * Third-party code should be prepared to handle both possible entry formats. + * @since v15.6.0 + */ + readonly infoAccess: string | undefined; + /** + * An array detailing the key usages for this certificate. + * @since v15.6.0 + */ + readonly keyUsage: string[]; + /** + * The issuer identification included in this certificate. + * @since v15.6.0 + */ + readonly issuer: string; + /** + * The issuer certificate or `undefined` if the issuer certificate is not + * available. + * @since v15.9.0 + */ + readonly issuerCertificate?: X509Certificate | undefined; + /** + * The public key `KeyObject` for this certificate. + * @since v15.6.0 + */ + readonly publicKey: KeyObject; + /** + * A `Buffer` containing the DER encoding of this certificate. + * @since v15.6.0 + */ + readonly raw: Buffer; + /** + * The serial number of this certificate. + * + * Serial numbers are assigned by certificate authorities and do not uniquely + * identify certificates. Consider using `x509.fingerprint256` as a unique + * identifier instead. + * @since v15.6.0 + */ + readonly serialNumber: string; + /** + * The date/time from which this certificate is considered valid. + * @since v15.6.0 + */ + readonly validFrom: string; + /** + * The date/time until which this certificate is considered valid. + * @since v15.6.0 + */ + readonly validTo: string; + constructor(buffer: BinaryLike); + /** + * Checks whether the certificate matches the given email address. + * + * If the `'subject'` option is undefined or set to `'default'`, the certificate + * subject is only considered if the subject alternative name extension either does + * not exist or does not contain any email addresses. + * + * If the `'subject'` option is set to `'always'` and if the subject alternative + * name extension either does not exist or does not contain a matching email + * address, the certificate subject is considered. + * + * If the `'subject'` option is set to `'never'`, the certificate subject is never + * considered, even if the certificate contains no subject alternative names. + * @since v15.6.0 + * @return Returns `email` if the certificate matches, `undefined` if it does not. + */ + checkEmail(email: string, options?: Pick): string | undefined; + /** + * Checks whether the certificate matches the given host name. + * + * If the certificate matches the given host name, the matching subject name is + * returned. The returned name might be an exact match (e.g., `foo.example.com`) + * or it might contain wildcards (e.g., `*.example.com`). Because host name + * comparisons are case-insensitive, the returned subject name might also differ + * from the given `name` in capitalization. + * + * If the `'subject'` option is undefined or set to `'default'`, the certificate + * subject is only considered if the subject alternative name extension either does + * not exist or does not contain any DNS names. This behavior is consistent with [RFC 2818](https://www.rfc-editor.org/rfc/rfc2818.txt) ("HTTP Over TLS"). + * + * If the `'subject'` option is set to `'always'` and if the subject alternative + * name extension either does not exist or does not contain a matching DNS name, + * the certificate subject is considered. + * + * If the `'subject'` option is set to `'never'`, the certificate subject is never + * considered, even if the certificate contains no subject alternative names. + * @since v15.6.0 + * @return Returns a subject name that matches `name`, or `undefined` if no subject name matches `name`. + */ + checkHost(name: string, options?: X509CheckOptions): string | undefined; + /** + * Checks whether the certificate matches the given IP address (IPv4 or IPv6). + * + * Only [RFC 5280](https://www.rfc-editor.org/rfc/rfc5280.txt) `iPAddress` subject alternative names are considered, and they + * must match the given `ip` address exactly. Other subject alternative names as + * well as the subject field of the certificate are ignored. + * @since v15.6.0 + * @return Returns `ip` if the certificate matches, `undefined` if it does not. + */ + checkIP(ip: string): string | undefined; + /** + * Checks whether this certificate was issued by the given `otherCert`. + * @since v15.6.0 + */ + checkIssued(otherCert: X509Certificate): boolean; + /** + * Checks whether the public key for this certificate is consistent with + * the given private key. + * @since v15.6.0 + * @param privateKey A private key. + */ + checkPrivateKey(privateKey: KeyObject): boolean; + /** + * There is no standard JSON encoding for X509 certificates. The`toJSON()` method returns a string containing the PEM encoded + * certificate. + * @since v15.6.0 + */ + toJSON(): string; + /** + * Returns information about this certificate using the legacy `certificate object` encoding. + * @since v15.6.0 + */ + toLegacyObject(): PeerCertificate; + /** + * Returns the PEM-encoded certificate. + * @since v15.6.0 + */ + toString(): string; + /** + * Verifies that this certificate was signed by the given public key. + * Does not perform any other validation checks on the certificate. + * @since v15.6.0 + * @param publicKey A public key. + */ + verify(publicKey: KeyObject): boolean; + } + type LargeNumberLike = NodeJS.ArrayBufferView | SharedArrayBuffer | ArrayBuffer | bigint; + interface GeneratePrimeOptions { + add?: LargeNumberLike | undefined; + rem?: LargeNumberLike | undefined; + /** + * @default false + */ + safe?: boolean | undefined; + bigint?: boolean | undefined; + } + interface GeneratePrimeOptionsBigInt extends GeneratePrimeOptions { + bigint: true; + } + interface GeneratePrimeOptionsArrayBuffer extends GeneratePrimeOptions { + bigint?: false | undefined; + } + /** + * Generates a pseudorandom prime of `size` bits. + * + * If `options.safe` is `true`, the prime will be a safe prime -- that is, `(prime - 1) / 2` will also be a prime. + * + * The `options.add` and `options.rem` parameters can be used to enforce additional + * requirements, e.g., for Diffie-Hellman: + * + * * If `options.add` and `options.rem` are both set, the prime will satisfy the + * condition that `prime % add = rem`. + * * If only `options.add` is set and `options.safe` is not `true`, the prime will + * satisfy the condition that `prime % add = 1`. + * * If only `options.add` is set and `options.safe` is set to `true`, the prime + * will instead satisfy the condition that `prime % add = 3`. This is necessary + * because `prime % add = 1` for `options.add > 2` would contradict the condition + * enforced by `options.safe`. + * * `options.rem` is ignored if `options.add` is not given. + * + * Both `options.add` and `options.rem` must be encoded as big-endian sequences + * if given as an `ArrayBuffer`, `SharedArrayBuffer`, `TypedArray`, `Buffer`, or `DataView`. + * + * By default, the prime is encoded as a big-endian sequence of octets + * in an [ArrayBuffer](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer). If the `bigint` option is `true`, then a + * [bigint](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt) is provided. + * @since v15.8.0 + * @param size The size (in bits) of the prime to generate. + */ + function generatePrime(size: number, callback: (err: Error | null, prime: ArrayBuffer) => void): void; + function generatePrime( + size: number, + options: GeneratePrimeOptionsBigInt, + callback: (err: Error | null, prime: bigint) => void, + ): void; + function generatePrime( + size: number, + options: GeneratePrimeOptionsArrayBuffer, + callback: (err: Error | null, prime: ArrayBuffer) => void, + ): void; + function generatePrime( + size: number, + options: GeneratePrimeOptions, + callback: (err: Error | null, prime: ArrayBuffer | bigint) => void, + ): void; + /** + * Generates a pseudorandom prime of `size` bits. + * + * If `options.safe` is `true`, the prime will be a safe prime -- that is, `(prime - 1) / 2` will also be a prime. + * + * The `options.add` and `options.rem` parameters can be used to enforce additional + * requirements, e.g., for Diffie-Hellman: + * + * * If `options.add` and `options.rem` are both set, the prime will satisfy the + * condition that `prime % add = rem`. + * * If only `options.add` is set and `options.safe` is not `true`, the prime will + * satisfy the condition that `prime % add = 1`. + * * If only `options.add` is set and `options.safe` is set to `true`, the prime + * will instead satisfy the condition that `prime % add = 3`. This is necessary + * because `prime % add = 1` for `options.add > 2` would contradict the condition + * enforced by `options.safe`. + * * `options.rem` is ignored if `options.add` is not given. + * + * Both `options.add` and `options.rem` must be encoded as big-endian sequences + * if given as an `ArrayBuffer`, `SharedArrayBuffer`, `TypedArray`, `Buffer`, or `DataView`. + * + * By default, the prime is encoded as a big-endian sequence of octets + * in an [ArrayBuffer](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer). If the `bigint` option is `true`, then a + * [bigint](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt) is provided. + * @since v15.8.0 + * @param size The size (in bits) of the prime to generate. + */ + function generatePrimeSync(size: number): ArrayBuffer; + function generatePrimeSync(size: number, options: GeneratePrimeOptionsBigInt): bigint; + function generatePrimeSync(size: number, options: GeneratePrimeOptionsArrayBuffer): ArrayBuffer; + function generatePrimeSync(size: number, options: GeneratePrimeOptions): ArrayBuffer | bigint; + interface CheckPrimeOptions { + /** + * The number of Miller-Rabin probabilistic primality iterations to perform. + * When the value is 0 (zero), a number of checks is used that yields a false positive rate of at most `2**-64` for random input. + * Care must be used when selecting a number of checks. + * Refer to the OpenSSL documentation for the BN_is_prime_ex function nchecks options for more details. + * + * @default 0 + */ + checks?: number | undefined; + } + /** + * Checks the primality of the `candidate`. + * @since v15.8.0 + * @param candidate A possible prime encoded as a sequence of big endian octets of arbitrary length. + */ + function checkPrime(value: LargeNumberLike, callback: (err: Error | null, result: boolean) => void): void; + function checkPrime( + value: LargeNumberLike, + options: CheckPrimeOptions, + callback: (err: Error | null, result: boolean) => void, + ): void; + /** + * Checks the primality of the `candidate`. + * @since v15.8.0 + * @param candidate A possible prime encoded as a sequence of big endian octets of arbitrary length. + * @return `true` if the candidate is a prime with an error probability less than `0.25 ** options.checks`. + */ + function checkPrimeSync(candidate: LargeNumberLike, options?: CheckPrimeOptions): boolean; + /** + * Load and set the `engine` for some or all OpenSSL functions (selected by flags). + * + * `engine` could be either an id or a path to the engine's shared library. + * + * The optional `flags` argument uses `ENGINE_METHOD_ALL` by default. The `flags` is a bit field taking one of or a mix of the following flags (defined in `crypto.constants`): + * + * * `crypto.constants.ENGINE_METHOD_RSA` + * * `crypto.constants.ENGINE_METHOD_DSA` + * * `crypto.constants.ENGINE_METHOD_DH` + * * `crypto.constants.ENGINE_METHOD_RAND` + * * `crypto.constants.ENGINE_METHOD_EC` + * * `crypto.constants.ENGINE_METHOD_CIPHERS` + * * `crypto.constants.ENGINE_METHOD_DIGESTS` + * * `crypto.constants.ENGINE_METHOD_PKEY_METHS` + * * `crypto.constants.ENGINE_METHOD_PKEY_ASN1_METHS` + * * `crypto.constants.ENGINE_METHOD_ALL` + * * `crypto.constants.ENGINE_METHOD_NONE` + * @since v0.11.11 + * @param flags + */ + function setEngine(engine: string, flags?: number): void; + /** + * A convenient alias for {@link webcrypto.getRandomValues}. This + * implementation is not compliant with the Web Crypto spec, to write + * web-compatible code use {@link webcrypto.getRandomValues} instead. + * @since v17.4.0 + * @return Returns `typedArray`. + */ + function getRandomValues(typedArray: T): T; + /** + * A convenient alias for `crypto.webcrypto.subtle`. + * @since v17.4.0 + */ + const subtle: webcrypto.SubtleCrypto; + /** + * An implementation of the Web Crypto API standard. + * + * See the {@link https://nodejs.org/docs/latest/api/webcrypto.html Web Crypto API documentation} for details. + * @since v15.0.0 + */ + const webcrypto: webcrypto.Crypto; + namespace webcrypto { + type BufferSource = ArrayBufferView | ArrayBuffer; + type KeyFormat = "jwk" | "pkcs8" | "raw" | "spki"; + type KeyType = "private" | "public" | "secret"; + type KeyUsage = + | "decrypt" + | "deriveBits" + | "deriveKey" + | "encrypt" + | "sign" + | "unwrapKey" + | "verify" + | "wrapKey"; + type AlgorithmIdentifier = Algorithm | string; + type HashAlgorithmIdentifier = AlgorithmIdentifier; + type NamedCurve = string; + type BigInteger = Uint8Array; + interface AesCbcParams extends Algorithm { + iv: BufferSource; + } + interface AesCtrParams extends Algorithm { + counter: BufferSource; + length: number; + } + interface AesDerivedKeyParams extends Algorithm { + length: number; + } + interface AesGcmParams extends Algorithm { + additionalData?: BufferSource; + iv: BufferSource; + tagLength?: number; + } + interface AesKeyAlgorithm extends KeyAlgorithm { + length: number; + } + interface AesKeyGenParams extends Algorithm { + length: number; + } + interface Algorithm { + name: string; + } + interface EcKeyAlgorithm extends KeyAlgorithm { + namedCurve: NamedCurve; + } + interface EcKeyGenParams extends Algorithm { + namedCurve: NamedCurve; + } + interface EcKeyImportParams extends Algorithm { + namedCurve: NamedCurve; + } + interface EcdhKeyDeriveParams extends Algorithm { + public: CryptoKey; + } + interface EcdsaParams extends Algorithm { + hash: HashAlgorithmIdentifier; + } + interface Ed448Params extends Algorithm { + context?: BufferSource; + } + interface HkdfParams extends Algorithm { + hash: HashAlgorithmIdentifier; + info: BufferSource; + salt: BufferSource; + } + interface HmacImportParams extends Algorithm { + hash: HashAlgorithmIdentifier; + length?: number; + } + interface HmacKeyAlgorithm extends KeyAlgorithm { + hash: KeyAlgorithm; + length: number; + } + interface HmacKeyGenParams extends Algorithm { + hash: HashAlgorithmIdentifier; + length?: number; + } + interface JsonWebKey { + alg?: string; + crv?: string; + d?: string; + dp?: string; + dq?: string; + e?: string; + ext?: boolean; + k?: string; + key_ops?: string[]; + kty?: string; + n?: string; + oth?: RsaOtherPrimesInfo[]; + p?: string; + q?: string; + qi?: string; + use?: string; + x?: string; + y?: string; + } + interface KeyAlgorithm { + name: string; + } + interface Pbkdf2Params extends Algorithm { + hash: HashAlgorithmIdentifier; + iterations: number; + salt: BufferSource; + } + interface RsaHashedImportParams extends Algorithm { + hash: HashAlgorithmIdentifier; + } + interface RsaHashedKeyAlgorithm extends RsaKeyAlgorithm { + hash: KeyAlgorithm; + } + interface RsaHashedKeyGenParams extends RsaKeyGenParams { + hash: HashAlgorithmIdentifier; + } + interface RsaKeyAlgorithm extends KeyAlgorithm { + modulusLength: number; + publicExponent: BigInteger; + } + interface RsaKeyGenParams extends Algorithm { + modulusLength: number; + publicExponent: BigInteger; + } + interface RsaOaepParams extends Algorithm { + label?: BufferSource; + } + interface RsaOtherPrimesInfo { + d?: string; + r?: string; + t?: string; + } + interface RsaPssParams extends Algorithm { + saltLength: number; + } + /** + * Calling `require('node:crypto').webcrypto` returns an instance of the `Crypto` class. + * `Crypto` is a singleton that provides access to the remainder of the crypto API. + * @since v15.0.0 + */ + interface Crypto { + /** + * Provides access to the `SubtleCrypto` API. + * @since v15.0.0 + */ + readonly subtle: SubtleCrypto; + /** + * Generates cryptographically strong random values. + * The given `typedArray` is filled with random values, and a reference to `typedArray` is returned. + * + * The given `typedArray` must be an integer-based instance of {@link NodeJS.TypedArray}, i.e. `Float32Array` and `Float64Array` are not accepted. + * + * An error will be thrown if the given `typedArray` is larger than 65,536 bytes. + * @since v15.0.0 + */ + getRandomValues>(typedArray: T): T; + /** + * Generates a random {@link https://www.rfc-editor.org/rfc/rfc4122.txt RFC 4122} version 4 UUID. + * The UUID is generated using a cryptographic pseudorandom number generator. + * @since v16.7.0 + */ + randomUUID(): UUID; + CryptoKey: CryptoKeyConstructor; + } + // This constructor throws ILLEGAL_CONSTRUCTOR so it should not be newable. + interface CryptoKeyConstructor { + /** Illegal constructor */ + (_: { readonly _: unique symbol }): never; // Allows instanceof to work but not be callable by the user. + readonly length: 0; + readonly name: "CryptoKey"; + readonly prototype: CryptoKey; + } + /** + * @since v15.0.0 + */ + interface CryptoKey { + /** + * An object detailing the algorithm for which the key can be used along with additional algorithm-specific parameters. + * @since v15.0.0 + */ + readonly algorithm: KeyAlgorithm; + /** + * When `true`, the {@link CryptoKey} can be extracted using either `subtleCrypto.exportKey()` or `subtleCrypto.wrapKey()`. + * @since v15.0.0 + */ + readonly extractable: boolean; + /** + * A string identifying whether the key is a symmetric (`'secret'`) or asymmetric (`'private'` or `'public'`) key. + * @since v15.0.0 + */ + readonly type: KeyType; + /** + * An array of strings identifying the operations for which the key may be used. + * + * The possible usages are: + * - `'encrypt'` - The key may be used to encrypt data. + * - `'decrypt'` - The key may be used to decrypt data. + * - `'sign'` - The key may be used to generate digital signatures. + * - `'verify'` - The key may be used to verify digital signatures. + * - `'deriveKey'` - The key may be used to derive a new key. + * - `'deriveBits'` - The key may be used to derive bits. + * - `'wrapKey'` - The key may be used to wrap another key. + * - `'unwrapKey'` - The key may be used to unwrap another key. + * + * Valid key usages depend on the key algorithm (identified by `cryptokey.algorithm.name`). + * @since v15.0.0 + */ + readonly usages: KeyUsage[]; + } + /** + * The `CryptoKeyPair` is a simple dictionary object with `publicKey` and `privateKey` properties, representing an asymmetric key pair. + * @since v15.0.0 + */ + interface CryptoKeyPair { + /** + * A {@link CryptoKey} whose type will be `'private'`. + * @since v15.0.0 + */ + privateKey: CryptoKey; + /** + * A {@link CryptoKey} whose type will be `'public'`. + * @since v15.0.0 + */ + publicKey: CryptoKey; + } + /** + * @since v15.0.0 + */ + interface SubtleCrypto { + /** + * Using the method and parameters specified in `algorithm` and the keying material provided by `key`, + * `subtle.decrypt()` attempts to decipher the provided `data`. If successful, + * the returned promise will be resolved with an `` containing the plaintext result. + * + * The algorithms currently supported include: + * + * - `'RSA-OAEP'` + * - `'AES-CTR'` + * - `'AES-CBC'` + * - `'AES-GCM'` + * @since v15.0.0 + */ + decrypt( + algorithm: AlgorithmIdentifier | RsaOaepParams | AesCtrParams | AesCbcParams | AesGcmParams, + key: CryptoKey, + data: BufferSource, + ): Promise; + /** + * Using the method and parameters specified in `algorithm` and the keying material provided by `baseKey`, + * `subtle.deriveBits()` attempts to generate `length` bits. + * The Node.js implementation requires that when `length` is a number it must be multiple of `8`. + * When `length` is `null` the maximum number of bits for a given algorithm is generated. This is allowed + * for the `'ECDH'`, `'X25519'`, and `'X448'` algorithms. + * If successful, the returned promise will be resolved with an `` containing the generated data. + * + * The algorithms currently supported include: + * + * - `'ECDH'` + * - `'X25519'` + * - `'X448'` + * - `'HKDF'` + * - `'PBKDF2'` + * @since v15.0.0 + */ + deriveBits(algorithm: EcdhKeyDeriveParams, baseKey: CryptoKey, length: number | null): Promise; + deriveBits( + algorithm: AlgorithmIdentifier | HkdfParams | Pbkdf2Params, + baseKey: CryptoKey, + length: number, + ): Promise; + /** + * Using the method and parameters specified in `algorithm`, and the keying material provided by `baseKey`, + * `subtle.deriveKey()` attempts to generate a new ` based on the method and parameters in `derivedKeyAlgorithm`. + * + * Calling `subtle.deriveKey()` is equivalent to calling `subtle.deriveBits()` to generate raw keying material, + * then passing the result into the `subtle.importKey()` method using the `deriveKeyAlgorithm`, `extractable`, and `keyUsages` parameters as input. + * + * The algorithms currently supported include: + * + * - `'ECDH'` + * - `'X25519'` + * - `'X448'` + * - `'HKDF'` + * - `'PBKDF2'` + * @param keyUsages See {@link https://nodejs.org/docs/latest/api/webcrypto.html#cryptokeyusages Key usages}. + * @since v15.0.0 + */ + deriveKey( + algorithm: AlgorithmIdentifier | EcdhKeyDeriveParams | HkdfParams | Pbkdf2Params, + baseKey: CryptoKey, + derivedKeyAlgorithm: + | AlgorithmIdentifier + | AesDerivedKeyParams + | HmacImportParams + | HkdfParams + | Pbkdf2Params, + extractable: boolean, + keyUsages: readonly KeyUsage[], + ): Promise; + /** + * Using the method identified by `algorithm`, `subtle.digest()` attempts to generate a digest of `data`. + * If successful, the returned promise is resolved with an `` containing the computed digest. + * + * If `algorithm` is provided as a ``, it must be one of: + * + * - `'SHA-1'` + * - `'SHA-256'` + * - `'SHA-384'` + * - `'SHA-512'` + * + * If `algorithm` is provided as an ``, it must have a `name` property whose value is one of the above. + * @since v15.0.0 + */ + digest(algorithm: AlgorithmIdentifier, data: BufferSource): Promise; + /** + * Using the method and parameters specified by `algorithm` and the keying material provided by `key`, + * `subtle.encrypt()` attempts to encipher `data`. If successful, + * the returned promise is resolved with an `` containing the encrypted result. + * + * The algorithms currently supported include: + * + * - `'RSA-OAEP'` + * - `'AES-CTR'` + * - `'AES-CBC'` + * - `'AES-GCM'` + * @since v15.0.0 + */ + encrypt( + algorithm: AlgorithmIdentifier | RsaOaepParams | AesCtrParams | AesCbcParams | AesGcmParams, + key: CryptoKey, + data: BufferSource, + ): Promise; + /** + * Exports the given key into the specified format, if supported. + * + * If the `` is not extractable, the returned promise will reject. + * + * When `format` is either `'pkcs8'` or `'spki'` and the export is successful, + * the returned promise will be resolved with an `` containing the exported key data. + * + * When `format` is `'jwk'` and the export is successful, the returned promise will be resolved with a + * JavaScript object conforming to the {@link https://tools.ietf.org/html/rfc7517 JSON Web Key} specification. + * @param format Must be one of `'raw'`, `'pkcs8'`, `'spki'`, or `'jwk'`. + * @returns `` containing ``. + * @since v15.0.0 + */ + exportKey(format: "jwk", key: CryptoKey): Promise; + exportKey(format: Exclude, key: CryptoKey): Promise; + /** + * Using the method and parameters provided in `algorithm`, + * `subtle.generateKey()` attempts to generate new keying material. + * Depending the method used, the method may generate either a single `` or a ``. + * + * The `` (public and private key) generating algorithms supported include: + * + * - `'RSASSA-PKCS1-v1_5'` + * - `'RSA-PSS'` + * - `'RSA-OAEP'` + * - `'ECDSA'` + * - `'Ed25519'` + * - `'Ed448'` + * - `'ECDH'` + * - `'X25519'` + * - `'X448'` + * The `` (secret key) generating algorithms supported include: + * + * - `'HMAC'` + * - `'AES-CTR'` + * - `'AES-CBC'` + * - `'AES-GCM'` + * - `'AES-KW'` + * @param keyUsages See {@link https://nodejs.org/docs/latest/api/webcrypto.html#cryptokeyusages Key usages}. + * @since v15.0.0 + */ + generateKey( + algorithm: RsaHashedKeyGenParams | EcKeyGenParams, + extractable: boolean, + keyUsages: readonly KeyUsage[], + ): Promise; + generateKey( + algorithm: AesKeyGenParams | HmacKeyGenParams | Pbkdf2Params, + extractable: boolean, + keyUsages: readonly KeyUsage[], + ): Promise; + generateKey( + algorithm: AlgorithmIdentifier, + extractable: boolean, + keyUsages: KeyUsage[], + ): Promise; + /** + * The `subtle.importKey()` method attempts to interpret the provided `keyData` as the given `format` + * to create a `` instance using the provided `algorithm`, `extractable`, and `keyUsages` arguments. + * If the import is successful, the returned promise will be resolved with the created ``. + * + * If importing a `'PBKDF2'` key, `extractable` must be `false`. + * @param format Must be one of `'raw'`, `'pkcs8'`, `'spki'`, or `'jwk'`. + * @param keyUsages See {@link https://nodejs.org/docs/latest/api/webcrypto.html#cryptokeyusages Key usages}. + * @since v15.0.0 + */ + importKey( + format: "jwk", + keyData: JsonWebKey, + algorithm: + | AlgorithmIdentifier + | RsaHashedImportParams + | EcKeyImportParams + | HmacImportParams + | AesKeyAlgorithm, + extractable: boolean, + keyUsages: readonly KeyUsage[], + ): Promise; + importKey( + format: Exclude, + keyData: BufferSource, + algorithm: + | AlgorithmIdentifier + | RsaHashedImportParams + | EcKeyImportParams + | HmacImportParams + | AesKeyAlgorithm, + extractable: boolean, + keyUsages: KeyUsage[], + ): Promise; + /** + * Using the method and parameters given by `algorithm` and the keying material provided by `key`, + * `subtle.sign()` attempts to generate a cryptographic signature of `data`. If successful, + * the returned promise is resolved with an `` containing the generated signature. + * + * The algorithms currently supported include: + * + * - `'RSASSA-PKCS1-v1_5'` + * - `'RSA-PSS'` + * - `'ECDSA'` + * - `'Ed25519'` + * - `'Ed448'` + * - `'HMAC'` + * @since v15.0.0 + */ + sign( + algorithm: AlgorithmIdentifier | RsaPssParams | EcdsaParams | Ed448Params, + key: CryptoKey, + data: BufferSource, + ): Promise; + /** + * In cryptography, "wrapping a key" refers to exporting and then encrypting the keying material. + * The `subtle.unwrapKey()` method attempts to decrypt a wrapped key and create a `` instance. + * It is equivalent to calling `subtle.decrypt()` first on the encrypted key data (using the `wrappedKey`, `unwrapAlgo`, and `unwrappingKey` arguments as input) + * then passing the results in to the `subtle.importKey()` method using the `unwrappedKeyAlgo`, `extractable`, and `keyUsages` arguments as inputs. + * If successful, the returned promise is resolved with a `` object. + * + * The wrapping algorithms currently supported include: + * + * - `'RSA-OAEP'` + * - `'AES-CTR'` + * - `'AES-CBC'` + * - `'AES-GCM'` + * - `'AES-KW'` + * + * The unwrapped key algorithms supported include: + * + * - `'RSASSA-PKCS1-v1_5'` + * - `'RSA-PSS'` + * - `'RSA-OAEP'` + * - `'ECDSA'` + * - `'Ed25519'` + * - `'Ed448'` + * - `'ECDH'` + * - `'X25519'` + * - `'X448'` + * - `'HMAC'` + * - `'AES-CTR'` + * - `'AES-CBC'` + * - `'AES-GCM'` + * - `'AES-KW'` + * @param format Must be one of `'raw'`, `'pkcs8'`, `'spki'`, or `'jwk'`. + * @param keyUsages See {@link https://nodejs.org/docs/latest/api/webcrypto.html#cryptokeyusages Key usages}. + * @since v15.0.0 + */ + unwrapKey( + format: KeyFormat, + wrappedKey: BufferSource, + unwrappingKey: CryptoKey, + unwrapAlgorithm: AlgorithmIdentifier | RsaOaepParams | AesCtrParams | AesCbcParams | AesGcmParams, + unwrappedKeyAlgorithm: + | AlgorithmIdentifier + | RsaHashedImportParams + | EcKeyImportParams + | HmacImportParams + | AesKeyAlgorithm, + extractable: boolean, + keyUsages: KeyUsage[], + ): Promise; + /** + * Using the method and parameters given in `algorithm` and the keying material provided by `key`, + * `subtle.verify()` attempts to verify that `signature` is a valid cryptographic signature of `data`. + * The returned promise is resolved with either `true` or `false`. + * + * The algorithms currently supported include: + * + * - `'RSASSA-PKCS1-v1_5'` + * - `'RSA-PSS'` + * - `'ECDSA'` + * - `'Ed25519'` + * - `'Ed448'` + * - `'HMAC'` + * @since v15.0.0 + */ + verify( + algorithm: AlgorithmIdentifier | RsaPssParams | EcdsaParams | Ed448Params, + key: CryptoKey, + signature: BufferSource, + data: BufferSource, + ): Promise; + /** + * In cryptography, "wrapping a key" refers to exporting and then encrypting the keying material. + * The `subtle.wrapKey()` method exports the keying material into the format identified by `format`, + * then encrypts it using the method and parameters specified by `wrapAlgo` and the keying material provided by `wrappingKey`. + * It is the equivalent to calling `subtle.exportKey()` using `format` and `key` as the arguments, + * then passing the result to the `subtle.encrypt()` method using `wrappingKey` and `wrapAlgo` as inputs. + * If successful, the returned promise will be resolved with an `` containing the encrypted key data. + * + * The wrapping algorithms currently supported include: + * + * - `'RSA-OAEP'` + * - `'AES-CTR'` + * - `'AES-CBC'` + * - `'AES-GCM'` + * - `'AES-KW'` + * @param format Must be one of `'raw'`, `'pkcs8'`, `'spki'`, or `'jwk'`. + * @since v15.0.0 + */ + wrapKey( + format: KeyFormat, + key: CryptoKey, + wrappingKey: CryptoKey, + wrapAlgorithm: AlgorithmIdentifier | RsaOaepParams | AesCtrParams | AesCbcParams | AesGcmParams, + ): Promise; + } + } + + global { + var crypto: typeof globalThis extends { + crypto: infer T; + onmessage: any; + } ? T + : webcrypto.Crypto; + } +} +declare module "node:crypto" { + export * from "crypto"; +} diff --git a/node_modules/@types/node/dgram.d.ts b/node_modules/@types/node/dgram.d.ts new file mode 100644 index 0000000..3843f23 --- /dev/null +++ b/node_modules/@types/node/dgram.d.ts @@ -0,0 +1,596 @@ +/** + * The `node:dgram` module provides an implementation of UDP datagram sockets. + * + * ```js + * import dgram from 'node:dgram'; + * + * const server = dgram.createSocket('udp4'); + * + * server.on('error', (err) => { + * console.error(`server error:\n${err.stack}`); + * server.close(); + * }); + * + * server.on('message', (msg, rinfo) => { + * console.log(`server got: ${msg} from ${rinfo.address}:${rinfo.port}`); + * }); + * + * server.on('listening', () => { + * const address = server.address(); + * console.log(`server listening ${address.address}:${address.port}`); + * }); + * + * server.bind(41234); + * // Prints: server listening 0.0.0.0:41234 + * ``` + * @see [source](https://github.com/nodejs/node/blob/v20.13.1/lib/dgram.js) + */ +declare module "dgram" { + import { AddressInfo } from "node:net"; + import * as dns from "node:dns"; + import { Abortable, EventEmitter } from "node:events"; + interface RemoteInfo { + address: string; + family: "IPv4" | "IPv6"; + port: number; + size: number; + } + interface BindOptions { + port?: number | undefined; + address?: string | undefined; + exclusive?: boolean | undefined; + fd?: number | undefined; + } + type SocketType = "udp4" | "udp6"; + interface SocketOptions extends Abortable { + type: SocketType; + reuseAddr?: boolean | undefined; + /** + * @default false + */ + ipv6Only?: boolean | undefined; + recvBufferSize?: number | undefined; + sendBufferSize?: number | undefined; + lookup?: + | (( + hostname: string, + options: dns.LookupOneOptions, + callback: (err: NodeJS.ErrnoException | null, address: string, family: number) => void, + ) => void) + | undefined; + } + /** + * Creates a `dgram.Socket` object. Once the socket is created, calling `socket.bind()` will instruct the socket to begin listening for datagram + * messages. When `address` and `port` are not passed to `socket.bind()` the + * method will bind the socket to the "all interfaces" address on a random port + * (it does the right thing for both `udp4` and `udp6` sockets). The bound address + * and port can be retrieved using `socket.address().address` and `socket.address().port`. + * + * If the `signal` option is enabled, calling `.abort()` on the corresponding `AbortController` is similar to calling `.close()` on the socket: + * + * ```js + * const controller = new AbortController(); + * const { signal } = controller; + * const server = dgram.createSocket({ type: 'udp4', signal }); + * server.on('message', (msg, rinfo) => { + * console.log(`server got: ${msg} from ${rinfo.address}:${rinfo.port}`); + * }); + * // Later, when you want to close the server. + * controller.abort(); + * ``` + * @since v0.11.13 + * @param options Available options are: + * @param callback Attached as a listener for `'message'` events. Optional. + */ + function createSocket(type: SocketType, callback?: (msg: Buffer, rinfo: RemoteInfo) => void): Socket; + function createSocket(options: SocketOptions, callback?: (msg: Buffer, rinfo: RemoteInfo) => void): Socket; + /** + * Encapsulates the datagram functionality. + * + * New instances of `dgram.Socket` are created using {@link createSocket}. + * The `new` keyword is not to be used to create `dgram.Socket` instances. + * @since v0.1.99 + */ + class Socket extends EventEmitter { + /** + * Tells the kernel to join a multicast group at the given `multicastAddress` and `multicastInterface` using the `IP_ADD_MEMBERSHIP` socket option. If the `multicastInterface` argument is not + * specified, the operating system will choose + * one interface and will add membership to it. To add membership to every + * available interface, call `addMembership` multiple times, once per interface. + * + * When called on an unbound socket, this method will implicitly bind to a random + * port, listening on all interfaces. + * + * When sharing a UDP socket across multiple `cluster` workers, the`socket.addMembership()` function must be called only once or an`EADDRINUSE` error will occur: + * + * ```js + * import cluster from 'node:cluster'; + * import dgram from 'node:dgram'; + * + * if (cluster.isPrimary) { + * cluster.fork(); // Works ok. + * cluster.fork(); // Fails with EADDRINUSE. + * } else { + * const s = dgram.createSocket('udp4'); + * s.bind(1234, () => { + * s.addMembership('224.0.0.114'); + * }); + * } + * ``` + * @since v0.6.9 + */ + addMembership(multicastAddress: string, multicastInterface?: string): void; + /** + * Returns an object containing the address information for a socket. + * For UDP sockets, this object will contain `address`, `family`, and `port` properties. + * + * This method throws `EBADF` if called on an unbound socket. + * @since v0.1.99 + */ + address(): AddressInfo; + /** + * For UDP sockets, causes the `dgram.Socket` to listen for datagram + * messages on a named `port` and optional `address`. If `port` is not + * specified or is `0`, the operating system will attempt to bind to a + * random port. If `address` is not specified, the operating system will + * attempt to listen on all addresses. Once binding is complete, a `'listening'` event is emitted and the optional `callback` function is + * called. + * + * Specifying both a `'listening'` event listener and passing a `callback` to the `socket.bind()` method is not harmful but not very + * useful. + * + * A bound datagram socket keeps the Node.js process running to receive + * datagram messages. + * + * If binding fails, an `'error'` event is generated. In rare case (e.g. + * attempting to bind with a closed socket), an `Error` may be thrown. + * + * Example of a UDP server listening on port 41234: + * + * ```js + * import dgram from 'node:dgram'; + * + * const server = dgram.createSocket('udp4'); + * + * server.on('error', (err) => { + * console.error(`server error:\n${err.stack}`); + * server.close(); + * }); + * + * server.on('message', (msg, rinfo) => { + * console.log(`server got: ${msg} from ${rinfo.address}:${rinfo.port}`); + * }); + * + * server.on('listening', () => { + * const address = server.address(); + * console.log(`server listening ${address.address}:${address.port}`); + * }); + * + * server.bind(41234); + * // Prints: server listening 0.0.0.0:41234 + * ``` + * @since v0.1.99 + * @param callback with no parameters. Called when binding is complete. + */ + bind(port?: number, address?: string, callback?: () => void): this; + bind(port?: number, callback?: () => void): this; + bind(callback?: () => void): this; + bind(options: BindOptions, callback?: () => void): this; + /** + * Close the underlying socket and stop listening for data on it. If a callback is + * provided, it is added as a listener for the `'close'` event. + * @since v0.1.99 + * @param callback Called when the socket has been closed. + */ + close(callback?: () => void): this; + /** + * Associates the `dgram.Socket` to a remote address and port. Every + * message sent by this handle is automatically sent to that destination. Also, + * the socket will only receive messages from that remote peer. + * Trying to call `connect()` on an already connected socket will result + * in an `ERR_SOCKET_DGRAM_IS_CONNECTED` exception. If `address` is not + * provided, `'127.0.0.1'` (for `udp4` sockets) or `'::1'` (for `udp6` sockets) + * will be used by default. Once the connection is complete, a `'connect'` event + * is emitted and the optional `callback` function is called. In case of failure, + * the `callback` is called or, failing this, an `'error'` event is emitted. + * @since v12.0.0 + * @param callback Called when the connection is completed or on error. + */ + connect(port: number, address?: string, callback?: () => void): void; + connect(port: number, callback: () => void): void; + /** + * A synchronous function that disassociates a connected `dgram.Socket` from + * its remote address. Trying to call `disconnect()` on an unbound or already + * disconnected socket will result in an `ERR_SOCKET_DGRAM_NOT_CONNECTED` exception. + * @since v12.0.0 + */ + disconnect(): void; + /** + * Instructs the kernel to leave a multicast group at `multicastAddress` using the `IP_DROP_MEMBERSHIP` socket option. This method is automatically called by the + * kernel when the socket is closed or the process terminates, so most apps will + * never have reason to call this. + * + * If `multicastInterface` is not specified, the operating system will attempt to + * drop membership on all valid interfaces. + * @since v0.6.9 + */ + dropMembership(multicastAddress: string, multicastInterface?: string): void; + /** + * This method throws `ERR_SOCKET_BUFFER_SIZE` if called on an unbound socket. + * @since v8.7.0 + * @return the `SO_RCVBUF` socket receive buffer size in bytes. + */ + getRecvBufferSize(): number; + /** + * This method throws `ERR_SOCKET_BUFFER_SIZE` if called on an unbound socket. + * @since v8.7.0 + * @return the `SO_SNDBUF` socket send buffer size in bytes. + */ + getSendBufferSize(): number; + /** + * @since v18.8.0, v16.19.0 + * @return Number of bytes queued for sending. + */ + getSendQueueSize(): number; + /** + * @since v18.8.0, v16.19.0 + * @return Number of send requests currently in the queue awaiting to be processed. + */ + getSendQueueCount(): number; + /** + * By default, binding a socket will cause it to block the Node.js process from + * exiting as long as the socket is open. The `socket.unref()` method can be used + * to exclude the socket from the reference counting that keeps the Node.js + * process active. The `socket.ref()` method adds the socket back to the reference + * counting and restores the default behavior. + * + * Calling `socket.ref()` multiples times will have no additional effect. + * + * The `socket.ref()` method returns a reference to the socket so calls can be + * chained. + * @since v0.9.1 + */ + ref(): this; + /** + * Returns an object containing the `address`, `family`, and `port` of the remote + * endpoint. This method throws an `ERR_SOCKET_DGRAM_NOT_CONNECTED` exception + * if the socket is not connected. + * @since v12.0.0 + */ + remoteAddress(): AddressInfo; + /** + * Broadcasts a datagram on the socket. + * For connectionless sockets, the destination `port` and `address` must be + * specified. Connected sockets, on the other hand, will use their associated + * remote endpoint, so the `port` and `address` arguments must not be set. + * + * The `msg` argument contains the message to be sent. + * Depending on its type, different behavior can apply. If `msg` is a `Buffer`, + * any `TypedArray` or a `DataView`, + * the `offset` and `length` specify the offset within the `Buffer` where the + * message begins and the number of bytes in the message, respectively. + * If `msg` is a `String`, then it is automatically converted to a `Buffer` with `'utf8'` encoding. With messages that + * contain multi-byte characters, `offset` and `length` will be calculated with + * respect to `byte length` and not the character position. + * If `msg` is an array, `offset` and `length` must not be specified. + * + * The `address` argument is a string. If the value of `address` is a host name, + * DNS will be used to resolve the address of the host. If `address` is not + * provided or otherwise nullish, `'127.0.0.1'` (for `udp4` sockets) or `'::1'` (for `udp6` sockets) will be used by default. + * + * If the socket has not been previously bound with a call to `bind`, the socket + * is assigned a random port number and is bound to the "all interfaces" address + * (`'0.0.0.0'` for `udp4` sockets, `'::0'` for `udp6` sockets.) + * + * An optional `callback` function may be specified to as a way of reporting + * DNS errors or for determining when it is safe to reuse the `buf` object. + * DNS lookups delay the time to send for at least one tick of the + * Node.js event loop. + * + * The only way to know for sure that the datagram has been sent is by using a `callback`. If an error occurs and a `callback` is given, the error will be + * passed as the first argument to the `callback`. If a `callback` is not given, + * the error is emitted as an `'error'` event on the `socket` object. + * + * Offset and length are optional but both _must_ be set if either are used. + * They are supported only when the first argument is a `Buffer`, a `TypedArray`, + * or a `DataView`. + * + * This method throws `ERR_SOCKET_BAD_PORT` if called on an unbound socket. + * + * Example of sending a UDP packet to a port on `localhost`; + * + * ```js + * import dgram from 'node:dgram'; + * import { Buffer } from 'node:buffer'; + * + * const message = Buffer.from('Some bytes'); + * const client = dgram.createSocket('udp4'); + * client.send(message, 41234, 'localhost', (err) => { + * client.close(); + * }); + * ``` + * + * Example of sending a UDP packet composed of multiple buffers to a port on`127.0.0.1`; + * + * ```js + * import dgram from 'node:dgram'; + * import { Buffer } from 'node:buffer'; + * + * const buf1 = Buffer.from('Some '); + * const buf2 = Buffer.from('bytes'); + * const client = dgram.createSocket('udp4'); + * client.send([buf1, buf2], 41234, (err) => { + * client.close(); + * }); + * ``` + * + * Sending multiple buffers might be faster or slower depending on the + * application and operating system. Run benchmarks to + * determine the optimal strategy on a case-by-case basis. Generally speaking, + * however, sending multiple buffers is faster. + * + * Example of sending a UDP packet using a socket connected to a port on `localhost`: + * + * ```js + * import dgram from 'node:dgram'; + * import { Buffer } from 'node:buffer'; + * + * const message = Buffer.from('Some bytes'); + * const client = dgram.createSocket('udp4'); + * client.connect(41234, 'localhost', (err) => { + * client.send(message, (err) => { + * client.close(); + * }); + * }); + * ``` + * @since v0.1.99 + * @param msg Message to be sent. + * @param offset Offset in the buffer where the message starts. + * @param length Number of bytes in the message. + * @param port Destination port. + * @param address Destination host name or IP address. + * @param callback Called when the message has been sent. + */ + send( + msg: string | Uint8Array | readonly any[], + port?: number, + address?: string, + callback?: (error: Error | null, bytes: number) => void, + ): void; + send( + msg: string | Uint8Array | readonly any[], + port?: number, + callback?: (error: Error | null, bytes: number) => void, + ): void; + send( + msg: string | Uint8Array | readonly any[], + callback?: (error: Error | null, bytes: number) => void, + ): void; + send( + msg: string | Uint8Array, + offset: number, + length: number, + port?: number, + address?: string, + callback?: (error: Error | null, bytes: number) => void, + ): void; + send( + msg: string | Uint8Array, + offset: number, + length: number, + port?: number, + callback?: (error: Error | null, bytes: number) => void, + ): void; + send( + msg: string | Uint8Array, + offset: number, + length: number, + callback?: (error: Error | null, bytes: number) => void, + ): void; + /** + * Sets or clears the `SO_BROADCAST` socket option. When set to `true`, UDP + * packets may be sent to a local interface's broadcast address. + * + * This method throws `EBADF` if called on an unbound socket. + * @since v0.6.9 + */ + setBroadcast(flag: boolean): void; + /** + * _All references to scope in this section are referring to [IPv6 Zone Indices](https://en.wikipedia.org/wiki/IPv6_address#Scoped_literal_IPv6_addresses), which are defined by [RFC + * 4007](https://tools.ietf.org/html/rfc4007). In string form, an IP_ + * _with a scope index is written as `'IP%scope'` where scope is an interface name_ + * _or interface number._ + * + * Sets the default outgoing multicast interface of the socket to a chosen + * interface or back to system interface selection. The `multicastInterface` must + * be a valid string representation of an IP from the socket's family. + * + * For IPv4 sockets, this should be the IP configured for the desired physical + * interface. All packets sent to multicast on the socket will be sent on the + * interface determined by the most recent successful use of this call. + * + * For IPv6 sockets, `multicastInterface` should include a scope to indicate the + * interface as in the examples that follow. In IPv6, individual `send` calls can + * also use explicit scope in addresses, so only packets sent to a multicast + * address without specifying an explicit scope are affected by the most recent + * successful use of this call. + * + * This method throws `EBADF` if called on an unbound socket. + * + * #### Example: IPv6 outgoing multicast interface + * + * On most systems, where scope format uses the interface name: + * + * ```js + * const socket = dgram.createSocket('udp6'); + * + * socket.bind(1234, () => { + * socket.setMulticastInterface('::%eth1'); + * }); + * ``` + * + * On Windows, where scope format uses an interface number: + * + * ```js + * const socket = dgram.createSocket('udp6'); + * + * socket.bind(1234, () => { + * socket.setMulticastInterface('::%2'); + * }); + * ``` + * + * #### Example: IPv4 outgoing multicast interface + * + * All systems use an IP of the host on the desired physical interface: + * + * ```js + * const socket = dgram.createSocket('udp4'); + * + * socket.bind(1234, () => { + * socket.setMulticastInterface('10.0.0.2'); + * }); + * ``` + * @since v8.6.0 + */ + setMulticastInterface(multicastInterface: string): void; + /** + * Sets or clears the `IP_MULTICAST_LOOP` socket option. When set to `true`, + * multicast packets will also be received on the local interface. + * + * This method throws `EBADF` if called on an unbound socket. + * @since v0.3.8 + */ + setMulticastLoopback(flag: boolean): boolean; + /** + * Sets the `IP_MULTICAST_TTL` socket option. While TTL generally stands for + * "Time to Live", in this context it specifies the number of IP hops that a + * packet is allowed to travel through, specifically for multicast traffic. Each + * router or gateway that forwards a packet decrements the TTL. If the TTL is + * decremented to 0 by a router, it will not be forwarded. + * + * The `ttl` argument may be between 0 and 255\. The default on most systems is `1`. + * + * This method throws `EBADF` if called on an unbound socket. + * @since v0.3.8 + */ + setMulticastTTL(ttl: number): number; + /** + * Sets the `SO_RCVBUF` socket option. Sets the maximum socket receive buffer + * in bytes. + * + * This method throws `ERR_SOCKET_BUFFER_SIZE` if called on an unbound socket. + * @since v8.7.0 + */ + setRecvBufferSize(size: number): void; + /** + * Sets the `SO_SNDBUF` socket option. Sets the maximum socket send buffer + * in bytes. + * + * This method throws `ERR_SOCKET_BUFFER_SIZE` if called on an unbound socket. + * @since v8.7.0 + */ + setSendBufferSize(size: number): void; + /** + * Sets the `IP_TTL` socket option. While TTL generally stands for "Time to Live", + * in this context it specifies the number of IP hops that a packet is allowed to + * travel through. Each router or gateway that forwards a packet decrements the + * TTL. If the TTL is decremented to 0 by a router, it will not be forwarded. + * Changing TTL values is typically done for network probes or when multicasting. + * + * The `ttl` argument may be between 1 and 255\. The default on most systems + * is 64. + * + * This method throws `EBADF` if called on an unbound socket. + * @since v0.1.101 + */ + setTTL(ttl: number): number; + /** + * By default, binding a socket will cause it to block the Node.js process from + * exiting as long as the socket is open. The `socket.unref()` method can be used + * to exclude the socket from the reference counting that keeps the Node.js + * process active, allowing the process to exit even if the socket is still + * listening. + * + * Calling `socket.unref()` multiple times will have no additional effect. + * + * The `socket.unref()` method returns a reference to the socket so calls can be + * chained. + * @since v0.9.1 + */ + unref(): this; + /** + * Tells the kernel to join a source-specific multicast channel at the given `sourceAddress` and `groupAddress`, using the `multicastInterface` with the `IP_ADD_SOURCE_MEMBERSHIP` socket + * option. If the `multicastInterface` argument + * is not specified, the operating system will choose one interface and will add + * membership to it. To add membership to every available interface, call `socket.addSourceSpecificMembership()` multiple times, once per interface. + * + * When called on an unbound socket, this method will implicitly bind to a random + * port, listening on all interfaces. + * @since v13.1.0, v12.16.0 + */ + addSourceSpecificMembership(sourceAddress: string, groupAddress: string, multicastInterface?: string): void; + /** + * Instructs the kernel to leave a source-specific multicast channel at the given `sourceAddress` and `groupAddress` using the `IP_DROP_SOURCE_MEMBERSHIP` socket option. This method is + * automatically called by the kernel when the + * socket is closed or the process terminates, so most apps will never have + * reason to call this. + * + * If `multicastInterface` is not specified, the operating system will attempt to + * drop membership on all valid interfaces. + * @since v13.1.0, v12.16.0 + */ + dropSourceSpecificMembership(sourceAddress: string, groupAddress: string, multicastInterface?: string): void; + /** + * events.EventEmitter + * 1. close + * 2. connect + * 3. error + * 4. listening + * 5. message + */ + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "close", listener: () => void): this; + addListener(event: "connect", listener: () => void): this; + addListener(event: "error", listener: (err: Error) => void): this; + addListener(event: "listening", listener: () => void): this; + addListener(event: "message", listener: (msg: Buffer, rinfo: RemoteInfo) => void): this; + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: "close"): boolean; + emit(event: "connect"): boolean; + emit(event: "error", err: Error): boolean; + emit(event: "listening"): boolean; + emit(event: "message", msg: Buffer, rinfo: RemoteInfo): boolean; + on(event: string, listener: (...args: any[]) => void): this; + on(event: "close", listener: () => void): this; + on(event: "connect", listener: () => void): this; + on(event: "error", listener: (err: Error) => void): this; + on(event: "listening", listener: () => void): this; + on(event: "message", listener: (msg: Buffer, rinfo: RemoteInfo) => void): this; + once(event: string, listener: (...args: any[]) => void): this; + once(event: "close", listener: () => void): this; + once(event: "connect", listener: () => void): this; + once(event: "error", listener: (err: Error) => void): this; + once(event: "listening", listener: () => void): this; + once(event: "message", listener: (msg: Buffer, rinfo: RemoteInfo) => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "close", listener: () => void): this; + prependListener(event: "connect", listener: () => void): this; + prependListener(event: "error", listener: (err: Error) => void): this; + prependListener(event: "listening", listener: () => void): this; + prependListener(event: "message", listener: (msg: Buffer, rinfo: RemoteInfo) => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "connect", listener: () => void): this; + prependOnceListener(event: "error", listener: (err: Error) => void): this; + prependOnceListener(event: "listening", listener: () => void): this; + prependOnceListener(event: "message", listener: (msg: Buffer, rinfo: RemoteInfo) => void): this; + /** + * Calls `socket.close()` and returns a promise that fulfills when the socket has closed. + * @since v20.5.0 + */ + [Symbol.asyncDispose](): Promise; + } +} +declare module "node:dgram" { + export * from "dgram"; +} diff --git a/node_modules/@types/node/diagnostics_channel.d.ts b/node_modules/@types/node/diagnostics_channel.d.ts new file mode 100644 index 0000000..e25ca69 --- /dev/null +++ b/node_modules/@types/node/diagnostics_channel.d.ts @@ -0,0 +1,554 @@ +/** + * The `node:diagnostics_channel` module provides an API to create named channels + * to report arbitrary message data for diagnostics purposes. + * + * It can be accessed using: + * + * ```js + * import diagnostics_channel from 'node:diagnostics_channel'; + * ``` + * + * It is intended that a module writer wanting to report diagnostics messages + * will create one or many top-level channels to report messages through. + * Channels may also be acquired at runtime but it is not encouraged + * due to the additional overhead of doing so. Channels may be exported for + * convenience, but as long as the name is known it can be acquired anywhere. + * + * If you intend for your module to produce diagnostics data for others to + * consume it is recommended that you include documentation of what named + * channels are used along with the shape of the message data. Channel names + * should generally include the module name to avoid collisions with data from + * other modules. + * @since v15.1.0, v14.17.0 + * @see [source](https://github.com/nodejs/node/blob/v20.13.1/lib/diagnostics_channel.js) + */ +declare module "diagnostics_channel" { + import { AsyncLocalStorage } from "node:async_hooks"; + /** + * Check if there are active subscribers to the named channel. This is helpful if + * the message you want to send might be expensive to prepare. + * + * This API is optional but helpful when trying to publish messages from very + * performance-sensitive code. + * + * ```js + * import diagnostics_channel from 'node:diagnostics_channel'; + * + * if (diagnostics_channel.hasSubscribers('my-channel')) { + * // There are subscribers, prepare and publish message + * } + * ``` + * @since v15.1.0, v14.17.0 + * @param name The channel name + * @return If there are active subscribers + */ + function hasSubscribers(name: string | symbol): boolean; + /** + * This is the primary entry-point for anyone wanting to publish to a named + * channel. It produces a channel object which is optimized to reduce overhead at + * publish time as much as possible. + * + * ```js + * import diagnostics_channel from 'node:diagnostics_channel'; + * + * const channel = diagnostics_channel.channel('my-channel'); + * ``` + * @since v15.1.0, v14.17.0 + * @param name The channel name + * @return The named channel object + */ + function channel(name: string | symbol): Channel; + type ChannelListener = (message: unknown, name: string | symbol) => void; + /** + * Register a message handler to subscribe to this channel. This message handler + * will be run synchronously whenever a message is published to the channel. Any + * errors thrown in the message handler will trigger an `'uncaughtException'`. + * + * ```js + * import diagnostics_channel from 'node:diagnostics_channel'; + * + * diagnostics_channel.subscribe('my-channel', (message, name) => { + * // Received data + * }); + * ``` + * @since v18.7.0, v16.17.0 + * @param name The channel name + * @param onMessage The handler to receive channel messages + */ + function subscribe(name: string | symbol, onMessage: ChannelListener): void; + /** + * Remove a message handler previously registered to this channel with {@link subscribe}. + * + * ```js + * import diagnostics_channel from 'node:diagnostics_channel'; + * + * function onMessage(message, name) { + * // Received data + * } + * + * diagnostics_channel.subscribe('my-channel', onMessage); + * + * diagnostics_channel.unsubscribe('my-channel', onMessage); + * ``` + * @since v18.7.0, v16.17.0 + * @param name The channel name + * @param onMessage The previous subscribed handler to remove + * @return `true` if the handler was found, `false` otherwise. + */ + function unsubscribe(name: string | symbol, onMessage: ChannelListener): boolean; + /** + * Creates a `TracingChannel` wrapper for the given `TracingChannel Channels`. If a name is given, the corresponding tracing + * channels will be created in the form of `tracing:${name}:${eventType}` where `eventType` corresponds to the types of `TracingChannel Channels`. + * + * ```js + * import diagnostics_channel from 'node:diagnostics_channel'; + * + * const channelsByName = diagnostics_channel.tracingChannel('my-channel'); + * + * // or... + * + * const channelsByCollection = diagnostics_channel.tracingChannel({ + * start: diagnostics_channel.channel('tracing:my-channel:start'), + * end: diagnostics_channel.channel('tracing:my-channel:end'), + * asyncStart: diagnostics_channel.channel('tracing:my-channel:asyncStart'), + * asyncEnd: diagnostics_channel.channel('tracing:my-channel:asyncEnd'), + * error: diagnostics_channel.channel('tracing:my-channel:error'), + * }); + * ``` + * @since v19.9.0 + * @experimental + * @param nameOrChannels Channel name or object containing all the `TracingChannel Channels` + * @return Collection of channels to trace with + */ + function tracingChannel< + StoreType = unknown, + ContextType extends object = StoreType extends object ? StoreType : object, + >( + nameOrChannels: string | TracingChannelCollection, + ): TracingChannel; + /** + * The class `Channel` represents an individual named channel within the data + * pipeline. It is used to track subscribers and to publish messages when there + * are subscribers present. It exists as a separate object to avoid channel + * lookups at publish time, enabling very fast publish speeds and allowing + * for heavy use while incurring very minimal cost. Channels are created with {@link channel}, constructing a channel directly + * with `new Channel(name)` is not supported. + * @since v15.1.0, v14.17.0 + */ + class Channel { + readonly name: string | symbol; + /** + * Check if there are active subscribers to this channel. This is helpful if + * the message you want to send might be expensive to prepare. + * + * This API is optional but helpful when trying to publish messages from very + * performance-sensitive code. + * + * ```js + * import diagnostics_channel from 'node:diagnostics_channel'; + * + * const channel = diagnostics_channel.channel('my-channel'); + * + * if (channel.hasSubscribers) { + * // There are subscribers, prepare and publish message + * } + * ``` + * @since v15.1.0, v14.17.0 + */ + readonly hasSubscribers: boolean; + private constructor(name: string | symbol); + /** + * Publish a message to any subscribers to the channel. This will trigger + * message handlers synchronously so they will execute within the same context. + * + * ```js + * import diagnostics_channel from 'node:diagnostics_channel'; + * + * const channel = diagnostics_channel.channel('my-channel'); + * + * channel.publish({ + * some: 'message', + * }); + * ``` + * @since v15.1.0, v14.17.0 + * @param message The message to send to the channel subscribers + */ + publish(message: unknown): void; + /** + * Register a message handler to subscribe to this channel. This message handler + * will be run synchronously whenever a message is published to the channel. Any + * errors thrown in the message handler will trigger an `'uncaughtException'`. + * + * ```js + * import diagnostics_channel from 'node:diagnostics_channel'; + * + * const channel = diagnostics_channel.channel('my-channel'); + * + * channel.subscribe((message, name) => { + * // Received data + * }); + * ``` + * @since v15.1.0, v14.17.0 + * @deprecated Since v18.7.0,v16.17.0 - Use {@link subscribe(name, onMessage)} + * @param onMessage The handler to receive channel messages + */ + subscribe(onMessage: ChannelListener): void; + /** + * Remove a message handler previously registered to this channel with `channel.subscribe(onMessage)`. + * + * ```js + * import diagnostics_channel from 'node:diagnostics_channel'; + * + * const channel = diagnostics_channel.channel('my-channel'); + * + * function onMessage(message, name) { + * // Received data + * } + * + * channel.subscribe(onMessage); + * + * channel.unsubscribe(onMessage); + * ``` + * @since v15.1.0, v14.17.0 + * @deprecated Since v18.7.0,v16.17.0 - Use {@link unsubscribe(name, onMessage)} + * @param onMessage The previous subscribed handler to remove + * @return `true` if the handler was found, `false` otherwise. + */ + unsubscribe(onMessage: ChannelListener): void; + /** + * When `channel.runStores(context, ...)` is called, the given context data + * will be applied to any store bound to the channel. If the store has already been + * bound the previous `transform` function will be replaced with the new one. + * The `transform` function may be omitted to set the given context data as the + * context directly. + * + * ```js + * import diagnostics_channel from 'node:diagnostics_channel'; + * import { AsyncLocalStorage } from 'node:async_hooks'; + * + * const store = new AsyncLocalStorage(); + * + * const channel = diagnostics_channel.channel('my-channel'); + * + * channel.bindStore(store, (data) => { + * return { data }; + * }); + * ``` + * @since v19.9.0 + * @experimental + * @param store The store to which to bind the context data + * @param transform Transform context data before setting the store context + */ + bindStore(store: AsyncLocalStorage, transform?: (context: ContextType) => StoreType): void; + /** + * Remove a message handler previously registered to this channel with `channel.bindStore(store)`. + * + * ```js + * import diagnostics_channel from 'node:diagnostics_channel'; + * import { AsyncLocalStorage } from 'node:async_hooks'; + * + * const store = new AsyncLocalStorage(); + * + * const channel = diagnostics_channel.channel('my-channel'); + * + * channel.bindStore(store); + * channel.unbindStore(store); + * ``` + * @since v19.9.0 + * @experimental + * @param store The store to unbind from the channel. + * @return `true` if the store was found, `false` otherwise. + */ + unbindStore(store: any): void; + /** + * Applies the given data to any AsyncLocalStorage instances bound to the channel + * for the duration of the given function, then publishes to the channel within + * the scope of that data is applied to the stores. + * + * If a transform function was given to `channel.bindStore(store)` it will be + * applied to transform the message data before it becomes the context value for + * the store. The prior storage context is accessible from within the transform + * function in cases where context linking is required. + * + * The context applied to the store should be accessible in any async code which + * continues from execution which began during the given function, however + * there are some situations in which `context loss` may occur. + * + * ```js + * import diagnostics_channel from 'node:diagnostics_channel'; + * import { AsyncLocalStorage } from 'node:async_hooks'; + * + * const store = new AsyncLocalStorage(); + * + * const channel = diagnostics_channel.channel('my-channel'); + * + * channel.bindStore(store, (message) => { + * const parent = store.getStore(); + * return new Span(message, parent); + * }); + * channel.runStores({ some: 'message' }, () => { + * store.getStore(); // Span({ some: 'message' }) + * }); + * ``` + * @since v19.9.0 + * @experimental + * @param context Message to send to subscribers and bind to stores + * @param fn Handler to run within the entered storage context + * @param thisArg The receiver to be used for the function call. + * @param args Optional arguments to pass to the function. + */ + runStores(): void; + } + interface TracingChannelSubscribers { + start: (message: ContextType) => void; + end: ( + message: ContextType & { + error?: unknown; + result?: unknown; + }, + ) => void; + asyncStart: ( + message: ContextType & { + error?: unknown; + result?: unknown; + }, + ) => void; + asyncEnd: ( + message: ContextType & { + error?: unknown; + result?: unknown; + }, + ) => void; + error: ( + message: ContextType & { + error: unknown; + }, + ) => void; + } + interface TracingChannelCollection { + start: Channel; + end: Channel; + asyncStart: Channel; + asyncEnd: Channel; + error: Channel; + } + /** + * The class `TracingChannel` is a collection of `TracingChannel Channels` which + * together express a single traceable action. It is used to formalize and + * simplify the process of producing events for tracing application flow. {@link tracingChannel} is used to construct a `TracingChannel`. As with `Channel` it is recommended to create and reuse a + * single `TracingChannel` at the top-level of the file rather than creating them + * dynamically. + * @since v19.9.0 + * @experimental + */ + class TracingChannel implements TracingChannelCollection { + start: Channel; + end: Channel; + asyncStart: Channel; + asyncEnd: Channel; + error: Channel; + /** + * Helper to subscribe a collection of functions to the corresponding channels. + * This is the same as calling `channel.subscribe(onMessage)` on each channel + * individually. + * + * ```js + * import diagnostics_channel from 'node:diagnostics_channel'; + * + * const channels = diagnostics_channel.tracingChannel('my-channel'); + * + * channels.subscribe({ + * start(message) { + * // Handle start message + * }, + * end(message) { + * // Handle end message + * }, + * asyncStart(message) { + * // Handle asyncStart message + * }, + * asyncEnd(message) { + * // Handle asyncEnd message + * }, + * error(message) { + * // Handle error message + * }, + * }); + * ``` + * @since v19.9.0 + * @experimental + * @param subscribers Set of `TracingChannel Channels` subscribers + */ + subscribe(subscribers: TracingChannelSubscribers): void; + /** + * Helper to unsubscribe a collection of functions from the corresponding channels. + * This is the same as calling `channel.unsubscribe(onMessage)` on each channel + * individually. + * + * ```js + * import diagnostics_channel from 'node:diagnostics_channel'; + * + * const channels = diagnostics_channel.tracingChannel('my-channel'); + * + * channels.unsubscribe({ + * start(message) { + * // Handle start message + * }, + * end(message) { + * // Handle end message + * }, + * asyncStart(message) { + * // Handle asyncStart message + * }, + * asyncEnd(message) { + * // Handle asyncEnd message + * }, + * error(message) { + * // Handle error message + * }, + * }); + * ``` + * @since v19.9.0 + * @experimental + * @param subscribers Set of `TracingChannel Channels` subscribers + * @return `true` if all handlers were successfully unsubscribed, and `false` otherwise. + */ + unsubscribe(subscribers: TracingChannelSubscribers): void; + /** + * Trace a synchronous function call. This will always produce a `start event` and `end event` around the execution and may produce an `error event` if the given function throws an error. + * This will run the given function using `channel.runStores(context, ...)` on the `start` channel which ensures all + * events should have any bound stores set to match this trace context. + * + * To ensure only correct trace graphs are formed, events will only be published if subscribers are present prior to starting the trace. Subscriptions + * which are added after the trace begins will not receive future events from that trace, only future traces will be seen. + * + * ```js + * import diagnostics_channel from 'node:diagnostics_channel'; + * + * const channels = diagnostics_channel.tracingChannel('my-channel'); + * + * channels.traceSync(() => { + * // Do something + * }, { + * some: 'thing', + * }); + * ``` + * @since v19.9.0 + * @experimental + * @param fn Function to wrap a trace around + * @param context Shared object to correlate events through + * @param thisArg The receiver to be used for the function call + * @param args Optional arguments to pass to the function + * @return The return value of the given function + */ + traceSync( + fn: (this: ThisArg, ...args: Args) => any, + context?: ContextType, + thisArg?: ThisArg, + ...args: Args + ): void; + /** + * Trace a promise-returning function call. This will always produce a `start event` and `end event` around the synchronous portion of the + * function execution, and will produce an `asyncStart event` and `asyncEnd event` when a promise continuation is reached. It may also + * produce an `error event` if the given function throws an error or the + * returned promise rejects. This will run the given function using `channel.runStores(context, ...)` on the `start` channel which ensures all + * events should have any bound stores set to match this trace context. + * + * To ensure only correct trace graphs are formed, events will only be published if subscribers are present prior to starting the trace. Subscriptions + * which are added after the trace begins will not receive future events from that trace, only future traces will be seen. + * + * ```js + * import diagnostics_channel from 'node:diagnostics_channel'; + * + * const channels = diagnostics_channel.tracingChannel('my-channel'); + * + * channels.tracePromise(async () => { + * // Do something + * }, { + * some: 'thing', + * }); + * ``` + * @since v19.9.0 + * @experimental + * @param fn Promise-returning function to wrap a trace around + * @param context Shared object to correlate trace events through + * @param thisArg The receiver to be used for the function call + * @param args Optional arguments to pass to the function + * @return Chained from promise returned by the given function + */ + tracePromise( + fn: (this: ThisArg, ...args: Args) => Promise, + context?: ContextType, + thisArg?: ThisArg, + ...args: Args + ): void; + /** + * Trace a callback-receiving function call. This will always produce a `start event` and `end event` around the synchronous portion of the + * function execution, and will produce a `asyncStart event` and `asyncEnd event` around the callback execution. It may also produce an `error event` if the given function throws an error or + * the returned + * promise rejects. This will run the given function using `channel.runStores(context, ...)` on the `start` channel which ensures all + * events should have any bound stores set to match this trace context. + * + * The `position` will be -1 by default to indicate the final argument should + * be used as the callback. + * + * ```js + * import diagnostics_channel from 'node:diagnostics_channel'; + * + * const channels = diagnostics_channel.tracingChannel('my-channel'); + * + * channels.traceCallback((arg1, callback) => { + * // Do something + * callback(null, 'result'); + * }, 1, { + * some: 'thing', + * }, thisArg, arg1, callback); + * ``` + * + * The callback will also be run with `channel.runStores(context, ...)` which + * enables context loss recovery in some cases. + * + * To ensure only correct trace graphs are formed, events will only be published if subscribers are present prior to starting the trace. Subscriptions + * which are added after the trace begins will not receive future events from that trace, only future traces will be seen. + * + * ```js + * import diagnostics_channel from 'node:diagnostics_channel'; + * import { AsyncLocalStorage } from 'node:async_hooks'; + * + * const channels = diagnostics_channel.tracingChannel('my-channel'); + * const myStore = new AsyncLocalStorage(); + * + * // The start channel sets the initial store data to something + * // and stores that store data value on the trace context object + * channels.start.bindStore(myStore, (data) => { + * const span = new Span(data); + * data.span = span; + * return span; + * }); + * + * // Then asyncStart can restore from that data it stored previously + * channels.asyncStart.bindStore(myStore, (data) => { + * return data.span; + * }); + * ``` + * @since v19.9.0 + * @experimental + * @param fn callback using function to wrap a trace around + * @param position Zero-indexed argument position of expected callback + * @param context Shared object to correlate trace events through + * @param thisArg The receiver to be used for the function call + * @param args Optional arguments to pass to the function + * @return The return value of the given function + */ + traceCallback any>( + fn: Fn, + position: number | undefined, + context: ContextType | undefined, + thisArg: any, + ...args: Parameters + ): void; + } +} +declare module "node:diagnostics_channel" { + export * from "diagnostics_channel"; +} diff --git a/node_modules/@types/node/dns.d.ts b/node_modules/@types/node/dns.d.ts new file mode 100644 index 0000000..0a195c2 --- /dev/null +++ b/node_modules/@types/node/dns.d.ts @@ -0,0 +1,864 @@ +/** + * The `node:dns` module enables name resolution. For example, use it to look up IP + * addresses of host names. + * + * Although named for the [Domain Name System (DNS)](https://en.wikipedia.org/wiki/Domain_Name_System), it does not always use the + * DNS protocol for lookups. {@link lookup} uses the operating system + * facilities to perform name resolution. It may not need to perform any network + * communication. To perform name resolution the way other applications on the same + * system do, use {@link lookup}. + * + * ```js + * const dns = require('node:dns'); + * + * dns.lookup('example.org', (err, address, family) => { + * console.log('address: %j family: IPv%s', address, family); + * }); + * // address: "93.184.216.34" family: IPv4 + * ``` + * + * All other functions in the `node:dns` module connect to an actual DNS server to + * perform name resolution. They will always use the network to perform DNS + * queries. These functions do not use the same set of configuration files used by {@link lookup} (e.g. `/etc/hosts`). Use these functions to always perform + * DNS queries, bypassing other name-resolution facilities. + * + * ```js + * const dns = require('node:dns'); + * + * dns.resolve4('archive.org', (err, addresses) => { + * if (err) throw err; + * + * console.log(`addresses: ${JSON.stringify(addresses)}`); + * + * addresses.forEach((a) => { + * dns.reverse(a, (err, hostnames) => { + * if (err) { + * throw err; + * } + * console.log(`reverse for ${a}: ${JSON.stringify(hostnames)}`); + * }); + * }); + * }); + * ``` + * + * See the [Implementation considerations section](https://nodejs.org/docs/latest-v20.x/api/dns.html#implementation-considerations) for more information. + * @see [source](https://github.com/nodejs/node/blob/v20.13.1/lib/dns.js) + */ +declare module "dns" { + import * as dnsPromises from "node:dns/promises"; + // Supported getaddrinfo flags. + /** + * Limits returned address types to the types of non-loopback addresses configured on the system. For example, IPv4 addresses are + * only returned if the current system has at least one IPv4 address configured. + */ + export const ADDRCONFIG: number; + /** + * If the IPv6 family was specified, but no IPv6 addresses were found, then return IPv4 mapped IPv6 addresses. It is not supported + * on some operating systems (e.g. FreeBSD 10.1). + */ + export const V4MAPPED: number; + /** + * If `dns.V4MAPPED` is specified, return resolved IPv6 addresses as + * well as IPv4 mapped IPv6 addresses. + */ + export const ALL: number; + export interface LookupOptions { + /** + * The record family. Must be `4`, `6`, or `0`. For backward compatibility reasons, `'IPv4'` and `'IPv6'` are interpreted + * as `4` and `6` respectively. The value 0 indicates that either an IPv4 or IPv6 address is returned. If the value `0` is used + * with `{ all: true } (see below)`, both IPv4 and IPv6 addresses are returned. + * @default 0 + */ + family?: number | "IPv4" | "IPv6" | undefined; + /** + * One or more [supported `getaddrinfo`](https://nodejs.org/docs/latest-v20.x/api/dns.html#supported-getaddrinfo-flags) flags. Multiple flags may be + * passed by bitwise `OR`ing their values. + */ + hints?: number | undefined; + /** + * When `true`, the callback returns all resolved addresses in an array. Otherwise, returns a single address. + * @default false + */ + all?: boolean | undefined; + /** + * When `verbatim`, the resolved addresses are return unsorted. When `ipv4first`, the resolved addresses are sorted + * by placing IPv4 addresses before IPv6 addresses. When `ipv6first`, the resolved addresses are sorted by placing IPv6 + * addresses before IPv4 addresses. Default value is configurable using + * {@link setDefaultResultOrder} or [`--dns-result-order`](https://nodejs.org/docs/latest-v20.x/api/cli.html#--dns-result-orderorder). + * @default `verbatim` (addresses are not reordered) + */ + order?: "ipv4first" | "ipv6first" | "verbatim" | undefined; + /** + * When `true`, the callback receives IPv4 and IPv6 addresses in the order the DNS resolver returned them. When `false`, IPv4 + * addresses are placed before IPv6 addresses. This option will be deprecated in favor of `order`. When both are specified, + * `order` has higher precedence. New code should only use `order`. Default value is configurable using {@link setDefaultResultOrder} + * or [`--dns-result-order`](https://nodejs.org/docs/latest-v20.x/api/cli.html#--dns-result-orderorder). + * @default true (addresses are not reordered) + */ + verbatim?: boolean | undefined; + } + export interface LookupOneOptions extends LookupOptions { + all?: false | undefined; + } + export interface LookupAllOptions extends LookupOptions { + all: true; + } + export interface LookupAddress { + /** + * A string representation of an IPv4 or IPv6 address. + */ + address: string; + /** + * `4` or `6`, denoting the family of `address`, or `0` if the address is not an IPv4 or IPv6 address. `0` is a likely indicator of a + * bug in the name resolution service used by the operating system. + */ + family: number; + } + /** + * Resolves a host name (e.g. `'nodejs.org'`) into the first found A (IPv4) or + * AAAA (IPv6) record. All `option` properties are optional. If `options` is an + * integer, then it must be `4` or `6` – if `options` is `0` or not provided, then + * IPv4 and IPv6 addresses are both returned if found. + * + * With the `all` option set to `true`, the arguments for `callback` change to `(err, addresses)`, with `addresses` being an array of objects with the + * properties `address` and `family`. + * + * On error, `err` is an `Error` object, where `err.code` is the error code. + * Keep in mind that `err.code` will be set to `'ENOTFOUND'` not only when + * the host name does not exist but also when the lookup fails in other ways + * such as no available file descriptors. + * + * `dns.lookup()` does not necessarily have anything to do with the DNS protocol. + * The implementation uses an operating system facility that can associate names + * with addresses and vice versa. This implementation can have subtle but + * important consequences on the behavior of any Node.js program. Please take some + * time to consult the [Implementation considerations section](https://nodejs.org/docs/latest-v20.x/api/dns.html#implementation-considerations) + * before using `dns.lookup()`. + * + * Example usage: + * + * ```js + * const dns = require('node:dns'); + * const options = { + * family: 6, + * hints: dns.ADDRCONFIG | dns.V4MAPPED, + * }; + * dns.lookup('example.com', options, (err, address, family) => + * console.log('address: %j family: IPv%s', address, family)); + * // address: "2606:2800:220:1:248:1893:25c8:1946" family: IPv6 + * + * // When options.all is true, the result will be an Array. + * options.all = true; + * dns.lookup('example.com', options, (err, addresses) => + * console.log('addresses: %j', addresses)); + * // addresses: [{"address":"2606:2800:220:1:248:1893:25c8:1946","family":6}] + * ``` + * + * If this method is invoked as its [util.promisify()](https://nodejs.org/docs/latest-v20.x/api/util.html#utilpromisifyoriginal) ed + * version, and `all` is not set to `true`, it returns a `Promise` for an `Object` with `address` and `family` properties. + * @since v0.1.90 + */ + export function lookup( + hostname: string, + family: number, + callback: (err: NodeJS.ErrnoException | null, address: string, family: number) => void, + ): void; + export function lookup( + hostname: string, + options: LookupOneOptions, + callback: (err: NodeJS.ErrnoException | null, address: string, family: number) => void, + ): void; + export function lookup( + hostname: string, + options: LookupAllOptions, + callback: (err: NodeJS.ErrnoException | null, addresses: LookupAddress[]) => void, + ): void; + export function lookup( + hostname: string, + options: LookupOptions, + callback: (err: NodeJS.ErrnoException | null, address: string | LookupAddress[], family: number) => void, + ): void; + export function lookup( + hostname: string, + callback: (err: NodeJS.ErrnoException | null, address: string, family: number) => void, + ): void; + export namespace lookup { + function __promisify__(hostname: string, options: LookupAllOptions): Promise; + function __promisify__(hostname: string, options?: LookupOneOptions | number): Promise; + function __promisify__(hostname: string, options: LookupOptions): Promise; + } + /** + * Resolves the given `address` and `port` into a host name and service using + * the operating system's underlying `getnameinfo` implementation. + * + * If `address` is not a valid IP address, a `TypeError` will be thrown. + * The `port` will be coerced to a number. If it is not a legal port, a `TypeError` will be thrown. + * + * On an error, `err` is an [`Error`](https://nodejs.org/docs/latest-v20.x/api/errors.html#class-error) object, + * where `err.code` is the error code. + * + * ```js + * const dns = require('node:dns'); + * dns.lookupService('127.0.0.1', 22, (err, hostname, service) => { + * console.log(hostname, service); + * // Prints: localhost ssh + * }); + * ``` + * + * If this method is invoked as its [util.promisify()](https://nodejs.org/docs/latest-v20.x/api/util.html#utilpromisifyoriginal) ed + * version, it returns a `Promise` for an `Object` with `hostname` and `service` properties. + * @since v0.11.14 + */ + export function lookupService( + address: string, + port: number, + callback: (err: NodeJS.ErrnoException | null, hostname: string, service: string) => void, + ): void; + export namespace lookupService { + function __promisify__( + address: string, + port: number, + ): Promise<{ + hostname: string; + service: string; + }>; + } + export interface ResolveOptions { + ttl: boolean; + } + export interface ResolveWithTtlOptions extends ResolveOptions { + ttl: true; + } + export interface RecordWithTtl { + address: string; + ttl: number; + } + /** @deprecated Use `AnyARecord` or `AnyAaaaRecord` instead. */ + export type AnyRecordWithTtl = AnyARecord | AnyAaaaRecord; + export interface AnyARecord extends RecordWithTtl { + type: "A"; + } + export interface AnyAaaaRecord extends RecordWithTtl { + type: "AAAA"; + } + export interface CaaRecord { + critical: number; + issue?: string | undefined; + issuewild?: string | undefined; + iodef?: string | undefined; + contactemail?: string | undefined; + contactphone?: string | undefined; + } + export interface MxRecord { + priority: number; + exchange: string; + } + export interface AnyMxRecord extends MxRecord { + type: "MX"; + } + export interface NaptrRecord { + flags: string; + service: string; + regexp: string; + replacement: string; + order: number; + preference: number; + } + export interface AnyNaptrRecord extends NaptrRecord { + type: "NAPTR"; + } + export interface SoaRecord { + nsname: string; + hostmaster: string; + serial: number; + refresh: number; + retry: number; + expire: number; + minttl: number; + } + export interface AnySoaRecord extends SoaRecord { + type: "SOA"; + } + export interface SrvRecord { + priority: number; + weight: number; + port: number; + name: string; + } + export interface AnySrvRecord extends SrvRecord { + type: "SRV"; + } + export interface AnyTxtRecord { + type: "TXT"; + entries: string[]; + } + export interface AnyNsRecord { + type: "NS"; + value: string; + } + export interface AnyPtrRecord { + type: "PTR"; + value: string; + } + export interface AnyCnameRecord { + type: "CNAME"; + value: string; + } + export type AnyRecord = + | AnyARecord + | AnyAaaaRecord + | AnyCnameRecord + | AnyMxRecord + | AnyNaptrRecord + | AnyNsRecord + | AnyPtrRecord + | AnySoaRecord + | AnySrvRecord + | AnyTxtRecord; + /** + * Uses the DNS protocol to resolve a host name (e.g. `'nodejs.org'`) into an array + * of the resource records. The `callback` function has arguments `(err, records)`. When successful, `records` will be an array of resource + * records. The type and structure of individual results varies based on `rrtype`: + * + * + * + * On error, `err` is an [`Error`](https://nodejs.org/docs/latest-v20.x/api/errors.html#class-error) object, + * where `err.code` is one of the `DNS error codes`. + * @since v0.1.27 + * @param hostname Host name to resolve. + * @param [rrtype='A'] Resource record type. + */ + export function resolve( + hostname: string, + callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void, + ): void; + export function resolve( + hostname: string, + rrtype: "A", + callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void, + ): void; + export function resolve( + hostname: string, + rrtype: "AAAA", + callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void, + ): void; + export function resolve( + hostname: string, + rrtype: "ANY", + callback: (err: NodeJS.ErrnoException | null, addresses: AnyRecord[]) => void, + ): void; + export function resolve( + hostname: string, + rrtype: "CNAME", + callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void, + ): void; + export function resolve( + hostname: string, + rrtype: "MX", + callback: (err: NodeJS.ErrnoException | null, addresses: MxRecord[]) => void, + ): void; + export function resolve( + hostname: string, + rrtype: "NAPTR", + callback: (err: NodeJS.ErrnoException | null, addresses: NaptrRecord[]) => void, + ): void; + export function resolve( + hostname: string, + rrtype: "NS", + callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void, + ): void; + export function resolve( + hostname: string, + rrtype: "PTR", + callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void, + ): void; + export function resolve( + hostname: string, + rrtype: "SOA", + callback: (err: NodeJS.ErrnoException | null, addresses: SoaRecord) => void, + ): void; + export function resolve( + hostname: string, + rrtype: "SRV", + callback: (err: NodeJS.ErrnoException | null, addresses: SrvRecord[]) => void, + ): void; + export function resolve( + hostname: string, + rrtype: "TXT", + callback: (err: NodeJS.ErrnoException | null, addresses: string[][]) => void, + ): void; + export function resolve( + hostname: string, + rrtype: string, + callback: ( + err: NodeJS.ErrnoException | null, + addresses: string[] | MxRecord[] | NaptrRecord[] | SoaRecord | SrvRecord[] | string[][] | AnyRecord[], + ) => void, + ): void; + export namespace resolve { + function __promisify__(hostname: string, rrtype?: "A" | "AAAA" | "CNAME" | "NS" | "PTR"): Promise; + function __promisify__(hostname: string, rrtype: "ANY"): Promise; + function __promisify__(hostname: string, rrtype: "MX"): Promise; + function __promisify__(hostname: string, rrtype: "NAPTR"): Promise; + function __promisify__(hostname: string, rrtype: "SOA"): Promise; + function __promisify__(hostname: string, rrtype: "SRV"): Promise; + function __promisify__(hostname: string, rrtype: "TXT"): Promise; + function __promisify__( + hostname: string, + rrtype: string, + ): Promise; + } + /** + * Uses the DNS protocol to resolve a IPv4 addresses (`A` records) for the `hostname`. The `addresses` argument passed to the `callback` function + * will contain an array of IPv4 addresses (e.g.`['74.125.79.104', '74.125.79.105', '74.125.79.106']`). + * @since v0.1.16 + * @param hostname Host name to resolve. + */ + export function resolve4( + hostname: string, + callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void, + ): void; + export function resolve4( + hostname: string, + options: ResolveWithTtlOptions, + callback: (err: NodeJS.ErrnoException | null, addresses: RecordWithTtl[]) => void, + ): void; + export function resolve4( + hostname: string, + options: ResolveOptions, + callback: (err: NodeJS.ErrnoException | null, addresses: string[] | RecordWithTtl[]) => void, + ): void; + export namespace resolve4 { + function __promisify__(hostname: string): Promise; + function __promisify__(hostname: string, options: ResolveWithTtlOptions): Promise; + function __promisify__(hostname: string, options?: ResolveOptions): Promise; + } + /** + * Uses the DNS protocol to resolve IPv6 addresses (`AAAA` records) for the `hostname`. The `addresses` argument passed to the `callback` function + * will contain an array of IPv6 addresses. + * @since v0.1.16 + * @param hostname Host name to resolve. + */ + export function resolve6( + hostname: string, + callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void, + ): void; + export function resolve6( + hostname: string, + options: ResolveWithTtlOptions, + callback: (err: NodeJS.ErrnoException | null, addresses: RecordWithTtl[]) => void, + ): void; + export function resolve6( + hostname: string, + options: ResolveOptions, + callback: (err: NodeJS.ErrnoException | null, addresses: string[] | RecordWithTtl[]) => void, + ): void; + export namespace resolve6 { + function __promisify__(hostname: string): Promise; + function __promisify__(hostname: string, options: ResolveWithTtlOptions): Promise; + function __promisify__(hostname: string, options?: ResolveOptions): Promise; + } + /** + * Uses the DNS protocol to resolve `CNAME` records for the `hostname`. The `addresses` argument passed to the `callback` function + * will contain an array of canonical name records available for the `hostname` (e.g. `['bar.example.com']`). + * @since v0.3.2 + */ + export function resolveCname( + hostname: string, + callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void, + ): void; + export namespace resolveCname { + function __promisify__(hostname: string): Promise; + } + /** + * Uses the DNS protocol to resolve `CAA` records for the `hostname`. The `addresses` argument passed to the `callback` function + * will contain an array of certification authority authorization records + * available for the `hostname` (e.g. `[{critical: 0, iodef: 'mailto:pki@example.com'}, {critical: 128, issue: 'pki.example.com'}]`). + * @since v15.0.0, v14.17.0 + */ + export function resolveCaa( + hostname: string, + callback: (err: NodeJS.ErrnoException | null, records: CaaRecord[]) => void, + ): void; + export namespace resolveCaa { + function __promisify__(hostname: string): Promise; + } + /** + * Uses the DNS protocol to resolve mail exchange records (`MX` records) for the `hostname`. The `addresses` argument passed to the `callback` function will + * contain an array of objects containing both a `priority` and `exchange` property (e.g. `[{priority: 10, exchange: 'mx.example.com'}, ...]`). + * @since v0.1.27 + */ + export function resolveMx( + hostname: string, + callback: (err: NodeJS.ErrnoException | null, addresses: MxRecord[]) => void, + ): void; + export namespace resolveMx { + function __promisify__(hostname: string): Promise; + } + /** + * Uses the DNS protocol to resolve regular expression-based records (`NAPTR` records) for the `hostname`. The `addresses` argument passed to the `callback` function will contain an array of + * objects with the following properties: + * + * * `flags` + * * `service` + * * `regexp` + * * `replacement` + * * `order` + * * `preference` + * + * ```js + * { + * flags: 's', + * service: 'SIP+D2U', + * regexp: '', + * replacement: '_sip._udp.example.com', + * order: 30, + * preference: 100 + * } + * ``` + * @since v0.9.12 + */ + export function resolveNaptr( + hostname: string, + callback: (err: NodeJS.ErrnoException | null, addresses: NaptrRecord[]) => void, + ): void; + export namespace resolveNaptr { + function __promisify__(hostname: string): Promise; + } + /** + * Uses the DNS protocol to resolve name server records (`NS` records) for the `hostname`. The `addresses` argument passed to the `callback` function will + * contain an array of name server records available for `hostname` (e.g. `['ns1.example.com', 'ns2.example.com']`). + * @since v0.1.90 + */ + export function resolveNs( + hostname: string, + callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void, + ): void; + export namespace resolveNs { + function __promisify__(hostname: string): Promise; + } + /** + * Uses the DNS protocol to resolve pointer records (`PTR` records) for the `hostname`. The `addresses` argument passed to the `callback` function will + * be an array of strings containing the reply records. + * @since v6.0.0 + */ + export function resolvePtr( + hostname: string, + callback: (err: NodeJS.ErrnoException | null, addresses: string[]) => void, + ): void; + export namespace resolvePtr { + function __promisify__(hostname: string): Promise; + } + /** + * Uses the DNS protocol to resolve a start of authority record (`SOA` record) for + * the `hostname`. The `address` argument passed to the `callback` function will + * be an object with the following properties: + * + * * `nsname` + * * `hostmaster` + * * `serial` + * * `refresh` + * * `retry` + * * `expire` + * * `minttl` + * + * ```js + * { + * nsname: 'ns.example.com', + * hostmaster: 'root.example.com', + * serial: 2013101809, + * refresh: 10000, + * retry: 2400, + * expire: 604800, + * minttl: 3600 + * } + * ``` + * @since v0.11.10 + */ + export function resolveSoa( + hostname: string, + callback: (err: NodeJS.ErrnoException | null, address: SoaRecord) => void, + ): void; + export namespace resolveSoa { + function __promisify__(hostname: string): Promise; + } + /** + * Uses the DNS protocol to resolve service records (`SRV` records) for the `hostname`. The `addresses` argument passed to the `callback` function will + * be an array of objects with the following properties: + * + * * `priority` + * * `weight` + * * `port` + * * `name` + * + * ```js + * { + * priority: 10, + * weight: 5, + * port: 21223, + * name: 'service.example.com' + * } + * ``` + * @since v0.1.27 + */ + export function resolveSrv( + hostname: string, + callback: (err: NodeJS.ErrnoException | null, addresses: SrvRecord[]) => void, + ): void; + export namespace resolveSrv { + function __promisify__(hostname: string): Promise; + } + /** + * Uses the DNS protocol to resolve text queries (`TXT` records) for the `hostname`. The `records` argument passed to the `callback` function is a + * two-dimensional array of the text records available for `hostname` (e.g.`[ ['v=spf1 ip4:0.0.0.0 ', '~all' ] ]`). Each sub-array contains TXT chunks of + * one record. Depending on the use case, these could be either joined together or + * treated separately. + * @since v0.1.27 + */ + export function resolveTxt( + hostname: string, + callback: (err: NodeJS.ErrnoException | null, addresses: string[][]) => void, + ): void; + export namespace resolveTxt { + function __promisify__(hostname: string): Promise; + } + /** + * Uses the DNS protocol to resolve all records (also known as `ANY` or `*` query). + * The `ret` argument passed to the `callback` function will be an array containing + * various types of records. Each object has a property `type` that indicates the + * type of the current record. And depending on the `type`, additional properties + * will be present on the object: + * + * + * + * Here is an example of the `ret` object passed to the callback: + * + * ```js + * [ { type: 'A', address: '127.0.0.1', ttl: 299 }, + * { type: 'CNAME', value: 'example.com' }, + * { type: 'MX', exchange: 'alt4.aspmx.l.example.com', priority: 50 }, + * { type: 'NS', value: 'ns1.example.com' }, + * { type: 'TXT', entries: [ 'v=spf1 include:_spf.example.com ~all' ] }, + * { type: 'SOA', + * nsname: 'ns1.example.com', + * hostmaster: 'admin.example.com', + * serial: 156696742, + * refresh: 900, + * retry: 900, + * expire: 1800, + * minttl: 60 } ] + * ``` + * + * DNS server operators may choose not to respond to `ANY` queries. It may be better to call individual methods like {@link resolve4}, {@link resolveMx}, and so on. For more details, see + * [RFC 8482](https://tools.ietf.org/html/rfc8482). + */ + export function resolveAny( + hostname: string, + callback: (err: NodeJS.ErrnoException | null, addresses: AnyRecord[]) => void, + ): void; + export namespace resolveAny { + function __promisify__(hostname: string): Promise; + } + /** + * Performs a reverse DNS query that resolves an IPv4 or IPv6 address to an + * array of host names. + * + * On error, `err` is an [`Error`](https://nodejs.org/docs/latest-v20.x/api/errors.html#class-error) object, where `err.code` is + * one of the [DNS error codes](https://nodejs.org/docs/latest-v20.x/api/dns.html#error-codes). + * @since v0.1.16 + */ + export function reverse( + ip: string, + callback: (err: NodeJS.ErrnoException | null, hostnames: string[]) => void, + ): void; + /** + * Get the default value for `order` in {@link lookup} and [`dnsPromises.lookup()`](https://nodejs.org/docs/latest-v20.x/api/dns.html#dnspromiseslookuphostname-options). + * The value could be: + * + * * `ipv4first`: for `order` defaulting to `ipv4first`. + * * `ipv6first`: for `order` defaulting to `ipv6first`. + * * `verbatim`: for `order` defaulting to `verbatim`. + * @since v18.17.0 + */ + export function getDefaultResultOrder(): "ipv4first" | "ipv6first" | "verbatim"; + /** + * Sets the IP address and port of servers to be used when performing DNS + * resolution. The `servers` argument is an array of [RFC 5952](https://tools.ietf.org/html/rfc5952#section-6) formatted + * addresses. If the port is the IANA default DNS port (53) it can be omitted. + * + * ```js + * dns.setServers([ + * '4.4.4.4', + * '[2001:4860:4860::8888]', + * '4.4.4.4:1053', + * '[2001:4860:4860::8888]:1053', + * ]); + * ``` + * + * An error will be thrown if an invalid address is provided. + * + * The `dns.setServers()` method must not be called while a DNS query is in + * progress. + * + * The {@link setServers} method affects only {@link resolve}, `dns.resolve*()` and {@link reverse} (and specifically _not_ {@link lookup}). + * + * This method works much like [resolve.conf](https://man7.org/linux/man-pages/man5/resolv.conf.5.html). + * That is, if attempting to resolve with the first server provided results in a `NOTFOUND` error, the `resolve()` method will _not_ attempt to resolve with + * subsequent servers provided. Fallback DNS servers will only be used if the + * earlier ones time out or result in some other error. + * @since v0.11.3 + * @param servers array of [RFC 5952](https://datatracker.ietf.org/doc/html/rfc5952#section-6) formatted addresses + */ + export function setServers(servers: readonly string[]): void; + /** + * Returns an array of IP address strings, formatted according to [RFC 5952](https://tools.ietf.org/html/rfc5952#section-6), + * that are currently configured for DNS resolution. A string will include a port + * section if a custom port is used. + * + * ```js + * [ + * '4.4.4.4', + * '2001:4860:4860::8888', + * '4.4.4.4:1053', + * '[2001:4860:4860::8888]:1053', + * ] + * ``` + * @since v0.11.3 + */ + export function getServers(): string[]; + /** + * Set the default value of `order` in {@link lookup} and [`dnsPromises.lookup()`](https://nodejs.org/docs/latest-v20.x/api/dns.html#dnspromiseslookuphostname-options). + * The value could be: + * + * * `ipv4first`: sets default `order` to `ipv4first`. + * * `ipv6first`: sets default `order` to `ipv6first`. + * * `verbatim`: sets default `order` to `verbatim`. + * + * The default is `verbatim` and {@link setDefaultResultOrder} have higher + * priority than [`--dns-result-order`](https://nodejs.org/docs/latest-v20.x/api/cli.html#--dns-result-orderorder). When using + * [worker threads](https://nodejs.org/docs/latest-v20.x/api/worker_threads.html), {@link setDefaultResultOrder} from the main + * thread won't affect the default dns orders in workers. + * @since v16.4.0, v14.18.0 + * @param order must be `'ipv4first'`, `'ipv6first'` or `'verbatim'`. + */ + export function setDefaultResultOrder(order: "ipv4first" | "ipv6first" | "verbatim"): void; + // Error codes + export const NODATA: "NODATA"; + export const FORMERR: "FORMERR"; + export const SERVFAIL: "SERVFAIL"; + export const NOTFOUND: "NOTFOUND"; + export const NOTIMP: "NOTIMP"; + export const REFUSED: "REFUSED"; + export const BADQUERY: "BADQUERY"; + export const BADNAME: "BADNAME"; + export const BADFAMILY: "BADFAMILY"; + export const BADRESP: "BADRESP"; + export const CONNREFUSED: "TIMEOUT"; + export const TIMEOUT: "TIMEOUT"; + export const EOF: "EOF"; + export const FILE: "FILE"; + export const NOMEM: "NOMEM"; + export const DESTRUCTION: "DESTRUCTION"; + export const BADSTR: "BADSTR"; + export const BADFLAGS: "BADFLAGS"; + export const NONAME: "NONAME"; + export const BADHINTS: "BADHINTS"; + export const NOTINITIALIZED: "NOTINITIALIZED"; + export const LOADIPHLPAPI: "LOADIPHLPAPI"; + export const ADDRGETNETWORKPARAMS: "ADDRGETNETWORKPARAMS"; + export const CANCELLED: "CANCELLED"; + export interface ResolverOptions { + /** + * Query timeout in milliseconds, or `-1` to use the default timeout. + */ + timeout?: number | undefined; + /** + * The number of tries the resolver will try contacting each name server before giving up. + * @default 4 + */ + tries?: number; + } + /** + * An independent resolver for DNS requests. + * + * Creating a new resolver uses the default server settings. Setting + * the servers used for a resolver using [`resolver.setServers()`](https://nodejs.org/docs/latest-v20.x/api/dns.html#dnssetserversservers) does not affect + * other resolvers: + * + * ```js + * const { Resolver } = require('node:dns'); + * const resolver = new Resolver(); + * resolver.setServers(['4.4.4.4']); + * + * // This request will use the server at 4.4.4.4, independent of global settings. + * resolver.resolve4('example.org', (err, addresses) => { + * // ... + * }); + * ``` + * + * The following methods from the `node:dns` module are available: + * + * * `resolver.getServers()` + * * `resolver.resolve()` + * * `resolver.resolve4()` + * * `resolver.resolve6()` + * * `resolver.resolveAny()` + * * `resolver.resolveCaa()` + * * `resolver.resolveCname()` + * * `resolver.resolveMx()` + * * `resolver.resolveNaptr()` + * * `resolver.resolveNs()` + * * `resolver.resolvePtr()` + * * `resolver.resolveSoa()` + * * `resolver.resolveSrv()` + * * `resolver.resolveTxt()` + * * `resolver.reverse()` + * * `resolver.setServers()` + * @since v8.3.0 + */ + export class Resolver { + constructor(options?: ResolverOptions); + /** + * Cancel all outstanding DNS queries made by this resolver. The corresponding + * callbacks will be called with an error with code `ECANCELLED`. + * @since v8.3.0 + */ + cancel(): void; + getServers: typeof getServers; + resolve: typeof resolve; + resolve4: typeof resolve4; + resolve6: typeof resolve6; + resolveAny: typeof resolveAny; + resolveCaa: typeof resolveCaa; + resolveCname: typeof resolveCname; + resolveMx: typeof resolveMx; + resolveNaptr: typeof resolveNaptr; + resolveNs: typeof resolveNs; + resolvePtr: typeof resolvePtr; + resolveSoa: typeof resolveSoa; + resolveSrv: typeof resolveSrv; + resolveTxt: typeof resolveTxt; + reverse: typeof reverse; + /** + * The resolver instance will send its requests from the specified IP address. + * This allows programs to specify outbound interfaces when used on multi-homed + * systems. + * + * If a v4 or v6 address is not specified, it is set to the default and the + * operating system will choose a local address automatically. + * + * The resolver will use the v4 local address when making requests to IPv4 DNS + * servers, and the v6 local address when making requests to IPv6 DNS servers. + * The `rrtype` of resolution requests has no impact on the local address used. + * @since v15.1.0, v14.17.0 + * @param [ipv4='0.0.0.0'] A string representation of an IPv4 address. + * @param [ipv6='::0'] A string representation of an IPv6 address. + */ + setLocalAddress(ipv4?: string, ipv6?: string): void; + setServers: typeof setServers; + } + export { dnsPromises as promises }; +} +declare module "node:dns" { + export * from "dns"; +} diff --git a/node_modules/@types/node/dns/promises.d.ts b/node_modules/@types/node/dns/promises.d.ts new file mode 100644 index 0000000..6f972ab --- /dev/null +++ b/node_modules/@types/node/dns/promises.d.ts @@ -0,0 +1,474 @@ +/** + * The `dns.promises` API provides an alternative set of asynchronous DNS methods + * that return `Promise` objects rather than using callbacks. The API is accessible + * via `require('node:dns').promises` or `require('node:dns/promises')`. + * @since v10.6.0 + */ +declare module "dns/promises" { + import { + AnyRecord, + CaaRecord, + LookupAddress, + LookupAllOptions, + LookupOneOptions, + LookupOptions, + MxRecord, + NaptrRecord, + RecordWithTtl, + ResolveOptions, + ResolverOptions, + ResolveWithTtlOptions, + SoaRecord, + SrvRecord, + } from "node:dns"; + /** + * Returns an array of IP address strings, formatted according to [RFC 5952](https://tools.ietf.org/html/rfc5952#section-6), + * that are currently configured for DNS resolution. A string will include a port + * section if a custom port is used. + * + * ```js + * [ + * '4.4.4.4', + * '2001:4860:4860::8888', + * '4.4.4.4:1053', + * '[2001:4860:4860::8888]:1053', + * ] + * ``` + * @since v10.6.0 + */ + function getServers(): string[]; + /** + * Resolves a host name (e.g. `'nodejs.org'`) into the first found A (IPv4) or + * AAAA (IPv6) record. All `option` properties are optional. If `options` is an + * integer, then it must be `4` or `6` – if `options` is not provided, then IPv4 + * and IPv6 addresses are both returned if found. + * + * With the `all` option set to `true`, the `Promise` is resolved with `addresses` being an array of objects with the properties `address` and `family`. + * + * On error, the `Promise` is rejected with an [`Error`](https://nodejs.org/docs/latest-v20.x/api/errors.html#class-error) object, where `err.code` is the error code. + * Keep in mind that `err.code` will be set to `'ENOTFOUND'` not only when + * the host name does not exist but also when the lookup fails in other ways + * such as no available file descriptors. + * + * [`dnsPromises.lookup()`](https://nodejs.org/docs/latest-v20.x/api/dns.html#dnspromiseslookuphostname-options) does not necessarily have anything to do with the DNS + * protocol. The implementation uses an operating system facility that can + * associate names with addresses and vice versa. This implementation can have + * subtle but important consequences on the behavior of any Node.js program. Please + * take some time to consult the [Implementation considerations section](https://nodejs.org/docs/latest-v20.x/api/dns.html#implementation-considerations) before + * using `dnsPromises.lookup()`. + * + * Example usage: + * + * ```js + * const dns = require('node:dns'); + * const dnsPromises = dns.promises; + * const options = { + * family: 6, + * hints: dns.ADDRCONFIG | dns.V4MAPPED, + * }; + * + * dnsPromises.lookup('example.com', options).then((result) => { + * console.log('address: %j family: IPv%s', result.address, result.family); + * // address: "2606:2800:220:1:248:1893:25c8:1946" family: IPv6 + * }); + * + * // When options.all is true, the result will be an Array. + * options.all = true; + * dnsPromises.lookup('example.com', options).then((result) => { + * console.log('addresses: %j', result); + * // addresses: [{"address":"2606:2800:220:1:248:1893:25c8:1946","family":6}] + * }); + * ``` + * @since v10.6.0 + */ + function lookup(hostname: string, family: number): Promise; + function lookup(hostname: string, options: LookupOneOptions): Promise; + function lookup(hostname: string, options: LookupAllOptions): Promise; + function lookup(hostname: string, options: LookupOptions): Promise; + function lookup(hostname: string): Promise; + /** + * Resolves the given `address` and `port` into a host name and service using + * the operating system's underlying `getnameinfo` implementation. + * + * If `address` is not a valid IP address, a `TypeError` will be thrown. + * The `port` will be coerced to a number. If it is not a legal port, a `TypeError` will be thrown. + * + * On error, the `Promise` is rejected with an [`Error`](https://nodejs.org/docs/latest-v20.x/api/errors.html#class-error) object, where `err.code` is the error code. + * + * ```js + * const dnsPromises = require('node:dns').promises; + * dnsPromises.lookupService('127.0.0.1', 22).then((result) => { + * console.log(result.hostname, result.service); + * // Prints: localhost ssh + * }); + * ``` + * @since v10.6.0 + */ + function lookupService( + address: string, + port: number, + ): Promise<{ + hostname: string; + service: string; + }>; + /** + * Uses the DNS protocol to resolve a host name (e.g. `'nodejs.org'`) into an array + * of the resource records. When successful, the `Promise` is resolved with an + * array of resource records. The type and structure of individual results vary + * based on `rrtype`: + * + * + * + * On error, the `Promise` is rejected with an [`Error`](https://nodejs.org/docs/latest-v20.x/api/errors.html#class-error) object, where `err.code` + * is one of the [DNS error codes](https://nodejs.org/docs/latest-v20.x/api/dns.html#error-codes). + * @since v10.6.0 + * @param hostname Host name to resolve. + * @param [rrtype='A'] Resource record type. + */ + function resolve(hostname: string): Promise; + function resolve(hostname: string, rrtype: "A"): Promise; + function resolve(hostname: string, rrtype: "AAAA"): Promise; + function resolve(hostname: string, rrtype: "ANY"): Promise; + function resolve(hostname: string, rrtype: "CAA"): Promise; + function resolve(hostname: string, rrtype: "CNAME"): Promise; + function resolve(hostname: string, rrtype: "MX"): Promise; + function resolve(hostname: string, rrtype: "NAPTR"): Promise; + function resolve(hostname: string, rrtype: "NS"): Promise; + function resolve(hostname: string, rrtype: "PTR"): Promise; + function resolve(hostname: string, rrtype: "SOA"): Promise; + function resolve(hostname: string, rrtype: "SRV"): Promise; + function resolve(hostname: string, rrtype: "TXT"): Promise; + function resolve( + hostname: string, + rrtype: string, + ): Promise; + /** + * Uses the DNS protocol to resolve IPv4 addresses (`A` records) for the `hostname`. On success, the `Promise` is resolved with an array of IPv4 + * addresses (e.g. `['74.125.79.104', '74.125.79.105', '74.125.79.106']`). + * @since v10.6.0 + * @param hostname Host name to resolve. + */ + function resolve4(hostname: string): Promise; + function resolve4(hostname: string, options: ResolveWithTtlOptions): Promise; + function resolve4(hostname: string, options: ResolveOptions): Promise; + /** + * Uses the DNS protocol to resolve IPv6 addresses (`AAAA` records) for the `hostname`. On success, the `Promise` is resolved with an array of IPv6 + * addresses. + * @since v10.6.0 + * @param hostname Host name to resolve. + */ + function resolve6(hostname: string): Promise; + function resolve6(hostname: string, options: ResolveWithTtlOptions): Promise; + function resolve6(hostname: string, options: ResolveOptions): Promise; + /** + * Uses the DNS protocol to resolve all records (also known as `ANY` or `*` query). + * On success, the `Promise` is resolved with an array containing various types of + * records. Each object has a property `type` that indicates the type of the + * current record. And depending on the `type`, additional properties will be + * present on the object: + * + * + * + * Here is an example of the result object: + * + * ```js + * [ { type: 'A', address: '127.0.0.1', ttl: 299 }, + * { type: 'CNAME', value: 'example.com' }, + * { type: 'MX', exchange: 'alt4.aspmx.l.example.com', priority: 50 }, + * { type: 'NS', value: 'ns1.example.com' }, + * { type: 'TXT', entries: [ 'v=spf1 include:_spf.example.com ~all' ] }, + * { type: 'SOA', + * nsname: 'ns1.example.com', + * hostmaster: 'admin.example.com', + * serial: 156696742, + * refresh: 900, + * retry: 900, + * expire: 1800, + * minttl: 60 } ] + * ``` + * @since v10.6.0 + */ + function resolveAny(hostname: string): Promise; + /** + * Uses the DNS protocol to resolve `CAA` records for the `hostname`. On success, + * the `Promise` is resolved with an array of objects containing available + * certification authority authorization records available for the `hostname` (e.g. `[{critical: 0, iodef: 'mailto:pki@example.com'},{critical: 128, issue: 'pki.example.com'}]`). + * @since v15.0.0, v14.17.0 + */ + function resolveCaa(hostname: string): Promise; + /** + * Uses the DNS protocol to resolve `CNAME` records for the `hostname`. On success, + * the `Promise` is resolved with an array of canonical name records available for + * the `hostname` (e.g. `['bar.example.com']`). + * @since v10.6.0 + */ + function resolveCname(hostname: string): Promise; + /** + * Uses the DNS protocol to resolve mail exchange records (`MX` records) for the `hostname`. On success, the `Promise` is resolved with an array of objects + * containing both a `priority` and `exchange` property (e.g.`[{priority: 10, exchange: 'mx.example.com'}, ...]`). + * @since v10.6.0 + */ + function resolveMx(hostname: string): Promise; + /** + * Uses the DNS protocol to resolve regular expression-based records (`NAPTR` records) for the `hostname`. On success, the `Promise` is resolved with an array + * of objects with the following properties: + * + * * `flags` + * * `service` + * * `regexp` + * * `replacement` + * * `order` + * * `preference` + * + * ```js + * { + * flags: 's', + * service: 'SIP+D2U', + * regexp: '', + * replacement: '_sip._udp.example.com', + * order: 30, + * preference: 100 + * } + * ``` + * @since v10.6.0 + */ + function resolveNaptr(hostname: string): Promise; + /** + * Uses the DNS protocol to resolve name server records (`NS` records) for the `hostname`. On success, the `Promise` is resolved with an array of name server + * records available for `hostname` (e.g.`['ns1.example.com', 'ns2.example.com']`). + * @since v10.6.0 + */ + function resolveNs(hostname: string): Promise; + /** + * Uses the DNS protocol to resolve pointer records (`PTR` records) for the `hostname`. On success, the `Promise` is resolved with an array of strings + * containing the reply records. + * @since v10.6.0 + */ + function resolvePtr(hostname: string): Promise; + /** + * Uses the DNS protocol to resolve a start of authority record (`SOA` record) for + * the `hostname`. On success, the `Promise` is resolved with an object with the + * following properties: + * + * * `nsname` + * * `hostmaster` + * * `serial` + * * `refresh` + * * `retry` + * * `expire` + * * `minttl` + * + * ```js + * { + * nsname: 'ns.example.com', + * hostmaster: 'root.example.com', + * serial: 2013101809, + * refresh: 10000, + * retry: 2400, + * expire: 604800, + * minttl: 3600 + * } + * ``` + * @since v10.6.0 + */ + function resolveSoa(hostname: string): Promise; + /** + * Uses the DNS protocol to resolve service records (`SRV` records) for the `hostname`. On success, the `Promise` is resolved with an array of objects with + * the following properties: + * + * * `priority` + * * `weight` + * * `port` + * * `name` + * + * ```js + * { + * priority: 10, + * weight: 5, + * port: 21223, + * name: 'service.example.com' + * } + * ``` + * @since v10.6.0 + */ + function resolveSrv(hostname: string): Promise; + /** + * Uses the DNS protocol to resolve text queries (`TXT` records) for the `hostname`. On success, the `Promise` is resolved with a two-dimensional array + * of the text records available for `hostname` (e.g.`[ ['v=spf1 ip4:0.0.0.0 ', '~all' ] ]`). Each sub-array contains TXT chunks of + * one record. Depending on the use case, these could be either joined together or + * treated separately. + * @since v10.6.0 + */ + function resolveTxt(hostname: string): Promise; + /** + * Performs a reverse DNS query that resolves an IPv4 or IPv6 address to an + * array of host names. + * + * On error, the `Promise` is rejected with an [`Error`](https://nodejs.org/docs/latest-v20.x/api/errors.html#class-error) object, where `err.code` + * is one of the [DNS error codes](https://nodejs.org/docs/latest-v20.x/api/dns.html#error-codes). + * @since v10.6.0 + */ + function reverse(ip: string): Promise; + /** + * Get the default value for `verbatim` in {@link lookup} and [dnsPromises.lookup()](https://nodejs.org/docs/latest-v20.x/api/dns.html#dnspromiseslookuphostname-options). + * The value could be: + * + * * `ipv4first`: for `verbatim` defaulting to `false`. + * * `verbatim`: for `verbatim` defaulting to `true`. + * @since v20.1.0 + */ + function getDefaultResultOrder(): "ipv4first" | "verbatim"; + /** + * Sets the IP address and port of servers to be used when performing DNS + * resolution. The `servers` argument is an array of [RFC 5952](https://tools.ietf.org/html/rfc5952#section-6) formatted + * addresses. If the port is the IANA default DNS port (53) it can be omitted. + * + * ```js + * dnsPromises.setServers([ + * '4.4.4.4', + * '[2001:4860:4860::8888]', + * '4.4.4.4:1053', + * '[2001:4860:4860::8888]:1053', + * ]); + * ``` + * + * An error will be thrown if an invalid address is provided. + * + * The `dnsPromises.setServers()` method must not be called while a DNS query is in + * progress. + * + * This method works much like [resolve.conf](https://man7.org/linux/man-pages/man5/resolv.conf.5.html). + * That is, if attempting to resolve with the first server provided results in a `NOTFOUND` error, the `resolve()` method will _not_ attempt to resolve with + * subsequent servers provided. Fallback DNS servers will only be used if the + * earlier ones time out or result in some other error. + * @since v10.6.0 + * @param servers array of `RFC 5952` formatted addresses + */ + function setServers(servers: readonly string[]): void; + /** + * Set the default value of `order` in `dns.lookup()` and `{@link lookup}`. The value could be: + * + * * `ipv4first`: sets default `order` to `ipv4first`. + * * `ipv6first`: sets default `order` to `ipv6first`. + * * `verbatim`: sets default `order` to `verbatim`. + * + * The default is `verbatim` and [dnsPromises.setDefaultResultOrder()](https://nodejs.org/docs/latest-v20.x/api/dns.html#dnspromisessetdefaultresultorderorder) + * have higher priority than [`--dns-result-order`](https://nodejs.org/docs/latest-v20.x/api/cli.html#--dns-result-orderorder). + * When using [worker threads](https://nodejs.org/docs/latest-v20.x/api/worker_threads.html), [`dnsPromises.setDefaultResultOrder()`](https://nodejs.org/docs/latest-v20.x/api/dns.html#dnspromisessetdefaultresultorderorder) + * from the main thread won't affect the default dns orders in workers. + * @since v16.4.0, v14.18.0 + * @param order must be `'ipv4first'`, `'ipv6first'` or `'verbatim'`. + */ + function setDefaultResultOrder(order: "ipv4first" | "ipv6first" | "verbatim"): void; + const NODATA: "NODATA"; + const FORMERR: "FORMERR"; + const SERVFAIL: "SERVFAIL"; + const NOTFOUND: "NOTFOUND"; + const NOTIMP: "NOTIMP"; + const REFUSED: "REFUSED"; + const BADQUERY: "BADQUERY"; + const BADNAME: "BADNAME"; + const BADFAMILY: "BADFAMILY"; + const BADRESP: "BADRESP"; + const CONNREFUSED: "TIMEOUT"; + const TIMEOUT: "TIMEOUT"; + const EOF: "EOF"; + const FILE: "FILE"; + const NOMEM: "NOMEM"; + const DESTRUCTION: "DESTRUCTION"; + const BADSTR: "BADSTR"; + const BADFLAGS: "BADFLAGS"; + const NONAME: "NONAME"; + const BADHINTS: "BADHINTS"; + const NOTINITIALIZED: "NOTINITIALIZED"; + const LOADIPHLPAPI: "LOADIPHLPAPI"; + const ADDRGETNETWORKPARAMS: "ADDRGETNETWORKPARAMS"; + const CANCELLED: "CANCELLED"; + /** + * An independent resolver for DNS requests. + * + * Creating a new resolver uses the default server settings. Setting + * the servers used for a resolver using [`resolver.setServers()`](https://nodejs.org/docs/latest-v20.x/api/dns.html#dnspromisessetserversservers) does not affect + * other resolvers: + * + * ```js + * const { Resolver } = require('node:dns').promises; + * const resolver = new Resolver(); + * resolver.setServers(['4.4.4.4']); + * + * // This request will use the server at 4.4.4.4, independent of global settings. + * resolver.resolve4('example.org').then((addresses) => { + * // ... + * }); + * + * // Alternatively, the same code can be written using async-await style. + * (async function() { + * const addresses = await resolver.resolve4('example.org'); + * })(); + * ``` + * + * The following methods from the `dnsPromises` API are available: + * + * * `resolver.getServers()` + * * `resolver.resolve()` + * * `resolver.resolve4()` + * * `resolver.resolve6()` + * * `resolver.resolveAny()` + * * `resolver.resolveCaa()` + * * `resolver.resolveCname()` + * * `resolver.resolveMx()` + * * `resolver.resolveNaptr()` + * * `resolver.resolveNs()` + * * `resolver.resolvePtr()` + * * `resolver.resolveSoa()` + * * `resolver.resolveSrv()` + * * `resolver.resolveTxt()` + * * `resolver.reverse()` + * * `resolver.setServers()` + * @since v10.6.0 + */ + class Resolver { + constructor(options?: ResolverOptions); + /** + * Cancel all outstanding DNS queries made by this resolver. The corresponding + * callbacks will be called with an error with code `ECANCELLED`. + * @since v8.3.0 + */ + cancel(): void; + getServers: typeof getServers; + resolve: typeof resolve; + resolve4: typeof resolve4; + resolve6: typeof resolve6; + resolveAny: typeof resolveAny; + resolveCaa: typeof resolveCaa; + resolveCname: typeof resolveCname; + resolveMx: typeof resolveMx; + resolveNaptr: typeof resolveNaptr; + resolveNs: typeof resolveNs; + resolvePtr: typeof resolvePtr; + resolveSoa: typeof resolveSoa; + resolveSrv: typeof resolveSrv; + resolveTxt: typeof resolveTxt; + reverse: typeof reverse; + /** + * The resolver instance will send its requests from the specified IP address. + * This allows programs to specify outbound interfaces when used on multi-homed + * systems. + * + * If a v4 or v6 address is not specified, it is set to the default and the + * operating system will choose a local address automatically. + * + * The resolver will use the v4 local address when making requests to IPv4 DNS + * servers, and the v6 local address when making requests to IPv6 DNS servers. + * The `rrtype` of resolution requests has no impact on the local address used. + * @since v15.1.0, v14.17.0 + * @param [ipv4='0.0.0.0'] A string representation of an IPv4 address. + * @param [ipv6='::0'] A string representation of an IPv6 address. + */ + setLocalAddress(ipv4?: string, ipv6?: string): void; + setServers: typeof setServers; + } +} +declare module "node:dns/promises" { + export * from "dns/promises"; +} diff --git a/node_modules/@types/node/dom-events.d.ts b/node_modules/@types/node/dom-events.d.ts new file mode 100644 index 0000000..f47f71d --- /dev/null +++ b/node_modules/@types/node/dom-events.d.ts @@ -0,0 +1,124 @@ +export {}; // Don't export anything! + +//// DOM-like Events +// NB: The Event / EventTarget / EventListener implementations below were copied +// from lib.dom.d.ts, then edited to reflect Node's documentation at +// https://nodejs.org/api/events.html#class-eventtarget. +// Please read that link to understand important implementation differences. + +// This conditional type will be the existing global Event in a browser, or +// the copy below in a Node environment. +type __Event = typeof globalThis extends { onmessage: any; Event: any } ? {} + : { + /** This is not used in Node.js and is provided purely for completeness. */ + readonly bubbles: boolean; + /** Alias for event.stopPropagation(). This is not used in Node.js and is provided purely for completeness. */ + cancelBubble: () => void; + /** True if the event was created with the cancelable option */ + readonly cancelable: boolean; + /** This is not used in Node.js and is provided purely for completeness. */ + readonly composed: boolean; + /** Returns an array containing the current EventTarget as the only entry or empty if the event is not being dispatched. This is not used in Node.js and is provided purely for completeness. */ + composedPath(): [EventTarget?]; + /** Alias for event.target. */ + readonly currentTarget: EventTarget | null; + /** Is true if cancelable is true and event.preventDefault() has been called. */ + readonly defaultPrevented: boolean; + /** This is not used in Node.js and is provided purely for completeness. */ + readonly eventPhase: 0 | 2; + /** The `AbortSignal` "abort" event is emitted with `isTrusted` set to `true`. The value is `false` in all other cases. */ + readonly isTrusted: boolean; + /** Sets the `defaultPrevented` property to `true` if `cancelable` is `true`. */ + preventDefault(): void; + /** This is not used in Node.js and is provided purely for completeness. */ + returnValue: boolean; + /** Alias for event.target. */ + readonly srcElement: EventTarget | null; + /** Stops the invocation of event listeners after the current one completes. */ + stopImmediatePropagation(): void; + /** This is not used in Node.js and is provided purely for completeness. */ + stopPropagation(): void; + /** The `EventTarget` dispatching the event */ + readonly target: EventTarget | null; + /** The millisecond timestamp when the Event object was created. */ + readonly timeStamp: number; + /** Returns the type of event, e.g. "click", "hashchange", or "submit". */ + readonly type: string; + }; + +// See comment above explaining conditional type +type __EventTarget = typeof globalThis extends { onmessage: any; EventTarget: any } ? {} + : { + /** + * Adds a new handler for the `type` event. Any given `listener` is added only once per `type` and per `capture` option value. + * + * If the `once` option is true, the `listener` is removed after the next time a `type` event is dispatched. + * + * The `capture` option is not used by Node.js in any functional way other than tracking registered event listeners per the `EventTarget` specification. + * Specifically, the `capture` option is used as part of the key when registering a `listener`. + * Any individual `listener` may be added once with `capture = false`, and once with `capture = true`. + */ + addEventListener( + type: string, + listener: EventListener | EventListenerObject, + options?: AddEventListenerOptions | boolean, + ): void; + /** Dispatches a synthetic event event to target and returns true if either event's cancelable attribute value is false or its preventDefault() method was not invoked, and false otherwise. */ + dispatchEvent(event: Event): boolean; + /** Removes the event listener in target's event listener list with the same type, callback, and options. */ + removeEventListener( + type: string, + listener: EventListener | EventListenerObject, + options?: EventListenerOptions | boolean, + ): void; + }; + +interface EventInit { + bubbles?: boolean; + cancelable?: boolean; + composed?: boolean; +} + +interface EventListenerOptions { + /** Not directly used by Node.js. Added for API completeness. Default: `false`. */ + capture?: boolean; +} + +interface AddEventListenerOptions extends EventListenerOptions { + /** When `true`, the listener is automatically removed when it is first invoked. Default: `false`. */ + once?: boolean; + /** When `true`, serves as a hint that the listener will not call the `Event` object's `preventDefault()` method. Default: false. */ + passive?: boolean; + /** The listener will be removed when the given AbortSignal object's `abort()` method is called. */ + signal?: AbortSignal; +} + +interface EventListener { + (evt: Event): void; +} + +interface EventListenerObject { + handleEvent(object: Event): void; +} + +import {} from "events"; // Make this an ambient declaration +declare global { + /** An event which takes place in the DOM. */ + interface Event extends __Event {} + var Event: typeof globalThis extends { onmessage: any; Event: infer T } ? T + : { + prototype: __Event; + new(type: string, eventInitDict?: EventInit): __Event; + }; + + /** + * EventTarget is a DOM interface implemented by objects that can + * receive events and may have listeners for them. + */ + interface EventTarget extends __EventTarget {} + var EventTarget: typeof globalThis extends { onmessage: any; EventTarget: infer T } ? T + : { + prototype: __EventTarget; + new(): __EventTarget; + }; +} diff --git a/node_modules/@types/node/domain.d.ts b/node_modules/@types/node/domain.d.ts new file mode 100644 index 0000000..d8bc999 --- /dev/null +++ b/node_modules/@types/node/domain.d.ts @@ -0,0 +1,170 @@ +/** + * **This module is pending deprecation.** Once a replacement API has been + * finalized, this module will be fully deprecated. Most developers should + * **not** have cause to use this module. Users who absolutely must have + * the functionality that domains provide may rely on it for the time being + * but should expect to have to migrate to a different solution + * in the future. + * + * Domains provide a way to handle multiple different IO operations as a + * single group. If any of the event emitters or callbacks registered to a + * domain emit an `'error'` event, or throw an error, then the domain object + * will be notified, rather than losing the context of the error in the `process.on('uncaughtException')` handler, or causing the program to + * exit immediately with an error code. + * @deprecated Since v1.4.2 - Deprecated + * @see [source](https://github.com/nodejs/node/blob/v20.13.1/lib/domain.js) + */ +declare module "domain" { + import EventEmitter = require("node:events"); + /** + * The `Domain` class encapsulates the functionality of routing errors and + * uncaught exceptions to the active `Domain` object. + * + * To handle the errors that it catches, listen to its `'error'` event. + */ + class Domain extends EventEmitter { + /** + * An array of timers and event emitters that have been explicitly added + * to the domain. + */ + members: Array; + /** + * The `enter()` method is plumbing used by the `run()`, `bind()`, and `intercept()` methods to set the active domain. It sets `domain.active` and `process.domain` to the domain, and implicitly + * pushes the domain onto the domain + * stack managed by the domain module (see {@link exit} for details on the + * domain stack). The call to `enter()` delimits the beginning of a chain of + * asynchronous calls and I/O operations bound to a domain. + * + * Calling `enter()` changes only the active domain, and does not alter the domain + * itself. `enter()` and `exit()` can be called an arbitrary number of times on a + * single domain. + */ + enter(): void; + /** + * The `exit()` method exits the current domain, popping it off the domain stack. + * Any time execution is going to switch to the context of a different chain of + * asynchronous calls, it's important to ensure that the current domain is exited. + * The call to `exit()` delimits either the end of or an interruption to the chain + * of asynchronous calls and I/O operations bound to a domain. + * + * If there are multiple, nested domains bound to the current execution context, `exit()` will exit any domains nested within this domain. + * + * Calling `exit()` changes only the active domain, and does not alter the domain + * itself. `enter()` and `exit()` can be called an arbitrary number of times on a + * single domain. + */ + exit(): void; + /** + * Run the supplied function in the context of the domain, implicitly + * binding all event emitters, timers, and low-level requests that are + * created in that context. Optionally, arguments can be passed to + * the function. + * + * This is the most basic way to use a domain. + * + * ```js + * const domain = require('node:domain'); + * const fs = require('node:fs'); + * const d = domain.create(); + * d.on('error', (er) => { + * console.error('Caught error!', er); + * }); + * d.run(() => { + * process.nextTick(() => { + * setTimeout(() => { // Simulating some various async stuff + * fs.open('non-existent file', 'r', (er, fd) => { + * if (er) throw er; + * // proceed... + * }); + * }, 100); + * }); + * }); + * ``` + * + * In this example, the `d.on('error')` handler will be triggered, rather + * than crashing the program. + */ + run(fn: (...args: any[]) => T, ...args: any[]): T; + /** + * Explicitly adds an emitter to the domain. If any event handlers called by + * the emitter throw an error, or if the emitter emits an `'error'` event, it + * will be routed to the domain's `'error'` event, just like with implicit + * binding. + * + * This also works with timers that are returned from `setInterval()` and `setTimeout()`. If their callback function throws, it will be caught by + * the domain `'error'` handler. + * + * If the Timer or `EventEmitter` was already bound to a domain, it is removed + * from that one, and bound to this one instead. + * @param emitter emitter or timer to be added to the domain + */ + add(emitter: EventEmitter | NodeJS.Timer): void; + /** + * The opposite of {@link add}. Removes domain handling from the + * specified emitter. + * @param emitter emitter or timer to be removed from the domain + */ + remove(emitter: EventEmitter | NodeJS.Timer): void; + /** + * The returned function will be a wrapper around the supplied callback + * function. When the returned function is called, any errors that are + * thrown will be routed to the domain's `'error'` event. + * + * ```js + * const d = domain.create(); + * + * function readSomeFile(filename, cb) { + * fs.readFile(filename, 'utf8', d.bind((er, data) => { + * // If this throws, it will also be passed to the domain. + * return cb(er, data ? JSON.parse(data) : null); + * })); + * } + * + * d.on('error', (er) => { + * // An error occurred somewhere. If we throw it now, it will crash the program + * // with the normal line number and stack message. + * }); + * ``` + * @param callback The callback function + * @return The bound function + */ + bind(callback: T): T; + /** + * This method is almost identical to {@link bind}. However, in + * addition to catching thrown errors, it will also intercept `Error` objects sent as the first argument to the function. + * + * In this way, the common `if (err) return callback(err);` pattern can be replaced + * with a single error handler in a single place. + * + * ```js + * const d = domain.create(); + * + * function readSomeFile(filename, cb) { + * fs.readFile(filename, 'utf8', d.intercept((data) => { + * // Note, the first argument is never passed to the + * // callback since it is assumed to be the 'Error' argument + * // and thus intercepted by the domain. + * + * // If this throws, it will also be passed to the domain + * // so the error-handling logic can be moved to the 'error' + * // event on the domain instead of being repeated throughout + * // the program. + * return cb(null, JSON.parse(data)); + * })); + * } + * + * d.on('error', (er) => { + * // An error occurred somewhere. If we throw it now, it will crash the program + * // with the normal line number and stack message. + * }); + * ``` + * @param callback The callback function + * @return The intercepted function + */ + intercept(callback: T): T; + } + function create(): Domain; +} +declare module "node:domain" { + export * from "domain"; +} diff --git a/node_modules/@types/node/events.d.ts b/node_modules/@types/node/events.d.ts new file mode 100644 index 0000000..8e49722 --- /dev/null +++ b/node_modules/@types/node/events.d.ts @@ -0,0 +1,904 @@ +/** + * Much of the Node.js core API is built around an idiomatic asynchronous + * event-driven architecture in which certain kinds of objects (called "emitters") + * emit named events that cause `Function` objects ("listeners") to be called. + * + * For instance: a `net.Server` object emits an event each time a peer + * connects to it; a `fs.ReadStream` emits an event when the file is opened; + * a `stream` emits an event whenever data is available to be read. + * + * All objects that emit events are instances of the `EventEmitter` class. These + * objects expose an `eventEmitter.on()` function that allows one or more + * functions to be attached to named events emitted by the object. Typically, + * event names are camel-cased strings but any valid JavaScript property key + * can be used. + * + * When the `EventEmitter` object emits an event, all of the functions attached + * to that specific event are called _synchronously_. Any values returned by the + * called listeners are _ignored_ and discarded. + * + * The following example shows a simple `EventEmitter` instance with a single + * listener. The `eventEmitter.on()` method is used to register listeners, while + * the `eventEmitter.emit()` method is used to trigger the event. + * + * ```js + * import { EventEmitter } from 'node:events'; + * + * class MyEmitter extends EventEmitter {} + * + * const myEmitter = new MyEmitter(); + * myEmitter.on('event', () => { + * console.log('an event occurred!'); + * }); + * myEmitter.emit('event'); + * ``` + * @see [source](https://github.com/nodejs/node/blob/v20.13.1/lib/events.js) + */ +declare module "events" { + import { AsyncResource, AsyncResourceOptions } from "node:async_hooks"; + // NOTE: This class is in the docs but is **not actually exported** by Node. + // If https://github.com/nodejs/node/issues/39903 gets resolved and Node + // actually starts exporting the class, uncomment below. + // import { EventListener, EventListenerObject } from '__dom-events'; + // /** The NodeEventTarget is a Node.js-specific extension to EventTarget that emulates a subset of the EventEmitter API. */ + // interface NodeEventTarget extends EventTarget { + // /** + // * Node.js-specific extension to the `EventTarget` class that emulates the equivalent `EventEmitter` API. + // * The only difference between `addListener()` and `addEventListener()` is that addListener() will return a reference to the EventTarget. + // */ + // addListener(type: string, listener: EventListener | EventListenerObject, options?: { once: boolean }): this; + // /** Node.js-specific extension to the `EventTarget` class that returns an array of event `type` names for which event listeners are registered. */ + // eventNames(): string[]; + // /** Node.js-specific extension to the `EventTarget` class that returns the number of event listeners registered for the `type`. */ + // listenerCount(type: string): number; + // /** Node.js-specific alias for `eventTarget.removeListener()`. */ + // off(type: string, listener: EventListener | EventListenerObject): this; + // /** Node.js-specific alias for `eventTarget.addListener()`. */ + // on(type: string, listener: EventListener | EventListenerObject, options?: { once: boolean }): this; + // /** Node.js-specific extension to the `EventTarget` class that adds a `once` listener for the given event `type`. This is equivalent to calling `on` with the `once` option set to `true`. */ + // once(type: string, listener: EventListener | EventListenerObject): this; + // /** + // * Node.js-specific extension to the `EventTarget` class. + // * If `type` is specified, removes all registered listeners for `type`, + // * otherwise removes all registered listeners. + // */ + // removeAllListeners(type: string): this; + // /** + // * Node.js-specific extension to the `EventTarget` class that removes the listener for the given `type`. + // * The only difference between `removeListener()` and `removeEventListener()` is that `removeListener()` will return a reference to the `EventTarget`. + // */ + // removeListener(type: string, listener: EventListener | EventListenerObject): this; + // } + interface EventEmitterOptions { + /** + * Enables automatic capturing of promise rejection. + */ + captureRejections?: boolean | undefined; + } + interface StaticEventEmitterOptions { + /** + * Can be used to cancel awaiting events. + */ + signal?: AbortSignal | undefined; + /** + * Names of events that will end the iteration. + */ + close?: string[] | undefined; + /** + * The high watermark. The emitter is paused every time the size + * of events being buffered is higher than it. Supported only + * on emitters implementing `pause()` and `resume()` methods. + * @default `Number.MAX_SAFE_INTEGER` + */ + highWaterMark?: number | undefined; + /** + * The low watermark. The emitter is resumed every time the size of events being buffered + * is lower than it. Supported only on emitters implementing `pause()` and `resume()` methods. + * @default 1 + */ + lowWaterMark?: number | undefined; + } + interface EventEmitter = DefaultEventMap> extends NodeJS.EventEmitter {} + type EventMap = Record | DefaultEventMap; + type DefaultEventMap = [never]; + type AnyRest = [...args: any[]]; + type Args = T extends DefaultEventMap ? AnyRest : ( + K extends keyof T ? T[K] : never + ); + type Key = T extends DefaultEventMap ? string | symbol : K | keyof T; + type Key2 = T extends DefaultEventMap ? string | symbol : K & keyof T; + type Listener = T extends DefaultEventMap ? F : ( + K extends keyof T ? ( + T[K] extends unknown[] ? (...args: T[K]) => void : never + ) + : never + ); + type Listener1 = Listener void>; + type Listener2 = Listener; + + /** + * The `EventEmitter` class is defined and exposed by the `node:events` module: + * + * ```js + * import { EventEmitter } from 'node:events'; + * ``` + * + * All `EventEmitter`s emit the event `'newListener'` when new listeners are + * added and `'removeListener'` when existing listeners are removed. + * + * It supports the following option: + * @since v0.1.26 + */ + class EventEmitter = DefaultEventMap> { + constructor(options?: EventEmitterOptions); + + [EventEmitter.captureRejectionSymbol]?(error: Error, event: Key, ...args: Args): void; + + /** + * Creates a `Promise` that is fulfilled when the `EventEmitter` emits the given + * event or that is rejected if the `EventEmitter` emits `'error'` while waiting. + * The `Promise` will resolve with an array of all the arguments emitted to the + * given event. + * + * This method is intentionally generic and works with the web platform [EventTarget](https://dom.spec.whatwg.org/#interface-eventtarget) interface, which has no special`'error'` event + * semantics and does not listen to the `'error'` event. + * + * ```js + * import { once, EventEmitter } from 'node:events'; + * import process from 'node:process'; + * + * const ee = new EventEmitter(); + * + * process.nextTick(() => { + * ee.emit('myevent', 42); + * }); + * + * const [value] = await once(ee, 'myevent'); + * console.log(value); + * + * const err = new Error('kaboom'); + * process.nextTick(() => { + * ee.emit('error', err); + * }); + * + * try { + * await once(ee, 'myevent'); + * } catch (err) { + * console.error('error happened', err); + * } + * ``` + * + * The special handling of the `'error'` event is only used when `events.once()` is used to wait for another event. If `events.once()` is used to wait for the + * '`error'` event itself, then it is treated as any other kind of event without + * special handling: + * + * ```js + * import { EventEmitter, once } from 'node:events'; + * + * const ee = new EventEmitter(); + * + * once(ee, 'error') + * .then(([err]) => console.log('ok', err.message)) + * .catch((err) => console.error('error', err.message)); + * + * ee.emit('error', new Error('boom')); + * + * // Prints: ok boom + * ``` + * + * An `AbortSignal` can be used to cancel waiting for the event: + * + * ```js + * import { EventEmitter, once } from 'node:events'; + * + * const ee = new EventEmitter(); + * const ac = new AbortController(); + * + * async function foo(emitter, event, signal) { + * try { + * await once(emitter, event, { signal }); + * console.log('event emitted!'); + * } catch (error) { + * if (error.name === 'AbortError') { + * console.error('Waiting for the event was canceled!'); + * } else { + * console.error('There was an error', error.message); + * } + * } + * } + * + * foo(ee, 'foo', ac.signal); + * ac.abort(); // Abort waiting for the event + * ee.emit('foo'); // Prints: Waiting for the event was canceled! + * ``` + * @since v11.13.0, v10.16.0 + */ + static once( + emitter: NodeJS.EventEmitter, + eventName: string | symbol, + options?: Pick, + ): Promise; + static once(emitter: EventTarget, eventName: string, options?: StaticEventEmitterOptions): Promise; + /** + * ```js + * import { on, EventEmitter } from 'node:events'; + * import process from 'node:process'; + * + * const ee = new EventEmitter(); + * + * // Emit later on + * process.nextTick(() => { + * ee.emit('foo', 'bar'); + * ee.emit('foo', 42); + * }); + * + * for await (const event of on(ee, 'foo')) { + * // The execution of this inner block is synchronous and it + * // processes one event at a time (even with await). Do not use + * // if concurrent execution is required. + * console.log(event); // prints ['bar'] [42] + * } + * // Unreachable here + * ``` + * + * Returns an `AsyncIterator` that iterates `eventName` events. It will throw + * if the `EventEmitter` emits `'error'`. It removes all listeners when + * exiting the loop. The `value` returned by each iteration is an array + * composed of the emitted event arguments. + * + * An `AbortSignal` can be used to cancel waiting on events: + * + * ```js + * import { on, EventEmitter } from 'node:events'; + * import process from 'node:process'; + * + * const ac = new AbortController(); + * + * (async () => { + * const ee = new EventEmitter(); + * + * // Emit later on + * process.nextTick(() => { + * ee.emit('foo', 'bar'); + * ee.emit('foo', 42); + * }); + * + * for await (const event of on(ee, 'foo', { signal: ac.signal })) { + * // The execution of this inner block is synchronous and it + * // processes one event at a time (even with await). Do not use + * // if concurrent execution is required. + * console.log(event); // prints ['bar'] [42] + * } + * // Unreachable here + * })(); + * + * process.nextTick(() => ac.abort()); + * ``` + * @since v13.6.0, v12.16.0 + * @param eventName The name of the event being listened for + * @return An `AsyncIterator` that iterates `eventName` events emitted by the `emitter` + */ + static on( + emitter: NodeJS.EventEmitter, + eventName: string, + options?: StaticEventEmitterOptions, + ): AsyncIterableIterator; + /** + * A class method that returns the number of listeners for the given `eventName` registered on the given `emitter`. + * + * ```js + * import { EventEmitter, listenerCount } from 'node:events'; + * + * const myEmitter = new EventEmitter(); + * myEmitter.on('event', () => {}); + * myEmitter.on('event', () => {}); + * console.log(listenerCount(myEmitter, 'event')); + * // Prints: 2 + * ``` + * @since v0.9.12 + * @deprecated Since v3.2.0 - Use `listenerCount` instead. + * @param emitter The emitter to query + * @param eventName The event name + */ + static listenerCount(emitter: NodeJS.EventEmitter, eventName: string | symbol): number; + /** + * Returns a copy of the array of listeners for the event named `eventName`. + * + * For `EventEmitter`s this behaves exactly the same as calling `.listeners` on + * the emitter. + * + * For `EventTarget`s this is the only way to get the event listeners for the + * event target. This is useful for debugging and diagnostic purposes. + * + * ```js + * import { getEventListeners, EventEmitter } from 'node:events'; + * + * { + * const ee = new EventEmitter(); + * const listener = () => console.log('Events are fun'); + * ee.on('foo', listener); + * console.log(getEventListeners(ee, 'foo')); // [ [Function: listener] ] + * } + * { + * const et = new EventTarget(); + * const listener = () => console.log('Events are fun'); + * et.addEventListener('foo', listener); + * console.log(getEventListeners(et, 'foo')); // [ [Function: listener] ] + * } + * ``` + * @since v15.2.0, v14.17.0 + */ + static getEventListeners(emitter: EventTarget | NodeJS.EventEmitter, name: string | symbol): Function[]; + /** + * Returns the currently set max amount of listeners. + * + * For `EventEmitter`s this behaves exactly the same as calling `.getMaxListeners` on + * the emitter. + * + * For `EventTarget`s this is the only way to get the max event listeners for the + * event target. If the number of event handlers on a single EventTarget exceeds + * the max set, the EventTarget will print a warning. + * + * ```js + * import { getMaxListeners, setMaxListeners, EventEmitter } from 'node:events'; + * + * { + * const ee = new EventEmitter(); + * console.log(getMaxListeners(ee)); // 10 + * setMaxListeners(11, ee); + * console.log(getMaxListeners(ee)); // 11 + * } + * { + * const et = new EventTarget(); + * console.log(getMaxListeners(et)); // 10 + * setMaxListeners(11, et); + * console.log(getMaxListeners(et)); // 11 + * } + * ``` + * @since v19.9.0 + */ + static getMaxListeners(emitter: EventTarget | NodeJS.EventEmitter): number; + /** + * ```js + * import { setMaxListeners, EventEmitter } from 'node:events'; + * + * const target = new EventTarget(); + * const emitter = new EventEmitter(); + * + * setMaxListeners(5, target, emitter); + * ``` + * @since v15.4.0 + * @param n A non-negative number. The maximum number of listeners per `EventTarget` event. + * @param eventsTargets Zero or more {EventTarget} or {EventEmitter} instances. If none are specified, `n` is set as the default max for all newly created {EventTarget} and {EventEmitter} + * objects. + */ + static setMaxListeners(n?: number, ...eventTargets: Array): void; + /** + * Listens once to the `abort` event on the provided `signal`. + * + * Listening to the `abort` event on abort signals is unsafe and may + * lead to resource leaks since another third party with the signal can + * call `e.stopImmediatePropagation()`. Unfortunately Node.js cannot change + * this since it would violate the web standard. Additionally, the original + * API makes it easy to forget to remove listeners. + * + * This API allows safely using `AbortSignal`s in Node.js APIs by solving these + * two issues by listening to the event such that `stopImmediatePropagation` does + * not prevent the listener from running. + * + * Returns a disposable so that it may be unsubscribed from more easily. + * + * ```js + * import { addAbortListener } from 'node:events'; + * + * function example(signal) { + * let disposable; + * try { + * signal.addEventListener('abort', (e) => e.stopImmediatePropagation()); + * disposable = addAbortListener(signal, (e) => { + * // Do something when signal is aborted. + * }); + * } finally { + * disposable?.[Symbol.dispose](); + * } + * } + * ``` + * @since v20.5.0 + * @experimental + * @return Disposable that removes the `abort` listener. + */ + static addAbortListener(signal: AbortSignal, resource: (event: Event) => void): Disposable; + /** + * This symbol shall be used to install a listener for only monitoring `'error'` events. Listeners installed using this symbol are called before the regular `'error'` listeners are called. + * + * Installing a listener using this symbol does not change the behavior once an `'error'` event is emitted. Therefore, the process will still crash if no + * regular `'error'` listener is installed. + * @since v13.6.0, v12.17.0 + */ + static readonly errorMonitor: unique symbol; + /** + * Value: `Symbol.for('nodejs.rejection')` + * + * See how to write a custom `rejection handler`. + * @since v13.4.0, v12.16.0 + */ + static readonly captureRejectionSymbol: unique symbol; + /** + * Value: [boolean](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) + * + * Change the default `captureRejections` option on all new `EventEmitter` objects. + * @since v13.4.0, v12.16.0 + */ + static captureRejections: boolean; + /** + * By default, a maximum of `10` listeners can be registered for any single + * event. This limit can be changed for individual `EventEmitter` instances + * using the `emitter.setMaxListeners(n)` method. To change the default + * for _all_`EventEmitter` instances, the `events.defaultMaxListeners` property + * can be used. If this value is not a positive number, a `RangeError` is thrown. + * + * Take caution when setting the `events.defaultMaxListeners` because the + * change affects _all_ `EventEmitter` instances, including those created before + * the change is made. However, calling `emitter.setMaxListeners(n)` still has + * precedence over `events.defaultMaxListeners`. + * + * This is not a hard limit. The `EventEmitter` instance will allow + * more listeners to be added but will output a trace warning to stderr indicating + * that a "possible EventEmitter memory leak" has been detected. For any single + * `EventEmitter`, the `emitter.getMaxListeners()` and `emitter.setMaxListeners()` methods can be used to + * temporarily avoid this warning: + * + * ```js + * import { EventEmitter } from 'node:events'; + * const emitter = new EventEmitter(); + * emitter.setMaxListeners(emitter.getMaxListeners() + 1); + * emitter.once('event', () => { + * // do stuff + * emitter.setMaxListeners(Math.max(emitter.getMaxListeners() - 1, 0)); + * }); + * ``` + * + * The `--trace-warnings` command-line flag can be used to display the + * stack trace for such warnings. + * + * The emitted warning can be inspected with `process.on('warning')` and will + * have the additional `emitter`, `type`, and `count` properties, referring to + * the event emitter instance, the event's name and the number of attached + * listeners, respectively. + * Its `name` property is set to `'MaxListenersExceededWarning'`. + * @since v0.11.2 + */ + static defaultMaxListeners: number; + } + import internal = require("node:events"); + namespace EventEmitter { + // Should just be `export { EventEmitter }`, but that doesn't work in TypeScript 3.4 + export { internal as EventEmitter }; + export interface Abortable { + /** + * When provided the corresponding `AbortController` can be used to cancel an asynchronous action. + */ + signal?: AbortSignal | undefined; + } + + export interface EventEmitterReferencingAsyncResource extends AsyncResource { + readonly eventEmitter: EventEmitterAsyncResource; + } + + export interface EventEmitterAsyncResourceOptions extends AsyncResourceOptions, EventEmitterOptions { + /** + * The type of async event, this is required when instantiating `EventEmitterAsyncResource` + * directly rather than as a child class. + * @default new.target.name if instantiated as a child class. + */ + name?: string; + } + + /** + * Integrates `EventEmitter` with `AsyncResource` for `EventEmitter`s that + * require manual async tracking. Specifically, all events emitted by instances + * of `events.EventEmitterAsyncResource` will run within its `async context`. + * + * ```js + * import { EventEmitterAsyncResource, EventEmitter } from 'node:events'; + * import { notStrictEqual, strictEqual } from 'node:assert'; + * import { executionAsyncId, triggerAsyncId } from 'node:async_hooks'; + * + * // Async tracking tooling will identify this as 'Q'. + * const ee1 = new EventEmitterAsyncResource({ name: 'Q' }); + * + * // 'foo' listeners will run in the EventEmitters async context. + * ee1.on('foo', () => { + * strictEqual(executionAsyncId(), ee1.asyncId); + * strictEqual(triggerAsyncId(), ee1.triggerAsyncId); + * }); + * + * const ee2 = new EventEmitter(); + * + * // 'foo' listeners on ordinary EventEmitters that do not track async + * // context, however, run in the same async context as the emit(). + * ee2.on('foo', () => { + * notStrictEqual(executionAsyncId(), ee2.asyncId); + * notStrictEqual(triggerAsyncId(), ee2.triggerAsyncId); + * }); + * + * Promise.resolve().then(() => { + * ee1.emit('foo'); + * ee2.emit('foo'); + * }); + * ``` + * + * The `EventEmitterAsyncResource` class has the same methods and takes the + * same options as `EventEmitter` and `AsyncResource` themselves. + * @since v17.4.0, v16.14.0 + */ + export class EventEmitterAsyncResource extends EventEmitter { + /** + * @param options Only optional in child class. + */ + constructor(options?: EventEmitterAsyncResourceOptions); + /** + * Call all `destroy` hooks. This should only ever be called once. An error will + * be thrown if it is called more than once. This **must** be manually called. If + * the resource is left to be collected by the GC then the `destroy` hooks will + * never be called. + */ + emitDestroy(): void; + /** + * The unique `asyncId` assigned to the resource. + */ + readonly asyncId: number; + /** + * The same triggerAsyncId that is passed to the AsyncResource constructor. + */ + readonly triggerAsyncId: number; + /** + * The returned `AsyncResource` object has an additional `eventEmitter` property + * that provides a reference to this `EventEmitterAsyncResource`. + */ + readonly asyncResource: EventEmitterReferencingAsyncResource; + } + } + global { + namespace NodeJS { + interface EventEmitter = DefaultEventMap> { + [EventEmitter.captureRejectionSymbol]?(error: Error, event: Key, ...args: Args): void; + /** + * Alias for `emitter.on(eventName, listener)`. + * @since v0.1.26 + */ + addListener(eventName: Key, listener: Listener1): this; + /** + * Adds the `listener` function to the end of the listeners array for the event + * named `eventName`. No checks are made to see if the `listener` has already + * been added. Multiple calls passing the same combination of `eventName` and + * `listener` will result in the `listener` being added, and called, multiple times. + * + * ```js + * server.on('connection', (stream) => { + * console.log('someone connected!'); + * }); + * ``` + * + * Returns a reference to the `EventEmitter`, so that calls can be chained. + * + * By default, event listeners are invoked in the order they are added. The `emitter.prependListener()` method can be used as an alternative to add the + * event listener to the beginning of the listeners array. + * + * ```js + * import { EventEmitter } from 'node:events'; + * const myEE = new EventEmitter(); + * myEE.on('foo', () => console.log('a')); + * myEE.prependListener('foo', () => console.log('b')); + * myEE.emit('foo'); + * // Prints: + * // b + * // a + * ``` + * @since v0.1.101 + * @param eventName The name of the event. + * @param listener The callback function + */ + on(eventName: Key, listener: Listener1): this; + /** + * Adds a **one-time** `listener` function for the event named `eventName`. The + * next time `eventName` is triggered, this listener is removed and then invoked. + * + * ```js + * server.once('connection', (stream) => { + * console.log('Ah, we have our first user!'); + * }); + * ``` + * + * Returns a reference to the `EventEmitter`, so that calls can be chained. + * + * By default, event listeners are invoked in the order they are added. The `emitter.prependOnceListener()` method can be used as an alternative to add the + * event listener to the beginning of the listeners array. + * + * ```js + * import { EventEmitter } from 'node:events'; + * const myEE = new EventEmitter(); + * myEE.once('foo', () => console.log('a')); + * myEE.prependOnceListener('foo', () => console.log('b')); + * myEE.emit('foo'); + * // Prints: + * // b + * // a + * ``` + * @since v0.3.0 + * @param eventName The name of the event. + * @param listener The callback function + */ + once(eventName: Key, listener: Listener1): this; + /** + * Removes the specified `listener` from the listener array for the event named `eventName`. + * + * ```js + * const callback = (stream) => { + * console.log('someone connected!'); + * }; + * server.on('connection', callback); + * // ... + * server.removeListener('connection', callback); + * ``` + * + * `removeListener()` will remove, at most, one instance of a listener from the + * listener array. If any single listener has been added multiple times to the + * listener array for the specified `eventName`, then `removeListener()` must be + * called multiple times to remove each instance. + * + * Once an event is emitted, all listeners attached to it at the + * time of emitting are called in order. This implies that any `removeListener()` or `removeAllListeners()` calls _after_ emitting and _before_ the last listener finishes execution + * will not remove them from`emit()` in progress. Subsequent events behave as expected. + * + * ```js + * import { EventEmitter } from 'node:events'; + * class MyEmitter extends EventEmitter {} + * const myEmitter = new MyEmitter(); + * + * const callbackA = () => { + * console.log('A'); + * myEmitter.removeListener('event', callbackB); + * }; + * + * const callbackB = () => { + * console.log('B'); + * }; + * + * myEmitter.on('event', callbackA); + * + * myEmitter.on('event', callbackB); + * + * // callbackA removes listener callbackB but it will still be called. + * // Internal listener array at time of emit [callbackA, callbackB] + * myEmitter.emit('event'); + * // Prints: + * // A + * // B + * + * // callbackB is now removed. + * // Internal listener array [callbackA] + * myEmitter.emit('event'); + * // Prints: + * // A + * ``` + * + * Because listeners are managed using an internal array, calling this will + * change the position indices of any listener registered _after_ the listener + * being removed. This will not impact the order in which listeners are called, + * but it means that any copies of the listener array as returned by + * the `emitter.listeners()` method will need to be recreated. + * + * When a single function has been added as a handler multiple times for a single + * event (as in the example below), `removeListener()` will remove the most + * recently added instance. In the example the `once('ping')` listener is removed: + * + * ```js + * import { EventEmitter } from 'node:events'; + * const ee = new EventEmitter(); + * + * function pong() { + * console.log('pong'); + * } + * + * ee.on('ping', pong); + * ee.once('ping', pong); + * ee.removeListener('ping', pong); + * + * ee.emit('ping'); + * ee.emit('ping'); + * ``` + * + * Returns a reference to the `EventEmitter`, so that calls can be chained. + * @since v0.1.26 + */ + removeListener(eventName: Key, listener: Listener1): this; + /** + * Alias for `emitter.removeListener()`. + * @since v10.0.0 + */ + off(eventName: Key, listener: Listener1): this; + /** + * Removes all listeners, or those of the specified `eventName`. + * + * It is bad practice to remove listeners added elsewhere in the code, + * particularly when the `EventEmitter` instance was created by some other + * component or module (e.g. sockets or file streams). + * + * Returns a reference to the `EventEmitter`, so that calls can be chained. + * @since v0.1.26 + */ + removeAllListeners(eventName?: Key): this; + /** + * By default `EventEmitter`s will print a warning if more than `10` listeners are + * added for a particular event. This is a useful default that helps finding + * memory leaks. The `emitter.setMaxListeners()` method allows the limit to be + * modified for this specific `EventEmitter` instance. The value can be set to `Infinity` (or `0`) to indicate an unlimited number of listeners. + * + * Returns a reference to the `EventEmitter`, so that calls can be chained. + * @since v0.3.5 + */ + setMaxListeners(n: number): this; + /** + * Returns the current max listener value for the `EventEmitter` which is either + * set by `emitter.setMaxListeners(n)` or defaults to {@link defaultMaxListeners}. + * @since v1.0.0 + */ + getMaxListeners(): number; + /** + * Returns a copy of the array of listeners for the event named `eventName`. + * + * ```js + * server.on('connection', (stream) => { + * console.log('someone connected!'); + * }); + * console.log(util.inspect(server.listeners('connection'))); + * // Prints: [ [Function] ] + * ``` + * @since v0.1.26 + */ + listeners(eventName: Key): Array>; + /** + * Returns a copy of the array of listeners for the event named `eventName`, + * including any wrappers (such as those created by `.once()`). + * + * ```js + * import { EventEmitter } from 'node:events'; + * const emitter = new EventEmitter(); + * emitter.once('log', () => console.log('log once')); + * + * // Returns a new Array with a function `onceWrapper` which has a property + * // `listener` which contains the original listener bound above + * const listeners = emitter.rawListeners('log'); + * const logFnWrapper = listeners[0]; + * + * // Logs "log once" to the console and does not unbind the `once` event + * logFnWrapper.listener(); + * + * // Logs "log once" to the console and removes the listener + * logFnWrapper(); + * + * emitter.on('log', () => console.log('log persistently')); + * // Will return a new Array with a single function bound by `.on()` above + * const newListeners = emitter.rawListeners('log'); + * + * // Logs "log persistently" twice + * newListeners[0](); + * emitter.emit('log'); + * ``` + * @since v9.4.0 + */ + rawListeners(eventName: Key): Array>; + /** + * Synchronously calls each of the listeners registered for the event named `eventName`, in the order they were registered, passing the supplied arguments + * to each. + * + * Returns `true` if the event had listeners, `false` otherwise. + * + * ```js + * import { EventEmitter } from 'node:events'; + * const myEmitter = new EventEmitter(); + * + * // First listener + * myEmitter.on('event', function firstListener() { + * console.log('Helloooo! first listener'); + * }); + * // Second listener + * myEmitter.on('event', function secondListener(arg1, arg2) { + * console.log(`event with parameters ${arg1}, ${arg2} in second listener`); + * }); + * // Third listener + * myEmitter.on('event', function thirdListener(...args) { + * const parameters = args.join(', '); + * console.log(`event with parameters ${parameters} in third listener`); + * }); + * + * console.log(myEmitter.listeners('event')); + * + * myEmitter.emit('event', 1, 2, 3, 4, 5); + * + * // Prints: + * // [ + * // [Function: firstListener], + * // [Function: secondListener], + * // [Function: thirdListener] + * // ] + * // Helloooo! first listener + * // event with parameters 1, 2 in second listener + * // event with parameters 1, 2, 3, 4, 5 in third listener + * ``` + * @since v0.1.26 + */ + emit(eventName: Key, ...args: Args): boolean; + /** + * Returns the number of listeners listening for the event named `eventName`. + * If `listener` is provided, it will return how many times the listener is found + * in the list of the listeners of the event. + * @since v3.2.0 + * @param eventName The name of the event being listened for + * @param listener The event handler function + */ + listenerCount(eventName: Key, listener?: Listener2): number; + /** + * Adds the `listener` function to the _beginning_ of the listeners array for the + * event named `eventName`. No checks are made to see if the `listener` has + * already been added. Multiple calls passing the same combination of `eventName` + * and `listener` will result in the `listener` being added, and called, multiple times. + * + * ```js + * server.prependListener('connection', (stream) => { + * console.log('someone connected!'); + * }); + * ``` + * + * Returns a reference to the `EventEmitter`, so that calls can be chained. + * @since v6.0.0 + * @param eventName The name of the event. + * @param listener The callback function + */ + prependListener(eventName: Key, listener: Listener1): this; + /** + * Adds a **one-time**`listener` function for the event named `eventName` to the _beginning_ of the listeners array. The next time `eventName` is triggered, this + * listener is removed, and then invoked. + * + * ```js + * server.prependOnceListener('connection', (stream) => { + * console.log('Ah, we have our first user!'); + * }); + * ``` + * + * Returns a reference to the `EventEmitter`, so that calls can be chained. + * @since v6.0.0 + * @param eventName The name of the event. + * @param listener The callback function + */ + prependOnceListener(eventName: Key, listener: Listener1): this; + /** + * Returns an array listing the events for which the emitter has registered + * listeners. The values in the array are strings or `Symbol`s. + * + * ```js + * import { EventEmitter } from 'node:events'; + * + * const myEE = new EventEmitter(); + * myEE.on('foo', () => {}); + * myEE.on('bar', () => {}); + * + * const sym = Symbol('symbol'); + * myEE.on(sym, () => {}); + * + * console.log(myEE.eventNames()); + * // Prints: [ 'foo', 'bar', Symbol(symbol) ] + * ``` + * @since v6.0.0 + */ + eventNames(): Array<(string | symbol) & Key2>; + } + } + } + export = EventEmitter; +} +declare module "node:events" { + import events = require("events"); + export = events; +} diff --git a/node_modules/@types/node/fs.d.ts b/node_modules/@types/node/fs.d.ts new file mode 100644 index 0000000..dc1d5da --- /dev/null +++ b/node_modules/@types/node/fs.d.ts @@ -0,0 +1,4317 @@ +/** + * The `node:fs` module enables interacting with the file system in a + * way modeled on standard POSIX functions. + * + * To use the promise-based APIs: + * + * ```js + * import * as fs from 'node:fs/promises'; + * ``` + * + * To use the callback and sync APIs: + * + * ```js + * import * as fs from 'node:fs'; + * ``` + * + * All file system operations have synchronous, callback, and promise-based + * forms, and are accessible using both CommonJS syntax and ES6 Modules (ESM). + * @see [source](https://github.com/nodejs/node/blob/v20.13.1/lib/fs.js) + */ +declare module "fs" { + import * as stream from "node:stream"; + import { Abortable, EventEmitter } from "node:events"; + import { URL } from "node:url"; + import * as promises from "node:fs/promises"; + export { promises }; + /** + * Valid types for path values in "fs". + */ + export type PathLike = string | Buffer | URL; + export type PathOrFileDescriptor = PathLike | number; + export type TimeLike = string | number | Date; + export type NoParamCallback = (err: NodeJS.ErrnoException | null) => void; + export type BufferEncodingOption = + | "buffer" + | { + encoding: "buffer"; + }; + export interface ObjectEncodingOptions { + encoding?: BufferEncoding | null | undefined; + } + export type EncodingOption = ObjectEncodingOptions | BufferEncoding | undefined | null; + export type OpenMode = number | string; + export type Mode = number | string; + export interface StatsBase { + isFile(): boolean; + isDirectory(): boolean; + isBlockDevice(): boolean; + isCharacterDevice(): boolean; + isSymbolicLink(): boolean; + isFIFO(): boolean; + isSocket(): boolean; + dev: T; + ino: T; + mode: T; + nlink: T; + uid: T; + gid: T; + rdev: T; + size: T; + blksize: T; + blocks: T; + atimeMs: T; + mtimeMs: T; + ctimeMs: T; + birthtimeMs: T; + atime: Date; + mtime: Date; + ctime: Date; + birthtime: Date; + } + export interface Stats extends StatsBase {} + /** + * A `fs.Stats` object provides information about a file. + * + * Objects returned from {@link stat}, {@link lstat}, {@link fstat}, and + * their synchronous counterparts are of this type. + * If `bigint` in the `options` passed to those methods is true, the numeric values + * will be `bigint` instead of `number`, and the object will contain additional + * nanosecond-precision properties suffixed with `Ns`. `Stat` objects are not to be created directly using the `new` keyword. + * + * ```console + * Stats { + * dev: 2114, + * ino: 48064969, + * mode: 33188, + * nlink: 1, + * uid: 85, + * gid: 100, + * rdev: 0, + * size: 527, + * blksize: 4096, + * blocks: 8, + * atimeMs: 1318289051000.1, + * mtimeMs: 1318289051000.1, + * ctimeMs: 1318289051000.1, + * birthtimeMs: 1318289051000.1, + * atime: Mon, 10 Oct 2011 23:24:11 GMT, + * mtime: Mon, 10 Oct 2011 23:24:11 GMT, + * ctime: Mon, 10 Oct 2011 23:24:11 GMT, + * birthtime: Mon, 10 Oct 2011 23:24:11 GMT } + * ``` + * + * `bigint` version: + * + * ```console + * BigIntStats { + * dev: 2114n, + * ino: 48064969n, + * mode: 33188n, + * nlink: 1n, + * uid: 85n, + * gid: 100n, + * rdev: 0n, + * size: 527n, + * blksize: 4096n, + * blocks: 8n, + * atimeMs: 1318289051000n, + * mtimeMs: 1318289051000n, + * ctimeMs: 1318289051000n, + * birthtimeMs: 1318289051000n, + * atimeNs: 1318289051000000000n, + * mtimeNs: 1318289051000000000n, + * ctimeNs: 1318289051000000000n, + * birthtimeNs: 1318289051000000000n, + * atime: Mon, 10 Oct 2011 23:24:11 GMT, + * mtime: Mon, 10 Oct 2011 23:24:11 GMT, + * ctime: Mon, 10 Oct 2011 23:24:11 GMT, + * birthtime: Mon, 10 Oct 2011 23:24:11 GMT } + * ``` + * @since v0.1.21 + */ + export class Stats {} + export interface StatsFsBase { + /** Type of file system. */ + type: T; + /** Optimal transfer block size. */ + bsize: T; + /** Total data blocks in file system. */ + blocks: T; + /** Free blocks in file system. */ + bfree: T; + /** Available blocks for unprivileged users */ + bavail: T; + /** Total file nodes in file system. */ + files: T; + /** Free file nodes in file system. */ + ffree: T; + } + export interface StatsFs extends StatsFsBase {} + /** + * Provides information about a mounted file system. + * + * Objects returned from {@link statfs} and its synchronous counterpart are of + * this type. If `bigint` in the `options` passed to those methods is `true`, the + * numeric values will be `bigint` instead of `number`. + * + * ```console + * StatFs { + * type: 1397114950, + * bsize: 4096, + * blocks: 121938943, + * bfree: 61058895, + * bavail: 61058895, + * files: 999, + * ffree: 1000000 + * } + * ``` + * + * `bigint` version: + * + * ```console + * StatFs { + * type: 1397114950n, + * bsize: 4096n, + * blocks: 121938943n, + * bfree: 61058895n, + * bavail: 61058895n, + * files: 999n, + * ffree: 1000000n + * } + * ``` + * @since v19.6.0, v18.15.0 + */ + export class StatsFs {} + export interface BigIntStatsFs extends StatsFsBase {} + export interface StatFsOptions { + bigint?: boolean | undefined; + } + /** + * A representation of a directory entry, which can be a file or a subdirectory + * within the directory, as returned by reading from an `fs.Dir`. The + * directory entry is a combination of the file name and file type pairs. + * + * Additionally, when {@link readdir} or {@link readdirSync} is called with + * the `withFileTypes` option set to `true`, the resulting array is filled with `fs.Dirent` objects, rather than strings or `Buffer` s. + * @since v10.10.0 + */ + export class Dirent { + /** + * Returns `true` if the `fs.Dirent` object describes a regular file. + * @since v10.10.0 + */ + isFile(): boolean; + /** + * Returns `true` if the `fs.Dirent` object describes a file system + * directory. + * @since v10.10.0 + */ + isDirectory(): boolean; + /** + * Returns `true` if the `fs.Dirent` object describes a block device. + * @since v10.10.0 + */ + isBlockDevice(): boolean; + /** + * Returns `true` if the `fs.Dirent` object describes a character device. + * @since v10.10.0 + */ + isCharacterDevice(): boolean; + /** + * Returns `true` if the `fs.Dirent` object describes a symbolic link. + * @since v10.10.0 + */ + isSymbolicLink(): boolean; + /** + * Returns `true` if the `fs.Dirent` object describes a first-in-first-out + * (FIFO) pipe. + * @since v10.10.0 + */ + isFIFO(): boolean; + /** + * Returns `true` if the `fs.Dirent` object describes a socket. + * @since v10.10.0 + */ + isSocket(): boolean; + /** + * The file name that this `fs.Dirent` object refers to. The type of this + * value is determined by the `options.encoding` passed to {@link readdir} or {@link readdirSync}. + * @since v10.10.0 + */ + name: string; + /** + * The base path that this `fs.Dirent` object refers to. + * @since v20.12.0 + */ + parentPath: string; + /** + * Alias for `dirent.parentPath`. + * @since v20.1.0 + * @deprecated Since v20.12.0 + */ + path: string; + } + /** + * A class representing a directory stream. + * + * Created by {@link opendir}, {@link opendirSync}, or `fsPromises.opendir()`. + * + * ```js + * import { opendir } from 'node:fs/promises'; + * + * try { + * const dir = await opendir('./'); + * for await (const dirent of dir) + * console.log(dirent.name); + * } catch (err) { + * console.error(err); + * } + * ``` + * + * When using the async iterator, the `fs.Dir` object will be automatically + * closed after the iterator exits. + * @since v12.12.0 + */ + export class Dir implements AsyncIterable { + /** + * The read-only path of this directory as was provided to {@link opendir},{@link opendirSync}, or `fsPromises.opendir()`. + * @since v12.12.0 + */ + readonly path: string; + /** + * Asynchronously iterates over the directory via `readdir(3)` until all entries have been read. + */ + [Symbol.asyncIterator](): AsyncIterableIterator; + /** + * Asynchronously close the directory's underlying resource handle. + * Subsequent reads will result in errors. + * + * A promise is returned that will be fulfilled after the resource has been + * closed. + * @since v12.12.0 + */ + close(): Promise; + close(cb: NoParamCallback): void; + /** + * Synchronously close the directory's underlying resource handle. + * Subsequent reads will result in errors. + * @since v12.12.0 + */ + closeSync(): void; + /** + * Asynchronously read the next directory entry via [`readdir(3)`](http://man7.org/linux/man-pages/man3/readdir.3.html) as an `fs.Dirent`. + * + * A promise is returned that will be fulfilled with an `fs.Dirent`, or `null` if there are no more directory entries to read. + * + * Directory entries returned by this function are in no particular order as + * provided by the operating system's underlying directory mechanisms. + * Entries added or removed while iterating over the directory might not be + * included in the iteration results. + * @since v12.12.0 + * @return containing {fs.Dirent|null} + */ + read(): Promise; + read(cb: (err: NodeJS.ErrnoException | null, dirEnt: Dirent | null) => void): void; + /** + * Synchronously read the next directory entry as an `fs.Dirent`. See the + * POSIX [`readdir(3)`](http://man7.org/linux/man-pages/man3/readdir.3.html) documentation for more detail. + * + * If there are no more directory entries to read, `null` will be returned. + * + * Directory entries returned by this function are in no particular order as + * provided by the operating system's underlying directory mechanisms. + * Entries added or removed while iterating over the directory might not be + * included in the iteration results. + * @since v12.12.0 + */ + readSync(): Dirent | null; + } + /** + * Class: fs.StatWatcher + * @since v14.3.0, v12.20.0 + * Extends `EventEmitter` + * A successful call to {@link watchFile} method will return a new fs.StatWatcher object. + */ + export interface StatWatcher extends EventEmitter { + /** + * When called, requests that the Node.js event loop _not_ exit so long as the `fs.StatWatcher` is active. Calling `watcher.ref()` multiple times will have + * no effect. + * + * By default, all `fs.StatWatcher` objects are "ref'ed", making it normally + * unnecessary to call `watcher.ref()` unless `watcher.unref()` had been + * called previously. + * @since v14.3.0, v12.20.0 + */ + ref(): this; + /** + * When called, the active `fs.StatWatcher` object will not require the Node.js + * event loop to remain active. If there is no other activity keeping the + * event loop running, the process may exit before the `fs.StatWatcher` object's + * callback is invoked. Calling `watcher.unref()` multiple times will have + * no effect. + * @since v14.3.0, v12.20.0 + */ + unref(): this; + } + export interface FSWatcher extends EventEmitter { + /** + * Stop watching for changes on the given `fs.FSWatcher`. Once stopped, the `fs.FSWatcher` object is no longer usable. + * @since v0.5.8 + */ + close(): void; + /** + * When called, requests that the Node.js event loop _not_ exit so long as the `fs.FSWatcher` is active. Calling `watcher.ref()` multiple times will have + * no effect. + * + * By default, all `fs.FSWatcher` objects are "ref'ed", making it normally + * unnecessary to call `watcher.ref()` unless `watcher.unref()` had been + * called previously. + * @since v14.3.0, v12.20.0 + */ + ref(): this; + /** + * When called, the active `fs.FSWatcher` object will not require the Node.js + * event loop to remain active. If there is no other activity keeping the + * event loop running, the process may exit before the `fs.FSWatcher` object's + * callback is invoked. Calling `watcher.unref()` multiple times will have + * no effect. + * @since v14.3.0, v12.20.0 + */ + unref(): this; + /** + * events.EventEmitter + * 1. change + * 2. close + * 3. error + */ + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "change", listener: (eventType: string, filename: string | Buffer) => void): this; + addListener(event: "close", listener: () => void): this; + addListener(event: "error", listener: (error: Error) => void): this; + on(event: string, listener: (...args: any[]) => void): this; + on(event: "change", listener: (eventType: string, filename: string | Buffer) => void): this; + on(event: "close", listener: () => void): this; + on(event: "error", listener: (error: Error) => void): this; + once(event: string, listener: (...args: any[]) => void): this; + once(event: "change", listener: (eventType: string, filename: string | Buffer) => void): this; + once(event: "close", listener: () => void): this; + once(event: "error", listener: (error: Error) => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "change", listener: (eventType: string, filename: string | Buffer) => void): this; + prependListener(event: "close", listener: () => void): this; + prependListener(event: "error", listener: (error: Error) => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "change", listener: (eventType: string, filename: string | Buffer) => void): this; + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "error", listener: (error: Error) => void): this; + } + /** + * Instances of `fs.ReadStream` are created and returned using the {@link createReadStream} function. + * @since v0.1.93 + */ + export class ReadStream extends stream.Readable { + close(callback?: (err?: NodeJS.ErrnoException | null) => void): void; + /** + * The number of bytes that have been read so far. + * @since v6.4.0 + */ + bytesRead: number; + /** + * The path to the file the stream is reading from as specified in the first + * argument to `fs.createReadStream()`. If `path` is passed as a string, then`readStream.path` will be a string. If `path` is passed as a `Buffer`, then`readStream.path` will be a + * `Buffer`. If `fd` is specified, then`readStream.path` will be `undefined`. + * @since v0.1.93 + */ + path: string | Buffer; + /** + * This property is `true` if the underlying file has not been opened yet, + * i.e. before the `'ready'` event is emitted. + * @since v11.2.0, v10.16.0 + */ + pending: boolean; + /** + * events.EventEmitter + * 1. open + * 2. close + * 3. ready + */ + addListener(event: "close", listener: () => void): this; + addListener(event: "data", listener: (chunk: Buffer | string) => void): this; + addListener(event: "end", listener: () => void): this; + addListener(event: "error", listener: (err: Error) => void): this; + addListener(event: "open", listener: (fd: number) => void): this; + addListener(event: "pause", listener: () => void): this; + addListener(event: "readable", listener: () => void): this; + addListener(event: "ready", listener: () => void): this; + addListener(event: "resume", listener: () => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + on(event: "close", listener: () => void): this; + on(event: "data", listener: (chunk: Buffer | string) => void): this; + on(event: "end", listener: () => void): this; + on(event: "error", listener: (err: Error) => void): this; + on(event: "open", listener: (fd: number) => void): this; + on(event: "pause", listener: () => void): this; + on(event: "readable", listener: () => void): this; + on(event: "ready", listener: () => void): this; + on(event: "resume", listener: () => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + once(event: "close", listener: () => void): this; + once(event: "data", listener: (chunk: Buffer | string) => void): this; + once(event: "end", listener: () => void): this; + once(event: "error", listener: (err: Error) => void): this; + once(event: "open", listener: (fd: number) => void): this; + once(event: "pause", listener: () => void): this; + once(event: "readable", listener: () => void): this; + once(event: "ready", listener: () => void): this; + once(event: "resume", listener: () => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + prependListener(event: "close", listener: () => void): this; + prependListener(event: "data", listener: (chunk: Buffer | string) => void): this; + prependListener(event: "end", listener: () => void): this; + prependListener(event: "error", listener: (err: Error) => void): this; + prependListener(event: "open", listener: (fd: number) => void): this; + prependListener(event: "pause", listener: () => void): this; + prependListener(event: "readable", listener: () => void): this; + prependListener(event: "ready", listener: () => void): this; + prependListener(event: "resume", listener: () => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "data", listener: (chunk: Buffer | string) => void): this; + prependOnceListener(event: "end", listener: () => void): this; + prependOnceListener(event: "error", listener: (err: Error) => void): this; + prependOnceListener(event: "open", listener: (fd: number) => void): this; + prependOnceListener(event: "pause", listener: () => void): this; + prependOnceListener(event: "readable", listener: () => void): this; + prependOnceListener(event: "ready", listener: () => void): this; + prependOnceListener(event: "resume", listener: () => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + } + /** + * * Extends `stream.Writable` + * + * Instances of `fs.WriteStream` are created and returned using the {@link createWriteStream} function. + * @since v0.1.93 + */ + export class WriteStream extends stream.Writable { + /** + * Closes `writeStream`. Optionally accepts a + * callback that will be executed once the `writeStream`is closed. + * @since v0.9.4 + */ + close(callback?: (err?: NodeJS.ErrnoException | null) => void): void; + /** + * The number of bytes written so far. Does not include data that is still queued + * for writing. + * @since v0.4.7 + */ + bytesWritten: number; + /** + * The path to the file the stream is writing to as specified in the first + * argument to {@link createWriteStream}. If `path` is passed as a string, then`writeStream.path` will be a string. If `path` is passed as a `Buffer`, then`writeStream.path` will be a + * `Buffer`. + * @since v0.1.93 + */ + path: string | Buffer; + /** + * This property is `true` if the underlying file has not been opened yet, + * i.e. before the `'ready'` event is emitted. + * @since v11.2.0 + */ + pending: boolean; + /** + * events.EventEmitter + * 1. open + * 2. close + * 3. ready + */ + addListener(event: "close", listener: () => void): this; + addListener(event: "drain", listener: () => void): this; + addListener(event: "error", listener: (err: Error) => void): this; + addListener(event: "finish", listener: () => void): this; + addListener(event: "open", listener: (fd: number) => void): this; + addListener(event: "pipe", listener: (src: stream.Readable) => void): this; + addListener(event: "ready", listener: () => void): this; + addListener(event: "unpipe", listener: (src: stream.Readable) => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + on(event: "close", listener: () => void): this; + on(event: "drain", listener: () => void): this; + on(event: "error", listener: (err: Error) => void): this; + on(event: "finish", listener: () => void): this; + on(event: "open", listener: (fd: number) => void): this; + on(event: "pipe", listener: (src: stream.Readable) => void): this; + on(event: "ready", listener: () => void): this; + on(event: "unpipe", listener: (src: stream.Readable) => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + once(event: "close", listener: () => void): this; + once(event: "drain", listener: () => void): this; + once(event: "error", listener: (err: Error) => void): this; + once(event: "finish", listener: () => void): this; + once(event: "open", listener: (fd: number) => void): this; + once(event: "pipe", listener: (src: stream.Readable) => void): this; + once(event: "ready", listener: () => void): this; + once(event: "unpipe", listener: (src: stream.Readable) => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + prependListener(event: "close", listener: () => void): this; + prependListener(event: "drain", listener: () => void): this; + prependListener(event: "error", listener: (err: Error) => void): this; + prependListener(event: "finish", listener: () => void): this; + prependListener(event: "open", listener: (fd: number) => void): this; + prependListener(event: "pipe", listener: (src: stream.Readable) => void): this; + prependListener(event: "ready", listener: () => void): this; + prependListener(event: "unpipe", listener: (src: stream.Readable) => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "drain", listener: () => void): this; + prependOnceListener(event: "error", listener: (err: Error) => void): this; + prependOnceListener(event: "finish", listener: () => void): this; + prependOnceListener(event: "open", listener: (fd: number) => void): this; + prependOnceListener(event: "pipe", listener: (src: stream.Readable) => void): this; + prependOnceListener(event: "ready", listener: () => void): this; + prependOnceListener(event: "unpipe", listener: (src: stream.Readable) => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + } + /** + * Asynchronously rename file at `oldPath` to the pathname provided + * as `newPath`. In the case that `newPath` already exists, it will + * be overwritten. If there is a directory at `newPath`, an error will + * be raised instead. No arguments other than a possible exception are + * given to the completion callback. + * + * See also: [`rename(2)`](http://man7.org/linux/man-pages/man2/rename.2.html). + * + * ```js + * import { rename } from 'node:fs'; + * + * rename('oldFile.txt', 'newFile.txt', (err) => { + * if (err) throw err; + * console.log('Rename complete!'); + * }); + * ``` + * @since v0.0.2 + */ + export function rename(oldPath: PathLike, newPath: PathLike, callback: NoParamCallback): void; + export namespace rename { + /** + * Asynchronous rename(2) - Change the name or location of a file or directory. + * @param oldPath A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * @param newPath A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + */ + function __promisify__(oldPath: PathLike, newPath: PathLike): Promise; + } + /** + * Renames the file from `oldPath` to `newPath`. Returns `undefined`. + * + * See the POSIX [`rename(2)`](http://man7.org/linux/man-pages/man2/rename.2.html) documentation for more details. + * @since v0.1.21 + */ + export function renameSync(oldPath: PathLike, newPath: PathLike): void; + /** + * Truncates the file. No arguments other than a possible exception are + * given to the completion callback. A file descriptor can also be passed as the + * first argument. In this case, `fs.ftruncate()` is called. + * + * ```js + * import { truncate } from 'node:fs'; + * // Assuming that 'path/file.txt' is a regular file. + * truncate('path/file.txt', (err) => { + * if (err) throw err; + * console.log('path/file.txt was truncated'); + * }); + * ``` + * + * Passing a file descriptor is deprecated and may result in an error being thrown + * in the future. + * + * See the POSIX [`truncate(2)`](http://man7.org/linux/man-pages/man2/truncate.2.html) documentation for more details. + * @since v0.8.6 + * @param [len=0] + */ + export function truncate(path: PathLike, len: number | undefined | null, callback: NoParamCallback): void; + /** + * Asynchronous truncate(2) - Truncate a file to a specified length. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + export function truncate(path: PathLike, callback: NoParamCallback): void; + export namespace truncate { + /** + * Asynchronous truncate(2) - Truncate a file to a specified length. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param len If not specified, defaults to `0`. + */ + function __promisify__(path: PathLike, len?: number | null): Promise; + } + /** + * Truncates the file. Returns `undefined`. A file descriptor can also be + * passed as the first argument. In this case, `fs.ftruncateSync()` is called. + * + * Passing a file descriptor is deprecated and may result in an error being thrown + * in the future. + * @since v0.8.6 + * @param [len=0] + */ + export function truncateSync(path: PathLike, len?: number | null): void; + /** + * Truncates the file descriptor. No arguments other than a possible exception are + * given to the completion callback. + * + * See the POSIX [`ftruncate(2)`](http://man7.org/linux/man-pages/man2/ftruncate.2.html) documentation for more detail. + * + * If the file referred to by the file descriptor was larger than `len` bytes, only + * the first `len` bytes will be retained in the file. + * + * For example, the following program retains only the first four bytes of the + * file: + * + * ```js + * import { open, close, ftruncate } from 'node:fs'; + * + * function closeFd(fd) { + * close(fd, (err) => { + * if (err) throw err; + * }); + * } + * + * open('temp.txt', 'r+', (err, fd) => { + * if (err) throw err; + * + * try { + * ftruncate(fd, 4, (err) => { + * closeFd(fd); + * if (err) throw err; + * }); + * } catch (err) { + * closeFd(fd); + * if (err) throw err; + * } + * }); + * ``` + * + * If the file previously was shorter than `len` bytes, it is extended, and the + * extended part is filled with null bytes (`'\0'`): + * + * If `len` is negative then `0` will be used. + * @since v0.8.6 + * @param [len=0] + */ + export function ftruncate(fd: number, len: number | undefined | null, callback: NoParamCallback): void; + /** + * Asynchronous ftruncate(2) - Truncate a file to a specified length. + * @param fd A file descriptor. + */ + export function ftruncate(fd: number, callback: NoParamCallback): void; + export namespace ftruncate { + /** + * Asynchronous ftruncate(2) - Truncate a file to a specified length. + * @param fd A file descriptor. + * @param len If not specified, defaults to `0`. + */ + function __promisify__(fd: number, len?: number | null): Promise; + } + /** + * Truncates the file descriptor. Returns `undefined`. + * + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link ftruncate}. + * @since v0.8.6 + * @param [len=0] + */ + export function ftruncateSync(fd: number, len?: number | null): void; + /** + * Asynchronously changes owner and group of a file. No arguments other than a + * possible exception are given to the completion callback. + * + * See the POSIX [`chown(2)`](http://man7.org/linux/man-pages/man2/chown.2.html) documentation for more detail. + * @since v0.1.97 + */ + export function chown(path: PathLike, uid: number, gid: number, callback: NoParamCallback): void; + export namespace chown { + /** + * Asynchronous chown(2) - Change ownership of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function __promisify__(path: PathLike, uid: number, gid: number): Promise; + } + /** + * Synchronously changes owner and group of a file. Returns `undefined`. + * This is the synchronous version of {@link chown}. + * + * See the POSIX [`chown(2)`](http://man7.org/linux/man-pages/man2/chown.2.html) documentation for more detail. + * @since v0.1.97 + */ + export function chownSync(path: PathLike, uid: number, gid: number): void; + /** + * Sets the owner of the file. No arguments other than a possible exception are + * given to the completion callback. + * + * See the POSIX [`fchown(2)`](http://man7.org/linux/man-pages/man2/fchown.2.html) documentation for more detail. + * @since v0.4.7 + */ + export function fchown(fd: number, uid: number, gid: number, callback: NoParamCallback): void; + export namespace fchown { + /** + * Asynchronous fchown(2) - Change ownership of a file. + * @param fd A file descriptor. + */ + function __promisify__(fd: number, uid: number, gid: number): Promise; + } + /** + * Sets the owner of the file. Returns `undefined`. + * + * See the POSIX [`fchown(2)`](http://man7.org/linux/man-pages/man2/fchown.2.html) documentation for more detail. + * @since v0.4.7 + * @param uid The file's new owner's user id. + * @param gid The file's new group's group id. + */ + export function fchownSync(fd: number, uid: number, gid: number): void; + /** + * Set the owner of the symbolic link. No arguments other than a possible + * exception are given to the completion callback. + * + * See the POSIX [`lchown(2)`](http://man7.org/linux/man-pages/man2/lchown.2.html) documentation for more detail. + */ + export function lchown(path: PathLike, uid: number, gid: number, callback: NoParamCallback): void; + export namespace lchown { + /** + * Asynchronous lchown(2) - Change ownership of a file. Does not dereference symbolic links. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function __promisify__(path: PathLike, uid: number, gid: number): Promise; + } + /** + * Set the owner for the path. Returns `undefined`. + * + * See the POSIX [`lchown(2)`](http://man7.org/linux/man-pages/man2/lchown.2.html) documentation for more details. + * @param uid The file's new owner's user id. + * @param gid The file's new group's group id. + */ + export function lchownSync(path: PathLike, uid: number, gid: number): void; + /** + * Changes the access and modification times of a file in the same way as {@link utimes}, with the difference that if the path refers to a symbolic + * link, then the link is not dereferenced: instead, the timestamps of the + * symbolic link itself are changed. + * + * No arguments other than a possible exception are given to the completion + * callback. + * @since v14.5.0, v12.19.0 + */ + export function lutimes(path: PathLike, atime: TimeLike, mtime: TimeLike, callback: NoParamCallback): void; + export namespace lutimes { + /** + * Changes the access and modification times of a file in the same way as `fsPromises.utimes()`, + * with the difference that if the path refers to a symbolic link, then the link is not + * dereferenced: instead, the timestamps of the symbolic link itself are changed. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param atime The last access time. If a string is provided, it will be coerced to number. + * @param mtime The last modified time. If a string is provided, it will be coerced to number. + */ + function __promisify__(path: PathLike, atime: TimeLike, mtime: TimeLike): Promise; + } + /** + * Change the file system timestamps of the symbolic link referenced by `path`. + * Returns `undefined`, or throws an exception when parameters are incorrect or + * the operation fails. This is the synchronous version of {@link lutimes}. + * @since v14.5.0, v12.19.0 + */ + export function lutimesSync(path: PathLike, atime: TimeLike, mtime: TimeLike): void; + /** + * Asynchronously changes the permissions of a file. No arguments other than a + * possible exception are given to the completion callback. + * + * See the POSIX [`chmod(2)`](http://man7.org/linux/man-pages/man2/chmod.2.html) documentation for more detail. + * + * ```js + * import { chmod } from 'node:fs'; + * + * chmod('my_file.txt', 0o775, (err) => { + * if (err) throw err; + * console.log('The permissions for file "my_file.txt" have been changed!'); + * }); + * ``` + * @since v0.1.30 + */ + export function chmod(path: PathLike, mode: Mode, callback: NoParamCallback): void; + export namespace chmod { + /** + * Asynchronous chmod(2) - Change permissions of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param mode A file mode. If a string is passed, it is parsed as an octal integer. + */ + function __promisify__(path: PathLike, mode: Mode): Promise; + } + /** + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link chmod}. + * + * See the POSIX [`chmod(2)`](http://man7.org/linux/man-pages/man2/chmod.2.html) documentation for more detail. + * @since v0.6.7 + */ + export function chmodSync(path: PathLike, mode: Mode): void; + /** + * Sets the permissions on the file. No arguments other than a possible exception + * are given to the completion callback. + * + * See the POSIX [`fchmod(2)`](http://man7.org/linux/man-pages/man2/fchmod.2.html) documentation for more detail. + * @since v0.4.7 + */ + export function fchmod(fd: number, mode: Mode, callback: NoParamCallback): void; + export namespace fchmod { + /** + * Asynchronous fchmod(2) - Change permissions of a file. + * @param fd A file descriptor. + * @param mode A file mode. If a string is passed, it is parsed as an octal integer. + */ + function __promisify__(fd: number, mode: Mode): Promise; + } + /** + * Sets the permissions on the file. Returns `undefined`. + * + * See the POSIX [`fchmod(2)`](http://man7.org/linux/man-pages/man2/fchmod.2.html) documentation for more detail. + * @since v0.4.7 + */ + export function fchmodSync(fd: number, mode: Mode): void; + /** + * Changes the permissions on a symbolic link. No arguments other than a possible + * exception are given to the completion callback. + * + * This method is only implemented on macOS. + * + * See the POSIX [`lchmod(2)`](https://www.freebsd.org/cgi/man.cgi?query=lchmod&sektion=2) documentation for more detail. + * @deprecated Since v0.4.7 + */ + export function lchmod(path: PathLike, mode: Mode, callback: NoParamCallback): void; + /** @deprecated */ + export namespace lchmod { + /** + * Asynchronous lchmod(2) - Change permissions of a file. Does not dereference symbolic links. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param mode A file mode. If a string is passed, it is parsed as an octal integer. + */ + function __promisify__(path: PathLike, mode: Mode): Promise; + } + /** + * Changes the permissions on a symbolic link. Returns `undefined`. + * + * This method is only implemented on macOS. + * + * See the POSIX [`lchmod(2)`](https://www.freebsd.org/cgi/man.cgi?query=lchmod&sektion=2) documentation for more detail. + * @deprecated Since v0.4.7 + */ + export function lchmodSync(path: PathLike, mode: Mode): void; + /** + * Asynchronous [`stat(2)`](http://man7.org/linux/man-pages/man2/stat.2.html). The callback gets two arguments `(err, stats)` where`stats` is an `fs.Stats` object. + * + * In case of an error, the `err.code` will be one of `Common System Errors`. + * + * {@link stat} follows symbolic links. Use {@link lstat} to look at the + * links themselves. + * + * Using `fs.stat()` to check for the existence of a file before calling`fs.open()`, `fs.readFile()`, or `fs.writeFile()` is not recommended. + * Instead, user code should open/read/write the file directly and handle the + * error raised if the file is not available. + * + * To check if a file exists without manipulating it afterwards, {@link access} is recommended. + * + * For example, given the following directory structure: + * + * ```text + * - txtDir + * -- file.txt + * - app.js + * ``` + * + * The next program will check for the stats of the given paths: + * + * ```js + * import { stat } from 'node:fs'; + * + * const pathsToCheck = ['./txtDir', './txtDir/file.txt']; + * + * for (let i = 0; i < pathsToCheck.length; i++) { + * stat(pathsToCheck[i], (err, stats) => { + * console.log(stats.isDirectory()); + * console.log(stats); + * }); + * } + * ``` + * + * The resulting output will resemble: + * + * ```console + * true + * Stats { + * dev: 16777220, + * mode: 16877, + * nlink: 3, + * uid: 501, + * gid: 20, + * rdev: 0, + * blksize: 4096, + * ino: 14214262, + * size: 96, + * blocks: 0, + * atimeMs: 1561174653071.963, + * mtimeMs: 1561174614583.3518, + * ctimeMs: 1561174626623.5366, + * birthtimeMs: 1561174126937.2893, + * atime: 2019-06-22T03:37:33.072Z, + * mtime: 2019-06-22T03:36:54.583Z, + * ctime: 2019-06-22T03:37:06.624Z, + * birthtime: 2019-06-22T03:28:46.937Z + * } + * false + * Stats { + * dev: 16777220, + * mode: 33188, + * nlink: 1, + * uid: 501, + * gid: 20, + * rdev: 0, + * blksize: 4096, + * ino: 14214074, + * size: 8, + * blocks: 8, + * atimeMs: 1561174616618.8555, + * mtimeMs: 1561174614584, + * ctimeMs: 1561174614583.8145, + * birthtimeMs: 1561174007710.7478, + * atime: 2019-06-22T03:36:56.619Z, + * mtime: 2019-06-22T03:36:54.584Z, + * ctime: 2019-06-22T03:36:54.584Z, + * birthtime: 2019-06-22T03:26:47.711Z + * } + * ``` + * @since v0.0.2 + */ + export function stat(path: PathLike, callback: (err: NodeJS.ErrnoException | null, stats: Stats) => void): void; + export function stat( + path: PathLike, + options: + | (StatOptions & { + bigint?: false | undefined; + }) + | undefined, + callback: (err: NodeJS.ErrnoException | null, stats: Stats) => void, + ): void; + export function stat( + path: PathLike, + options: StatOptions & { + bigint: true; + }, + callback: (err: NodeJS.ErrnoException | null, stats: BigIntStats) => void, + ): void; + export function stat( + path: PathLike, + options: StatOptions | undefined, + callback: (err: NodeJS.ErrnoException | null, stats: Stats | BigIntStats) => void, + ): void; + export namespace stat { + /** + * Asynchronous stat(2) - Get file status. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function __promisify__( + path: PathLike, + options?: StatOptions & { + bigint?: false | undefined; + }, + ): Promise; + function __promisify__( + path: PathLike, + options: StatOptions & { + bigint: true; + }, + ): Promise; + function __promisify__(path: PathLike, options?: StatOptions): Promise; + } + export interface StatSyncFn extends Function { + (path: PathLike, options?: undefined): Stats; + ( + path: PathLike, + options?: StatSyncOptions & { + bigint?: false | undefined; + throwIfNoEntry: false; + }, + ): Stats | undefined; + ( + path: PathLike, + options: StatSyncOptions & { + bigint: true; + throwIfNoEntry: false; + }, + ): BigIntStats | undefined; + ( + path: PathLike, + options?: StatSyncOptions & { + bigint?: false | undefined; + }, + ): Stats; + ( + path: PathLike, + options: StatSyncOptions & { + bigint: true; + }, + ): BigIntStats; + ( + path: PathLike, + options: StatSyncOptions & { + bigint: boolean; + throwIfNoEntry?: false | undefined; + }, + ): Stats | BigIntStats; + (path: PathLike, options?: StatSyncOptions): Stats | BigIntStats | undefined; + } + /** + * Synchronous stat(2) - Get file status. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + export const statSync: StatSyncFn; + /** + * Invokes the callback with the `fs.Stats` for the file descriptor. + * + * See the POSIX [`fstat(2)`](http://man7.org/linux/man-pages/man2/fstat.2.html) documentation for more detail. + * @since v0.1.95 + */ + export function fstat(fd: number, callback: (err: NodeJS.ErrnoException | null, stats: Stats) => void): void; + export function fstat( + fd: number, + options: + | (StatOptions & { + bigint?: false | undefined; + }) + | undefined, + callback: (err: NodeJS.ErrnoException | null, stats: Stats) => void, + ): void; + export function fstat( + fd: number, + options: StatOptions & { + bigint: true; + }, + callback: (err: NodeJS.ErrnoException | null, stats: BigIntStats) => void, + ): void; + export function fstat( + fd: number, + options: StatOptions | undefined, + callback: (err: NodeJS.ErrnoException | null, stats: Stats | BigIntStats) => void, + ): void; + export namespace fstat { + /** + * Asynchronous fstat(2) - Get file status. + * @param fd A file descriptor. + */ + function __promisify__( + fd: number, + options?: StatOptions & { + bigint?: false | undefined; + }, + ): Promise; + function __promisify__( + fd: number, + options: StatOptions & { + bigint: true; + }, + ): Promise; + function __promisify__(fd: number, options?: StatOptions): Promise; + } + /** + * Retrieves the `fs.Stats` for the file descriptor. + * + * See the POSIX [`fstat(2)`](http://man7.org/linux/man-pages/man2/fstat.2.html) documentation for more detail. + * @since v0.1.95 + */ + export function fstatSync( + fd: number, + options?: StatOptions & { + bigint?: false | undefined; + }, + ): Stats; + export function fstatSync( + fd: number, + options: StatOptions & { + bigint: true; + }, + ): BigIntStats; + export function fstatSync(fd: number, options?: StatOptions): Stats | BigIntStats; + /** + * Retrieves the `fs.Stats` for the symbolic link referred to by the path. + * The callback gets two arguments `(err, stats)` where `stats` is a `fs.Stats` object. `lstat()` is identical to `stat()`, except that if `path` is a symbolic + * link, then the link itself is stat-ed, not the file that it refers to. + * + * See the POSIX [`lstat(2)`](http://man7.org/linux/man-pages/man2/lstat.2.html) documentation for more details. + * @since v0.1.30 + */ + export function lstat(path: PathLike, callback: (err: NodeJS.ErrnoException | null, stats: Stats) => void): void; + export function lstat( + path: PathLike, + options: + | (StatOptions & { + bigint?: false | undefined; + }) + | undefined, + callback: (err: NodeJS.ErrnoException | null, stats: Stats) => void, + ): void; + export function lstat( + path: PathLike, + options: StatOptions & { + bigint: true; + }, + callback: (err: NodeJS.ErrnoException | null, stats: BigIntStats) => void, + ): void; + export function lstat( + path: PathLike, + options: StatOptions | undefined, + callback: (err: NodeJS.ErrnoException | null, stats: Stats | BigIntStats) => void, + ): void; + export namespace lstat { + /** + * Asynchronous lstat(2) - Get file status. Does not dereference symbolic links. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function __promisify__( + path: PathLike, + options?: StatOptions & { + bigint?: false | undefined; + }, + ): Promise; + function __promisify__( + path: PathLike, + options: StatOptions & { + bigint: true; + }, + ): Promise; + function __promisify__(path: PathLike, options?: StatOptions): Promise; + } + /** + * Asynchronous [`statfs(2)`](http://man7.org/linux/man-pages/man2/statfs.2.html). Returns information about the mounted file system which + * contains `path`. The callback gets two arguments `(err, stats)` where `stats`is an `fs.StatFs` object. + * + * In case of an error, the `err.code` will be one of `Common System Errors`. + * @since v19.6.0, v18.15.0 + * @param path A path to an existing file or directory on the file system to be queried. + */ + export function statfs(path: PathLike, callback: (err: NodeJS.ErrnoException | null, stats: StatsFs) => void): void; + export function statfs( + path: PathLike, + options: + | (StatFsOptions & { + bigint?: false | undefined; + }) + | undefined, + callback: (err: NodeJS.ErrnoException | null, stats: StatsFs) => void, + ): void; + export function statfs( + path: PathLike, + options: StatFsOptions & { + bigint: true; + }, + callback: (err: NodeJS.ErrnoException | null, stats: BigIntStatsFs) => void, + ): void; + export function statfs( + path: PathLike, + options: StatFsOptions | undefined, + callback: (err: NodeJS.ErrnoException | null, stats: StatsFs | BigIntStatsFs) => void, + ): void; + export namespace statfs { + /** + * Asynchronous statfs(2) - Returns information about the mounted file system which contains path. The callback gets two arguments (err, stats) where stats is an object. + * @param path A path to an existing file or directory on the file system to be queried. + */ + function __promisify__( + path: PathLike, + options?: StatFsOptions & { + bigint?: false | undefined; + }, + ): Promise; + function __promisify__( + path: PathLike, + options: StatFsOptions & { + bigint: true; + }, + ): Promise; + function __promisify__(path: PathLike, options?: StatFsOptions): Promise; + } + /** + * Synchronous [`statfs(2)`](http://man7.org/linux/man-pages/man2/statfs.2.html). Returns information about the mounted file system which + * contains `path`. + * + * In case of an error, the `err.code` will be one of `Common System Errors`. + * @since v19.6.0, v18.15.0 + * @param path A path to an existing file or directory on the file system to be queried. + */ + export function statfsSync( + path: PathLike, + options?: StatFsOptions & { + bigint?: false | undefined; + }, + ): StatsFs; + export function statfsSync( + path: PathLike, + options: StatFsOptions & { + bigint: true; + }, + ): BigIntStatsFs; + export function statfsSync(path: PathLike, options?: StatFsOptions): StatsFs | BigIntStatsFs; + /** + * Synchronous lstat(2) - Get file status. Does not dereference symbolic links. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + export const lstatSync: StatSyncFn; + /** + * Creates a new link from the `existingPath` to the `newPath`. See the POSIX [`link(2)`](http://man7.org/linux/man-pages/man2/link.2.html) documentation for more detail. No arguments other than + * a possible + * exception are given to the completion callback. + * @since v0.1.31 + */ + export function link(existingPath: PathLike, newPath: PathLike, callback: NoParamCallback): void; + export namespace link { + /** + * Asynchronous link(2) - Create a new link (also known as a hard link) to an existing file. + * @param existingPath A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param newPath A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function __promisify__(existingPath: PathLike, newPath: PathLike): Promise; + } + /** + * Creates a new link from the `existingPath` to the `newPath`. See the POSIX [`link(2)`](http://man7.org/linux/man-pages/man2/link.2.html) documentation for more detail. Returns `undefined`. + * @since v0.1.31 + */ + export function linkSync(existingPath: PathLike, newPath: PathLike): void; + /** + * Creates the link called `path` pointing to `target`. No arguments other than a + * possible exception are given to the completion callback. + * + * See the POSIX [`symlink(2)`](http://man7.org/linux/man-pages/man2/symlink.2.html) documentation for more details. + * + * The `type` argument is only available on Windows and ignored on other platforms. + * It can be set to `'dir'`, `'file'`, or `'junction'`. If the `type` argument is + * not a string, Node.js will autodetect `target` type and use `'file'` or `'dir'`. + * If the `target` does not exist, `'file'` will be used. Windows junction points + * require the destination path to be absolute. When using `'junction'`, the`target` argument will automatically be normalized to absolute path. Junction + * points on NTFS volumes can only point to directories. + * + * Relative targets are relative to the link's parent directory. + * + * ```js + * import { symlink } from 'node:fs'; + * + * symlink('./mew', './mewtwo', callback); + * ``` + * + * The above example creates a symbolic link `mewtwo` which points to `mew` in the + * same directory: + * + * ```bash + * $ tree . + * . + * ├── mew + * └── mewtwo -> ./mew + * ``` + * @since v0.1.31 + * @param [type='null'] + */ + export function symlink( + target: PathLike, + path: PathLike, + type: symlink.Type | undefined | null, + callback: NoParamCallback, + ): void; + /** + * Asynchronous symlink(2) - Create a new symbolic link to an existing file. + * @param target A path to an existing file. If a URL is provided, it must use the `file:` protocol. + * @param path A path to the new symlink. If a URL is provided, it must use the `file:` protocol. + */ + export function symlink(target: PathLike, path: PathLike, callback: NoParamCallback): void; + export namespace symlink { + /** + * Asynchronous symlink(2) - Create a new symbolic link to an existing file. + * @param target A path to an existing file. If a URL is provided, it must use the `file:` protocol. + * @param path A path to the new symlink. If a URL is provided, it must use the `file:` protocol. + * @param type May be set to `'dir'`, `'file'`, or `'junction'` (default is `'file'`) and is only available on Windows (ignored on other platforms). + * When using `'junction'`, the `target` argument will automatically be normalized to an absolute path. + */ + function __promisify__(target: PathLike, path: PathLike, type?: string | null): Promise; + type Type = "dir" | "file" | "junction"; + } + /** + * Returns `undefined`. + * + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link symlink}. + * @since v0.1.31 + * @param [type='null'] + */ + export function symlinkSync(target: PathLike, path: PathLike, type?: symlink.Type | null): void; + /** + * Reads the contents of the symbolic link referred to by `path`. The callback gets + * two arguments `(err, linkString)`. + * + * See the POSIX [`readlink(2)`](http://man7.org/linux/man-pages/man2/readlink.2.html) documentation for more details. + * + * The optional `options` argument can be a string specifying an encoding, or an + * object with an `encoding` property specifying the character encoding to use for + * the link path passed to the callback. If the `encoding` is set to `'buffer'`, + * the link path returned will be passed as a `Buffer` object. + * @since v0.1.31 + */ + export function readlink( + path: PathLike, + options: EncodingOption, + callback: (err: NodeJS.ErrnoException | null, linkString: string) => void, + ): void; + /** + * Asynchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function readlink( + path: PathLike, + options: BufferEncodingOption, + callback: (err: NodeJS.ErrnoException | null, linkString: Buffer) => void, + ): void; + /** + * Asynchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function readlink( + path: PathLike, + options: EncodingOption, + callback: (err: NodeJS.ErrnoException | null, linkString: string | Buffer) => void, + ): void; + /** + * Asynchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + export function readlink( + path: PathLike, + callback: (err: NodeJS.ErrnoException | null, linkString: string) => void, + ): void; + export namespace readlink { + /** + * Asynchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__(path: PathLike, options?: EncodingOption): Promise; + /** + * Asynchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__(path: PathLike, options: BufferEncodingOption): Promise; + /** + * Asynchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__(path: PathLike, options?: EncodingOption): Promise; + } + /** + * Returns the symbolic link's string value. + * + * See the POSIX [`readlink(2)`](http://man7.org/linux/man-pages/man2/readlink.2.html) documentation for more details. + * + * The optional `options` argument can be a string specifying an encoding, or an + * object with an `encoding` property specifying the character encoding to use for + * the link path returned. If the `encoding` is set to `'buffer'`, + * the link path returned will be passed as a `Buffer` object. + * @since v0.1.31 + */ + export function readlinkSync(path: PathLike, options?: EncodingOption): string; + /** + * Synchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function readlinkSync(path: PathLike, options: BufferEncodingOption): Buffer; + /** + * Synchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function readlinkSync(path: PathLike, options?: EncodingOption): string | Buffer; + /** + * Asynchronously computes the canonical pathname by resolving `.`, `..`, and + * symbolic links. + * + * A canonical pathname is not necessarily unique. Hard links and bind mounts can + * expose a file system entity through many pathnames. + * + * This function behaves like [`realpath(3)`](http://man7.org/linux/man-pages/man3/realpath.3.html), with some exceptions: + * + * 1. No case conversion is performed on case-insensitive file systems. + * 2. The maximum number of symbolic links is platform-independent and generally + * (much) higher than what the native [`realpath(3)`](http://man7.org/linux/man-pages/man3/realpath.3.html) implementation supports. + * + * The `callback` gets two arguments `(err, resolvedPath)`. May use `process.cwd` to resolve relative paths. + * + * Only paths that can be converted to UTF8 strings are supported. + * + * The optional `options` argument can be a string specifying an encoding, or an + * object with an `encoding` property specifying the character encoding to use for + * the path passed to the callback. If the `encoding` is set to `'buffer'`, + * the path returned will be passed as a `Buffer` object. + * + * If `path` resolves to a socket or a pipe, the function will return a system + * dependent name for that object. + * @since v0.1.31 + */ + export function realpath( + path: PathLike, + options: EncodingOption, + callback: (err: NodeJS.ErrnoException | null, resolvedPath: string) => void, + ): void; + /** + * Asynchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function realpath( + path: PathLike, + options: BufferEncodingOption, + callback: (err: NodeJS.ErrnoException | null, resolvedPath: Buffer) => void, + ): void; + /** + * Asynchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function realpath( + path: PathLike, + options: EncodingOption, + callback: (err: NodeJS.ErrnoException | null, resolvedPath: string | Buffer) => void, + ): void; + /** + * Asynchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + export function realpath( + path: PathLike, + callback: (err: NodeJS.ErrnoException | null, resolvedPath: string) => void, + ): void; + export namespace realpath { + /** + * Asynchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__(path: PathLike, options?: EncodingOption): Promise; + /** + * Asynchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__(path: PathLike, options: BufferEncodingOption): Promise; + /** + * Asynchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__(path: PathLike, options?: EncodingOption): Promise; + /** + * Asynchronous [`realpath(3)`](http://man7.org/linux/man-pages/man3/realpath.3.html). + * + * The `callback` gets two arguments `(err, resolvedPath)`. + * + * Only paths that can be converted to UTF8 strings are supported. + * + * The optional `options` argument can be a string specifying an encoding, or an + * object with an `encoding` property specifying the character encoding to use for + * the path passed to the callback. If the `encoding` is set to `'buffer'`, + * the path returned will be passed as a `Buffer` object. + * + * On Linux, when Node.js is linked against musl libc, the procfs file system must + * be mounted on `/proc` in order for this function to work. Glibc does not have + * this restriction. + * @since v9.2.0 + */ + function native( + path: PathLike, + options: EncodingOption, + callback: (err: NodeJS.ErrnoException | null, resolvedPath: string) => void, + ): void; + function native( + path: PathLike, + options: BufferEncodingOption, + callback: (err: NodeJS.ErrnoException | null, resolvedPath: Buffer) => void, + ): void; + function native( + path: PathLike, + options: EncodingOption, + callback: (err: NodeJS.ErrnoException | null, resolvedPath: string | Buffer) => void, + ): void; + function native( + path: PathLike, + callback: (err: NodeJS.ErrnoException | null, resolvedPath: string) => void, + ): void; + } + /** + * Returns the resolved pathname. + * + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link realpath}. + * @since v0.1.31 + */ + export function realpathSync(path: PathLike, options?: EncodingOption): string; + /** + * Synchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function realpathSync(path: PathLike, options: BufferEncodingOption): Buffer; + /** + * Synchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function realpathSync(path: PathLike, options?: EncodingOption): string | Buffer; + export namespace realpathSync { + function native(path: PathLike, options?: EncodingOption): string; + function native(path: PathLike, options: BufferEncodingOption): Buffer; + function native(path: PathLike, options?: EncodingOption): string | Buffer; + } + /** + * Asynchronously removes a file or symbolic link. No arguments other than a + * possible exception are given to the completion callback. + * + * ```js + * import { unlink } from 'node:fs'; + * // Assuming that 'path/file.txt' is a regular file. + * unlink('path/file.txt', (err) => { + * if (err) throw err; + * console.log('path/file.txt was deleted'); + * }); + * ``` + * + * `fs.unlink()` will not work on a directory, empty or otherwise. To remove a + * directory, use {@link rmdir}. + * + * See the POSIX [`unlink(2)`](http://man7.org/linux/man-pages/man2/unlink.2.html) documentation for more details. + * @since v0.0.2 + */ + export function unlink(path: PathLike, callback: NoParamCallback): void; + export namespace unlink { + /** + * Asynchronous unlink(2) - delete a name and possibly the file it refers to. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function __promisify__(path: PathLike): Promise; + } + /** + * Synchronous [`unlink(2)`](http://man7.org/linux/man-pages/man2/unlink.2.html). Returns `undefined`. + * @since v0.1.21 + */ + export function unlinkSync(path: PathLike): void; + export interface RmDirOptions { + /** + * If an `EBUSY`, `EMFILE`, `ENFILE`, `ENOTEMPTY`, or + * `EPERM` error is encountered, Node.js will retry the operation with a linear + * backoff wait of `retryDelay` ms longer on each try. This option represents the + * number of retries. This option is ignored if the `recursive` option is not + * `true`. + * @default 0 + */ + maxRetries?: number | undefined; + /** + * @deprecated since v14.14.0 In future versions of Node.js and will trigger a warning + * `fs.rmdir(path, { recursive: true })` will throw if `path` does not exist or is a file. + * Use `fs.rm(path, { recursive: true, force: true })` instead. + * + * If `true`, perform a recursive directory removal. In + * recursive mode, operations are retried on failure. + * @default false + */ + recursive?: boolean | undefined; + /** + * The amount of time in milliseconds to wait between retries. + * This option is ignored if the `recursive` option is not `true`. + * @default 100 + */ + retryDelay?: number | undefined; + } + /** + * Asynchronous [`rmdir(2)`](http://man7.org/linux/man-pages/man2/rmdir.2.html). No arguments other than a possible exception are given + * to the completion callback. + * + * Using `fs.rmdir()` on a file (not a directory) results in an `ENOENT` error on + * Windows and an `ENOTDIR` error on POSIX. + * + * To get a behavior similar to the `rm -rf` Unix command, use {@link rm} with options `{ recursive: true, force: true }`. + * @since v0.0.2 + */ + export function rmdir(path: PathLike, callback: NoParamCallback): void; + export function rmdir(path: PathLike, options: RmDirOptions, callback: NoParamCallback): void; + export namespace rmdir { + /** + * Asynchronous rmdir(2) - delete a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + function __promisify__(path: PathLike, options?: RmDirOptions): Promise; + } + /** + * Synchronous [`rmdir(2)`](http://man7.org/linux/man-pages/man2/rmdir.2.html). Returns `undefined`. + * + * Using `fs.rmdirSync()` on a file (not a directory) results in an `ENOENT` error + * on Windows and an `ENOTDIR` error on POSIX. + * + * To get a behavior similar to the `rm -rf` Unix command, use {@link rmSync} with options `{ recursive: true, force: true }`. + * @since v0.1.21 + */ + export function rmdirSync(path: PathLike, options?: RmDirOptions): void; + export interface RmOptions { + /** + * When `true`, exceptions will be ignored if `path` does not exist. + * @default false + */ + force?: boolean | undefined; + /** + * If an `EBUSY`, `EMFILE`, `ENFILE`, `ENOTEMPTY`, or + * `EPERM` error is encountered, Node.js will retry the operation with a linear + * backoff wait of `retryDelay` ms longer on each try. This option represents the + * number of retries. This option is ignored if the `recursive` option is not + * `true`. + * @default 0 + */ + maxRetries?: number | undefined; + /** + * If `true`, perform a recursive directory removal. In + * recursive mode, operations are retried on failure. + * @default false + */ + recursive?: boolean | undefined; + /** + * The amount of time in milliseconds to wait between retries. + * This option is ignored if the `recursive` option is not `true`. + * @default 100 + */ + retryDelay?: number | undefined; + } + /** + * Asynchronously removes files and directories (modeled on the standard POSIX `rm` utility). No arguments other than a possible exception are given to the + * completion callback. + * @since v14.14.0 + */ + export function rm(path: PathLike, callback: NoParamCallback): void; + export function rm(path: PathLike, options: RmOptions, callback: NoParamCallback): void; + export namespace rm { + /** + * Asynchronously removes files and directories (modeled on the standard POSIX `rm` utility). + */ + function __promisify__(path: PathLike, options?: RmOptions): Promise; + } + /** + * Synchronously removes files and directories (modeled on the standard POSIX `rm` utility). Returns `undefined`. + * @since v14.14.0 + */ + export function rmSync(path: PathLike, options?: RmOptions): void; + export interface MakeDirectoryOptions { + /** + * Indicates whether parent folders should be created. + * If a folder was created, the path to the first created folder will be returned. + * @default false + */ + recursive?: boolean | undefined; + /** + * A file mode. If a string is passed, it is parsed as an octal integer. If not specified + * @default 0o777 + */ + mode?: Mode | undefined; + } + /** + * Asynchronously creates a directory. + * + * The callback is given a possible exception and, if `recursive` is `true`, the + * first directory path created, `(err[, path])`.`path` can still be `undefined` when `recursive` is `true`, if no directory was + * created (for instance, if it was previously created). + * + * The optional `options` argument can be an integer specifying `mode` (permission + * and sticky bits), or an object with a `mode` property and a `recursive` property indicating whether parent directories should be created. Calling `fs.mkdir()` when `path` is a directory that + * exists results in an error only + * when `recursive` is false. If `recursive` is false and the directory exists, + * an `EEXIST` error occurs. + * + * ```js + * import { mkdir } from 'node:fs'; + * + * // Create ./tmp/a/apple, regardless of whether ./tmp and ./tmp/a exist. + * mkdir('./tmp/a/apple', { recursive: true }, (err) => { + * if (err) throw err; + * }); + * ``` + * + * On Windows, using `fs.mkdir()` on the root directory even with recursion will + * result in an error: + * + * ```js + * import { mkdir } from 'node:fs'; + * + * mkdir('/', { recursive: true }, (err) => { + * // => [Error: EPERM: operation not permitted, mkdir 'C:\'] + * }); + * ``` + * + * See the POSIX [`mkdir(2)`](http://man7.org/linux/man-pages/man2/mkdir.2.html) documentation for more details. + * @since v0.1.8 + */ + export function mkdir( + path: PathLike, + options: MakeDirectoryOptions & { + recursive: true; + }, + callback: (err: NodeJS.ErrnoException | null, path?: string) => void, + ): void; + /** + * Asynchronous mkdir(2) - create a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders + * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. + */ + export function mkdir( + path: PathLike, + options: + | Mode + | (MakeDirectoryOptions & { + recursive?: false | undefined; + }) + | null + | undefined, + callback: NoParamCallback, + ): void; + /** + * Asynchronous mkdir(2) - create a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders + * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. + */ + export function mkdir( + path: PathLike, + options: Mode | MakeDirectoryOptions | null | undefined, + callback: (err: NodeJS.ErrnoException | null, path?: string) => void, + ): void; + /** + * Asynchronous mkdir(2) - create a directory with a mode of `0o777`. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + export function mkdir(path: PathLike, callback: NoParamCallback): void; + export namespace mkdir { + /** + * Asynchronous mkdir(2) - create a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders + * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. + */ + function __promisify__( + path: PathLike, + options: MakeDirectoryOptions & { + recursive: true; + }, + ): Promise; + /** + * Asynchronous mkdir(2) - create a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders + * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. + */ + function __promisify__( + path: PathLike, + options?: + | Mode + | (MakeDirectoryOptions & { + recursive?: false | undefined; + }) + | null, + ): Promise; + /** + * Asynchronous mkdir(2) - create a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders + * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. + */ + function __promisify__( + path: PathLike, + options?: Mode | MakeDirectoryOptions | null, + ): Promise; + } + /** + * Synchronously creates a directory. Returns `undefined`, or if `recursive` is `true`, the first directory path created. + * This is the synchronous version of {@link mkdir}. + * + * See the POSIX [`mkdir(2)`](http://man7.org/linux/man-pages/man2/mkdir.2.html) documentation for more details. + * @since v0.1.21 + */ + export function mkdirSync( + path: PathLike, + options: MakeDirectoryOptions & { + recursive: true; + }, + ): string | undefined; + /** + * Synchronous mkdir(2) - create a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders + * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. + */ + export function mkdirSync( + path: PathLike, + options?: + | Mode + | (MakeDirectoryOptions & { + recursive?: false | undefined; + }) + | null, + ): void; + /** + * Synchronous mkdir(2) - create a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders + * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. + */ + export function mkdirSync(path: PathLike, options?: Mode | MakeDirectoryOptions | null): string | undefined; + /** + * Creates a unique temporary directory. + * + * Generates six random characters to be appended behind a required `prefix` to create a unique temporary directory. Due to platform + * inconsistencies, avoid trailing `X` characters in `prefix`. Some platforms, + * notably the BSDs, can return more than six random characters, and replace + * trailing `X` characters in `prefix` with random characters. + * + * The created directory path is passed as a string to the callback's second + * parameter. + * + * The optional `options` argument can be a string specifying an encoding, or an + * object with an `encoding` property specifying the character encoding to use. + * + * ```js + * import { mkdtemp } from 'node:fs'; + * import { join } from 'node:path'; + * import { tmpdir } from 'node:os'; + * + * mkdtemp(join(tmpdir(), 'foo-'), (err, directory) => { + * if (err) throw err; + * console.log(directory); + * // Prints: /tmp/foo-itXde2 or C:\Users\...\AppData\Local\Temp\foo-itXde2 + * }); + * ``` + * + * The `fs.mkdtemp()` method will append the six randomly selected characters + * directly to the `prefix` string. For instance, given a directory `/tmp`, if the + * intention is to create a temporary directory _within_`/tmp`, the `prefix`must end with a trailing platform-specific path separator + * (`require('node:path').sep`). + * + * ```js + * import { tmpdir } from 'node:os'; + * import { mkdtemp } from 'node:fs'; + * + * // The parent directory for the new temporary directory + * const tmpDir = tmpdir(); + * + * // This method is *INCORRECT*: + * mkdtemp(tmpDir, (err, directory) => { + * if (err) throw err; + * console.log(directory); + * // Will print something similar to `/tmpabc123`. + * // A new temporary directory is created at the file system root + * // rather than *within* the /tmp directory. + * }); + * + * // This method is *CORRECT*: + * import { sep } from 'node:path'; + * mkdtemp(`${tmpDir}${sep}`, (err, directory) => { + * if (err) throw err; + * console.log(directory); + * // Will print something similar to `/tmp/abc123`. + * // A new temporary directory is created within + * // the /tmp directory. + * }); + * ``` + * @since v5.10.0 + */ + export function mkdtemp( + prefix: string, + options: EncodingOption, + callback: (err: NodeJS.ErrnoException | null, folder: string) => void, + ): void; + /** + * Asynchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function mkdtemp( + prefix: string, + options: + | "buffer" + | { + encoding: "buffer"; + }, + callback: (err: NodeJS.ErrnoException | null, folder: Buffer) => void, + ): void; + /** + * Asynchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function mkdtemp( + prefix: string, + options: EncodingOption, + callback: (err: NodeJS.ErrnoException | null, folder: string | Buffer) => void, + ): void; + /** + * Asynchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + */ + export function mkdtemp( + prefix: string, + callback: (err: NodeJS.ErrnoException | null, folder: string) => void, + ): void; + export namespace mkdtemp { + /** + * Asynchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__(prefix: string, options?: EncodingOption): Promise; + /** + * Asynchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__(prefix: string, options: BufferEncodingOption): Promise; + /** + * Asynchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__(prefix: string, options?: EncodingOption): Promise; + } + /** + * Returns the created directory path. + * + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link mkdtemp}. + * + * The optional `options` argument can be a string specifying an encoding, or an + * object with an `encoding` property specifying the character encoding to use. + * @since v5.10.0 + */ + export function mkdtempSync(prefix: string, options?: EncodingOption): string; + /** + * Synchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function mkdtempSync(prefix: string, options: BufferEncodingOption): Buffer; + /** + * Synchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required prefix to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function mkdtempSync(prefix: string, options?: EncodingOption): string | Buffer; + /** + * Reads the contents of a directory. The callback gets two arguments `(err, files)` where `files` is an array of the names of the files in the directory excluding `'.'` and `'..'`. + * + * See the POSIX [`readdir(3)`](http://man7.org/linux/man-pages/man3/readdir.3.html) documentation for more details. + * + * The optional `options` argument can be a string specifying an encoding, or an + * object with an `encoding` property specifying the character encoding to use for + * the filenames passed to the callback. If the `encoding` is set to `'buffer'`, + * the filenames returned will be passed as `Buffer` objects. + * + * If `options.withFileTypes` is set to `true`, the `files` array will contain `fs.Dirent` objects. + * @since v0.1.8 + */ + export function readdir( + path: PathLike, + options: + | { + encoding: BufferEncoding | null; + withFileTypes?: false | undefined; + recursive?: boolean | undefined; + } + | BufferEncoding + | undefined + | null, + callback: (err: NodeJS.ErrnoException | null, files: string[]) => void, + ): void; + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function readdir( + path: PathLike, + options: + | { + encoding: "buffer"; + withFileTypes?: false | undefined; + recursive?: boolean | undefined; + } + | "buffer", + callback: (err: NodeJS.ErrnoException | null, files: Buffer[]) => void, + ): void; + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function readdir( + path: PathLike, + options: + | (ObjectEncodingOptions & { + withFileTypes?: false | undefined; + recursive?: boolean | undefined; + }) + | BufferEncoding + | undefined + | null, + callback: (err: NodeJS.ErrnoException | null, files: string[] | Buffer[]) => void, + ): void; + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + export function readdir( + path: PathLike, + callback: (err: NodeJS.ErrnoException | null, files: string[]) => void, + ): void; + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options If called with `withFileTypes: true` the result data will be an array of Dirent. + */ + export function readdir( + path: PathLike, + options: ObjectEncodingOptions & { + withFileTypes: true; + recursive?: boolean | undefined; + }, + callback: (err: NodeJS.ErrnoException | null, files: Dirent[]) => void, + ): void; + export namespace readdir { + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__( + path: PathLike, + options?: + | { + encoding: BufferEncoding | null; + withFileTypes?: false | undefined; + recursive?: boolean | undefined; + } + | BufferEncoding + | null, + ): Promise; + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__( + path: PathLike, + options: + | "buffer" + | { + encoding: "buffer"; + withFileTypes?: false | undefined; + recursive?: boolean | undefined; + }, + ): Promise; + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function __promisify__( + path: PathLike, + options?: + | (ObjectEncodingOptions & { + withFileTypes?: false | undefined; + recursive?: boolean | undefined; + }) + | BufferEncoding + | null, + ): Promise; + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options If called with `withFileTypes: true` the result data will be an array of Dirent + */ + function __promisify__( + path: PathLike, + options: ObjectEncodingOptions & { + withFileTypes: true; + recursive?: boolean | undefined; + }, + ): Promise; + } + /** + * Reads the contents of the directory. + * + * See the POSIX [`readdir(3)`](http://man7.org/linux/man-pages/man3/readdir.3.html) documentation for more details. + * + * The optional `options` argument can be a string specifying an encoding, or an + * object with an `encoding` property specifying the character encoding to use for + * the filenames returned. If the `encoding` is set to `'buffer'`, + * the filenames returned will be passed as `Buffer` objects. + * + * If `options.withFileTypes` is set to `true`, the result will contain `fs.Dirent` objects. + * @since v0.1.21 + */ + export function readdirSync( + path: PathLike, + options?: + | { + encoding: BufferEncoding | null; + withFileTypes?: false | undefined; + recursive?: boolean | undefined; + } + | BufferEncoding + | null, + ): string[]; + /** + * Synchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function readdirSync( + path: PathLike, + options: + | { + encoding: "buffer"; + withFileTypes?: false | undefined; + recursive?: boolean | undefined; + } + | "buffer", + ): Buffer[]; + /** + * Synchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + export function readdirSync( + path: PathLike, + options?: + | (ObjectEncodingOptions & { + withFileTypes?: false | undefined; + recursive?: boolean | undefined; + }) + | BufferEncoding + | null, + ): string[] | Buffer[]; + /** + * Synchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options If called with `withFileTypes: true` the result data will be an array of Dirent. + */ + export function readdirSync( + path: PathLike, + options: ObjectEncodingOptions & { + withFileTypes: true; + recursive?: boolean | undefined; + }, + ): Dirent[]; + /** + * Closes the file descriptor. No arguments other than a possible exception are + * given to the completion callback. + * + * Calling `fs.close()` on any file descriptor (`fd`) that is currently in use + * through any other `fs` operation may lead to undefined behavior. + * + * See the POSIX [`close(2)`](http://man7.org/linux/man-pages/man2/close.2.html) documentation for more detail. + * @since v0.0.2 + */ + export function close(fd: number, callback?: NoParamCallback): void; + export namespace close { + /** + * Asynchronous close(2) - close a file descriptor. + * @param fd A file descriptor. + */ + function __promisify__(fd: number): Promise; + } + /** + * Closes the file descriptor. Returns `undefined`. + * + * Calling `fs.closeSync()` on any file descriptor (`fd`) that is currently in use + * through any other `fs` operation may lead to undefined behavior. + * + * See the POSIX [`close(2)`](http://man7.org/linux/man-pages/man2/close.2.html) documentation for more detail. + * @since v0.1.21 + */ + export function closeSync(fd: number): void; + /** + * Asynchronous file open. See the POSIX [`open(2)`](http://man7.org/linux/man-pages/man2/open.2.html) documentation for more details. + * + * `mode` sets the file mode (permission and sticky bits), but only if the file was + * created. On Windows, only the write permission can be manipulated; see {@link chmod}. + * + * The callback gets two arguments `(err, fd)`. + * + * Some characters (`< > : " / \ | ? *`) are reserved under Windows as documented + * by [Naming Files, Paths, and Namespaces](https://docs.microsoft.com/en-us/windows/desktop/FileIO/naming-a-file). Under NTFS, if the filename contains + * a colon, Node.js will open a file system stream, as described by [this MSDN page](https://docs.microsoft.com/en-us/windows/desktop/FileIO/using-streams). + * + * Functions based on `fs.open()` exhibit this behavior as well:`fs.writeFile()`, `fs.readFile()`, etc. + * @since v0.0.2 + * @param [flags='r'] See `support of file system `flags``. + * @param [mode=0o666] + */ + export function open( + path: PathLike, + flags: OpenMode | undefined, + mode: Mode | undefined | null, + callback: (err: NodeJS.ErrnoException | null, fd: number) => void, + ): void; + /** + * Asynchronous open(2) - open and possibly create a file. If the file is created, its mode will be `0o666`. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param [flags='r'] See `support of file system `flags``. + */ + export function open( + path: PathLike, + flags: OpenMode | undefined, + callback: (err: NodeJS.ErrnoException | null, fd: number) => void, + ): void; + /** + * Asynchronous open(2) - open and possibly create a file. If the file is created, its mode will be `0o666`. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + */ + export function open(path: PathLike, callback: (err: NodeJS.ErrnoException | null, fd: number) => void): void; + export namespace open { + /** + * Asynchronous open(2) - open and possibly create a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param mode A file mode. If a string is passed, it is parsed as an octal integer. If not supplied, defaults to `0o666`. + */ + function __promisify__(path: PathLike, flags: OpenMode, mode?: Mode | null): Promise; + } + /** + * Returns an integer representing the file descriptor. + * + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link open}. + * @since v0.1.21 + * @param [flags='r'] + * @param [mode=0o666] + */ + export function openSync(path: PathLike, flags: OpenMode, mode?: Mode | null): number; + /** + * Change the file system timestamps of the object referenced by `path`. + * + * The `atime` and `mtime` arguments follow these rules: + * + * * Values can be either numbers representing Unix epoch time in seconds, `Date`s, or a numeric string like `'123456789.0'`. + * * If the value can not be converted to a number, or is `NaN`, `Infinity`, or `-Infinity`, an `Error` will be thrown. + * @since v0.4.2 + */ + export function utimes(path: PathLike, atime: TimeLike, mtime: TimeLike, callback: NoParamCallback): void; + export namespace utimes { + /** + * Asynchronously change file timestamps of the file referenced by the supplied path. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param atime The last access time. If a string is provided, it will be coerced to number. + * @param mtime The last modified time. If a string is provided, it will be coerced to number. + */ + function __promisify__(path: PathLike, atime: TimeLike, mtime: TimeLike): Promise; + } + /** + * Returns `undefined`. + * + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link utimes}. + * @since v0.4.2 + */ + export function utimesSync(path: PathLike, atime: TimeLike, mtime: TimeLike): void; + /** + * Change the file system timestamps of the object referenced by the supplied file + * descriptor. See {@link utimes}. + * @since v0.4.2 + */ + export function futimes(fd: number, atime: TimeLike, mtime: TimeLike, callback: NoParamCallback): void; + export namespace futimes { + /** + * Asynchronously change file timestamps of the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param atime The last access time. If a string is provided, it will be coerced to number. + * @param mtime The last modified time. If a string is provided, it will be coerced to number. + */ + function __promisify__(fd: number, atime: TimeLike, mtime: TimeLike): Promise; + } + /** + * Synchronous version of {@link futimes}. Returns `undefined`. + * @since v0.4.2 + */ + export function futimesSync(fd: number, atime: TimeLike, mtime: TimeLike): void; + /** + * Request that all data for the open file descriptor is flushed to the storage + * device. The specific implementation is operating system and device specific. + * Refer to the POSIX [`fsync(2)`](http://man7.org/linux/man-pages/man2/fsync.2.html) documentation for more detail. No arguments other + * than a possible exception are given to the completion callback. + * @since v0.1.96 + */ + export function fsync(fd: number, callback: NoParamCallback): void; + export namespace fsync { + /** + * Asynchronous fsync(2) - synchronize a file's in-core state with the underlying storage device. + * @param fd A file descriptor. + */ + function __promisify__(fd: number): Promise; + } + /** + * Request that all data for the open file descriptor is flushed to the storage + * device. The specific implementation is operating system and device specific. + * Refer to the POSIX [`fsync(2)`](http://man7.org/linux/man-pages/man2/fsync.2.html) documentation for more detail. Returns `undefined`. + * @since v0.1.96 + */ + export function fsyncSync(fd: number): void; + /** + * Write `buffer` to the file specified by `fd`. + * + * `offset` determines the part of the buffer to be written, and `length` is + * an integer specifying the number of bytes to write. + * + * `position` refers to the offset from the beginning of the file where this data + * should be written. If `typeof position !== 'number'`, the data will be written + * at the current position. See [`pwrite(2)`](http://man7.org/linux/man-pages/man2/pwrite.2.html). + * + * The callback will be given three arguments `(err, bytesWritten, buffer)` where `bytesWritten` specifies how many _bytes_ were written from `buffer`. + * + * If this method is invoked as its `util.promisify()` ed version, it returns + * a promise for an `Object` with `bytesWritten` and `buffer` properties. + * + * It is unsafe to use `fs.write()` multiple times on the same file without waiting + * for the callback. For this scenario, {@link createWriteStream} is + * recommended. + * + * On Linux, positional writes don't work when the file is opened in append mode. + * The kernel ignores the position argument and always appends the data to + * the end of the file. + * @since v0.0.2 + * @param [offset=0] + * @param [length=buffer.byteLength - offset] + * @param [position='null'] + */ + export function write( + fd: number, + buffer: TBuffer, + offset: number | undefined | null, + length: number | undefined | null, + position: number | undefined | null, + callback: (err: NodeJS.ErrnoException | null, written: number, buffer: TBuffer) => void, + ): void; + /** + * Asynchronously writes `buffer` to the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param offset The part of the buffer to be written. If not supplied, defaults to `0`. + * @param length The number of bytes to write. If not supplied, defaults to `buffer.length - offset`. + */ + export function write( + fd: number, + buffer: TBuffer, + offset: number | undefined | null, + length: number | undefined | null, + callback: (err: NodeJS.ErrnoException | null, written: number, buffer: TBuffer) => void, + ): void; + /** + * Asynchronously writes `buffer` to the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param offset The part of the buffer to be written. If not supplied, defaults to `0`. + */ + export function write( + fd: number, + buffer: TBuffer, + offset: number | undefined | null, + callback: (err: NodeJS.ErrnoException | null, written: number, buffer: TBuffer) => void, + ): void; + /** + * Asynchronously writes `buffer` to the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + */ + export function write( + fd: number, + buffer: TBuffer, + callback: (err: NodeJS.ErrnoException | null, written: number, buffer: TBuffer) => void, + ): void; + /** + * Asynchronously writes `string` to the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param string A string to write. + * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. + * @param encoding The expected string encoding. + */ + export function write( + fd: number, + string: string, + position: number | undefined | null, + encoding: BufferEncoding | undefined | null, + callback: (err: NodeJS.ErrnoException | null, written: number, str: string) => void, + ): void; + /** + * Asynchronously writes `string` to the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param string A string to write. + * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. + */ + export function write( + fd: number, + string: string, + position: number | undefined | null, + callback: (err: NodeJS.ErrnoException | null, written: number, str: string) => void, + ): void; + /** + * Asynchronously writes `string` to the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param string A string to write. + */ + export function write( + fd: number, + string: string, + callback: (err: NodeJS.ErrnoException | null, written: number, str: string) => void, + ): void; + export namespace write { + /** + * Asynchronously writes `buffer` to the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param offset The part of the buffer to be written. If not supplied, defaults to `0`. + * @param length The number of bytes to write. If not supplied, defaults to `buffer.length - offset`. + * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. + */ + function __promisify__( + fd: number, + buffer?: TBuffer, + offset?: number, + length?: number, + position?: number | null, + ): Promise<{ + bytesWritten: number; + buffer: TBuffer; + }>; + /** + * Asynchronously writes `string` to the file referenced by the supplied file descriptor. + * @param fd A file descriptor. + * @param string A string to write. + * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. + * @param encoding The expected string encoding. + */ + function __promisify__( + fd: number, + string: string, + position?: number | null, + encoding?: BufferEncoding | null, + ): Promise<{ + bytesWritten: number; + buffer: string; + }>; + } + /** + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link write}. + * @since v0.1.21 + * @param [offset=0] + * @param [length=buffer.byteLength - offset] + * @param [position='null'] + * @return The number of bytes written. + */ + export function writeSync( + fd: number, + buffer: NodeJS.ArrayBufferView, + offset?: number | null, + length?: number | null, + position?: number | null, + ): number; + /** + * Synchronously writes `string` to the file referenced by the supplied file descriptor, returning the number of bytes written. + * @param fd A file descriptor. + * @param string A string to write. + * @param position The offset from the beginning of the file where this data should be written. If not supplied, defaults to the current position. + * @param encoding The expected string encoding. + */ + export function writeSync( + fd: number, + string: string, + position?: number | null, + encoding?: BufferEncoding | null, + ): number; + export type ReadPosition = number | bigint; + export interface ReadSyncOptions { + /** + * @default 0 + */ + offset?: number | undefined; + /** + * @default `length of buffer` + */ + length?: number | undefined; + /** + * @default null + */ + position?: ReadPosition | null | undefined; + } + export interface ReadAsyncOptions extends ReadSyncOptions { + buffer?: TBuffer; + } + /** + * Read data from the file specified by `fd`. + * + * The callback is given the three arguments, `(err, bytesRead, buffer)`. + * + * If the file is not modified concurrently, the end-of-file is reached when the + * number of bytes read is zero. + * + * If this method is invoked as its `util.promisify()` ed version, it returns + * a promise for an `Object` with `bytesRead` and `buffer` properties. + * @since v0.0.2 + * @param buffer The buffer that the data will be written to. + * @param offset The position in `buffer` to write the data to. + * @param length The number of bytes to read. + * @param position Specifies where to begin reading from in the file. If `position` is `null` or `-1 `, data will be read from the current file position, and the file position will be updated. If + * `position` is an integer, the file position will be unchanged. + */ + export function read( + fd: number, + buffer: TBuffer, + offset: number, + length: number, + position: ReadPosition | null, + callback: (err: NodeJS.ErrnoException | null, bytesRead: number, buffer: TBuffer) => void, + ): void; + /** + * Similar to the above `fs.read` function, this version takes an optional `options` object. + * If not otherwise specified in an `options` object, + * `buffer` defaults to `Buffer.alloc(16384)`, + * `offset` defaults to `0`, + * `length` defaults to `buffer.byteLength`, `- offset` as of Node 17.6.0 + * `position` defaults to `null` + * @since v12.17.0, 13.11.0 + */ + export function read( + fd: number, + options: ReadAsyncOptions, + callback: (err: NodeJS.ErrnoException | null, bytesRead: number, buffer: TBuffer) => void, + ): void; + export function read( + fd: number, + callback: (err: NodeJS.ErrnoException | null, bytesRead: number, buffer: NodeJS.ArrayBufferView) => void, + ): void; + export namespace read { + /** + * @param fd A file descriptor. + * @param buffer The buffer that the data will be written to. + * @param offset The offset in the buffer at which to start writing. + * @param length The number of bytes to read. + * @param position The offset from the beginning of the file from which data should be read. If `null`, data will be read from the current position. + */ + function __promisify__( + fd: number, + buffer: TBuffer, + offset: number, + length: number, + position: number | null, + ): Promise<{ + bytesRead: number; + buffer: TBuffer; + }>; + function __promisify__( + fd: number, + options: ReadAsyncOptions, + ): Promise<{ + bytesRead: number; + buffer: TBuffer; + }>; + function __promisify__(fd: number): Promise<{ + bytesRead: number; + buffer: NodeJS.ArrayBufferView; + }>; + } + /** + * Returns the number of `bytesRead`. + * + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link read}. + * @since v0.1.21 + * @param [position='null'] + */ + export function readSync( + fd: number, + buffer: NodeJS.ArrayBufferView, + offset: number, + length: number, + position: ReadPosition | null, + ): number; + /** + * Similar to the above `fs.readSync` function, this version takes an optional `options` object. + * If no `options` object is specified, it will default with the above values. + */ + export function readSync(fd: number, buffer: NodeJS.ArrayBufferView, opts?: ReadSyncOptions): number; + /** + * Asynchronously reads the entire contents of a file. + * + * ```js + * import { readFile } from 'node:fs'; + * + * readFile('/etc/passwd', (err, data) => { + * if (err) throw err; + * console.log(data); + * }); + * ``` + * + * The callback is passed two arguments `(err, data)`, where `data` is the + * contents of the file. + * + * If no encoding is specified, then the raw buffer is returned. + * + * If `options` is a string, then it specifies the encoding: + * + * ```js + * import { readFile } from 'node:fs'; + * + * readFile('/etc/passwd', 'utf8', callback); + * ``` + * + * When the path is a directory, the behavior of `fs.readFile()` and {@link readFileSync} is platform-specific. On macOS, Linux, and Windows, an + * error will be returned. On FreeBSD, a representation of the directory's contents + * will be returned. + * + * ```js + * import { readFile } from 'node:fs'; + * + * // macOS, Linux, and Windows + * readFile('', (err, data) => { + * // => [Error: EISDIR: illegal operation on a directory, read ] + * }); + * + * // FreeBSD + * readFile('', (err, data) => { + * // => null, + * }); + * ``` + * + * It is possible to abort an ongoing request using an `AbortSignal`. If a + * request is aborted the callback is called with an `AbortError`: + * + * ```js + * import { readFile } from 'node:fs'; + * + * const controller = new AbortController(); + * const signal = controller.signal; + * readFile(fileInfo[0].name, { signal }, (err, buf) => { + * // ... + * }); + * // When you want to abort the request + * controller.abort(); + * ``` + * + * The `fs.readFile()` function buffers the entire file. To minimize memory costs, + * when possible prefer streaming via `fs.createReadStream()`. + * + * Aborting an ongoing request does not abort individual operating + * system requests but rather the internal buffering `fs.readFile` performs. + * @since v0.1.29 + * @param path filename or file descriptor + */ + export function readFile( + path: PathOrFileDescriptor, + options: + | ({ + encoding?: null | undefined; + flag?: string | undefined; + } & Abortable) + | undefined + | null, + callback: (err: NodeJS.ErrnoException | null, data: Buffer) => void, + ): void; + /** + * Asynchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param options Either the encoding for the result, or an object that contains the encoding and an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + export function readFile( + path: PathOrFileDescriptor, + options: + | ({ + encoding: BufferEncoding; + flag?: string | undefined; + } & Abortable) + | BufferEncoding, + callback: (err: NodeJS.ErrnoException | null, data: string) => void, + ): void; + /** + * Asynchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param options Either the encoding for the result, or an object that contains the encoding and an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + export function readFile( + path: PathOrFileDescriptor, + options: + | (ObjectEncodingOptions & { + flag?: string | undefined; + } & Abortable) + | BufferEncoding + | undefined + | null, + callback: (err: NodeJS.ErrnoException | null, data: string | Buffer) => void, + ): void; + /** + * Asynchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + */ + export function readFile( + path: PathOrFileDescriptor, + callback: (err: NodeJS.ErrnoException | null, data: Buffer) => void, + ): void; + export namespace readFile { + /** + * Asynchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param options An object that may contain an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + function __promisify__( + path: PathOrFileDescriptor, + options?: { + encoding?: null | undefined; + flag?: string | undefined; + } | null, + ): Promise; + /** + * Asynchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param options Either the encoding for the result, or an object that contains the encoding and an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + function __promisify__( + path: PathOrFileDescriptor, + options: + | { + encoding: BufferEncoding; + flag?: string | undefined; + } + | BufferEncoding, + ): Promise; + /** + * Asynchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param options Either the encoding for the result, or an object that contains the encoding and an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + function __promisify__( + path: PathOrFileDescriptor, + options?: + | (ObjectEncodingOptions & { + flag?: string | undefined; + }) + | BufferEncoding + | null, + ): Promise; + } + /** + * Returns the contents of the `path`. + * + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link readFile}. + * + * If the `encoding` option is specified then this function returns a + * string. Otherwise it returns a buffer. + * + * Similar to {@link readFile}, when the path is a directory, the behavior of `fs.readFileSync()` is platform-specific. + * + * ```js + * import { readFileSync } from 'node:fs'; + * + * // macOS, Linux, and Windows + * readFileSync(''); + * // => [Error: EISDIR: illegal operation on a directory, read ] + * + * // FreeBSD + * readFileSync(''); // => + * ``` + * @since v0.1.8 + * @param path filename or file descriptor + */ + export function readFileSync( + path: PathOrFileDescriptor, + options?: { + encoding?: null | undefined; + flag?: string | undefined; + } | null, + ): Buffer; + /** + * Synchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param options Either the encoding for the result, or an object that contains the encoding and an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + export function readFileSync( + path: PathOrFileDescriptor, + options: + | { + encoding: BufferEncoding; + flag?: string | undefined; + } + | BufferEncoding, + ): string; + /** + * Synchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param options Either the encoding for the result, or an object that contains the encoding and an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + export function readFileSync( + path: PathOrFileDescriptor, + options?: + | (ObjectEncodingOptions & { + flag?: string | undefined; + }) + | BufferEncoding + | null, + ): string | Buffer; + export type WriteFileOptions = + | ( + & ObjectEncodingOptions + & Abortable + & { + mode?: Mode | undefined; + flag?: string | undefined; + flush?: boolean | undefined; + } + ) + | BufferEncoding + | null; + /** + * When `file` is a filename, asynchronously writes data to the file, replacing the + * file if it already exists. `data` can be a string or a buffer. + * + * When `file` is a file descriptor, the behavior is similar to calling `fs.write()` directly (which is recommended). See the notes below on using + * a file descriptor. + * + * The `encoding` option is ignored if `data` is a buffer. + * + * The `mode` option only affects the newly created file. See {@link open} for more details. + * + * ```js + * import { writeFile } from 'node:fs'; + * import { Buffer } from 'node:buffer'; + * + * const data = new Uint8Array(Buffer.from('Hello Node.js')); + * writeFile('message.txt', data, (err) => { + * if (err) throw err; + * console.log('The file has been saved!'); + * }); + * ``` + * + * If `options` is a string, then it specifies the encoding: + * + * ```js + * import { writeFile } from 'node:fs'; + * + * writeFile('message.txt', 'Hello Node.js', 'utf8', callback); + * ``` + * + * It is unsafe to use `fs.writeFile()` multiple times on the same file without + * waiting for the callback. For this scenario, {@link createWriteStream} is + * recommended. + * + * Similarly to `fs.readFile` \- `fs.writeFile` is a convenience method that + * performs multiple `write` calls internally to write the buffer passed to it. + * For performance sensitive code consider using {@link createWriteStream}. + * + * It is possible to use an `AbortSignal` to cancel an `fs.writeFile()`. + * Cancelation is "best effort", and some amount of data is likely still + * to be written. + * + * ```js + * import { writeFile } from 'node:fs'; + * import { Buffer } from 'node:buffer'; + * + * const controller = new AbortController(); + * const { signal } = controller; + * const data = new Uint8Array(Buffer.from('Hello Node.js')); + * writeFile('message.txt', data, { signal }, (err) => { + * // When a request is aborted - the callback is called with an AbortError + * }); + * // When the request should be aborted + * controller.abort(); + * ``` + * + * Aborting an ongoing request does not abort individual operating + * system requests but rather the internal buffering `fs.writeFile` performs. + * @since v0.1.29 + * @param file filename or file descriptor + */ + export function writeFile( + file: PathOrFileDescriptor, + data: string | NodeJS.ArrayBufferView, + options: WriteFileOptions, + callback: NoParamCallback, + ): void; + /** + * Asynchronously writes data to a file, replacing the file if it already exists. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param data The data to write. If something other than a Buffer or Uint8Array is provided, the value is coerced to a string. + */ + export function writeFile( + path: PathOrFileDescriptor, + data: string | NodeJS.ArrayBufferView, + callback: NoParamCallback, + ): void; + export namespace writeFile { + /** + * Asynchronously writes data to a file, replacing the file if it already exists. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param data The data to write. If something other than a Buffer or Uint8Array is provided, the value is coerced to a string. + * @param options Either the encoding for the file, or an object optionally specifying the encoding, file mode, and flag. + * If `encoding` is not supplied, the default of `'utf8'` is used. + * If `mode` is not supplied, the default of `0o666` is used. + * If `mode` is a string, it is parsed as an octal integer. + * If `flag` is not supplied, the default of `'w'` is used. + */ + function __promisify__( + path: PathOrFileDescriptor, + data: string | NodeJS.ArrayBufferView, + options?: WriteFileOptions, + ): Promise; + } + /** + * Returns `undefined`. + * + * The `mode` option only affects the newly created file. See {@link open} for more details. + * + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link writeFile}. + * @since v0.1.29 + * @param file filename or file descriptor + */ + export function writeFileSync( + file: PathOrFileDescriptor, + data: string | NodeJS.ArrayBufferView, + options?: WriteFileOptions, + ): void; + /** + * Asynchronously append data to a file, creating the file if it does not yet + * exist. `data` can be a string or a `Buffer`. + * + * The `mode` option only affects the newly created file. See {@link open} for more details. + * + * ```js + * import { appendFile } from 'node:fs'; + * + * appendFile('message.txt', 'data to append', (err) => { + * if (err) throw err; + * console.log('The "data to append" was appended to file!'); + * }); + * ``` + * + * If `options` is a string, then it specifies the encoding: + * + * ```js + * import { appendFile } from 'node:fs'; + * + * appendFile('message.txt', 'data to append', 'utf8', callback); + * ``` + * + * The `path` may be specified as a numeric file descriptor that has been opened + * for appending (using `fs.open()` or `fs.openSync()`). The file descriptor will + * not be closed automatically. + * + * ```js + * import { open, close, appendFile } from 'node:fs'; + * + * function closeFd(fd) { + * close(fd, (err) => { + * if (err) throw err; + * }); + * } + * + * open('message.txt', 'a', (err, fd) => { + * if (err) throw err; + * + * try { + * appendFile(fd, 'data to append', 'utf8', (err) => { + * closeFd(fd); + * if (err) throw err; + * }); + * } catch (err) { + * closeFd(fd); + * throw err; + * } + * }); + * ``` + * @since v0.6.7 + * @param path filename or file descriptor + */ + export function appendFile( + path: PathOrFileDescriptor, + data: string | Uint8Array, + options: WriteFileOptions, + callback: NoParamCallback, + ): void; + /** + * Asynchronously append data to a file, creating the file if it does not exist. + * @param file A path to a file. If a URL is provided, it must use the `file:` protocol. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param data The data to write. If something other than a Buffer or Uint8Array is provided, the value is coerced to a string. + */ + export function appendFile(file: PathOrFileDescriptor, data: string | Uint8Array, callback: NoParamCallback): void; + export namespace appendFile { + /** + * Asynchronously append data to a file, creating the file if it does not exist. + * @param file A path to a file. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + * If a file descriptor is provided, the underlying file will _not_ be closed automatically. + * @param data The data to write. If something other than a Buffer or Uint8Array is provided, the value is coerced to a string. + * @param options Either the encoding for the file, or an object optionally specifying the encoding, file mode, and flag. + * If `encoding` is not supplied, the default of `'utf8'` is used. + * If `mode` is not supplied, the default of `0o666` is used. + * If `mode` is a string, it is parsed as an octal integer. + * If `flag` is not supplied, the default of `'a'` is used. + */ + function __promisify__( + file: PathOrFileDescriptor, + data: string | Uint8Array, + options?: WriteFileOptions, + ): Promise; + } + /** + * Synchronously append data to a file, creating the file if it does not yet + * exist. `data` can be a string or a `Buffer`. + * + * The `mode` option only affects the newly created file. See {@link open} for more details. + * + * ```js + * import { appendFileSync } from 'node:fs'; + * + * try { + * appendFileSync('message.txt', 'data to append'); + * console.log('The "data to append" was appended to file!'); + * } catch (err) { + * // Handle the error + * } + * ``` + * + * If `options` is a string, then it specifies the encoding: + * + * ```js + * import { appendFileSync } from 'node:fs'; + * + * appendFileSync('message.txt', 'data to append', 'utf8'); + * ``` + * + * The `path` may be specified as a numeric file descriptor that has been opened + * for appending (using `fs.open()` or `fs.openSync()`). The file descriptor will + * not be closed automatically. + * + * ```js + * import { openSync, closeSync, appendFileSync } from 'node:fs'; + * + * let fd; + * + * try { + * fd = openSync('message.txt', 'a'); + * appendFileSync(fd, 'data to append', 'utf8'); + * } catch (err) { + * // Handle the error + * } finally { + * if (fd !== undefined) + * closeSync(fd); + * } + * ``` + * @since v0.6.7 + * @param path filename or file descriptor + */ + export function appendFileSync( + path: PathOrFileDescriptor, + data: string | Uint8Array, + options?: WriteFileOptions, + ): void; + /** + * Watch for changes on `filename`. The callback `listener` will be called each + * time the file is accessed. + * + * The `options` argument may be omitted. If provided, it should be an object. The `options` object may contain a boolean named `persistent` that indicates + * whether the process should continue to run as long as files are being watched. + * The `options` object may specify an `interval` property indicating how often the + * target should be polled in milliseconds. + * + * The `listener` gets two arguments the current stat object and the previous + * stat object: + * + * ```js + * import { watchFile } from 'fs'; + * + * watchFile('message.text', (curr, prev) => { + * console.log(`the current mtime is: ${curr.mtime}`); + * console.log(`the previous mtime was: ${prev.mtime}`); + * }); + * ``` + * + * These stat objects are instances of `fs.Stat`. If the `bigint` option is `true`, + * the numeric values in these objects are specified as `BigInt`s. + * + * To be notified when the file was modified, not just accessed, it is necessary + * to compare `curr.mtimeMs` and `prev.mtimeMs`. + * + * When an `fs.watchFile` operation results in an `ENOENT` error, it + * will invoke the listener once, with all the fields zeroed (or, for dates, the + * Unix Epoch). If the file is created later on, the listener will be called + * again, with the latest stat objects. This is a change in functionality since + * v0.10. + * + * Using {@link watch} is more efficient than `fs.watchFile` and `fs.unwatchFile`. `fs.watch` should be used instead of `fs.watchFile` and `fs.unwatchFile` when possible. + * + * When a file being watched by `fs.watchFile()` disappears and reappears, + * then the contents of `previous` in the second callback event (the file's + * reappearance) will be the same as the contents of `previous` in the first + * callback event (its disappearance). + * + * This happens when: + * + * * the file is deleted, followed by a restore + * * the file is renamed and then renamed a second time back to its original name + * @since v0.1.31 + */ + export interface WatchFileOptions { + bigint?: boolean | undefined; + persistent?: boolean | undefined; + interval?: number | undefined; + } + /** + * Watch for changes on `filename`. The callback `listener` will be called each + * time the file is accessed. + * + * The `options` argument may be omitted. If provided, it should be an object. The `options` object may contain a boolean named `persistent` that indicates + * whether the process should continue to run as long as files are being watched. + * The `options` object may specify an `interval` property indicating how often the + * target should be polled in milliseconds. + * + * The `listener` gets two arguments the current stat object and the previous + * stat object: + * + * ```js + * import { watchFile } from 'node:fs'; + * + * watchFile('message.text', (curr, prev) => { + * console.log(`the current mtime is: ${curr.mtime}`); + * console.log(`the previous mtime was: ${prev.mtime}`); + * }); + * ``` + * + * These stat objects are instances of `fs.Stat`. If the `bigint` option is `true`, + * the numeric values in these objects are specified as `BigInt`s. + * + * To be notified when the file was modified, not just accessed, it is necessary + * to compare `curr.mtimeMs` and `prev.mtimeMs`. + * + * When an `fs.watchFile` operation results in an `ENOENT` error, it + * will invoke the listener once, with all the fields zeroed (or, for dates, the + * Unix Epoch). If the file is created later on, the listener will be called + * again, with the latest stat objects. This is a change in functionality since + * v0.10. + * + * Using {@link watch} is more efficient than `fs.watchFile` and `fs.unwatchFile`. `fs.watch` should be used instead of `fs.watchFile` and `fs.unwatchFile` when possible. + * + * When a file being watched by `fs.watchFile()` disappears and reappears, + * then the contents of `previous` in the second callback event (the file's + * reappearance) will be the same as the contents of `previous` in the first + * callback event (its disappearance). + * + * This happens when: + * + * * the file is deleted, followed by a restore + * * the file is renamed and then renamed a second time back to its original name + * @since v0.1.31 + */ + export function watchFile( + filename: PathLike, + options: + | (WatchFileOptions & { + bigint?: false | undefined; + }) + | undefined, + listener: StatsListener, + ): StatWatcher; + export function watchFile( + filename: PathLike, + options: + | (WatchFileOptions & { + bigint: true; + }) + | undefined, + listener: BigIntStatsListener, + ): StatWatcher; + /** + * Watch for changes on `filename`. The callback `listener` will be called each time the file is accessed. + * @param filename A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + */ + export function watchFile(filename: PathLike, listener: StatsListener): StatWatcher; + /** + * Stop watching for changes on `filename`. If `listener` is specified, only that + * particular listener is removed. Otherwise, _all_ listeners are removed, + * effectively stopping watching of `filename`. + * + * Calling `fs.unwatchFile()` with a filename that is not being watched is a + * no-op, not an error. + * + * Using {@link watch} is more efficient than `fs.watchFile()` and `fs.unwatchFile()`. `fs.watch()` should be used instead of `fs.watchFile()` and `fs.unwatchFile()` when possible. + * @since v0.1.31 + * @param listener Optional, a listener previously attached using `fs.watchFile()` + */ + export function unwatchFile(filename: PathLike, listener?: StatsListener): void; + export function unwatchFile(filename: PathLike, listener?: BigIntStatsListener): void; + export interface WatchOptions extends Abortable { + encoding?: BufferEncoding | "buffer" | undefined; + persistent?: boolean | undefined; + recursive?: boolean | undefined; + } + export type WatchEventType = "rename" | "change"; + export type WatchListener = (event: WatchEventType, filename: T | null) => void; + export type StatsListener = (curr: Stats, prev: Stats) => void; + export type BigIntStatsListener = (curr: BigIntStats, prev: BigIntStats) => void; + /** + * Watch for changes on `filename`, where `filename` is either a file or a + * directory. + * + * The second argument is optional. If `options` is provided as a string, it + * specifies the `encoding`. Otherwise `options` should be passed as an object. + * + * The listener callback gets two arguments `(eventType, filename)`. `eventType`is either `'rename'` or `'change'`, and `filename` is the name of the file + * which triggered the event. + * + * On most platforms, `'rename'` is emitted whenever a filename appears or + * disappears in the directory. + * + * The listener callback is attached to the `'change'` event fired by `fs.FSWatcher`, but it is not the same thing as the `'change'` value of `eventType`. + * + * If a `signal` is passed, aborting the corresponding AbortController will close + * the returned `fs.FSWatcher`. + * @since v0.5.10 + * @param listener + */ + export function watch( + filename: PathLike, + options: + | (WatchOptions & { + encoding: "buffer"; + }) + | "buffer", + listener?: WatchListener, + ): FSWatcher; + /** + * Watch for changes on `filename`, where `filename` is either a file or a directory, returning an `FSWatcher`. + * @param filename A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + * @param options Either the encoding for the filename provided to the listener, or an object optionally specifying encoding, persistent, and recursive options. + * If `encoding` is not supplied, the default of `'utf8'` is used. + * If `persistent` is not supplied, the default of `true` is used. + * If `recursive` is not supplied, the default of `false` is used. + */ + export function watch( + filename: PathLike, + options?: WatchOptions | BufferEncoding | null, + listener?: WatchListener, + ): FSWatcher; + /** + * Watch for changes on `filename`, where `filename` is either a file or a directory, returning an `FSWatcher`. + * @param filename A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + * @param options Either the encoding for the filename provided to the listener, or an object optionally specifying encoding, persistent, and recursive options. + * If `encoding` is not supplied, the default of `'utf8'` is used. + * If `persistent` is not supplied, the default of `true` is used. + * If `recursive` is not supplied, the default of `false` is used. + */ + export function watch( + filename: PathLike, + options: WatchOptions | string, + listener?: WatchListener, + ): FSWatcher; + /** + * Watch for changes on `filename`, where `filename` is either a file or a directory, returning an `FSWatcher`. + * @param filename A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + */ + export function watch(filename: PathLike, listener?: WatchListener): FSWatcher; + /** + * Test whether or not the given path exists by checking with the file system. + * Then call the `callback` argument with either true or false: + * + * ```js + * import { exists } from 'node:fs'; + * + * exists('/etc/passwd', (e) => { + * console.log(e ? 'it exists' : 'no passwd!'); + * }); + * ``` + * + * **The parameters for this callback are not consistent with other Node.js** + * **callbacks.** Normally, the first parameter to a Node.js callback is an `err` parameter, optionally followed by other parameters. The `fs.exists()` callback + * has only one boolean parameter. This is one reason `fs.access()` is recommended + * instead of `fs.exists()`. + * + * Using `fs.exists()` to check for the existence of a file before calling `fs.open()`, `fs.readFile()`, or `fs.writeFile()` is not recommended. Doing + * so introduces a race condition, since other processes may change the file's + * state between the two calls. Instead, user code should open/read/write the + * file directly and handle the error raised if the file does not exist. + * + * **write (NOT RECOMMENDED)** + * + * ```js + * import { exists, open, close } from 'node:fs'; + * + * exists('myfile', (e) => { + * if (e) { + * console.error('myfile already exists'); + * } else { + * open('myfile', 'wx', (err, fd) => { + * if (err) throw err; + * + * try { + * writeMyData(fd); + * } finally { + * close(fd, (err) => { + * if (err) throw err; + * }); + * } + * }); + * } + * }); + * ``` + * + * **write (RECOMMENDED)** + * + * ```js + * import { open, close } from 'node:fs'; + * open('myfile', 'wx', (err, fd) => { + * if (err) { + * if (err.code === 'EEXIST') { + * console.error('myfile already exists'); + * return; + * } + * + * throw err; + * } + * + * try { + * writeMyData(fd); + * } finally { + * close(fd, (err) => { + * if (err) throw err; + * }); + * } + * }); + * ``` + * + * **read (NOT RECOMMENDED)** + * + * ```js + * import { open, close, exists } from 'node:fs'; + * + * exists('myfile', (e) => { + * if (e) { + * open('myfile', 'r', (err, fd) => { + * if (err) throw err; + * + * try { + * readMyData(fd); + * } finally { + * close(fd, (err) => { + * if (err) throw err; + * }); + * } + * }); + * } else { + * console.error('myfile does not exist'); + * } + * }); + * ``` + * + * **read (RECOMMENDED)** + * + * ```js + * import { open, close } from 'node:fs'; + * + * open('myfile', 'r', (err, fd) => { + * if (err) { + * if (err.code === 'ENOENT') { + * console.error('myfile does not exist'); + * return; + * } + * + * throw err; + * } + * + * try { + * readMyData(fd); + * } finally { + * close(fd, (err) => { + * if (err) throw err; + * }); + * } + * }); + * ``` + * + * The "not recommended" examples above check for existence and then use the + * file; the "recommended" examples are better because they use the file directly + * and handle the error, if any. + * + * In general, check for the existence of a file only if the file won't be + * used directly, for example when its existence is a signal from another + * process. + * @since v0.0.2 + * @deprecated Since v1.0.0 - Use {@link stat} or {@link access} instead. + */ + export function exists(path: PathLike, callback: (exists: boolean) => void): void; + /** @deprecated */ + export namespace exists { + /** + * @param path A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + */ + function __promisify__(path: PathLike): Promise; + } + /** + * Returns `true` if the path exists, `false` otherwise. + * + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link exists}. + * + * `fs.exists()` is deprecated, but `fs.existsSync()` is not. The `callback` parameter to `fs.exists()` accepts parameters that are inconsistent with other + * Node.js callbacks. `fs.existsSync()` does not use a callback. + * + * ```js + * import { existsSync } from 'node:fs'; + * + * if (existsSync('/etc/passwd')) + * console.log('The path exists.'); + * ``` + * @since v0.1.21 + */ + export function existsSync(path: PathLike): boolean; + export namespace constants { + // File Access Constants + /** Constant for fs.access(). File is visible to the calling process. */ + const F_OK: number; + /** Constant for fs.access(). File can be read by the calling process. */ + const R_OK: number; + /** Constant for fs.access(). File can be written by the calling process. */ + const W_OK: number; + /** Constant for fs.access(). File can be executed by the calling process. */ + const X_OK: number; + // File Copy Constants + /** Constant for fs.copyFile. Flag indicating the destination file should not be overwritten if it already exists. */ + const COPYFILE_EXCL: number; + /** + * Constant for fs.copyFile. copy operation will attempt to create a copy-on-write reflink. + * If the underlying platform does not support copy-on-write, then a fallback copy mechanism is used. + */ + const COPYFILE_FICLONE: number; + /** + * Constant for fs.copyFile. Copy operation will attempt to create a copy-on-write reflink. + * If the underlying platform does not support copy-on-write, then the operation will fail with an error. + */ + const COPYFILE_FICLONE_FORCE: number; + // File Open Constants + /** Constant for fs.open(). Flag indicating to open a file for read-only access. */ + const O_RDONLY: number; + /** Constant for fs.open(). Flag indicating to open a file for write-only access. */ + const O_WRONLY: number; + /** Constant for fs.open(). Flag indicating to open a file for read-write access. */ + const O_RDWR: number; + /** Constant for fs.open(). Flag indicating to create the file if it does not already exist. */ + const O_CREAT: number; + /** Constant for fs.open(). Flag indicating that opening a file should fail if the O_CREAT flag is set and the file already exists. */ + const O_EXCL: number; + /** + * Constant for fs.open(). Flag indicating that if path identifies a terminal device, + * opening the path shall not cause that terminal to become the controlling terminal for the process + * (if the process does not already have one). + */ + const O_NOCTTY: number; + /** Constant for fs.open(). Flag indicating that if the file exists and is a regular file, and the file is opened successfully for write access, its length shall be truncated to zero. */ + const O_TRUNC: number; + /** Constant for fs.open(). Flag indicating that data will be appended to the end of the file. */ + const O_APPEND: number; + /** Constant for fs.open(). Flag indicating that the open should fail if the path is not a directory. */ + const O_DIRECTORY: number; + /** + * constant for fs.open(). + * Flag indicating reading accesses to the file system will no longer result in + * an update to the atime information associated with the file. + * This flag is available on Linux operating systems only. + */ + const O_NOATIME: number; + /** Constant for fs.open(). Flag indicating that the open should fail if the path is a symbolic link. */ + const O_NOFOLLOW: number; + /** Constant for fs.open(). Flag indicating that the file is opened for synchronous I/O. */ + const O_SYNC: number; + /** Constant for fs.open(). Flag indicating that the file is opened for synchronous I/O with write operations waiting for data integrity. */ + const O_DSYNC: number; + /** Constant for fs.open(). Flag indicating to open the symbolic link itself rather than the resource it is pointing to. */ + const O_SYMLINK: number; + /** Constant for fs.open(). When set, an attempt will be made to minimize caching effects of file I/O. */ + const O_DIRECT: number; + /** Constant for fs.open(). Flag indicating to open the file in nonblocking mode when possible. */ + const O_NONBLOCK: number; + // File Type Constants + /** Constant for fs.Stats mode property for determining a file's type. Bit mask used to extract the file type code. */ + const S_IFMT: number; + /** Constant for fs.Stats mode property for determining a file's type. File type constant for a regular file. */ + const S_IFREG: number; + /** Constant for fs.Stats mode property for determining a file's type. File type constant for a directory. */ + const S_IFDIR: number; + /** Constant for fs.Stats mode property for determining a file's type. File type constant for a character-oriented device file. */ + const S_IFCHR: number; + /** Constant for fs.Stats mode property for determining a file's type. File type constant for a block-oriented device file. */ + const S_IFBLK: number; + /** Constant for fs.Stats mode property for determining a file's type. File type constant for a FIFO/pipe. */ + const S_IFIFO: number; + /** Constant for fs.Stats mode property for determining a file's type. File type constant for a symbolic link. */ + const S_IFLNK: number; + /** Constant for fs.Stats mode property for determining a file's type. File type constant for a socket. */ + const S_IFSOCK: number; + // File Mode Constants + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable, writable and executable by owner. */ + const S_IRWXU: number; + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable by owner. */ + const S_IRUSR: number; + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating writable by owner. */ + const S_IWUSR: number; + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating executable by owner. */ + const S_IXUSR: number; + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable, writable and executable by group. */ + const S_IRWXG: number; + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable by group. */ + const S_IRGRP: number; + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating writable by group. */ + const S_IWGRP: number; + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating executable by group. */ + const S_IXGRP: number; + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable, writable and executable by others. */ + const S_IRWXO: number; + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating readable by others. */ + const S_IROTH: number; + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating writable by others. */ + const S_IWOTH: number; + /** Constant for fs.Stats mode property for determining access permissions for a file. File mode indicating executable by others. */ + const S_IXOTH: number; + /** + * When set, a memory file mapping is used to access the file. This flag + * is available on Windows operating systems only. On other operating systems, + * this flag is ignored. + */ + const UV_FS_O_FILEMAP: number; + } + /** + * Tests a user's permissions for the file or directory specified by `path`. + * The `mode` argument is an optional integer that specifies the accessibility + * checks to be performed. `mode` should be either the value `fs.constants.F_OK` or a mask consisting of the bitwise OR of any of `fs.constants.R_OK`, `fs.constants.W_OK`, and `fs.constants.X_OK` + * (e.g.`fs.constants.W_OK | fs.constants.R_OK`). Check `File access constants` for + * possible values of `mode`. + * + * The final argument, `callback`, is a callback function that is invoked with + * a possible error argument. If any of the accessibility checks fail, the error + * argument will be an `Error` object. The following examples check if `package.json` exists, and if it is readable or writable. + * + * ```js + * import { access, constants } from 'node:fs'; + * + * const file = 'package.json'; + * + * // Check if the file exists in the current directory. + * access(file, constants.F_OK, (err) => { + * console.log(`${file} ${err ? 'does not exist' : 'exists'}`); + * }); + * + * // Check if the file is readable. + * access(file, constants.R_OK, (err) => { + * console.log(`${file} ${err ? 'is not readable' : 'is readable'}`); + * }); + * + * // Check if the file is writable. + * access(file, constants.W_OK, (err) => { + * console.log(`${file} ${err ? 'is not writable' : 'is writable'}`); + * }); + * + * // Check if the file is readable and writable. + * access(file, constants.R_OK | constants.W_OK, (err) => { + * console.log(`${file} ${err ? 'is not' : 'is'} readable and writable`); + * }); + * ``` + * + * Do not use `fs.access()` to check for the accessibility of a file before calling `fs.open()`, `fs.readFile()`, or `fs.writeFile()`. Doing + * so introduces a race condition, since other processes may change the file's + * state between the two calls. Instead, user code should open/read/write the + * file directly and handle the error raised if the file is not accessible. + * + * **write (NOT RECOMMENDED)** + * + * ```js + * import { access, open, close } from 'node:fs'; + * + * access('myfile', (err) => { + * if (!err) { + * console.error('myfile already exists'); + * return; + * } + * + * open('myfile', 'wx', (err, fd) => { + * if (err) throw err; + * + * try { + * writeMyData(fd); + * } finally { + * close(fd, (err) => { + * if (err) throw err; + * }); + * } + * }); + * }); + * ``` + * + * **write (RECOMMENDED)** + * + * ```js + * import { open, close } from 'node:fs'; + * + * open('myfile', 'wx', (err, fd) => { + * if (err) { + * if (err.code === 'EEXIST') { + * console.error('myfile already exists'); + * return; + * } + * + * throw err; + * } + * + * try { + * writeMyData(fd); + * } finally { + * close(fd, (err) => { + * if (err) throw err; + * }); + * } + * }); + * ``` + * + * **read (NOT RECOMMENDED)** + * + * ```js + * import { access, open, close } from 'node:fs'; + * access('myfile', (err) => { + * if (err) { + * if (err.code === 'ENOENT') { + * console.error('myfile does not exist'); + * return; + * } + * + * throw err; + * } + * + * open('myfile', 'r', (err, fd) => { + * if (err) throw err; + * + * try { + * readMyData(fd); + * } finally { + * close(fd, (err) => { + * if (err) throw err; + * }); + * } + * }); + * }); + * ``` + * + * **read (RECOMMENDED)** + * + * ```js + * import { open, close } from 'node:fs'; + * + * open('myfile', 'r', (err, fd) => { + * if (err) { + * if (err.code === 'ENOENT') { + * console.error('myfile does not exist'); + * return; + * } + * + * throw err; + * } + * + * try { + * readMyData(fd); + * } finally { + * close(fd, (err) => { + * if (err) throw err; + * }); + * } + * }); + * ``` + * + * The "not recommended" examples above check for accessibility and then use the + * file; the "recommended" examples are better because they use the file directly + * and handle the error, if any. + * + * In general, check for the accessibility of a file only if the file will not be + * used directly, for example when its accessibility is a signal from another + * process. + * + * On Windows, access-control policies (ACLs) on a directory may limit access to + * a file or directory. The `fs.access()` function, however, does not check the + * ACL and therefore may report that a path is accessible even if the ACL restricts + * the user from reading or writing to it. + * @since v0.11.15 + * @param [mode=fs.constants.F_OK] + */ + export function access(path: PathLike, mode: number | undefined, callback: NoParamCallback): void; + /** + * Asynchronously tests a user's permissions for the file specified by path. + * @param path A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + */ + export function access(path: PathLike, callback: NoParamCallback): void; + export namespace access { + /** + * Asynchronously tests a user's permissions for the file specified by path. + * @param path A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + * URL support is _experimental_. + */ + function __promisify__(path: PathLike, mode?: number): Promise; + } + /** + * Synchronously tests a user's permissions for the file or directory specified + * by `path`. The `mode` argument is an optional integer that specifies the + * accessibility checks to be performed. `mode` should be either the value `fs.constants.F_OK` or a mask consisting of the bitwise OR of any of `fs.constants.R_OK`, `fs.constants.W_OK`, and + * `fs.constants.X_OK` (e.g.`fs.constants.W_OK | fs.constants.R_OK`). Check `File access constants` for + * possible values of `mode`. + * + * If any of the accessibility checks fail, an `Error` will be thrown. Otherwise, + * the method will return `undefined`. + * + * ```js + * import { accessSync, constants } from 'node:fs'; + * + * try { + * accessSync('etc/passwd', constants.R_OK | constants.W_OK); + * console.log('can read/write'); + * } catch (err) { + * console.error('no access!'); + * } + * ``` + * @since v0.11.15 + * @param [mode=fs.constants.F_OK] + */ + export function accessSync(path: PathLike, mode?: number): void; + interface StreamOptions { + flags?: string | undefined; + encoding?: BufferEncoding | undefined; + fd?: number | promises.FileHandle | undefined; + mode?: number | undefined; + autoClose?: boolean | undefined; + emitClose?: boolean | undefined; + start?: number | undefined; + signal?: AbortSignal | null | undefined; + highWaterMark?: number | undefined; + } + interface FSImplementation { + open?: (...args: any[]) => any; + close?: (...args: any[]) => any; + } + interface CreateReadStreamFSImplementation extends FSImplementation { + read: (...args: any[]) => any; + } + interface CreateWriteStreamFSImplementation extends FSImplementation { + write: (...args: any[]) => any; + writev?: (...args: any[]) => any; + } + interface ReadStreamOptions extends StreamOptions { + fs?: CreateReadStreamFSImplementation | null | undefined; + end?: number | undefined; + } + interface WriteStreamOptions extends StreamOptions { + fs?: CreateWriteStreamFSImplementation | null | undefined; + flush?: boolean | undefined; + } + /** + * Unlike the 16 KiB default `highWaterMark` for a `stream.Readable`, the stream + * returned by this method has a default `highWaterMark` of 64 KiB. + * + * `options` can include `start` and `end` values to read a range of bytes from + * the file instead of the entire file. Both `start` and `end` are inclusive and + * start counting at 0, allowed values are in the + * \[0, [`Number.MAX_SAFE_INTEGER`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/MAX_SAFE_INTEGER)\] range. If `fd` is specified and `start` is + * omitted or `undefined`, `fs.createReadStream()` reads sequentially from the + * current file position. The `encoding` can be any one of those accepted by `Buffer`. + * + * If `fd` is specified, `ReadStream` will ignore the `path` argument and will use + * the specified file descriptor. This means that no `'open'` event will be + * emitted. `fd` should be blocking; non-blocking `fd`s should be passed to `net.Socket`. + * + * If `fd` points to a character device that only supports blocking reads + * (such as keyboard or sound card), read operations do not finish until data is + * available. This can prevent the process from exiting and the stream from + * closing naturally. + * + * By default, the stream will emit a `'close'` event after it has been + * destroyed. Set the `emitClose` option to `false` to change this behavior. + * + * By providing the `fs` option, it is possible to override the corresponding `fs` implementations for `open`, `read`, and `close`. When providing the `fs` option, + * an override for `read` is required. If no `fd` is provided, an override for `open` is also required. If `autoClose` is `true`, an override for `close` is + * also required. + * + * ```js + * import { createReadStream } from 'node:fs'; + * + * // Create a stream from some character device. + * const stream = createReadStream('/dev/input/event0'); + * setTimeout(() => { + * stream.close(); // This may not close the stream. + * // Artificially marking end-of-stream, as if the underlying resource had + * // indicated end-of-file by itself, allows the stream to close. + * // This does not cancel pending read operations, and if there is such an + * // operation, the process may still not be able to exit successfully + * // until it finishes. + * stream.push(null); + * stream.read(0); + * }, 100); + * ``` + * + * If `autoClose` is false, then the file descriptor won't be closed, even if + * there's an error. It is the application's responsibility to close it and make + * sure there's no file descriptor leak. If `autoClose` is set to true (default + * behavior), on `'error'` or `'end'` the file descriptor will be closed + * automatically. + * + * `mode` sets the file mode (permission and sticky bits), but only if the + * file was created. + * + * An example to read the last 10 bytes of a file which is 100 bytes long: + * + * ```js + * import { createReadStream } from 'node:fs'; + * + * createReadStream('sample.txt', { start: 90, end: 99 }); + * ``` + * + * If `options` is a string, then it specifies the encoding. + * @since v0.1.31 + */ + export function createReadStream(path: PathLike, options?: BufferEncoding | ReadStreamOptions): ReadStream; + /** + * `options` may also include a `start` option to allow writing data at some + * position past the beginning of the file, allowed values are in the + * \[0, [`Number.MAX_SAFE_INTEGER`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/MAX_SAFE_INTEGER)\] range. Modifying a file rather than + * replacing it may require the `flags` option to be set to `r+` rather than the + * default `w`. The `encoding` can be any one of those accepted by `Buffer`. + * + * If `autoClose` is set to true (default behavior) on `'error'` or `'finish'` the file descriptor will be closed automatically. If `autoClose` is false, + * then the file descriptor won't be closed, even if there's an error. + * It is the application's responsibility to close it and make sure there's no + * file descriptor leak. + * + * By default, the stream will emit a `'close'` event after it has been + * destroyed. Set the `emitClose` option to `false` to change this behavior. + * + * By providing the `fs` option it is possible to override the corresponding `fs` implementations for `open`, `write`, `writev`, and `close`. Overriding `write()` without `writev()` can reduce + * performance as some optimizations (`_writev()`) + * will be disabled. When providing the `fs` option, overrides for at least one of `write` and `writev` are required. If no `fd` option is supplied, an override + * for `open` is also required. If `autoClose` is `true`, an override for `close` is also required. + * + * Like `fs.ReadStream`, if `fd` is specified, `fs.WriteStream` will ignore the `path` argument and will use the specified file descriptor. This means that no `'open'` event will be + * emitted. `fd` should be blocking; non-blocking `fd`s + * should be passed to `net.Socket`. + * + * If `options` is a string, then it specifies the encoding. + * @since v0.1.31 + */ + export function createWriteStream(path: PathLike, options?: BufferEncoding | WriteStreamOptions): WriteStream; + /** + * Forces all currently queued I/O operations associated with the file to the + * operating system's synchronized I/O completion state. Refer to the POSIX [`fdatasync(2)`](http://man7.org/linux/man-pages/man2/fdatasync.2.html) documentation for details. No arguments other + * than a possible + * exception are given to the completion callback. + * @since v0.1.96 + */ + export function fdatasync(fd: number, callback: NoParamCallback): void; + export namespace fdatasync { + /** + * Asynchronous fdatasync(2) - synchronize a file's in-core state with storage device. + * @param fd A file descriptor. + */ + function __promisify__(fd: number): Promise; + } + /** + * Forces all currently queued I/O operations associated with the file to the + * operating system's synchronized I/O completion state. Refer to the POSIX [`fdatasync(2)`](http://man7.org/linux/man-pages/man2/fdatasync.2.html) documentation for details. Returns `undefined`. + * @since v0.1.96 + */ + export function fdatasyncSync(fd: number): void; + /** + * Asynchronously copies `src` to `dest`. By default, `dest` is overwritten if it + * already exists. No arguments other than a possible exception are given to the + * callback function. Node.js makes no guarantees about the atomicity of the copy + * operation. If an error occurs after the destination file has been opened for + * writing, Node.js will attempt to remove the destination. + * + * `mode` is an optional integer that specifies the behavior + * of the copy operation. It is possible to create a mask consisting of the bitwise + * OR of two or more values (e.g.`fs.constants.COPYFILE_EXCL | fs.constants.COPYFILE_FICLONE`). + * + * * `fs.constants.COPYFILE_EXCL`: The copy operation will fail if `dest` already + * exists. + * * `fs.constants.COPYFILE_FICLONE`: The copy operation will attempt to create a + * copy-on-write reflink. If the platform does not support copy-on-write, then a + * fallback copy mechanism is used. + * * `fs.constants.COPYFILE_FICLONE_FORCE`: The copy operation will attempt to + * create a copy-on-write reflink. If the platform does not support + * copy-on-write, then the operation will fail. + * + * ```js + * import { copyFile, constants } from 'node:fs'; + * + * function callback(err) { + * if (err) throw err; + * console.log('source.txt was copied to destination.txt'); + * } + * + * // destination.txt will be created or overwritten by default. + * copyFile('source.txt', 'destination.txt', callback); + * + * // By using COPYFILE_EXCL, the operation will fail if destination.txt exists. + * copyFile('source.txt', 'destination.txt', constants.COPYFILE_EXCL, callback); + * ``` + * @since v8.5.0 + * @param src source filename to copy + * @param dest destination filename of the copy operation + * @param [mode=0] modifiers for copy operation. + */ + export function copyFile(src: PathLike, dest: PathLike, callback: NoParamCallback): void; + export function copyFile(src: PathLike, dest: PathLike, mode: number, callback: NoParamCallback): void; + export namespace copyFile { + function __promisify__(src: PathLike, dst: PathLike, mode?: number): Promise; + } + /** + * Synchronously copies `src` to `dest`. By default, `dest` is overwritten if it + * already exists. Returns `undefined`. Node.js makes no guarantees about the + * atomicity of the copy operation. If an error occurs after the destination file + * has been opened for writing, Node.js will attempt to remove the destination. + * + * `mode` is an optional integer that specifies the behavior + * of the copy operation. It is possible to create a mask consisting of the bitwise + * OR of two or more values (e.g.`fs.constants.COPYFILE_EXCL | fs.constants.COPYFILE_FICLONE`). + * + * * `fs.constants.COPYFILE_EXCL`: The copy operation will fail if `dest` already + * exists. + * * `fs.constants.COPYFILE_FICLONE`: The copy operation will attempt to create a + * copy-on-write reflink. If the platform does not support copy-on-write, then a + * fallback copy mechanism is used. + * * `fs.constants.COPYFILE_FICLONE_FORCE`: The copy operation will attempt to + * create a copy-on-write reflink. If the platform does not support + * copy-on-write, then the operation will fail. + * + * ```js + * import { copyFileSync, constants } from 'node:fs'; + * + * // destination.txt will be created or overwritten by default. + * copyFileSync('source.txt', 'destination.txt'); + * console.log('source.txt was copied to destination.txt'); + * + * // By using COPYFILE_EXCL, the operation will fail if destination.txt exists. + * copyFileSync('source.txt', 'destination.txt', constants.COPYFILE_EXCL); + * ``` + * @since v8.5.0 + * @param src source filename to copy + * @param dest destination filename of the copy operation + * @param [mode=0] modifiers for copy operation. + */ + export function copyFileSync(src: PathLike, dest: PathLike, mode?: number): void; + /** + * Write an array of `ArrayBufferView`s to the file specified by `fd` using `writev()`. + * + * `position` is the offset from the beginning of the file where this data + * should be written. If `typeof position !== 'number'`, the data will be written + * at the current position. + * + * The callback will be given three arguments: `err`, `bytesWritten`, and `buffers`. `bytesWritten` is how many bytes were written from `buffers`. + * + * If this method is `util.promisify()` ed, it returns a promise for an `Object` with `bytesWritten` and `buffers` properties. + * + * It is unsafe to use `fs.writev()` multiple times on the same file without + * waiting for the callback. For this scenario, use {@link createWriteStream}. + * + * On Linux, positional writes don't work when the file is opened in append mode. + * The kernel ignores the position argument and always appends the data to + * the end of the file. + * @since v12.9.0 + * @param [position='null'] + */ + export function writev( + fd: number, + buffers: readonly NodeJS.ArrayBufferView[], + cb: (err: NodeJS.ErrnoException | null, bytesWritten: number, buffers: NodeJS.ArrayBufferView[]) => void, + ): void; + export function writev( + fd: number, + buffers: readonly NodeJS.ArrayBufferView[], + position: number, + cb: (err: NodeJS.ErrnoException | null, bytesWritten: number, buffers: NodeJS.ArrayBufferView[]) => void, + ): void; + export interface WriteVResult { + bytesWritten: number; + buffers: NodeJS.ArrayBufferView[]; + } + export namespace writev { + function __promisify__( + fd: number, + buffers: readonly NodeJS.ArrayBufferView[], + position?: number, + ): Promise; + } + /** + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link writev}. + * @since v12.9.0 + * @param [position='null'] + * @return The number of bytes written. + */ + export function writevSync(fd: number, buffers: readonly NodeJS.ArrayBufferView[], position?: number): number; + /** + * Read from a file specified by `fd` and write to an array of `ArrayBufferView`s + * using `readv()`. + * + * `position` is the offset from the beginning of the file from where data + * should be read. If `typeof position !== 'number'`, the data will be read + * from the current position. + * + * The callback will be given three arguments: `err`, `bytesRead`, and `buffers`. `bytesRead` is how many bytes were read from the file. + * + * If this method is invoked as its `util.promisify()` ed version, it returns + * a promise for an `Object` with `bytesRead` and `buffers` properties. + * @since v13.13.0, v12.17.0 + * @param [position='null'] + */ + export function readv( + fd: number, + buffers: readonly NodeJS.ArrayBufferView[], + cb: (err: NodeJS.ErrnoException | null, bytesRead: number, buffers: NodeJS.ArrayBufferView[]) => void, + ): void; + export function readv( + fd: number, + buffers: readonly NodeJS.ArrayBufferView[], + position: number, + cb: (err: NodeJS.ErrnoException | null, bytesRead: number, buffers: NodeJS.ArrayBufferView[]) => void, + ): void; + export interface ReadVResult { + bytesRead: number; + buffers: NodeJS.ArrayBufferView[]; + } + export namespace readv { + function __promisify__( + fd: number, + buffers: readonly NodeJS.ArrayBufferView[], + position?: number, + ): Promise; + } + /** + * For detailed information, see the documentation of the asynchronous version of + * this API: {@link readv}. + * @since v13.13.0, v12.17.0 + * @param [position='null'] + * @return The number of bytes read. + */ + export function readvSync(fd: number, buffers: readonly NodeJS.ArrayBufferView[], position?: number): number; + + export interface OpenAsBlobOptions { + /** + * An optional mime type for the blob. + * + * @default 'undefined' + */ + type?: string | undefined; + } + + /** + * Returns a `Blob` whose data is backed by the given file. + * + * The file must not be modified after the `Blob` is created. Any modifications + * will cause reading the `Blob` data to fail with a `DOMException` error. + * Synchronous stat operations on the file when the `Blob` is created, and before + * each read in order to detect whether the file data has been modified on disk. + * + * ```js + * import { openAsBlob } from 'node:fs'; + * + * const blob = await openAsBlob('the.file.txt'); + * const ab = await blob.arrayBuffer(); + * blob.stream(); + * ``` + * @since v19.8.0 + * @experimental + */ + export function openAsBlob(path: PathLike, options?: OpenAsBlobOptions): Promise; + + export interface OpenDirOptions { + /** + * @default 'utf8' + */ + encoding?: BufferEncoding | undefined; + /** + * Number of directory entries that are buffered + * internally when reading from the directory. Higher values lead to better + * performance but higher memory usage. + * @default 32 + */ + bufferSize?: number | undefined; + /** + * @default false + */ + recursive?: boolean; + } + /** + * Synchronously open a directory. See [`opendir(3)`](http://man7.org/linux/man-pages/man3/opendir.3.html). + * + * Creates an `fs.Dir`, which contains all further functions for reading from + * and cleaning up the directory. + * + * The `encoding` option sets the encoding for the `path` while opening the + * directory and subsequent read operations. + * @since v12.12.0 + */ + export function opendirSync(path: PathLike, options?: OpenDirOptions): Dir; + /** + * Asynchronously open a directory. See the POSIX [`opendir(3)`](http://man7.org/linux/man-pages/man3/opendir.3.html) documentation for + * more details. + * + * Creates an `fs.Dir`, which contains all further functions for reading from + * and cleaning up the directory. + * + * The `encoding` option sets the encoding for the `path` while opening the + * directory and subsequent read operations. + * @since v12.12.0 + */ + export function opendir(path: PathLike, cb: (err: NodeJS.ErrnoException | null, dir: Dir) => void): void; + export function opendir( + path: PathLike, + options: OpenDirOptions, + cb: (err: NodeJS.ErrnoException | null, dir: Dir) => void, + ): void; + export namespace opendir { + function __promisify__(path: PathLike, options?: OpenDirOptions): Promise; + } + export interface BigIntStats extends StatsBase { + atimeNs: bigint; + mtimeNs: bigint; + ctimeNs: bigint; + birthtimeNs: bigint; + } + export interface BigIntOptions { + bigint: true; + } + export interface StatOptions { + bigint?: boolean | undefined; + } + export interface StatSyncOptions extends StatOptions { + throwIfNoEntry?: boolean | undefined; + } + interface CopyOptionsBase { + /** + * Dereference symlinks + * @default false + */ + dereference?: boolean; + /** + * When `force` is `false`, and the destination + * exists, throw an error. + * @default false + */ + errorOnExist?: boolean; + /** + * Overwrite existing file or directory. _The copy + * operation will ignore errors if you set this to false and the destination + * exists. Use the `errorOnExist` option to change this behavior. + * @default true + */ + force?: boolean; + /** + * Modifiers for copy operation. See `mode` flag of {@link copyFileSync()} + */ + mode?: number; + /** + * When `true` timestamps from `src` will + * be preserved. + * @default false + */ + preserveTimestamps?: boolean; + /** + * Copy directories recursively. + * @default false + */ + recursive?: boolean; + /** + * When true, path resolution for symlinks will be skipped + * @default false + */ + verbatimSymlinks?: boolean; + } + export interface CopyOptions extends CopyOptionsBase { + /** + * Function to filter copied files/directories. Return + * `true` to copy the item, `false` to ignore it. + */ + filter?(source: string, destination: string): boolean | Promise; + } + export interface CopySyncOptions extends CopyOptionsBase { + /** + * Function to filter copied files/directories. Return + * `true` to copy the item, `false` to ignore it. + */ + filter?(source: string, destination: string): boolean; + } + /** + * Asynchronously copies the entire directory structure from `src` to `dest`, + * including subdirectories and files. + * + * When copying a directory to another directory, globs are not supported and + * behavior is similar to `cp dir1/ dir2/`. + * @since v16.7.0 + * @experimental + * @param src source path to copy. + * @param dest destination path to copy to. + */ + export function cp( + source: string | URL, + destination: string | URL, + callback: (err: NodeJS.ErrnoException | null) => void, + ): void; + export function cp( + source: string | URL, + destination: string | URL, + opts: CopyOptions, + callback: (err: NodeJS.ErrnoException | null) => void, + ): void; + /** + * Synchronously copies the entire directory structure from `src` to `dest`, + * including subdirectories and files. + * + * When copying a directory to another directory, globs are not supported and + * behavior is similar to `cp dir1/ dir2/`. + * @since v16.7.0 + * @experimental + * @param src source path to copy. + * @param dest destination path to copy to. + */ + export function cpSync(source: string | URL, destination: string | URL, opts?: CopySyncOptions): void; +} +declare module "node:fs" { + export * from "fs"; +} diff --git a/node_modules/@types/node/fs/promises.d.ts b/node_modules/@types/node/fs/promises.d.ts new file mode 100644 index 0000000..3199063 --- /dev/null +++ b/node_modules/@types/node/fs/promises.d.ts @@ -0,0 +1,1245 @@ +/** + * The `fs/promises` API provides asynchronous file system methods that return + * promises. + * + * The promise APIs use the underlying Node.js threadpool to perform file + * system operations off the event loop thread. These operations are not + * synchronized or threadsafe. Care must be taken when performing multiple + * concurrent modifications on the same file or data corruption may occur. + * @since v10.0.0 + */ +declare module "fs/promises" { + import { Abortable } from "node:events"; + import { Stream } from "node:stream"; + import { ReadableStream } from "node:stream/web"; + import { + BigIntStats, + BigIntStatsFs, + BufferEncodingOption, + constants as fsConstants, + CopyOptions, + Dir, + Dirent, + MakeDirectoryOptions, + Mode, + ObjectEncodingOptions, + OpenDirOptions, + OpenMode, + PathLike, + ReadStream, + ReadVResult, + RmDirOptions, + RmOptions, + StatFsOptions, + StatOptions, + Stats, + StatsFs, + TimeLike, + WatchEventType, + WatchOptions, + WriteStream, + WriteVResult, + } from "node:fs"; + import { Interface as ReadlineInterface } from "node:readline"; + interface FileChangeInfo { + eventType: WatchEventType; + filename: T | null; + } + interface FlagAndOpenMode { + mode?: Mode | undefined; + flag?: OpenMode | undefined; + } + interface FileReadResult { + bytesRead: number; + buffer: T; + } + interface FileReadOptions { + /** + * @default `Buffer.alloc(0xffff)` + */ + buffer?: T; + /** + * @default 0 + */ + offset?: number | null; + /** + * @default `buffer.byteLength` + */ + length?: number | null; + position?: number | null; + } + interface CreateReadStreamOptions { + encoding?: BufferEncoding | null | undefined; + autoClose?: boolean | undefined; + emitClose?: boolean | undefined; + start?: number | undefined; + end?: number | undefined; + highWaterMark?: number | undefined; + } + interface CreateWriteStreamOptions { + encoding?: BufferEncoding | null | undefined; + autoClose?: boolean | undefined; + emitClose?: boolean | undefined; + start?: number | undefined; + highWaterMark?: number | undefined; + flush?: boolean | undefined; + } + interface ReadableWebStreamOptions { + /** + * Whether to open a normal or a `'bytes'` stream. + * @since v20.0.0 + */ + type?: "bytes" | undefined; + } + // TODO: Add `EventEmitter` close + interface FileHandle { + /** + * The numeric file descriptor managed by the {FileHandle} object. + * @since v10.0.0 + */ + readonly fd: number; + /** + * Alias of `filehandle.writeFile()`. + * + * When operating on file handles, the mode cannot be changed from what it was set + * to with `fsPromises.open()`. Therefore, this is equivalent to `filehandle.writeFile()`. + * @since v10.0.0 + * @return Fulfills with `undefined` upon success. + */ + appendFile( + data: string | Uint8Array, + options?: + | (ObjectEncodingOptions & FlagAndOpenMode & { flush?: boolean | undefined }) + | BufferEncoding + | null, + ): Promise; + /** + * Changes the ownership of the file. A wrapper for [`chown(2)`](http://man7.org/linux/man-pages/man2/chown.2.html). + * @since v10.0.0 + * @param uid The file's new owner's user id. + * @param gid The file's new group's group id. + * @return Fulfills with `undefined` upon success. + */ + chown(uid: number, gid: number): Promise; + /** + * Modifies the permissions on the file. See [`chmod(2)`](http://man7.org/linux/man-pages/man2/chmod.2.html). + * @since v10.0.0 + * @param mode the file mode bit mask. + * @return Fulfills with `undefined` upon success. + */ + chmod(mode: Mode): Promise; + /** + * Unlike the 16 KiB default `highWaterMark` for a `stream.Readable`, the stream + * returned by this method has a default `highWaterMark` of 64 KiB. + * + * `options` can include `start` and `end` values to read a range of bytes from + * the file instead of the entire file. Both `start` and `end` are inclusive and + * start counting at 0, allowed values are in the + * \[0, [`Number.MAX_SAFE_INTEGER`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/MAX_SAFE_INTEGER)\] range. If `start` is + * omitted or `undefined`, `filehandle.createReadStream()` reads sequentially from + * the current file position. The `encoding` can be any one of those accepted by `Buffer`. + * + * If the `FileHandle` points to a character device that only supports blocking + * reads (such as keyboard or sound card), read operations do not finish until data + * is available. This can prevent the process from exiting and the stream from + * closing naturally. + * + * By default, the stream will emit a `'close'` event after it has been + * destroyed. Set the `emitClose` option to `false` to change this behavior. + * + * ```js + * import { open } from 'node:fs/promises'; + * + * const fd = await open('/dev/input/event0'); + * // Create a stream from some character device. + * const stream = fd.createReadStream(); + * setTimeout(() => { + * stream.close(); // This may not close the stream. + * // Artificially marking end-of-stream, as if the underlying resource had + * // indicated end-of-file by itself, allows the stream to close. + * // This does not cancel pending read operations, and if there is such an + * // operation, the process may still not be able to exit successfully + * // until it finishes. + * stream.push(null); + * stream.read(0); + * }, 100); + * ``` + * + * If `autoClose` is false, then the file descriptor won't be closed, even if + * there's an error. It is the application's responsibility to close it and make + * sure there's no file descriptor leak. If `autoClose` is set to true (default + * behavior), on `'error'` or `'end'` the file descriptor will be closed + * automatically. + * + * An example to read the last 10 bytes of a file which is 100 bytes long: + * + * ```js + * import { open } from 'node:fs/promises'; + * + * const fd = await open('sample.txt'); + * fd.createReadStream({ start: 90, end: 99 }); + * ``` + * @since v16.11.0 + */ + createReadStream(options?: CreateReadStreamOptions): ReadStream; + /** + * `options` may also include a `start` option to allow writing data at some + * position past the beginning of the file, allowed values are in the + * \[0, [`Number.MAX_SAFE_INTEGER`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/MAX_SAFE_INTEGER)\] range. Modifying a file rather than + * replacing it may require the `flags` `open` option to be set to `r+` rather than + * the default `r`. The `encoding` can be any one of those accepted by `Buffer`. + * + * If `autoClose` is set to true (default behavior) on `'error'` or `'finish'` the file descriptor will be closed automatically. If `autoClose` is false, + * then the file descriptor won't be closed, even if there's an error. + * It is the application's responsibility to close it and make sure there's no + * file descriptor leak. + * + * By default, the stream will emit a `'close'` event after it has been + * destroyed. Set the `emitClose` option to `false` to change this behavior. + * @since v16.11.0 + */ + createWriteStream(options?: CreateWriteStreamOptions): WriteStream; + /** + * Forces all currently queued I/O operations associated with the file to the + * operating system's synchronized I/O completion state. Refer to the POSIX [`fdatasync(2)`](http://man7.org/linux/man-pages/man2/fdatasync.2.html) documentation for details. + * + * Unlike `filehandle.sync` this method does not flush modified metadata. + * @since v10.0.0 + * @return Fulfills with `undefined` upon success. + */ + datasync(): Promise; + /** + * Request that all data for the open file descriptor is flushed to the storage + * device. The specific implementation is operating system and device specific. + * Refer to the POSIX [`fsync(2)`](http://man7.org/linux/man-pages/man2/fsync.2.html) documentation for more detail. + * @since v10.0.0 + * @return Fulfills with `undefined` upon success. + */ + sync(): Promise; + /** + * Reads data from the file and stores that in the given buffer. + * + * If the file is not modified concurrently, the end-of-file is reached when the + * number of bytes read is zero. + * @since v10.0.0 + * @param buffer A buffer that will be filled with the file data read. + * @param offset The location in the buffer at which to start filling. + * @param length The number of bytes to read. + * @param position The location where to begin reading data from the file. If `null`, data will be read from the current file position, and the position will be updated. If `position` is an + * integer, the current file position will remain unchanged. + * @return Fulfills upon success with an object with two properties: + */ + read( + buffer: T, + offset?: number | null, + length?: number | null, + position?: number | null, + ): Promise>; + read(options?: FileReadOptions): Promise>; + /** + * Returns a `ReadableStream` that may be used to read the files data. + * + * An error will be thrown if this method is called more than once or is called + * after the `FileHandle` is closed or closing. + * + * ```js + * import { + * open, + * } from 'node:fs/promises'; + * + * const file = await open('./some/file/to/read'); + * + * for await (const chunk of file.readableWebStream()) + * console.log(chunk); + * + * await file.close(); + * ``` + * + * While the `ReadableStream` will read the file to completion, it will not + * close the `FileHandle` automatically. User code must still call the`fileHandle.close()` method. + * @since v17.0.0 + * @experimental + */ + readableWebStream(options?: ReadableWebStreamOptions): ReadableStream; + /** + * Asynchronously reads the entire contents of a file. + * + * If `options` is a string, then it specifies the `encoding`. + * + * The `FileHandle` has to support reading. + * + * If one or more `filehandle.read()` calls are made on a file handle and then a `filehandle.readFile()` call is made, the data will be read from the current + * position till the end of the file. It doesn't always read from the beginning + * of the file. + * @since v10.0.0 + * @return Fulfills upon a successful read with the contents of the file. If no encoding is specified (using `options.encoding`), the data is returned as a {Buffer} object. Otherwise, the + * data will be a string. + */ + readFile( + options?: { + encoding?: null | undefined; + flag?: OpenMode | undefined; + } | null, + ): Promise; + /** + * Asynchronously reads the entire contents of a file. The underlying file will _not_ be closed automatically. + * The `FileHandle` must have been opened for reading. + * @param options An object that may contain an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + readFile( + options: + | { + encoding: BufferEncoding; + flag?: OpenMode | undefined; + } + | BufferEncoding, + ): Promise; + /** + * Asynchronously reads the entire contents of a file. The underlying file will _not_ be closed automatically. + * The `FileHandle` must have been opened for reading. + * @param options An object that may contain an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + readFile( + options?: + | (ObjectEncodingOptions & { + flag?: OpenMode | undefined; + }) + | BufferEncoding + | null, + ): Promise; + /** + * Convenience method to create a `readline` interface and stream over the file. + * See `filehandle.createReadStream()` for the options. + * + * ```js + * import { open } from 'node:fs/promises'; + * + * const file = await open('./some/file/to/read'); + * + * for await (const line of file.readLines()) { + * console.log(line); + * } + * ``` + * @since v18.11.0 + */ + readLines(options?: CreateReadStreamOptions): ReadlineInterface; + /** + * @since v10.0.0 + * @return Fulfills with an {fs.Stats} for the file. + */ + stat( + opts?: StatOptions & { + bigint?: false | undefined; + }, + ): Promise; + stat( + opts: StatOptions & { + bigint: true; + }, + ): Promise; + stat(opts?: StatOptions): Promise; + /** + * Truncates the file. + * + * If the file was larger than `len` bytes, only the first `len` bytes will be + * retained in the file. + * + * The following example retains only the first four bytes of the file: + * + * ```js + * import { open } from 'node:fs/promises'; + * + * let filehandle = null; + * try { + * filehandle = await open('temp.txt', 'r+'); + * await filehandle.truncate(4); + * } finally { + * await filehandle?.close(); + * } + * ``` + * + * If the file previously was shorter than `len` bytes, it is extended, and the + * extended part is filled with null bytes (`'\0'`): + * + * If `len` is negative then `0` will be used. + * @since v10.0.0 + * @param [len=0] + * @return Fulfills with `undefined` upon success. + */ + truncate(len?: number): Promise; + /** + * Change the file system timestamps of the object referenced by the `FileHandle` then fulfills the promise with no arguments upon success. + * @since v10.0.0 + */ + utimes(atime: TimeLike, mtime: TimeLike): Promise; + /** + * Asynchronously writes data to a file, replacing the file if it already exists. `data` can be a string, a buffer, an + * [AsyncIterable](https://tc39.github.io/ecma262/#sec-asynciterable-interface), or an + * [Iterable](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#The_iterable_protocol) object. + * The promise is fulfilled with no arguments upon success. + * + * If `options` is a string, then it specifies the `encoding`. + * + * The `FileHandle` has to support writing. + * + * It is unsafe to use `filehandle.writeFile()` multiple times on the same file + * without waiting for the promise to be fulfilled (or rejected). + * + * If one or more `filehandle.write()` calls are made on a file handle and then a`filehandle.writeFile()` call is made, the data will be written from the + * current position till the end of the file. It doesn't always write from the + * beginning of the file. + * @since v10.0.0 + */ + writeFile( + data: string | Uint8Array, + options?: + | (ObjectEncodingOptions & FlagAndOpenMode & Abortable & { flush?: boolean | undefined }) + | BufferEncoding + | null, + ): Promise; + /** + * Write `buffer` to the file. + * + * The promise is fulfilled with an object containing two properties: + * + * It is unsafe to use `filehandle.write()` multiple times on the same file + * without waiting for the promise to be fulfilled (or rejected). For this + * scenario, use `filehandle.createWriteStream()`. + * + * On Linux, positional writes do not work when the file is opened in append mode. + * The kernel ignores the position argument and always appends the data to + * the end of the file. + * @since v10.0.0 + * @param offset The start position from within `buffer` where the data to write begins. + * @param [length=buffer.byteLength - offset] The number of bytes from `buffer` to write. + * @param [position='null'] The offset from the beginning of the file where the data from `buffer` should be written. If `position` is not a `number`, the data will be written at the current + * position. See the POSIX pwrite(2) documentation for more detail. + */ + write( + buffer: TBuffer, + offset?: number | null, + length?: number | null, + position?: number | null, + ): Promise<{ + bytesWritten: number; + buffer: TBuffer; + }>; + write( + data: string, + position?: number | null, + encoding?: BufferEncoding | null, + ): Promise<{ + bytesWritten: number; + buffer: string; + }>; + /** + * Write an array of [ArrayBufferView](https://developer.mozilla.org/en-US/docs/Web/API/ArrayBufferView) s to the file. + * + * The promise is fulfilled with an object containing a two properties: + * + * It is unsafe to call `writev()` multiple times on the same file without waiting + * for the promise to be fulfilled (or rejected). + * + * On Linux, positional writes don't work when the file is opened in append mode. + * The kernel ignores the position argument and always appends the data to + * the end of the file. + * @since v12.9.0 + * @param [position='null'] The offset from the beginning of the file where the data from `buffers` should be written. If `position` is not a `number`, the data will be written at the current + * position. + */ + writev(buffers: readonly NodeJS.ArrayBufferView[], position?: number): Promise; + /** + * Read from a file and write to an array of [ArrayBufferView](https://developer.mozilla.org/en-US/docs/Web/API/ArrayBufferView) s + * @since v13.13.0, v12.17.0 + * @param [position='null'] The offset from the beginning of the file where the data should be read from. If `position` is not a `number`, the data will be read from the current position. + * @return Fulfills upon success an object containing two properties: + */ + readv(buffers: readonly NodeJS.ArrayBufferView[], position?: number): Promise; + /** + * Closes the file handle after waiting for any pending operation on the handle to + * complete. + * + * ```js + * import { open } from 'node:fs/promises'; + * + * let filehandle; + * try { + * filehandle = await open('thefile.txt', 'r'); + * } finally { + * await filehandle?.close(); + * } + * ``` + * @since v10.0.0 + * @return Fulfills with `undefined` upon success. + */ + close(): Promise; + /** + * An alias for {@link FileHandle.close()}. + * @since v20.4.0 + */ + [Symbol.asyncDispose](): Promise; + } + const constants: typeof fsConstants; + /** + * Tests a user's permissions for the file or directory specified by `path`. + * The `mode` argument is an optional integer that specifies the accessibility + * checks to be performed. `mode` should be either the value `fs.constants.F_OK` or a mask consisting of the bitwise OR of any of `fs.constants.R_OK`, `fs.constants.W_OK`, and `fs.constants.X_OK` + * (e.g.`fs.constants.W_OK | fs.constants.R_OK`). Check `File access constants` for + * possible values of `mode`. + * + * If the accessibility check is successful, the promise is fulfilled with no + * value. If any of the accessibility checks fail, the promise is rejected + * with an [Error](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error) object. The following example checks if the file`/etc/passwd` can be read and + * written by the current process. + * + * ```js + * import { access, constants } from 'node:fs/promises'; + * + * try { + * await access('/etc/passwd', constants.R_OK | constants.W_OK); + * console.log('can access'); + * } catch { + * console.error('cannot access'); + * } + * ``` + * + * Using `fsPromises.access()` to check for the accessibility of a file before + * calling `fsPromises.open()` is not recommended. Doing so introduces a race + * condition, since other processes may change the file's state between the two + * calls. Instead, user code should open/read/write the file directly and handle + * the error raised if the file is not accessible. + * @since v10.0.0 + * @param [mode=fs.constants.F_OK] + * @return Fulfills with `undefined` upon success. + */ + function access(path: PathLike, mode?: number): Promise; + /** + * Asynchronously copies `src` to `dest`. By default, `dest` is overwritten if it + * already exists. + * + * No guarantees are made about the atomicity of the copy operation. If an + * error occurs after the destination file has been opened for writing, an attempt + * will be made to remove the destination. + * + * ```js + * import { copyFile, constants } from 'node:fs/promises'; + * + * try { + * await copyFile('source.txt', 'destination.txt'); + * console.log('source.txt was copied to destination.txt'); + * } catch { + * console.error('The file could not be copied'); + * } + * + * // By using COPYFILE_EXCL, the operation will fail if destination.txt exists. + * try { + * await copyFile('source.txt', 'destination.txt', constants.COPYFILE_EXCL); + * console.log('source.txt was copied to destination.txt'); + * } catch { + * console.error('The file could not be copied'); + * } + * ``` + * @since v10.0.0 + * @param src source filename to copy + * @param dest destination filename of the copy operation + * @param [mode=0] Optional modifiers that specify the behavior of the copy operation. It is possible to create a mask consisting of the bitwise OR of two or more values (e.g. + * `fs.constants.COPYFILE_EXCL | fs.constants.COPYFILE_FICLONE`) + * @return Fulfills with `undefined` upon success. + */ + function copyFile(src: PathLike, dest: PathLike, mode?: number): Promise; + /** + * Opens a `FileHandle`. + * + * Refer to the POSIX [`open(2)`](http://man7.org/linux/man-pages/man2/open.2.html) documentation for more detail. + * + * Some characters (`< > : " / \ | ? *`) are reserved under Windows as documented + * by [Naming Files, Paths, and Namespaces](https://docs.microsoft.com/en-us/windows/desktop/FileIO/naming-a-file). Under NTFS, if the filename contains + * a colon, Node.js will open a file system stream, as described by [this MSDN page](https://docs.microsoft.com/en-us/windows/desktop/FileIO/using-streams). + * @since v10.0.0 + * @param [flags='r'] See `support of file system `flags``. + * @param [mode=0o666] Sets the file mode (permission and sticky bits) if the file is created. + * @return Fulfills with a {FileHandle} object. + */ + function open(path: PathLike, flags?: string | number, mode?: Mode): Promise; + /** + * Renames `oldPath` to `newPath`. + * @since v10.0.0 + * @return Fulfills with `undefined` upon success. + */ + function rename(oldPath: PathLike, newPath: PathLike): Promise; + /** + * Truncates (shortens or extends the length) of the content at `path` to `len` bytes. + * @since v10.0.0 + * @param [len=0] + * @return Fulfills with `undefined` upon success. + */ + function truncate(path: PathLike, len?: number): Promise; + /** + * Removes the directory identified by `path`. + * + * Using `fsPromises.rmdir()` on a file (not a directory) results in the + * promise being rejected with an `ENOENT` error on Windows and an `ENOTDIR` error on POSIX. + * + * To get a behavior similar to the `rm -rf` Unix command, use `fsPromises.rm()` with options `{ recursive: true, force: true }`. + * @since v10.0.0 + * @return Fulfills with `undefined` upon success. + */ + function rmdir(path: PathLike, options?: RmDirOptions): Promise; + /** + * Removes files and directories (modeled on the standard POSIX `rm` utility). + * @since v14.14.0 + * @return Fulfills with `undefined` upon success. + */ + function rm(path: PathLike, options?: RmOptions): Promise; + /** + * Asynchronously creates a directory. + * + * The optional `options` argument can be an integer specifying `mode` (permission + * and sticky bits), or an object with a `mode` property and a `recursive` property indicating whether parent directories should be created. Calling `fsPromises.mkdir()` when `path` is a directory + * that exists results in a + * rejection only when `recursive` is false. + * + * ```js + * import { mkdir } from 'node:fs/promises'; + * + * try { + * const projectFolder = new URL('./test/project/', import.meta.url); + * const createDir = await mkdir(projectFolder, { recursive: true }); + * + * console.log(`created ${createDir}`); + * } catch (err) { + * console.error(err.message); + * } + * ``` + * @since v10.0.0 + * @return Upon success, fulfills with `undefined` if `recursive` is `false`, or the first directory path created if `recursive` is `true`. + */ + function mkdir( + path: PathLike, + options: MakeDirectoryOptions & { + recursive: true; + }, + ): Promise; + /** + * Asynchronous mkdir(2) - create a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders + * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. + */ + function mkdir( + path: PathLike, + options?: + | Mode + | (MakeDirectoryOptions & { + recursive?: false | undefined; + }) + | null, + ): Promise; + /** + * Asynchronous mkdir(2) - create a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options Either the file mode, or an object optionally specifying the file mode and whether parent folders + * should be created. If a string is passed, it is parsed as an octal integer. If not specified, defaults to `0o777`. + */ + function mkdir(path: PathLike, options?: Mode | MakeDirectoryOptions | null): Promise; + /** + * Reads the contents of a directory. + * + * The optional `options` argument can be a string specifying an encoding, or an + * object with an `encoding` property specifying the character encoding to use for + * the filenames. If the `encoding` is set to `'buffer'`, the filenames returned + * will be passed as `Buffer` objects. + * + * If `options.withFileTypes` is set to `true`, the returned array will contain `fs.Dirent` objects. + * + * ```js + * import { readdir } from 'node:fs/promises'; + * + * try { + * const files = await readdir(path); + * for (const file of files) + * console.log(file); + * } catch (err) { + * console.error(err); + * } + * ``` + * @since v10.0.0 + * @return Fulfills with an array of the names of the files in the directory excluding `'.'` and `'..'`. + */ + function readdir( + path: PathLike, + options?: + | (ObjectEncodingOptions & { + withFileTypes?: false | undefined; + recursive?: boolean | undefined; + }) + | BufferEncoding + | null, + ): Promise; + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function readdir( + path: PathLike, + options: + | { + encoding: "buffer"; + withFileTypes?: false | undefined; + recursive?: boolean | undefined; + } + | "buffer", + ): Promise; + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function readdir( + path: PathLike, + options?: + | (ObjectEncodingOptions & { + withFileTypes?: false | undefined; + recursive?: boolean | undefined; + }) + | BufferEncoding + | null, + ): Promise; + /** + * Asynchronous readdir(3) - read a directory. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options If called with `withFileTypes: true` the result data will be an array of Dirent. + */ + function readdir( + path: PathLike, + options: ObjectEncodingOptions & { + withFileTypes: true; + recursive?: boolean | undefined; + }, + ): Promise; + /** + * Reads the contents of the symbolic link referred to by `path`. See the POSIX [`readlink(2)`](http://man7.org/linux/man-pages/man2/readlink.2.html) documentation for more detail. The promise is + * fulfilled with the`linkString` upon success. + * + * The optional `options` argument can be a string specifying an encoding, or an + * object with an `encoding` property specifying the character encoding to use for + * the link path returned. If the `encoding` is set to `'buffer'`, the link path + * returned will be passed as a `Buffer` object. + * @since v10.0.0 + * @return Fulfills with the `linkString` upon success. + */ + function readlink(path: PathLike, options?: ObjectEncodingOptions | BufferEncoding | null): Promise; + /** + * Asynchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function readlink(path: PathLike, options: BufferEncodingOption): Promise; + /** + * Asynchronous readlink(2) - read value of a symbolic link. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function readlink(path: PathLike, options?: ObjectEncodingOptions | string | null): Promise; + /** + * Creates a symbolic link. + * + * The `type` argument is only used on Windows platforms and can be one of `'dir'`, `'file'`, or `'junction'`. If the `type` argument is not a string, Node.js will + * autodetect `target` type and use `'file'` or `'dir'`. If the `target` does not + * exist, `'file'` will be used. Windows junction points require the destination + * path to be absolute. When using `'junction'`, the `target` argument will + * automatically be normalized to absolute path. Junction points on NTFS volumes + * can only point to directories. + * @since v10.0.0 + * @param [type='null'] + * @return Fulfills with `undefined` upon success. + */ + function symlink(target: PathLike, path: PathLike, type?: string | null): Promise; + /** + * Equivalent to `fsPromises.stat()` unless `path` refers to a symbolic link, + * in which case the link itself is stat-ed, not the file that it refers to. + * Refer to the POSIX [`lstat(2)`](http://man7.org/linux/man-pages/man2/lstat.2.html) document for more detail. + * @since v10.0.0 + * @return Fulfills with the {fs.Stats} object for the given symbolic link `path`. + */ + function lstat( + path: PathLike, + opts?: StatOptions & { + bigint?: false | undefined; + }, + ): Promise; + function lstat( + path: PathLike, + opts: StatOptions & { + bigint: true; + }, + ): Promise; + function lstat(path: PathLike, opts?: StatOptions): Promise; + /** + * @since v10.0.0 + * @return Fulfills with the {fs.Stats} object for the given `path`. + */ + function stat( + path: PathLike, + opts?: StatOptions & { + bigint?: false | undefined; + }, + ): Promise; + function stat( + path: PathLike, + opts: StatOptions & { + bigint: true; + }, + ): Promise; + function stat(path: PathLike, opts?: StatOptions): Promise; + /** + * @since v19.6.0, v18.15.0 + * @return Fulfills with the {fs.StatFs} object for the given `path`. + */ + function statfs( + path: PathLike, + opts?: StatFsOptions & { + bigint?: false | undefined; + }, + ): Promise; + function statfs( + path: PathLike, + opts: StatFsOptions & { + bigint: true; + }, + ): Promise; + function statfs(path: PathLike, opts?: StatFsOptions): Promise; + /** + * Creates a new link from the `existingPath` to the `newPath`. See the POSIX [`link(2)`](http://man7.org/linux/man-pages/man2/link.2.html) documentation for more detail. + * @since v10.0.0 + * @return Fulfills with `undefined` upon success. + */ + function link(existingPath: PathLike, newPath: PathLike): Promise; + /** + * If `path` refers to a symbolic link, then the link is removed without affecting + * the file or directory to which that link refers. If the `path` refers to a file + * path that is not a symbolic link, the file is deleted. See the POSIX [`unlink(2)`](http://man7.org/linux/man-pages/man2/unlink.2.html) documentation for more detail. + * @since v10.0.0 + * @return Fulfills with `undefined` upon success. + */ + function unlink(path: PathLike): Promise; + /** + * Changes the permissions of a file. + * @since v10.0.0 + * @return Fulfills with `undefined` upon success. + */ + function chmod(path: PathLike, mode: Mode): Promise; + /** + * Changes the permissions on a symbolic link. + * + * This method is only implemented on macOS. + * @deprecated Since v10.0.0 + * @return Fulfills with `undefined` upon success. + */ + function lchmod(path: PathLike, mode: Mode): Promise; + /** + * Changes the ownership on a symbolic link. + * @since v10.0.0 + * @return Fulfills with `undefined` upon success. + */ + function lchown(path: PathLike, uid: number, gid: number): Promise; + /** + * Changes the access and modification times of a file in the same way as `fsPromises.utimes()`, with the difference that if the path refers to a + * symbolic link, then the link is not dereferenced: instead, the timestamps of + * the symbolic link itself are changed. + * @since v14.5.0, v12.19.0 + * @return Fulfills with `undefined` upon success. + */ + function lutimes(path: PathLike, atime: TimeLike, mtime: TimeLike): Promise; + /** + * Changes the ownership of a file. + * @since v10.0.0 + * @return Fulfills with `undefined` upon success. + */ + function chown(path: PathLike, uid: number, gid: number): Promise; + /** + * Change the file system timestamps of the object referenced by `path`. + * + * The `atime` and `mtime` arguments follow these rules: + * + * * Values can be either numbers representing Unix epoch time, `Date`s, or a + * numeric string like `'123456789.0'`. + * * If the value can not be converted to a number, or is `NaN`, `Infinity`, or `-Infinity`, an `Error` will be thrown. + * @since v10.0.0 + * @return Fulfills with `undefined` upon success. + */ + function utimes(path: PathLike, atime: TimeLike, mtime: TimeLike): Promise; + /** + * Determines the actual location of `path` using the same semantics as the `fs.realpath.native()` function. + * + * Only paths that can be converted to UTF8 strings are supported. + * + * The optional `options` argument can be a string specifying an encoding, or an + * object with an `encoding` property specifying the character encoding to use for + * the path. If the `encoding` is set to `'buffer'`, the path returned will be + * passed as a `Buffer` object. + * + * On Linux, when Node.js is linked against musl libc, the procfs file system must + * be mounted on `/proc` in order for this function to work. Glibc does not have + * this restriction. + * @since v10.0.0 + * @return Fulfills with the resolved path upon success. + */ + function realpath(path: PathLike, options?: ObjectEncodingOptions | BufferEncoding | null): Promise; + /** + * Asynchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function realpath(path: PathLike, options: BufferEncodingOption): Promise; + /** + * Asynchronous realpath(3) - return the canonicalized absolute pathname. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function realpath( + path: PathLike, + options?: ObjectEncodingOptions | BufferEncoding | null, + ): Promise; + /** + * Creates a unique temporary directory. A unique directory name is generated by + * appending six random characters to the end of the provided `prefix`. Due to + * platform inconsistencies, avoid trailing `X` characters in `prefix`. Some + * platforms, notably the BSDs, can return more than six random characters, and + * replace trailing `X` characters in `prefix` with random characters. + * + * The optional `options` argument can be a string specifying an encoding, or an + * object with an `encoding` property specifying the character encoding to use. + * + * ```js + * import { mkdtemp } from 'node:fs/promises'; + * import { join } from 'node:path'; + * import { tmpdir } from 'node:os'; + * + * try { + * await mkdtemp(join(tmpdir(), 'foo-')); + * } catch (err) { + * console.error(err); + * } + * ``` + * + * The `fsPromises.mkdtemp()` method will append the six randomly selected + * characters directly to the `prefix` string. For instance, given a directory `/tmp`, if the intention is to create a temporary directory _within_ `/tmp`, the `prefix` must end with a trailing + * platform-specific path separator + * (`require('node:path').sep`). + * @since v10.0.0 + * @return Fulfills with a string containing the file system path of the newly created temporary directory. + */ + function mkdtemp(prefix: string, options?: ObjectEncodingOptions | BufferEncoding | null): Promise; + /** + * Asynchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required `prefix` to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function mkdtemp(prefix: string, options: BufferEncodingOption): Promise; + /** + * Asynchronously creates a unique temporary directory. + * Generates six random characters to be appended behind a required `prefix` to create a unique temporary directory. + * @param options The encoding (or an object specifying the encoding), used as the encoding of the result. If not provided, `'utf8'` is used. + */ + function mkdtemp(prefix: string, options?: ObjectEncodingOptions | BufferEncoding | null): Promise; + /** + * Asynchronously writes data to a file, replacing the file if it already exists. `data` can be a string, a buffer, an + * [AsyncIterable](https://tc39.github.io/ecma262/#sec-asynciterable-interface), or an + * [Iterable](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#The_iterable_protocol) object. + * + * The `encoding` option is ignored if `data` is a buffer. + * + * If `options` is a string, then it specifies the encoding. + * + * The `mode` option only affects the newly created file. See `fs.open()` for more details. + * + * Any specified `FileHandle` has to support writing. + * + * It is unsafe to use `fsPromises.writeFile()` multiple times on the same file + * without waiting for the promise to be settled. + * + * Similarly to `fsPromises.readFile` \- `fsPromises.writeFile` is a convenience + * method that performs multiple `write` calls internally to write the buffer + * passed to it. For performance sensitive code consider using `fs.createWriteStream()` or `filehandle.createWriteStream()`. + * + * It is possible to use an `AbortSignal` to cancel an `fsPromises.writeFile()`. + * Cancelation is "best effort", and some amount of data is likely still + * to be written. + * + * ```js + * import { writeFile } from 'node:fs/promises'; + * import { Buffer } from 'node:buffer'; + * + * try { + * const controller = new AbortController(); + * const { signal } = controller; + * const data = new Uint8Array(Buffer.from('Hello Node.js')); + * const promise = writeFile('message.txt', data, { signal }); + * + * // Abort the request before the promise settles. + * controller.abort(); + * + * await promise; + * } catch (err) { + * // When a request is aborted - err is an AbortError + * console.error(err); + * } + * ``` + * + * Aborting an ongoing request does not abort individual operating + * system requests but rather the internal buffering `fs.writeFile` performs. + * @since v10.0.0 + * @param file filename or `FileHandle` + * @return Fulfills with `undefined` upon success. + */ + function writeFile( + file: PathLike | FileHandle, + data: + | string + | NodeJS.ArrayBufferView + | Iterable + | AsyncIterable + | Stream, + options?: + | (ObjectEncodingOptions & { + mode?: Mode | undefined; + flag?: OpenMode | undefined; + /** + * If all data is successfully written to the file, and `flush` + * is `true`, `filehandle.sync()` is used to flush the data. + * @default false + */ + flush?: boolean | undefined; + } & Abortable) + | BufferEncoding + | null, + ): Promise; + /** + * Asynchronously append data to a file, creating the file if it does not yet + * exist. `data` can be a string or a `Buffer`. + * + * If `options` is a string, then it specifies the `encoding`. + * + * The `mode` option only affects the newly created file. See `fs.open()` for more details. + * + * The `path` may be specified as a `FileHandle` that has been opened + * for appending (using `fsPromises.open()`). + * @since v10.0.0 + * @param path filename or {FileHandle} + * @return Fulfills with `undefined` upon success. + */ + function appendFile( + path: PathLike | FileHandle, + data: string | Uint8Array, + options?: (ObjectEncodingOptions & FlagAndOpenMode & { flush?: boolean | undefined }) | BufferEncoding | null, + ): Promise; + /** + * Asynchronously reads the entire contents of a file. + * + * If no encoding is specified (using `options.encoding`), the data is returned + * as a `Buffer` object. Otherwise, the data will be a string. + * + * If `options` is a string, then it specifies the encoding. + * + * When the `path` is a directory, the behavior of `fsPromises.readFile()` is + * platform-specific. On macOS, Linux, and Windows, the promise will be rejected + * with an error. On FreeBSD, a representation of the directory's contents will be + * returned. + * + * An example of reading a `package.json` file located in the same directory of the + * running code: + * + * ```js + * import { readFile } from 'node:fs/promises'; + * try { + * const filePath = new URL('./package.json', import.meta.url); + * const contents = await readFile(filePath, { encoding: 'utf8' }); + * console.log(contents); + * } catch (err) { + * console.error(err.message); + * } + * ``` + * + * It is possible to abort an ongoing `readFile` using an `AbortSignal`. If a + * request is aborted the promise returned is rejected with an `AbortError`: + * + * ```js + * import { readFile } from 'node:fs/promises'; + * + * try { + * const controller = new AbortController(); + * const { signal } = controller; + * const promise = readFile(fileName, { signal }); + * + * // Abort the request before the promise settles. + * controller.abort(); + * + * await promise; + * } catch (err) { + * // When a request is aborted - err is an AbortError + * console.error(err); + * } + * ``` + * + * Aborting an ongoing request does not abort individual operating + * system requests but rather the internal buffering `fs.readFile` performs. + * + * Any specified `FileHandle` has to support reading. + * @since v10.0.0 + * @param path filename or `FileHandle` + * @return Fulfills with the contents of the file. + */ + function readFile( + path: PathLike | FileHandle, + options?: + | ({ + encoding?: null | undefined; + flag?: OpenMode | undefined; + } & Abortable) + | null, + ): Promise; + /** + * Asynchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * If a `FileHandle` is provided, the underlying file will _not_ be closed automatically. + * @param options An object that may contain an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + function readFile( + path: PathLike | FileHandle, + options: + | ({ + encoding: BufferEncoding; + flag?: OpenMode | undefined; + } & Abortable) + | BufferEncoding, + ): Promise; + /** + * Asynchronously reads the entire contents of a file. + * @param path A path to a file. If a URL is provided, it must use the `file:` protocol. + * If a `FileHandle` is provided, the underlying file will _not_ be closed automatically. + * @param options An object that may contain an optional flag. + * If a flag is not provided, it defaults to `'r'`. + */ + function readFile( + path: PathLike | FileHandle, + options?: + | ( + & ObjectEncodingOptions + & Abortable + & { + flag?: OpenMode | undefined; + } + ) + | BufferEncoding + | null, + ): Promise; + /** + * Asynchronously open a directory for iterative scanning. See the POSIX [`opendir(3)`](http://man7.org/linux/man-pages/man3/opendir.3.html) documentation for more detail. + * + * Creates an `fs.Dir`, which contains all further functions for reading from + * and cleaning up the directory. + * + * The `encoding` option sets the encoding for the `path` while opening the + * directory and subsequent read operations. + * + * Example using async iteration: + * + * ```js + * import { opendir } from 'node:fs/promises'; + * + * try { + * const dir = await opendir('./'); + * for await (const dirent of dir) + * console.log(dirent.name); + * } catch (err) { + * console.error(err); + * } + * ``` + * + * When using the async iterator, the `fs.Dir` object will be automatically + * closed after the iterator exits. + * @since v12.12.0 + * @return Fulfills with an {fs.Dir}. + */ + function opendir(path: PathLike, options?: OpenDirOptions): Promise; + /** + * Returns an async iterator that watches for changes on `filename`, where `filename`is either a file or a directory. + * + * ```js + * const { watch } = require('node:fs/promises'); + * + * const ac = new AbortController(); + * const { signal } = ac; + * setTimeout(() => ac.abort(), 10000); + * + * (async () => { + * try { + * const watcher = watch(__filename, { signal }); + * for await (const event of watcher) + * console.log(event); + * } catch (err) { + * if (err.name === 'AbortError') + * return; + * throw err; + * } + * })(); + * ``` + * + * On most platforms, `'rename'` is emitted whenever a filename appears or + * disappears in the directory. + * + * All the `caveats` for `fs.watch()` also apply to `fsPromises.watch()`. + * @since v15.9.0, v14.18.0 + * @return of objects with the properties: + */ + function watch( + filename: PathLike, + options: + | (WatchOptions & { + encoding: "buffer"; + }) + | "buffer", + ): AsyncIterable>; + /** + * Watch for changes on `filename`, where `filename` is either a file or a directory, returning an `FSWatcher`. + * @param filename A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + * @param options Either the encoding for the filename provided to the listener, or an object optionally specifying encoding, persistent, and recursive options. + * If `encoding` is not supplied, the default of `'utf8'` is used. + * If `persistent` is not supplied, the default of `true` is used. + * If `recursive` is not supplied, the default of `false` is used. + */ + function watch(filename: PathLike, options?: WatchOptions | BufferEncoding): AsyncIterable>; + /** + * Watch for changes on `filename`, where `filename` is either a file or a directory, returning an `FSWatcher`. + * @param filename A path to a file or directory. If a URL is provided, it must use the `file:` protocol. + * @param options Either the encoding for the filename provided to the listener, or an object optionally specifying encoding, persistent, and recursive options. + * If `encoding` is not supplied, the default of `'utf8'` is used. + * If `persistent` is not supplied, the default of `true` is used. + * If `recursive` is not supplied, the default of `false` is used. + */ + function watch( + filename: PathLike, + options: WatchOptions | string, + ): AsyncIterable> | AsyncIterable>; + /** + * Asynchronously copies the entire directory structure from `src` to `dest`, + * including subdirectories and files. + * + * When copying a directory to another directory, globs are not supported and + * behavior is similar to `cp dir1/ dir2/`. + * @since v16.7.0 + * @experimental + * @param src source path to copy. + * @param dest destination path to copy to. + * @return Fulfills with `undefined` upon success. + */ + function cp(source: string | URL, destination: string | URL, opts?: CopyOptions): Promise; +} +declare module "node:fs/promises" { + export * from "fs/promises"; +} diff --git a/node_modules/@types/node/globals.d.ts b/node_modules/@types/node/globals.d.ts new file mode 100644 index 0000000..5f25006 --- /dev/null +++ b/node_modules/@types/node/globals.d.ts @@ -0,0 +1,411 @@ +export {}; // Make this a module + +// #region Fetch and friends +// Conditional type aliases, used at the end of this file. +// Will either be empty if lib-dom is included, or the undici version otherwise. +type _Request = typeof globalThis extends { onmessage: any } ? {} : import("undici-types").Request; +type _Response = typeof globalThis extends { onmessage: any } ? {} : import("undici-types").Response; +type _FormData = typeof globalThis extends { onmessage: any } ? {} : import("undici-types").FormData; +type _Headers = typeof globalThis extends { onmessage: any } ? {} : import("undici-types").Headers; +type _RequestInit = typeof globalThis extends { onmessage: any } ? {} + : import("undici-types").RequestInit; +type _ResponseInit = typeof globalThis extends { onmessage: any } ? {} + : import("undici-types").ResponseInit; +type _File = typeof globalThis extends { onmessage: any } ? {} : import("node:buffer").File; +// #endregion Fetch and friends + +declare global { + // Declare "static" methods in Error + interface ErrorConstructor { + /** Create .stack property on a target object */ + captureStackTrace(targetObject: object, constructorOpt?: Function): void; + + /** + * Optional override for formatting stack traces + * + * @see https://v8.dev/docs/stack-trace-api#customizing-stack-traces + */ + prepareStackTrace?: ((err: Error, stackTraces: NodeJS.CallSite[]) => any) | undefined; + + stackTraceLimit: number; + } + + /*-----------------------------------------------* + * * + * GLOBAL * + * * + ------------------------------------------------*/ + + // For backwards compability + interface NodeRequire extends NodeJS.Require {} + interface RequireResolve extends NodeJS.RequireResolve {} + interface NodeModule extends NodeJS.Module {} + + var process: NodeJS.Process; + var console: Console; + + var __filename: string; + var __dirname: string; + + var require: NodeRequire; + var module: NodeModule; + + // Same as module.exports + var exports: any; + + /** + * Only available if `--expose-gc` is passed to the process. + */ + var gc: undefined | (() => void); + + // #region borrowed + // from https://github.com/microsoft/TypeScript/blob/38da7c600c83e7b31193a62495239a0fe478cb67/lib/lib.webworker.d.ts#L633 until moved to separate lib + /** A controller object that allows you to abort one or more DOM requests as and when desired. */ + interface AbortController { + /** + * Returns the AbortSignal object associated with this object. + */ + + readonly signal: AbortSignal; + /** + * Invoking this method will set this object's AbortSignal's aborted flag and signal to any observers that the associated activity is to be aborted. + */ + abort(reason?: any): void; + } + + /** A signal object that allows you to communicate with a DOM request (such as a Fetch) and abort it if required via an AbortController object. */ + interface AbortSignal extends EventTarget { + /** + * Returns true if this AbortSignal's AbortController has signaled to abort, and false otherwise. + */ + readonly aborted: boolean; + readonly reason: any; + onabort: null | ((this: AbortSignal, event: Event) => any); + throwIfAborted(): void; + } + + var AbortController: typeof globalThis extends { onmessage: any; AbortController: infer T } ? T + : { + prototype: AbortController; + new(): AbortController; + }; + + var AbortSignal: typeof globalThis extends { onmessage: any; AbortSignal: infer T } ? T + : { + prototype: AbortSignal; + new(): AbortSignal; + abort(reason?: any): AbortSignal; + timeout(milliseconds: number): AbortSignal; + }; + // #endregion borrowed + + // #region Disposable + interface SymbolConstructor { + /** + * A method that is used to release resources held by an object. Called by the semantics of the `using` statement. + */ + readonly dispose: unique symbol; + + /** + * A method that is used to asynchronously release resources held by an object. Called by the semantics of the `await using` statement. + */ + readonly asyncDispose: unique symbol; + } + + interface Disposable { + [Symbol.dispose](): void; + } + + interface AsyncDisposable { + [Symbol.asyncDispose](): PromiseLike; + } + // #endregion Disposable + + // #region ArrayLike.at() + interface RelativeIndexable { + /** + * Takes an integer value and returns the item at that index, + * allowing for positive and negative integers. + * Negative integers count back from the last item in the array. + */ + at(index: number): T | undefined; + } + interface String extends RelativeIndexable {} + interface Array extends RelativeIndexable {} + interface ReadonlyArray extends RelativeIndexable {} + interface Int8Array extends RelativeIndexable {} + interface Uint8Array extends RelativeIndexable {} + interface Uint8ClampedArray extends RelativeIndexable {} + interface Int16Array extends RelativeIndexable {} + interface Uint16Array extends RelativeIndexable {} + interface Int32Array extends RelativeIndexable {} + interface Uint32Array extends RelativeIndexable {} + interface Float32Array extends RelativeIndexable {} + interface Float64Array extends RelativeIndexable {} + interface BigInt64Array extends RelativeIndexable {} + interface BigUint64Array extends RelativeIndexable {} + // #endregion ArrayLike.at() end + + /** + * @since v17.0.0 + * + * Creates a deep clone of an object. + */ + function structuredClone( + value: T, + transfer?: { transfer: ReadonlyArray }, + ): T; + + /*----------------------------------------------* + * * + * GLOBAL INTERFACES * + * * + *-----------------------------------------------*/ + namespace NodeJS { + interface CallSite { + /** + * Value of "this" + */ + getThis(): unknown; + + /** + * Type of "this" as a string. + * This is the name of the function stored in the constructor field of + * "this", if available. Otherwise the object's [[Class]] internal + * property. + */ + getTypeName(): string | null; + + /** + * Current function + */ + getFunction(): Function | undefined; + + /** + * Name of the current function, typically its name property. + * If a name property is not available an attempt will be made to try + * to infer a name from the function's context. + */ + getFunctionName(): string | null; + + /** + * Name of the property [of "this" or one of its prototypes] that holds + * the current function + */ + getMethodName(): string | null; + + /** + * Name of the script [if this function was defined in a script] + */ + getFileName(): string | undefined; + + /** + * Current line number [if this function was defined in a script] + */ + getLineNumber(): number | null; + + /** + * Current column number [if this function was defined in a script] + */ + getColumnNumber(): number | null; + + /** + * A call site object representing the location where eval was called + * [if this function was created using a call to eval] + */ + getEvalOrigin(): string | undefined; + + /** + * Is this a toplevel invocation, that is, is "this" the global object? + */ + isToplevel(): boolean; + + /** + * Does this call take place in code defined by a call to eval? + */ + isEval(): boolean; + + /** + * Is this call in native V8 code? + */ + isNative(): boolean; + + /** + * Is this a constructor call? + */ + isConstructor(): boolean; + + /** + * is this an async call (i.e. await, Promise.all(), or Promise.any())? + */ + isAsync(): boolean; + + /** + * is this an async call to Promise.all()? + */ + isPromiseAll(): boolean; + + /** + * returns the index of the promise element that was followed in + * Promise.all() or Promise.any() for async stack traces, or null + * if the CallSite is not an async + */ + getPromiseIndex(): number | null; + + getScriptNameOrSourceURL(): string; + getScriptHash(): string; + + getEnclosingColumnNumber(): number; + getEnclosingLineNumber(): number; + getPosition(): number; + + toString(): string; + } + + interface ErrnoException extends Error { + errno?: number | undefined; + code?: string | undefined; + path?: string | undefined; + syscall?: string | undefined; + } + + interface ReadableStream extends EventEmitter { + readable: boolean; + read(size?: number): string | Buffer; + setEncoding(encoding: BufferEncoding): this; + pause(): this; + resume(): this; + isPaused(): boolean; + pipe(destination: T, options?: { end?: boolean | undefined }): T; + unpipe(destination?: WritableStream): this; + unshift(chunk: string | Uint8Array, encoding?: BufferEncoding): void; + wrap(oldStream: ReadableStream): this; + [Symbol.asyncIterator](): AsyncIterableIterator; + } + + interface WritableStream extends EventEmitter { + writable: boolean; + write(buffer: Uint8Array | string, cb?: (err?: Error | null) => void): boolean; + write(str: string, encoding?: BufferEncoding, cb?: (err?: Error | null) => void): boolean; + end(cb?: () => void): this; + end(data: string | Uint8Array, cb?: () => void): this; + end(str: string, encoding?: BufferEncoding, cb?: () => void): this; + } + + interface ReadWriteStream extends ReadableStream, WritableStream {} + + interface RefCounted { + ref(): this; + unref(): this; + } + + type TypedArray = + | Uint8Array + | Uint8ClampedArray + | Uint16Array + | Uint32Array + | Int8Array + | Int16Array + | Int32Array + | BigUint64Array + | BigInt64Array + | Float32Array + | Float64Array; + type ArrayBufferView = TypedArray | DataView; + + interface Require { + (id: string): any; + resolve: RequireResolve; + cache: Dict; + /** + * @deprecated + */ + extensions: RequireExtensions; + main: Module | undefined; + } + + interface RequireResolve { + (id: string, options?: { paths?: string[] | undefined }): string; + paths(request: string): string[] | null; + } + + interface RequireExtensions extends Dict<(m: Module, filename: string) => any> { + ".js": (m: Module, filename: string) => any; + ".json": (m: Module, filename: string) => any; + ".node": (m: Module, filename: string) => any; + } + interface Module { + /** + * `true` if the module is running during the Node.js preload + */ + isPreloading: boolean; + exports: any; + require: Require; + id: string; + filename: string; + loaded: boolean; + /** @deprecated since v14.6.0 Please use `require.main` and `module.children` instead. */ + parent: Module | null | undefined; + children: Module[]; + /** + * @since v11.14.0 + * + * The directory name of the module. This is usually the same as the path.dirname() of the module.id. + */ + path: string; + paths: string[]; + } + + interface Dict { + [key: string]: T | undefined; + } + + interface ReadOnlyDict { + readonly [key: string]: T | undefined; + } + } + + interface RequestInit extends _RequestInit {} + + function fetch( + input: string | URL | globalThis.Request, + init?: RequestInit, + ): Promise; + + interface Request extends _Request {} + var Request: typeof globalThis extends { + onmessage: any; + Request: infer T; + } ? T + : typeof import("undici-types").Request; + + interface ResponseInit extends _ResponseInit {} + + interface Response extends _Response {} + var Response: typeof globalThis extends { + onmessage: any; + Response: infer T; + } ? T + : typeof import("undici-types").Response; + + interface FormData extends _FormData {} + var FormData: typeof globalThis extends { + onmessage: any; + FormData: infer T; + } ? T + : typeof import("undici-types").FormData; + + interface Headers extends _Headers {} + var Headers: typeof globalThis extends { + onmessage: any; + Headers: infer T; + } ? T + : typeof import("undici-types").Headers; + + interface File extends _File {} + var File: typeof globalThis extends { + onmessage: any; + File: infer T; + } ? T + : typeof import("node:buffer").File; +} diff --git a/node_modules/@types/node/globals.global.d.ts b/node_modules/@types/node/globals.global.d.ts new file mode 100644 index 0000000..ef1198c --- /dev/null +++ b/node_modules/@types/node/globals.global.d.ts @@ -0,0 +1 @@ +declare var global: typeof globalThis; diff --git a/node_modules/@types/node/http.d.ts b/node_modules/@types/node/http.d.ts new file mode 100644 index 0000000..a1018ee --- /dev/null +++ b/node_modules/@types/node/http.d.ts @@ -0,0 +1,1908 @@ +/** + * To use the HTTP server and client one must `require('node:http')`. + * + * The HTTP interfaces in Node.js are designed to support many features + * of the protocol which have been traditionally difficult to use. + * In particular, large, possibly chunk-encoded, messages. The interface is + * careful to never buffer entire requests or responses, so the + * user is able to stream data. + * + * HTTP message headers are represented by an object like this: + * + * ```json + * { "content-length": "123", + * "content-type": "text/plain", + * "connection": "keep-alive", + * "host": "example.com", + * "accept": "*" } + * ``` + * + * Keys are lowercased. Values are not modified. + * + * In order to support the full spectrum of possible HTTP applications, the Node.js + * HTTP API is very low-level. It deals with stream handling and message + * parsing only. It parses a message into headers and body but it does not + * parse the actual headers or the body. + * + * See `message.headers` for details on how duplicate headers are handled. + * + * The raw headers as they were received are retained in the `rawHeaders` property, which is an array of `[key, value, key2, value2, ...]`. For + * example, the previous message header object might have a `rawHeaders` list like the following: + * + * ```js + * [ 'ConTent-Length', '123456', + * 'content-LENGTH', '123', + * 'content-type', 'text/plain', + * 'CONNECTION', 'keep-alive', + * 'Host', 'example.com', + * 'accepT', '*' ] + * ``` + * @see [source](https://github.com/nodejs/node/blob/v20.13.1/lib/http.js) + */ +declare module "http" { + import * as stream from "node:stream"; + import { URL } from "node:url"; + import { LookupOptions } from "node:dns"; + import { EventEmitter } from "node:events"; + import { LookupFunction, Server as NetServer, Socket, TcpSocketConnectOpts } from "node:net"; + // incoming headers will never contain number + interface IncomingHttpHeaders extends NodeJS.Dict { + accept?: string | undefined; + "accept-language"?: string | undefined; + "accept-patch"?: string | undefined; + "accept-ranges"?: string | undefined; + "access-control-allow-credentials"?: string | undefined; + "access-control-allow-headers"?: string | undefined; + "access-control-allow-methods"?: string | undefined; + "access-control-allow-origin"?: string | undefined; + "access-control-expose-headers"?: string | undefined; + "access-control-max-age"?: string | undefined; + "access-control-request-headers"?: string | undefined; + "access-control-request-method"?: string | undefined; + age?: string | undefined; + allow?: string | undefined; + "alt-svc"?: string | undefined; + authorization?: string | undefined; + "cache-control"?: string | undefined; + connection?: string | undefined; + "content-disposition"?: string | undefined; + "content-encoding"?: string | undefined; + "content-language"?: string | undefined; + "content-length"?: string | undefined; + "content-location"?: string | undefined; + "content-range"?: string | undefined; + "content-type"?: string | undefined; + cookie?: string | undefined; + date?: string | undefined; + etag?: string | undefined; + expect?: string | undefined; + expires?: string | undefined; + forwarded?: string | undefined; + from?: string | undefined; + host?: string | undefined; + "if-match"?: string | undefined; + "if-modified-since"?: string | undefined; + "if-none-match"?: string | undefined; + "if-unmodified-since"?: string | undefined; + "last-modified"?: string | undefined; + location?: string | undefined; + origin?: string | undefined; + pragma?: string | undefined; + "proxy-authenticate"?: string | undefined; + "proxy-authorization"?: string | undefined; + "public-key-pins"?: string | undefined; + range?: string | undefined; + referer?: string | undefined; + "retry-after"?: string | undefined; + "sec-websocket-accept"?: string | undefined; + "sec-websocket-extensions"?: string | undefined; + "sec-websocket-key"?: string | undefined; + "sec-websocket-protocol"?: string | undefined; + "sec-websocket-version"?: string | undefined; + "set-cookie"?: string[] | undefined; + "strict-transport-security"?: string | undefined; + tk?: string | undefined; + trailer?: string | undefined; + "transfer-encoding"?: string | undefined; + upgrade?: string | undefined; + "user-agent"?: string | undefined; + vary?: string | undefined; + via?: string | undefined; + warning?: string | undefined; + "www-authenticate"?: string | undefined; + } + // outgoing headers allows numbers (as they are converted internally to strings) + type OutgoingHttpHeader = number | string | string[]; + interface OutgoingHttpHeaders extends NodeJS.Dict { + accept?: string | string[] | undefined; + "accept-charset"?: string | string[] | undefined; + "accept-encoding"?: string | string[] | undefined; + "accept-language"?: string | string[] | undefined; + "accept-ranges"?: string | undefined; + "access-control-allow-credentials"?: string | undefined; + "access-control-allow-headers"?: string | undefined; + "access-control-allow-methods"?: string | undefined; + "access-control-allow-origin"?: string | undefined; + "access-control-expose-headers"?: string | undefined; + "access-control-max-age"?: string | undefined; + "access-control-request-headers"?: string | undefined; + "access-control-request-method"?: string | undefined; + age?: string | undefined; + allow?: string | undefined; + authorization?: string | undefined; + "cache-control"?: string | undefined; + "cdn-cache-control"?: string | undefined; + connection?: string | string[] | undefined; + "content-disposition"?: string | undefined; + "content-encoding"?: string | undefined; + "content-language"?: string | undefined; + "content-length"?: string | number | undefined; + "content-location"?: string | undefined; + "content-range"?: string | undefined; + "content-security-policy"?: string | undefined; + "content-security-policy-report-only"?: string | undefined; + cookie?: string | string[] | undefined; + dav?: string | string[] | undefined; + dnt?: string | undefined; + date?: string | undefined; + etag?: string | undefined; + expect?: string | undefined; + expires?: string | undefined; + forwarded?: string | undefined; + from?: string | undefined; + host?: string | undefined; + "if-match"?: string | undefined; + "if-modified-since"?: string | undefined; + "if-none-match"?: string | undefined; + "if-range"?: string | undefined; + "if-unmodified-since"?: string | undefined; + "last-modified"?: string | undefined; + link?: string | string[] | undefined; + location?: string | undefined; + "max-forwards"?: string | undefined; + origin?: string | undefined; + prgama?: string | string[] | undefined; + "proxy-authenticate"?: string | string[] | undefined; + "proxy-authorization"?: string | undefined; + "public-key-pins"?: string | undefined; + "public-key-pins-report-only"?: string | undefined; + range?: string | undefined; + referer?: string | undefined; + "referrer-policy"?: string | undefined; + refresh?: string | undefined; + "retry-after"?: string | undefined; + "sec-websocket-accept"?: string | undefined; + "sec-websocket-extensions"?: string | string[] | undefined; + "sec-websocket-key"?: string | undefined; + "sec-websocket-protocol"?: string | string[] | undefined; + "sec-websocket-version"?: string | undefined; + server?: string | undefined; + "set-cookie"?: string | string[] | undefined; + "strict-transport-security"?: string | undefined; + te?: string | undefined; + trailer?: string | undefined; + "transfer-encoding"?: string | undefined; + "user-agent"?: string | undefined; + upgrade?: string | undefined; + "upgrade-insecure-requests"?: string | undefined; + vary?: string | undefined; + via?: string | string[] | undefined; + warning?: string | undefined; + "www-authenticate"?: string | string[] | undefined; + "x-content-type-options"?: string | undefined; + "x-dns-prefetch-control"?: string | undefined; + "x-frame-options"?: string | undefined; + "x-xss-protection"?: string | undefined; + } + interface ClientRequestArgs { + _defaultAgent?: Agent | undefined; + agent?: Agent | boolean | undefined; + auth?: string | null | undefined; + createConnection?: + | (( + options: ClientRequestArgs, + oncreate: (err: Error | null, socket: stream.Duplex) => void, + ) => stream.Duplex | null | undefined) + | undefined; + defaultPort?: number | string | undefined; + family?: number | undefined; + headers?: OutgoingHttpHeaders | undefined; + hints?: LookupOptions["hints"]; + host?: string | null | undefined; + hostname?: string | null | undefined; + insecureHTTPParser?: boolean | undefined; + localAddress?: string | undefined; + localPort?: number | undefined; + lookup?: LookupFunction | undefined; + /** + * @default 16384 + */ + maxHeaderSize?: number | undefined; + method?: string | undefined; + path?: string | null | undefined; + port?: number | string | null | undefined; + protocol?: string | null | undefined; + setHost?: boolean | undefined; + signal?: AbortSignal | undefined; + socketPath?: string | undefined; + timeout?: number | undefined; + uniqueHeaders?: Array | undefined; + joinDuplicateHeaders?: boolean; + } + interface ServerOptions< + Request extends typeof IncomingMessage = typeof IncomingMessage, + Response extends typeof ServerResponse = typeof ServerResponse, + > { + /** + * Specifies the `IncomingMessage` class to be used. Useful for extending the original `IncomingMessage`. + */ + IncomingMessage?: Request | undefined; + /** + * Specifies the `ServerResponse` class to be used. Useful for extending the original `ServerResponse`. + */ + ServerResponse?: Response | undefined; + /** + * Sets the timeout value in milliseconds for receiving the entire request from the client. + * @see Server.requestTimeout for more information. + * @default 300000 + * @since v18.0.0 + */ + requestTimeout?: number | undefined; + /** + * It joins the field line values of multiple headers in a request with `, ` instead of discarding the duplicates. + * @default false + * @since v18.14.0 + */ + joinDuplicateHeaders?: boolean; + /** + * The number of milliseconds of inactivity a server needs to wait for additional incoming data, + * after it has finished writing the last response, before a socket will be destroyed. + * @see Server.keepAliveTimeout for more information. + * @default 5000 + * @since v18.0.0 + */ + keepAliveTimeout?: number | undefined; + /** + * Sets the interval value in milliseconds to check for request and headers timeout in incomplete requests. + * @default 30000 + */ + connectionsCheckingInterval?: number | undefined; + /** + * Optionally overrides all `socket`s' `readableHighWaterMark` and `writableHighWaterMark`. + * This affects `highWaterMark` property of both `IncomingMessage` and `ServerResponse`. + * Default: @see stream.getDefaultHighWaterMark(). + * @since v20.1.0 + */ + highWaterMark?: number | undefined; + /** + * Use an insecure HTTP parser that accepts invalid HTTP headers when `true`. + * Using the insecure parser should be avoided. + * See --insecure-http-parser for more information. + * @default false + */ + insecureHTTPParser?: boolean | undefined; + /** + * Optionally overrides the value of `--max-http-header-size` for requests received by + * this server, i.e. the maximum length of request headers in bytes. + * @default 16384 + * @since v13.3.0 + */ + maxHeaderSize?: number | undefined; + /** + * If set to `true`, it disables the use of Nagle's algorithm immediately after a new incoming connection is received. + * @default true + * @since v16.5.0 + */ + noDelay?: boolean | undefined; + /** + * If set to `true`, it enables keep-alive functionality on the socket immediately after a new incoming connection is received, + * similarly on what is done in `socket.setKeepAlive([enable][, initialDelay])`. + * @default false + * @since v16.5.0 + */ + keepAlive?: boolean | undefined; + /** + * If set to a positive number, it sets the initial delay before the first keepalive probe is sent on an idle socket. + * @default 0 + * @since v16.5.0 + */ + keepAliveInitialDelay?: number | undefined; + /** + * A list of response headers that should be sent only once. + * If the header's value is an array, the items will be joined using `; `. + */ + uniqueHeaders?: Array | undefined; + } + type RequestListener< + Request extends typeof IncomingMessage = typeof IncomingMessage, + Response extends typeof ServerResponse = typeof ServerResponse, + > = (req: InstanceType, res: InstanceType & { req: InstanceType }) => void; + /** + * @since v0.1.17 + */ + class Server< + Request extends typeof IncomingMessage = typeof IncomingMessage, + Response extends typeof ServerResponse = typeof ServerResponse, + > extends NetServer { + constructor(requestListener?: RequestListener); + constructor(options: ServerOptions, requestListener?: RequestListener); + /** + * Sets the timeout value for sockets, and emits a `'timeout'` event on + * the Server object, passing the socket as an argument, if a timeout + * occurs. + * + * If there is a `'timeout'` event listener on the Server object, then it + * will be called with the timed-out socket as an argument. + * + * By default, the Server does not timeout sockets. However, if a callback + * is assigned to the Server's `'timeout'` event, timeouts must be handled + * explicitly. + * @since v0.9.12 + * @param [msecs=0 (no timeout)] + */ + setTimeout(msecs?: number, callback?: () => void): this; + setTimeout(callback: () => void): this; + /** + * Limits maximum incoming headers count. If set to 0, no limit will be applied. + * @since v0.7.0 + */ + maxHeadersCount: number | null; + /** + * The maximum number of requests socket can handle + * before closing keep alive connection. + * + * A value of `0` will disable the limit. + * + * When the limit is reached it will set the `Connection` header value to `close`, + * but will not actually close the connection, subsequent requests sent + * after the limit is reached will get `503 Service Unavailable` as a response. + * @since v16.10.0 + */ + maxRequestsPerSocket: number | null; + /** + * The number of milliseconds of inactivity before a socket is presumed + * to have timed out. + * + * A value of `0` will disable the timeout behavior on incoming connections. + * + * The socket timeout logic is set up on connection, so changing this + * value only affects new connections to the server, not any existing connections. + * @since v0.9.12 + */ + timeout: number; + /** + * Limit the amount of time the parser will wait to receive the complete HTTP + * headers. + * + * If the timeout expires, the server responds with status 408 without + * forwarding the request to the request listener and then closes the connection. + * + * It must be set to a non-zero value (e.g. 120 seconds) to protect against + * potential Denial-of-Service attacks in case the server is deployed without a + * reverse proxy in front. + * @since v11.3.0, v10.14.0 + */ + headersTimeout: number; + /** + * The number of milliseconds of inactivity a server needs to wait for additional + * incoming data, after it has finished writing the last response, before a socket + * will be destroyed. If the server receives new data before the keep-alive + * timeout has fired, it will reset the regular inactivity timeout, i.e., `server.timeout`. + * + * A value of `0` will disable the keep-alive timeout behavior on incoming + * connections. + * A value of `0` makes the http server behave similarly to Node.js versions prior + * to 8.0.0, which did not have a keep-alive timeout. + * + * The socket timeout logic is set up on connection, so changing this value only + * affects new connections to the server, not any existing connections. + * @since v8.0.0 + */ + keepAliveTimeout: number; + /** + * Sets the timeout value in milliseconds for receiving the entire request from + * the client. + * + * If the timeout expires, the server responds with status 408 without + * forwarding the request to the request listener and then closes the connection. + * + * It must be set to a non-zero value (e.g. 120 seconds) to protect against + * potential Denial-of-Service attacks in case the server is deployed without a + * reverse proxy in front. + * @since v14.11.0 + */ + requestTimeout: number; + /** + * Closes all connections connected to this server. + * @since v18.2.0 + */ + closeAllConnections(): void; + /** + * Closes all connections connected to this server which are not sending a request + * or waiting for a response. + * @since v18.2.0 + */ + closeIdleConnections(): void; + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "close", listener: () => void): this; + addListener(event: "connection", listener: (socket: Socket) => void): this; + addListener(event: "error", listener: (err: Error) => void): this; + addListener(event: "listening", listener: () => void): this; + addListener(event: "checkContinue", listener: RequestListener): this; + addListener(event: "checkExpectation", listener: RequestListener): this; + addListener(event: "clientError", listener: (err: Error, socket: stream.Duplex) => void): this; + addListener( + event: "connect", + listener: (req: InstanceType, socket: stream.Duplex, head: Buffer) => void, + ): this; + addListener(event: "dropRequest", listener: (req: InstanceType, socket: stream.Duplex) => void): this; + addListener(event: "request", listener: RequestListener): this; + addListener( + event: "upgrade", + listener: (req: InstanceType, socket: stream.Duplex, head: Buffer) => void, + ): this; + emit(event: string, ...args: any[]): boolean; + emit(event: "close"): boolean; + emit(event: "connection", socket: Socket): boolean; + emit(event: "error", err: Error): boolean; + emit(event: "listening"): boolean; + emit( + event: "checkContinue", + req: InstanceType, + res: InstanceType & { req: InstanceType }, + ): boolean; + emit( + event: "checkExpectation", + req: InstanceType, + res: InstanceType & { req: InstanceType }, + ): boolean; + emit(event: "clientError", err: Error, socket: stream.Duplex): boolean; + emit(event: "connect", req: InstanceType, socket: stream.Duplex, head: Buffer): boolean; + emit(event: "dropRequest", req: InstanceType, socket: stream.Duplex): boolean; + emit( + event: "request", + req: InstanceType, + res: InstanceType & { req: InstanceType }, + ): boolean; + emit(event: "upgrade", req: InstanceType, socket: stream.Duplex, head: Buffer): boolean; + on(event: string, listener: (...args: any[]) => void): this; + on(event: "close", listener: () => void): this; + on(event: "connection", listener: (socket: Socket) => void): this; + on(event: "error", listener: (err: Error) => void): this; + on(event: "listening", listener: () => void): this; + on(event: "checkContinue", listener: RequestListener): this; + on(event: "checkExpectation", listener: RequestListener): this; + on(event: "clientError", listener: (err: Error, socket: stream.Duplex) => void): this; + on(event: "connect", listener: (req: InstanceType, socket: stream.Duplex, head: Buffer) => void): this; + on(event: "dropRequest", listener: (req: InstanceType, socket: stream.Duplex) => void): this; + on(event: "request", listener: RequestListener): this; + on(event: "upgrade", listener: (req: InstanceType, socket: stream.Duplex, head: Buffer) => void): this; + once(event: string, listener: (...args: any[]) => void): this; + once(event: "close", listener: () => void): this; + once(event: "connection", listener: (socket: Socket) => void): this; + once(event: "error", listener: (err: Error) => void): this; + once(event: "listening", listener: () => void): this; + once(event: "checkContinue", listener: RequestListener): this; + once(event: "checkExpectation", listener: RequestListener): this; + once(event: "clientError", listener: (err: Error, socket: stream.Duplex) => void): this; + once( + event: "connect", + listener: (req: InstanceType, socket: stream.Duplex, head: Buffer) => void, + ): this; + once(event: "dropRequest", listener: (req: InstanceType, socket: stream.Duplex) => void): this; + once(event: "request", listener: RequestListener): this; + once( + event: "upgrade", + listener: (req: InstanceType, socket: stream.Duplex, head: Buffer) => void, + ): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "close", listener: () => void): this; + prependListener(event: "connection", listener: (socket: Socket) => void): this; + prependListener(event: "error", listener: (err: Error) => void): this; + prependListener(event: "listening", listener: () => void): this; + prependListener(event: "checkContinue", listener: RequestListener): this; + prependListener(event: "checkExpectation", listener: RequestListener): this; + prependListener(event: "clientError", listener: (err: Error, socket: stream.Duplex) => void): this; + prependListener( + event: "connect", + listener: (req: InstanceType, socket: stream.Duplex, head: Buffer) => void, + ): this; + prependListener( + event: "dropRequest", + listener: (req: InstanceType, socket: stream.Duplex) => void, + ): this; + prependListener(event: "request", listener: RequestListener): this; + prependListener( + event: "upgrade", + listener: (req: InstanceType, socket: stream.Duplex, head: Buffer) => void, + ): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "connection", listener: (socket: Socket) => void): this; + prependOnceListener(event: "error", listener: (err: Error) => void): this; + prependOnceListener(event: "listening", listener: () => void): this; + prependOnceListener(event: "checkContinue", listener: RequestListener): this; + prependOnceListener(event: "checkExpectation", listener: RequestListener): this; + prependOnceListener(event: "clientError", listener: (err: Error, socket: stream.Duplex) => void): this; + prependOnceListener( + event: "connect", + listener: (req: InstanceType, socket: stream.Duplex, head: Buffer) => void, + ): this; + prependOnceListener( + event: "dropRequest", + listener: (req: InstanceType, socket: stream.Duplex) => void, + ): this; + prependOnceListener(event: "request", listener: RequestListener): this; + prependOnceListener( + event: "upgrade", + listener: (req: InstanceType, socket: stream.Duplex, head: Buffer) => void, + ): this; + } + /** + * This class serves as the parent class of {@link ClientRequest} and {@link ServerResponse}. It is an abstract outgoing message from + * the perspective of the participants of an HTTP transaction. + * @since v0.1.17 + */ + class OutgoingMessage extends stream.Writable { + readonly req: Request; + chunkedEncoding: boolean; + shouldKeepAlive: boolean; + useChunkedEncodingByDefault: boolean; + sendDate: boolean; + /** + * @deprecated Use `writableEnded` instead. + */ + finished: boolean; + /** + * Read-only. `true` if the headers were sent, otherwise `false`. + * @since v0.9.3 + */ + readonly headersSent: boolean; + /** + * Alias of `outgoingMessage.socket`. + * @since v0.3.0 + * @deprecated Since v15.12.0,v14.17.1 - Use `socket` instead. + */ + readonly connection: Socket | null; + /** + * Reference to the underlying socket. Usually, users will not want to access + * this property. + * + * After calling `outgoingMessage.end()`, this property will be nulled. + * @since v0.3.0 + */ + readonly socket: Socket | null; + constructor(); + /** + * Once a socket is associated with the message and is connected, `socket.setTimeout()` will be called with `msecs` as the first parameter. + * @since v0.9.12 + * @param callback Optional function to be called when a timeout occurs. Same as binding to the `timeout` event. + */ + setTimeout(msecs: number, callback?: () => void): this; + /** + * Sets a single header value. If the header already exists in the to-be-sent + * headers, its value will be replaced. Use an array of strings to send multiple + * headers with the same name. + * @since v0.4.0 + * @param name Header name + * @param value Header value + */ + setHeader(name: string, value: number | string | readonly string[]): this; + /** + * Append a single header value to the header object. + * + * If the value is an array, this is equivalent to calling this method multiple + * times. + * + * If there were no previous values for the header, this is equivalent to calling `outgoingMessage.setHeader(name, value)`. + * + * Depending of the value of `options.uniqueHeaders` when the client request or the + * server were created, this will end up in the header being sent multiple times or + * a single time with values joined using `; `. + * @since v18.3.0, v16.17.0 + * @param name Header name + * @param value Header value + */ + appendHeader(name: string, value: string | readonly string[]): this; + /** + * Gets the value of the HTTP header with the given name. If that header is not + * set, the returned value will be `undefined`. + * @since v0.4.0 + * @param name Name of header + */ + getHeader(name: string): number | string | string[] | undefined; + /** + * Returns a shallow copy of the current outgoing headers. Since a shallow + * copy is used, array values may be mutated without additional calls to + * various header-related HTTP module methods. The keys of the returned + * object are the header names and the values are the respective header + * values. All header names are lowercase. + * + * The object returned by the `outgoingMessage.getHeaders()` method does + * not prototypically inherit from the JavaScript `Object`. This means that + * typical `Object` methods such as `obj.toString()`, `obj.hasOwnProperty()`, + * and others are not defined and will not work. + * + * ```js + * outgoingMessage.setHeader('Foo', 'bar'); + * outgoingMessage.setHeader('Set-Cookie', ['foo=bar', 'bar=baz']); + * + * const headers = outgoingMessage.getHeaders(); + * // headers === { foo: 'bar', 'set-cookie': ['foo=bar', 'bar=baz'] } + * ``` + * @since v7.7.0 + */ + getHeaders(): OutgoingHttpHeaders; + /** + * Returns an array containing the unique names of the current outgoing headers. + * All names are lowercase. + * @since v7.7.0 + */ + getHeaderNames(): string[]; + /** + * Returns `true` if the header identified by `name` is currently set in the + * outgoing headers. The header name is case-insensitive. + * + * ```js + * const hasContentType = outgoingMessage.hasHeader('content-type'); + * ``` + * @since v7.7.0 + */ + hasHeader(name: string): boolean; + /** + * Removes a header that is queued for implicit sending. + * + * ```js + * outgoingMessage.removeHeader('Content-Encoding'); + * ``` + * @since v0.4.0 + * @param name Header name + */ + removeHeader(name: string): void; + /** + * Adds HTTP trailers (headers but at the end of the message) to the message. + * + * Trailers will **only** be emitted if the message is chunked encoded. If not, + * the trailers will be silently discarded. + * + * HTTP requires the `Trailer` header to be sent to emit trailers, + * with a list of header field names in its value, e.g. + * + * ```js + * message.writeHead(200, { 'Content-Type': 'text/plain', + * 'Trailer': 'Content-MD5' }); + * message.write(fileData); + * message.addTrailers({ 'Content-MD5': '7895bf4b8828b55ceaf47747b4bca667' }); + * message.end(); + * ``` + * + * Attempting to set a header field name or value that contains invalid characters + * will result in a `TypeError` being thrown. + * @since v0.3.0 + */ + addTrailers(headers: OutgoingHttpHeaders | ReadonlyArray<[string, string]>): void; + /** + * Flushes the message headers. + * + * For efficiency reason, Node.js normally buffers the message headers + * until `outgoingMessage.end()` is called or the first chunk of message data + * is written. It then tries to pack the headers and data into a single TCP + * packet. + * + * It is usually desired (it saves a TCP round-trip), but not when the first + * data is not sent until possibly much later. `outgoingMessage.flushHeaders()` bypasses the optimization and kickstarts the message. + * @since v1.6.0 + */ + flushHeaders(): void; + } + /** + * This object is created internally by an HTTP server, not by the user. It is + * passed as the second parameter to the `'request'` event. + * @since v0.1.17 + */ + class ServerResponse extends OutgoingMessage { + /** + * When using implicit headers (not calling `response.writeHead()` explicitly), + * this property controls the status code that will be sent to the client when + * the headers get flushed. + * + * ```js + * response.statusCode = 404; + * ``` + * + * After response header was sent to the client, this property indicates the + * status code which was sent out. + * @since v0.4.0 + */ + statusCode: number; + /** + * When using implicit headers (not calling `response.writeHead()` explicitly), + * this property controls the status message that will be sent to the client when + * the headers get flushed. If this is left as `undefined` then the standard + * message for the status code will be used. + * + * ```js + * response.statusMessage = 'Not found'; + * ``` + * + * After response header was sent to the client, this property indicates the + * status message which was sent out. + * @since v0.11.8 + */ + statusMessage: string; + /** + * If set to `true`, Node.js will check whether the `Content-Length` header value and the size of the body, in bytes, are equal. + * Mismatching the `Content-Length` header value will result + * in an `Error` being thrown, identified by `code:``'ERR_HTTP_CONTENT_LENGTH_MISMATCH'`. + * @since v18.10.0, v16.18.0 + */ + strictContentLength: boolean; + constructor(req: Request); + assignSocket(socket: Socket): void; + detachSocket(socket: Socket): void; + /** + * Sends an HTTP/1.1 100 Continue message to the client, indicating that + * the request body should be sent. See the `'checkContinue'` event on `Server`. + * @since v0.3.0 + */ + writeContinue(callback?: () => void): void; + /** + * Sends an HTTP/1.1 103 Early Hints message to the client with a Link header, + * indicating that the user agent can preload/preconnect the linked resources. + * The `hints` is an object containing the values of headers to be sent with + * early hints message. The optional `callback` argument will be called when + * the response message has been written. + * + * **Example** + * + * ```js + * const earlyHintsLink = '; rel=preload; as=style'; + * response.writeEarlyHints({ + * 'link': earlyHintsLink, + * }); + * + * const earlyHintsLinks = [ + * '; rel=preload; as=style', + * '; rel=preload; as=script', + * ]; + * response.writeEarlyHints({ + * 'link': earlyHintsLinks, + * 'x-trace-id': 'id for diagnostics', + * }); + * + * const earlyHintsCallback = () => console.log('early hints message sent'); + * response.writeEarlyHints({ + * 'link': earlyHintsLinks, + * }, earlyHintsCallback); + * ``` + * @since v18.11.0 + * @param hints An object containing the values of headers + * @param callback Will be called when the response message has been written + */ + writeEarlyHints(hints: Record, callback?: () => void): void; + /** + * Sends a response header to the request. The status code is a 3-digit HTTP + * status code, like `404`. The last argument, `headers`, are the response headers. + * Optionally one can give a human-readable `statusMessage` as the second + * argument. + * + * `headers` may be an `Array` where the keys and values are in the same list. + * It is _not_ a list of tuples. So, the even-numbered offsets are key values, + * and the odd-numbered offsets are the associated values. The array is in the same + * format as `request.rawHeaders`. + * + * Returns a reference to the `ServerResponse`, so that calls can be chained. + * + * ```js + * const body = 'hello world'; + * response + * .writeHead(200, { + * 'Content-Length': Buffer.byteLength(body), + * 'Content-Type': 'text/plain', + * }) + * .end(body); + * ``` + * + * This method must only be called once on a message and it must + * be called before `response.end()` is called. + * + * If `response.write()` or `response.end()` are called before calling + * this, the implicit/mutable headers will be calculated and call this function. + * + * When headers have been set with `response.setHeader()`, they will be merged + * with any headers passed to `response.writeHead()`, with the headers passed + * to `response.writeHead()` given precedence. + * + * If this method is called and `response.setHeader()` has not been called, + * it will directly write the supplied header values onto the network channel + * without caching internally, and the `response.getHeader()` on the header + * will not yield the expected result. If progressive population of headers is + * desired with potential future retrieval and modification, use `response.setHeader()` instead. + * + * ```js + * // Returns content-type = text/plain + * const server = http.createServer((req, res) => { + * res.setHeader('Content-Type', 'text/html'); + * res.setHeader('X-Foo', 'bar'); + * res.writeHead(200, { 'Content-Type': 'text/plain' }); + * res.end('ok'); + * }); + * ``` + * + * `Content-Length` is read in bytes, not characters. Use `Buffer.byteLength()` to determine the length of the body in bytes. Node.js + * will check whether `Content-Length` and the length of the body which has + * been transmitted are equal or not. + * + * Attempting to set a header field name or value that contains invalid characters + * will result in a \[`Error`\]\[\] being thrown. + * @since v0.1.30 + */ + writeHead( + statusCode: number, + statusMessage?: string, + headers?: OutgoingHttpHeaders | OutgoingHttpHeader[], + ): this; + writeHead(statusCode: number, headers?: OutgoingHttpHeaders | OutgoingHttpHeader[]): this; + /** + * Sends a HTTP/1.1 102 Processing message to the client, indicating that + * the request body should be sent. + * @since v10.0.0 + */ + writeProcessing(): void; + } + interface InformationEvent { + statusCode: number; + statusMessage: string; + httpVersion: string; + httpVersionMajor: number; + httpVersionMinor: number; + headers: IncomingHttpHeaders; + rawHeaders: string[]; + } + /** + * This object is created internally and returned from {@link request}. It + * represents an _in-progress_ request whose header has already been queued. The + * header is still mutable using the `setHeader(name, value)`, `getHeader(name)`, `removeHeader(name)` API. The actual header will + * be sent along with the first data chunk or when calling `request.end()`. + * + * To get the response, add a listener for `'response'` to the request object. `'response'` will be emitted from the request object when the response + * headers have been received. The `'response'` event is executed with one + * argument which is an instance of {@link IncomingMessage}. + * + * During the `'response'` event, one can add listeners to the + * response object; particularly to listen for the `'data'` event. + * + * If no `'response'` handler is added, then the response will be + * entirely discarded. However, if a `'response'` event handler is added, + * then the data from the response object **must** be consumed, either by + * calling `response.read()` whenever there is a `'readable'` event, or + * by adding a `'data'` handler, or by calling the `.resume()` method. + * Until the data is consumed, the `'end'` event will not fire. Also, until + * the data is read it will consume memory that can eventually lead to a + * 'process out of memory' error. + * + * For backward compatibility, `res` will only emit `'error'` if there is an `'error'` listener registered. + * + * Set `Content-Length` header to limit the response body size. + * If `response.strictContentLength` is set to `true`, mismatching the `Content-Length` header value will result in an `Error` being thrown, + * identified by `code:``'ERR_HTTP_CONTENT_LENGTH_MISMATCH'`. + * + * `Content-Length` value should be in bytes, not characters. Use `Buffer.byteLength()` to determine the length of the body in bytes. + * @since v0.1.17 + */ + class ClientRequest extends OutgoingMessage { + /** + * The `request.aborted` property will be `true` if the request has + * been aborted. + * @since v0.11.14 + * @deprecated Since v17.0.0, v16.12.0 - Check `destroyed` instead. + */ + aborted: boolean; + /** + * The request host. + * @since v14.5.0, v12.19.0 + */ + host: string; + /** + * The request protocol. + * @since v14.5.0, v12.19.0 + */ + protocol: string; + /** + * When sending request through a keep-alive enabled agent, the underlying socket + * might be reused. But if server closes connection at unfortunate time, client + * may run into a 'ECONNRESET' error. + * + * ```js + * import http from 'node:http'; + * + * // Server has a 5 seconds keep-alive timeout by default + * http + * .createServer((req, res) => { + * res.write('hello\n'); + * res.end(); + * }) + * .listen(3000); + * + * setInterval(() => { + * // Adapting a keep-alive agent + * http.get('http://localhost:3000', { agent }, (res) => { + * res.on('data', (data) => { + * // Do nothing + * }); + * }); + * }, 5000); // Sending request on 5s interval so it's easy to hit idle timeout + * ``` + * + * By marking a request whether it reused socket or not, we can do + * automatic error retry base on it. + * + * ```js + * import http from 'node:http'; + * const agent = new http.Agent({ keepAlive: true }); + * + * function retriableRequest() { + * const req = http + * .get('http://localhost:3000', { agent }, (res) => { + * // ... + * }) + * .on('error', (err) => { + * // Check if retry is needed + * if (req.reusedSocket && err.code === 'ECONNRESET') { + * retriableRequest(); + * } + * }); + * } + * + * retriableRequest(); + * ``` + * @since v13.0.0, v12.16.0 + */ + reusedSocket: boolean; + /** + * Limits maximum response headers count. If set to 0, no limit will be applied. + */ + maxHeadersCount: number; + constructor(url: string | URL | ClientRequestArgs, cb?: (res: IncomingMessage) => void); + /** + * The request method. + * @since v0.1.97 + */ + method: string; + /** + * The request path. + * @since v0.4.0 + */ + path: string; + /** + * Marks the request as aborting. Calling this will cause remaining data + * in the response to be dropped and the socket to be destroyed. + * @since v0.3.8 + * @deprecated Since v14.1.0,v13.14.0 - Use `destroy` instead. + */ + abort(): void; + onSocket(socket: Socket): void; + /** + * Once a socket is assigned to this request and is connected `socket.setTimeout()` will be called. + * @since v0.5.9 + * @param timeout Milliseconds before a request times out. + * @param callback Optional function to be called when a timeout occurs. Same as binding to the `'timeout'` event. + */ + setTimeout(timeout: number, callback?: () => void): this; + /** + * Once a socket is assigned to this request and is connected `socket.setNoDelay()` will be called. + * @since v0.5.9 + */ + setNoDelay(noDelay?: boolean): void; + /** + * Once a socket is assigned to this request and is connected `socket.setKeepAlive()` will be called. + * @since v0.5.9 + */ + setSocketKeepAlive(enable?: boolean, initialDelay?: number): void; + /** + * Returns an array containing the unique names of the current outgoing raw + * headers. Header names are returned with their exact casing being set. + * + * ```js + * request.setHeader('Foo', 'bar'); + * request.setHeader('Set-Cookie', ['foo=bar', 'bar=baz']); + * + * const headerNames = request.getRawHeaderNames(); + * // headerNames === ['Foo', 'Set-Cookie'] + * ``` + * @since v15.13.0, v14.17.0 + */ + getRawHeaderNames(): string[]; + /** + * @deprecated + */ + addListener(event: "abort", listener: () => void): this; + addListener( + event: "connect", + listener: (response: IncomingMessage, socket: Socket, head: Buffer) => void, + ): this; + addListener(event: "continue", listener: () => void): this; + addListener(event: "information", listener: (info: InformationEvent) => void): this; + addListener(event: "response", listener: (response: IncomingMessage) => void): this; + addListener(event: "socket", listener: (socket: Socket) => void): this; + addListener(event: "timeout", listener: () => void): this; + addListener( + event: "upgrade", + listener: (response: IncomingMessage, socket: Socket, head: Buffer) => void, + ): this; + addListener(event: "close", listener: () => void): this; + addListener(event: "drain", listener: () => void): this; + addListener(event: "error", listener: (err: Error) => void): this; + addListener(event: "finish", listener: () => void): this; + addListener(event: "pipe", listener: (src: stream.Readable) => void): this; + addListener(event: "unpipe", listener: (src: stream.Readable) => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + /** + * @deprecated + */ + on(event: "abort", listener: () => void): this; + on(event: "connect", listener: (response: IncomingMessage, socket: Socket, head: Buffer) => void): this; + on(event: "continue", listener: () => void): this; + on(event: "information", listener: (info: InformationEvent) => void): this; + on(event: "response", listener: (response: IncomingMessage) => void): this; + on(event: "socket", listener: (socket: Socket) => void): this; + on(event: "timeout", listener: () => void): this; + on(event: "upgrade", listener: (response: IncomingMessage, socket: Socket, head: Buffer) => void): this; + on(event: "close", listener: () => void): this; + on(event: "drain", listener: () => void): this; + on(event: "error", listener: (err: Error) => void): this; + on(event: "finish", listener: () => void): this; + on(event: "pipe", listener: (src: stream.Readable) => void): this; + on(event: "unpipe", listener: (src: stream.Readable) => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + /** + * @deprecated + */ + once(event: "abort", listener: () => void): this; + once(event: "connect", listener: (response: IncomingMessage, socket: Socket, head: Buffer) => void): this; + once(event: "continue", listener: () => void): this; + once(event: "information", listener: (info: InformationEvent) => void): this; + once(event: "response", listener: (response: IncomingMessage) => void): this; + once(event: "socket", listener: (socket: Socket) => void): this; + once(event: "timeout", listener: () => void): this; + once(event: "upgrade", listener: (response: IncomingMessage, socket: Socket, head: Buffer) => void): this; + once(event: "close", listener: () => void): this; + once(event: "drain", listener: () => void): this; + once(event: "error", listener: (err: Error) => void): this; + once(event: "finish", listener: () => void): this; + once(event: "pipe", listener: (src: stream.Readable) => void): this; + once(event: "unpipe", listener: (src: stream.Readable) => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + /** + * @deprecated + */ + prependListener(event: "abort", listener: () => void): this; + prependListener( + event: "connect", + listener: (response: IncomingMessage, socket: Socket, head: Buffer) => void, + ): this; + prependListener(event: "continue", listener: () => void): this; + prependListener(event: "information", listener: (info: InformationEvent) => void): this; + prependListener(event: "response", listener: (response: IncomingMessage) => void): this; + prependListener(event: "socket", listener: (socket: Socket) => void): this; + prependListener(event: "timeout", listener: () => void): this; + prependListener( + event: "upgrade", + listener: (response: IncomingMessage, socket: Socket, head: Buffer) => void, + ): this; + prependListener(event: "close", listener: () => void): this; + prependListener(event: "drain", listener: () => void): this; + prependListener(event: "error", listener: (err: Error) => void): this; + prependListener(event: "finish", listener: () => void): this; + prependListener(event: "pipe", listener: (src: stream.Readable) => void): this; + prependListener(event: "unpipe", listener: (src: stream.Readable) => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + /** + * @deprecated + */ + prependOnceListener(event: "abort", listener: () => void): this; + prependOnceListener( + event: "connect", + listener: (response: IncomingMessage, socket: Socket, head: Buffer) => void, + ): this; + prependOnceListener(event: "continue", listener: () => void): this; + prependOnceListener(event: "information", listener: (info: InformationEvent) => void): this; + prependOnceListener(event: "response", listener: (response: IncomingMessage) => void): this; + prependOnceListener(event: "socket", listener: (socket: Socket) => void): this; + prependOnceListener(event: "timeout", listener: () => void): this; + prependOnceListener( + event: "upgrade", + listener: (response: IncomingMessage, socket: Socket, head: Buffer) => void, + ): this; + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "drain", listener: () => void): this; + prependOnceListener(event: "error", listener: (err: Error) => void): this; + prependOnceListener(event: "finish", listener: () => void): this; + prependOnceListener(event: "pipe", listener: (src: stream.Readable) => void): this; + prependOnceListener(event: "unpipe", listener: (src: stream.Readable) => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + } + /** + * An `IncomingMessage` object is created by {@link Server} or {@link ClientRequest} and passed as the first argument to the `'request'` and `'response'` event respectively. It may be used to + * access response + * status, headers, and data. + * + * Different from its `socket` value which is a subclass of `stream.Duplex`, the `IncomingMessage` itself extends `stream.Readable` and is created separately to + * parse and emit the incoming HTTP headers and payload, as the underlying socket + * may be reused multiple times in case of keep-alive. + * @since v0.1.17 + */ + class IncomingMessage extends stream.Readable { + constructor(socket: Socket); + /** + * The `message.aborted` property will be `true` if the request has + * been aborted. + * @since v10.1.0 + * @deprecated Since v17.0.0,v16.12.0 - Check `message.destroyed` from stream.Readable. + */ + aborted: boolean; + /** + * In case of server request, the HTTP version sent by the client. In the case of + * client response, the HTTP version of the connected-to server. + * Probably either `'1.1'` or `'1.0'`. + * + * Also `message.httpVersionMajor` is the first integer and `message.httpVersionMinor` is the second. + * @since v0.1.1 + */ + httpVersion: string; + httpVersionMajor: number; + httpVersionMinor: number; + /** + * The `message.complete` property will be `true` if a complete HTTP message has + * been received and successfully parsed. + * + * This property is particularly useful as a means of determining if a client or + * server fully transmitted a message before a connection was terminated: + * + * ```js + * const req = http.request({ + * host: '127.0.0.1', + * port: 8080, + * method: 'POST', + * }, (res) => { + * res.resume(); + * res.on('end', () => { + * if (!res.complete) + * console.error( + * 'The connection was terminated while the message was still being sent'); + * }); + * }); + * ``` + * @since v0.3.0 + */ + complete: boolean; + /** + * Alias for `message.socket`. + * @since v0.1.90 + * @deprecated Since v16.0.0 - Use `socket`. + */ + connection: Socket; + /** + * The `net.Socket` object associated with the connection. + * + * With HTTPS support, use `request.socket.getPeerCertificate()` to obtain the + * client's authentication details. + * + * This property is guaranteed to be an instance of the `net.Socket` class, + * a subclass of `stream.Duplex`, unless the user specified a socket + * type other than `net.Socket` or internally nulled. + * @since v0.3.0 + */ + socket: Socket; + /** + * The request/response headers object. + * + * Key-value pairs of header names and values. Header names are lower-cased. + * + * ```js + * // Prints something like: + * // + * // { 'user-agent': 'curl/7.22.0', + * // host: '127.0.0.1:8000', + * // accept: '*' } + * console.log(request.headers); + * ``` + * + * Duplicates in raw headers are handled in the following ways, depending on the + * header name: + * + * * Duplicates of `age`, `authorization`, `content-length`, `content-type`, `etag`, `expires`, `from`, `host`, `if-modified-since`, `if-unmodified-since`, `last-modified`, `location`, + * `max-forwards`, `proxy-authorization`, `referer`, `retry-after`, `server`, or `user-agent` are discarded. + * To allow duplicate values of the headers listed above to be joined, + * use the option `joinDuplicateHeaders` in {@link request} and {@link createServer}. See RFC 9110 Section 5.3 for more + * information. + * * `set-cookie` is always an array. Duplicates are added to the array. + * * For duplicate `cookie` headers, the values are joined together with `; `. + * * For all other headers, the values are joined together with `, `. + * @since v0.1.5 + */ + headers: IncomingHttpHeaders; + /** + * Similar to `message.headers`, but there is no join logic and the values are + * always arrays of strings, even for headers received just once. + * + * ```js + * // Prints something like: + * // + * // { 'user-agent': ['curl/7.22.0'], + * // host: ['127.0.0.1:8000'], + * // accept: ['*'] } + * console.log(request.headersDistinct); + * ``` + * @since v18.3.0, v16.17.0 + */ + headersDistinct: NodeJS.Dict; + /** + * The raw request/response headers list exactly as they were received. + * + * The keys and values are in the same list. It is _not_ a + * list of tuples. So, the even-numbered offsets are key values, and the + * odd-numbered offsets are the associated values. + * + * Header names are not lowercased, and duplicates are not merged. + * + * ```js + * // Prints something like: + * // + * // [ 'user-agent', + * // 'this is invalid because there can be only one', + * // 'User-Agent', + * // 'curl/7.22.0', + * // 'Host', + * // '127.0.0.1:8000', + * // 'ACCEPT', + * // '*' ] + * console.log(request.rawHeaders); + * ``` + * @since v0.11.6 + */ + rawHeaders: string[]; + /** + * The request/response trailers object. Only populated at the `'end'` event. + * @since v0.3.0 + */ + trailers: NodeJS.Dict; + /** + * Similar to `message.trailers`, but there is no join logic and the values are + * always arrays of strings, even for headers received just once. + * Only populated at the `'end'` event. + * @since v18.3.0, v16.17.0 + */ + trailersDistinct: NodeJS.Dict; + /** + * The raw request/response trailer keys and values exactly as they were + * received. Only populated at the `'end'` event. + * @since v0.11.6 + */ + rawTrailers: string[]; + /** + * Calls `message.socket.setTimeout(msecs, callback)`. + * @since v0.5.9 + */ + setTimeout(msecs: number, callback?: () => void): this; + /** + * **Only valid for request obtained from {@link Server}.** + * + * The request method as a string. Read only. Examples: `'GET'`, `'DELETE'`. + * @since v0.1.1 + */ + method?: string | undefined; + /** + * **Only valid for request obtained from {@link Server}.** + * + * Request URL string. This contains only the URL that is present in the actual + * HTTP request. Take the following request: + * + * ```http + * GET /status?name=ryan HTTP/1.1 + * Accept: text/plain + * ``` + * + * To parse the URL into its parts: + * + * ```js + * new URL(`http://${process.env.HOST ?? 'localhost'}${request.url}`); + * ``` + * + * When `request.url` is `'/status?name=ryan'` and `process.env.HOST` is undefined: + * + * ```console + * $ node + * > new URL(`http://${process.env.HOST ?? 'localhost'}${request.url}`); + * URL { + * href: 'http://localhost/status?name=ryan', + * origin: 'http://localhost', + * protocol: 'http:', + * username: '', + * password: '', + * host: 'localhost', + * hostname: 'localhost', + * port: '', + * pathname: '/status', + * search: '?name=ryan', + * searchParams: URLSearchParams { 'name' => 'ryan' }, + * hash: '' + * } + * ``` + * + * Ensure that you set `process.env.HOST` to the server's host name, or consider replacing this part entirely. If using `req.headers.host`, ensure proper + * validation is used, as clients may specify a custom `Host` header. + * @since v0.1.90 + */ + url?: string | undefined; + /** + * **Only valid for response obtained from {@link ClientRequest}.** + * + * The 3-digit HTTP response status code. E.G. `404`. + * @since v0.1.1 + */ + statusCode?: number | undefined; + /** + * **Only valid for response obtained from {@link ClientRequest}.** + * + * The HTTP response status message (reason phrase). E.G. `OK` or `Internal Server Error`. + * @since v0.11.10 + */ + statusMessage?: string | undefined; + /** + * Calls `destroy()` on the socket that received the `IncomingMessage`. If `error` is provided, an `'error'` event is emitted on the socket and `error` is passed + * as an argument to any listeners on the event. + * @since v0.3.0 + */ + destroy(error?: Error): this; + } + interface AgentOptions extends Partial { + /** + * Keep sockets around in a pool to be used by other requests in the future. Default = false + */ + keepAlive?: boolean | undefined; + /** + * When using HTTP KeepAlive, how often to send TCP KeepAlive packets over sockets being kept alive. Default = 1000. + * Only relevant if keepAlive is set to true. + */ + keepAliveMsecs?: number | undefined; + /** + * Maximum number of sockets to allow per host. Default for Node 0.10 is 5, default for Node 0.12 is Infinity + */ + maxSockets?: number | undefined; + /** + * Maximum number of sockets allowed for all hosts in total. Each request will use a new socket until the maximum is reached. Default: Infinity. + */ + maxTotalSockets?: number | undefined; + /** + * Maximum number of sockets to leave open in a free state. Only relevant if keepAlive is set to true. Default = 256. + */ + maxFreeSockets?: number | undefined; + /** + * Socket timeout in milliseconds. This will set the timeout after the socket is connected. + */ + timeout?: number | undefined; + /** + * Scheduling strategy to apply when picking the next free socket to use. + * @default `lifo` + */ + scheduling?: "fifo" | "lifo" | undefined; + } + /** + * An `Agent` is responsible for managing connection persistence + * and reuse for HTTP clients. It maintains a queue of pending requests + * for a given host and port, reusing a single socket connection for each + * until the queue is empty, at which time the socket is either destroyed + * or put into a pool where it is kept to be used again for requests to the + * same host and port. Whether it is destroyed or pooled depends on the `keepAlive` `option`. + * + * Pooled connections have TCP Keep-Alive enabled for them, but servers may + * still close idle connections, in which case they will be removed from the + * pool and a new connection will be made when a new HTTP request is made for + * that host and port. Servers may also refuse to allow multiple requests + * over the same connection, in which case the connection will have to be + * remade for every request and cannot be pooled. The `Agent` will still make + * the requests to that server, but each one will occur over a new connection. + * + * When a connection is closed by the client or the server, it is removed + * from the pool. Any unused sockets in the pool will be unrefed so as not + * to keep the Node.js process running when there are no outstanding requests. + * (see `socket.unref()`). + * + * It is good practice, to `destroy()` an `Agent` instance when it is no + * longer in use, because unused sockets consume OS resources. + * + * Sockets are removed from an agent when the socket emits either + * a `'close'` event or an `'agentRemove'` event. When intending to keep one + * HTTP request open for a long time without keeping it in the agent, something + * like the following may be done: + * + * ```js + * http.get(options, (res) => { + * // Do stuff + * }).on('socket', (socket) => { + * socket.emit('agentRemove'); + * }); + * ``` + * + * An agent may also be used for an individual request. By providing `{agent: false}` as an option to the `http.get()` or `http.request()` functions, a one-time use `Agent` with default options + * will be used + * for the client connection. + * + * `agent:false`: + * + * ```js + * http.get({ + * hostname: 'localhost', + * port: 80, + * path: '/', + * agent: false, // Create a new agent just for this one request + * }, (res) => { + * // Do stuff with response + * }); + * ``` + * + * `options` in [`socket.connect()`](https://nodejs.org/docs/latest-v20.x/api/net.html#socketconnectoptions-connectlistener) are also supported. + * + * To configure any of them, a custom {@link Agent} instance must be created. + * + * ```js + * const http = require('node:http'); + * const keepAliveAgent = new http.Agent({ keepAlive: true }); + * options.agent = keepAliveAgent; + * http.request(options, onResponseCallback) + * ``` + * @since v0.3.4 + */ + class Agent extends EventEmitter { + /** + * By default set to 256. For agents with `keepAlive` enabled, this + * sets the maximum number of sockets that will be left open in the free + * state. + * @since v0.11.7 + */ + maxFreeSockets: number; + /** + * By default set to `Infinity`. Determines how many concurrent sockets the agent + * can have open per origin. Origin is the returned value of `agent.getName()`. + * @since v0.3.6 + */ + maxSockets: number; + /** + * By default set to `Infinity`. Determines how many concurrent sockets the agent + * can have open. Unlike `maxSockets`, this parameter applies across all origins. + * @since v14.5.0, v12.19.0 + */ + maxTotalSockets: number; + /** + * An object which contains arrays of sockets currently awaiting use by + * the agent when `keepAlive` is enabled. Do not modify. + * + * Sockets in the `freeSockets` list will be automatically destroyed and + * removed from the array on `'timeout'`. + * @since v0.11.4 + */ + readonly freeSockets: NodeJS.ReadOnlyDict; + /** + * An object which contains arrays of sockets currently in use by the + * agent. Do not modify. + * @since v0.3.6 + */ + readonly sockets: NodeJS.ReadOnlyDict; + /** + * An object which contains queues of requests that have not yet been assigned to + * sockets. Do not modify. + * @since v0.5.9 + */ + readonly requests: NodeJS.ReadOnlyDict; + constructor(opts?: AgentOptions); + /** + * Destroy any sockets that are currently in use by the agent. + * + * It is usually not necessary to do this. However, if using an + * agent with `keepAlive` enabled, then it is best to explicitly shut down + * the agent when it is no longer needed. Otherwise, + * sockets might stay open for quite a long time before the server + * terminates them. + * @since v0.11.4 + */ + destroy(): void; + } + const METHODS: string[]; + const STATUS_CODES: { + [errorCode: number]: string | undefined; + [errorCode: string]: string | undefined; + }; + /** + * Returns a new instance of {@link Server}. + * + * The `requestListener` is a function which is automatically + * added to the `'request'` event. + * + * ```js + * import http from 'node:http'; + * + * // Create a local server to receive data from + * const server = http.createServer((req, res) => { + * res.writeHead(200, { 'Content-Type': 'application/json' }); + * res.end(JSON.stringify({ + * data: 'Hello World!', + * })); + * }); + * + * server.listen(8000); + * ``` + * + * ```js + * import http from 'node:http'; + * + * // Create a local server to receive data from + * const server = http.createServer(); + * + * // Listen to the request event + * server.on('request', (request, res) => { + * res.writeHead(200, { 'Content-Type': 'application/json' }); + * res.end(JSON.stringify({ + * data: 'Hello World!', + * })); + * }); + * + * server.listen(8000); + * ``` + * @since v0.1.13 + */ + function createServer< + Request extends typeof IncomingMessage = typeof IncomingMessage, + Response extends typeof ServerResponse = typeof ServerResponse, + >(requestListener?: RequestListener): Server; + function createServer< + Request extends typeof IncomingMessage = typeof IncomingMessage, + Response extends typeof ServerResponse = typeof ServerResponse, + >( + options: ServerOptions, + requestListener?: RequestListener, + ): Server; + // although RequestOptions are passed as ClientRequestArgs to ClientRequest directly, + // create interface RequestOptions would make the naming more clear to developers + interface RequestOptions extends ClientRequestArgs {} + /** + * `options` in `socket.connect()` are also supported. + * + * Node.js maintains several connections per server to make HTTP requests. + * This function allows one to transparently issue requests. + * + * `url` can be a string or a `URL` object. If `url` is a + * string, it is automatically parsed with `new URL()`. If it is a `URL` object, it will be automatically converted to an ordinary `options` object. + * + * If both `url` and `options` are specified, the objects are merged, with the `options` properties taking precedence. + * + * The optional `callback` parameter will be added as a one-time listener for + * the `'response'` event. + * + * `http.request()` returns an instance of the {@link ClientRequest} class. The `ClientRequest` instance is a writable stream. If one needs to + * upload a file with a POST request, then write to the `ClientRequest` object. + * + * ```js + * import http from 'node:http'; + * import { Buffer } from 'node:buffer'; + * + * const postData = JSON.stringify({ + * 'msg': 'Hello World!', + * }); + * + * const options = { + * hostname: 'www.google.com', + * port: 80, + * path: '/upload', + * method: 'POST', + * headers: { + * 'Content-Type': 'application/json', + * 'Content-Length': Buffer.byteLength(postData), + * }, + * }; + * + * const req = http.request(options, (res) => { + * console.log(`STATUS: ${res.statusCode}`); + * console.log(`HEADERS: ${JSON.stringify(res.headers)}`); + * res.setEncoding('utf8'); + * res.on('data', (chunk) => { + * console.log(`BODY: ${chunk}`); + * }); + * res.on('end', () => { + * console.log('No more data in response.'); + * }); + * }); + * + * req.on('error', (e) => { + * console.error(`problem with request: ${e.message}`); + * }); + * + * // Write data to request body + * req.write(postData); + * req.end(); + * ``` + * + * In the example `req.end()` was called. With `http.request()` one + * must always call `req.end()` to signify the end of the request - + * even if there is no data being written to the request body. + * + * If any error is encountered during the request (be that with DNS resolution, + * TCP level errors, or actual HTTP parse errors) an `'error'` event is emitted + * on the returned request object. As with all `'error'` events, if no listeners + * are registered the error will be thrown. + * + * There are a few special headers that should be noted. + * + * * Sending a 'Connection: keep-alive' will notify Node.js that the connection to + * the server should be persisted until the next request. + * * Sending a 'Content-Length' header will disable the default chunked encoding. + * * Sending an 'Expect' header will immediately send the request headers. + * Usually, when sending 'Expect: 100-continue', both a timeout and a listener + * for the `'continue'` event should be set. See RFC 2616 Section 8.2.3 for more + * information. + * * Sending an Authorization header will override using the `auth` option + * to compute basic authentication. + * + * Example using a `URL` as `options`: + * + * ```js + * const options = new URL('http://abc:xyz@example.com'); + * + * const req = http.request(options, (res) => { + * // ... + * }); + * ``` + * + * In a successful request, the following events will be emitted in the following + * order: + * + * * `'socket'` + * * `'response'` + * * `'data'` any number of times, on the `res` object + * (`'data'` will not be emitted at all if the response body is empty, for + * instance, in most redirects) + * * `'end'` on the `res` object + * * `'close'` + * + * In the case of a connection error, the following events will be emitted: + * + * * `'socket'` + * * `'error'` + * * `'close'` + * + * In the case of a premature connection close before the response is received, + * the following events will be emitted in the following order: + * + * * `'socket'` + * * `'error'` with an error with message `'Error: socket hang up'` and code `'ECONNRESET'` + * * `'close'` + * + * In the case of a premature connection close after the response is received, + * the following events will be emitted in the following order: + * + * * `'socket'` + * * `'response'` + * * `'data'` any number of times, on the `res` object + * * (connection closed here) + * * `'aborted'` on the `res` object + * * `'close'` + * * `'error'` on the `res` object with an error with message `'Error: aborted'` and code `'ECONNRESET'` + * * `'close'` on the `res` object + * + * If `req.destroy()` is called before a socket is assigned, the following + * events will be emitted in the following order: + * + * * (`req.destroy()` called here) + * * `'error'` with an error with message `'Error: socket hang up'` and code `'ECONNRESET'`, or the error with which `req.destroy()` was called + * * `'close'` + * + * If `req.destroy()` is called before the connection succeeds, the following + * events will be emitted in the following order: + * + * * `'socket'` + * * (`req.destroy()` called here) + * * `'error'` with an error with message `'Error: socket hang up'` and code `'ECONNRESET'`, or the error with which `req.destroy()` was called + * * `'close'` + * + * If `req.destroy()` is called after the response is received, the following + * events will be emitted in the following order: + * + * * `'socket'` + * * `'response'` + * * `'data'` any number of times, on the `res` object + * * (`req.destroy()` called here) + * * `'aborted'` on the `res` object + * * `'close'` + * * `'error'` on the `res` object with an error with message `'Error: aborted'` and code `'ECONNRESET'`, or the error with which `req.destroy()` was called + * * `'close'` on the `res` object + * + * If `req.abort()` is called before a socket is assigned, the following + * events will be emitted in the following order: + * + * * (`req.abort()` called here) + * * `'abort'` + * * `'close'` + * + * If `req.abort()` is called before the connection succeeds, the following + * events will be emitted in the following order: + * + * * `'socket'` + * * (`req.abort()` called here) + * * `'abort'` + * * `'error'` with an error with message `'Error: socket hang up'` and code `'ECONNRESET'` + * * `'close'` + * + * If `req.abort()` is called after the response is received, the following + * events will be emitted in the following order: + * + * * `'socket'` + * * `'response'` + * * `'data'` any number of times, on the `res` object + * * (`req.abort()` called here) + * * `'abort'` + * * `'aborted'` on the `res` object + * * `'error'` on the `res` object with an error with message `'Error: aborted'` and code `'ECONNRESET'`. + * * `'close'` + * * `'close'` on the `res` object + * + * Setting the `timeout` option or using the `setTimeout()` function will + * not abort the request or do anything besides add a `'timeout'` event. + * + * Passing an `AbortSignal` and then calling `abort()` on the corresponding `AbortController` will behave the same way as calling `.destroy()` on the + * request. Specifically, the `'error'` event will be emitted with an error with + * the message `'AbortError: The operation was aborted'`, the code `'ABORT_ERR'` and the `cause`, if one was provided. + * @since v0.3.6 + */ + function request(options: RequestOptions | string | URL, callback?: (res: IncomingMessage) => void): ClientRequest; + function request( + url: string | URL, + options: RequestOptions, + callback?: (res: IncomingMessage) => void, + ): ClientRequest; + /** + * Since most requests are GET requests without bodies, Node.js provides this + * convenience method. The only difference between this method and {@link request} is that it sets the method to GET by default and calls `req.end()` automatically. The callback must take care to + * consume the response + * data for reasons stated in {@link ClientRequest} section. + * + * The `callback` is invoked with a single argument that is an instance of {@link IncomingMessage}. + * + * JSON fetching example: + * + * ```js + * http.get('http://localhost:8000/', (res) => { + * const { statusCode } = res; + * const contentType = res.headers['content-type']; + * + * let error; + * // Any 2xx status code signals a successful response but + * // here we're only checking for 200. + * if (statusCode !== 200) { + * error = new Error('Request Failed.\n' + + * `Status Code: ${statusCode}`); + * } else if (!/^application\/json/.test(contentType)) { + * error = new Error('Invalid content-type.\n' + + * `Expected application/json but received ${contentType}`); + * } + * if (error) { + * console.error(error.message); + * // Consume response data to free up memory + * res.resume(); + * return; + * } + * + * res.setEncoding('utf8'); + * let rawData = ''; + * res.on('data', (chunk) => { rawData += chunk; }); + * res.on('end', () => { + * try { + * const parsedData = JSON.parse(rawData); + * console.log(parsedData); + * } catch (e) { + * console.error(e.message); + * } + * }); + * }).on('error', (e) => { + * console.error(`Got error: ${e.message}`); + * }); + * + * // Create a local server to receive data from + * const server = http.createServer((req, res) => { + * res.writeHead(200, { 'Content-Type': 'application/json' }); + * res.end(JSON.stringify({ + * data: 'Hello World!', + * })); + * }); + * + * server.listen(8000); + * ``` + * @since v0.3.6 + * @param options Accepts the same `options` as {@link request}, with the method set to GET by default. + */ + function get(options: RequestOptions | string | URL, callback?: (res: IncomingMessage) => void): ClientRequest; + function get(url: string | URL, options: RequestOptions, callback?: (res: IncomingMessage) => void): ClientRequest; + /** + * Performs the low-level validations on the provided `name` that are done when `res.setHeader(name, value)` is called. + * + * Passing illegal value as `name` will result in a `TypeError` being thrown, + * identified by `code: 'ERR_INVALID_HTTP_TOKEN'`. + * + * It is not necessary to use this method before passing headers to an HTTP request + * or response. The HTTP module will automatically validate such headers. + * + * Example: + * + * ```js + * import { validateHeaderName } from 'node:http'; + * + * try { + * validateHeaderName(''); + * } catch (err) { + * console.error(err instanceof TypeError); // --> true + * console.error(err.code); // --> 'ERR_INVALID_HTTP_TOKEN' + * console.error(err.message); // --> 'Header name must be a valid HTTP token [""]' + * } + * ``` + * @since v14.3.0 + * @param [label='Header name'] Label for error message. + */ + function validateHeaderName(name: string): void; + /** + * Performs the low-level validations on the provided `value` that are done when `res.setHeader(name, value)` is called. + * + * Passing illegal value as `value` will result in a `TypeError` being thrown. + * + * * Undefined value error is identified by `code: 'ERR_HTTP_INVALID_HEADER_VALUE'`. + * * Invalid value character error is identified by `code: 'ERR_INVALID_CHAR'`. + * + * It is not necessary to use this method before passing headers to an HTTP request + * or response. The HTTP module will automatically validate such headers. + * + * Examples: + * + * ```js + * import { validateHeaderValue } from 'node:http'; + * + * try { + * validateHeaderValue('x-my-header', undefined); + * } catch (err) { + * console.error(err instanceof TypeError); // --> true + * console.error(err.code === 'ERR_HTTP_INVALID_HEADER_VALUE'); // --> true + * console.error(err.message); // --> 'Invalid value "undefined" for header "x-my-header"' + * } + * + * try { + * validateHeaderValue('x-my-header', 'oʊmɪɡə'); + * } catch (err) { + * console.error(err instanceof TypeError); // --> true + * console.error(err.code === 'ERR_INVALID_CHAR'); // --> true + * console.error(err.message); // --> 'Invalid character in header content ["x-my-header"]' + * } + * ``` + * @since v14.3.0 + * @param name Header name + * @param value Header value + */ + function validateHeaderValue(name: string, value: string): void; + /** + * Set the maximum number of idle HTTP parsers. + * @since v18.8.0, v16.18.0 + * @param [max=1000] + */ + function setMaxIdleHTTPParsers(max: number): void; + /** + * Global instance of `Agent` which is used as the default for all HTTP client + * requests. Diverges from a default `Agent` configuration by having `keepAlive` + * enabled and a `timeout` of 5 seconds. + * @since v0.5.9 + */ + let globalAgent: Agent; + /** + * Read-only property specifying the maximum allowed size of HTTP headers in bytes. + * Defaults to 16KB. Configurable using the `--max-http-header-size` CLI option. + */ + const maxHeaderSize: number; +} +declare module "node:http" { + export * from "http"; +} diff --git a/node_modules/@types/node/http2.d.ts b/node_modules/@types/node/http2.d.ts new file mode 100644 index 0000000..5212c9b --- /dev/null +++ b/node_modules/@types/node/http2.d.ts @@ -0,0 +1,2418 @@ +/** + * The `node:http2` module provides an implementation of the [HTTP/2](https://tools.ietf.org/html/rfc7540) protocol. + * It can be accessed using: + * + * ```js + * const http2 = require('node:http2'); + * ``` + * @since v8.4.0 + * @see [source](https://github.com/nodejs/node/blob/v20.13.1/lib/http2.js) + */ +declare module "http2" { + import EventEmitter = require("node:events"); + import * as fs from "node:fs"; + import * as net from "node:net"; + import * as stream from "node:stream"; + import * as tls from "node:tls"; + import * as url from "node:url"; + import { + IncomingHttpHeaders as Http1IncomingHttpHeaders, + IncomingMessage, + OutgoingHttpHeaders, + ServerResponse, + } from "node:http"; + export { OutgoingHttpHeaders } from "node:http"; + export interface IncomingHttpStatusHeader { + ":status"?: number | undefined; + } + export interface IncomingHttpHeaders extends Http1IncomingHttpHeaders { + ":path"?: string | undefined; + ":method"?: string | undefined; + ":authority"?: string | undefined; + ":scheme"?: string | undefined; + } + // Http2Stream + export interface StreamPriorityOptions { + exclusive?: boolean | undefined; + parent?: number | undefined; + weight?: number | undefined; + silent?: boolean | undefined; + } + export interface StreamState { + localWindowSize?: number | undefined; + state?: number | undefined; + localClose?: number | undefined; + remoteClose?: number | undefined; + sumDependencyWeight?: number | undefined; + weight?: number | undefined; + } + export interface ServerStreamResponseOptions { + endStream?: boolean | undefined; + waitForTrailers?: boolean | undefined; + } + export interface StatOptions { + offset: number; + length: number; + } + export interface ServerStreamFileResponseOptions { + // eslint-disable-next-line @typescript-eslint/no-invalid-void-type + statCheck?(stats: fs.Stats, headers: OutgoingHttpHeaders, statOptions: StatOptions): void | boolean; + waitForTrailers?: boolean | undefined; + offset?: number | undefined; + length?: number | undefined; + } + export interface ServerStreamFileResponseOptionsWithError extends ServerStreamFileResponseOptions { + onError?(err: NodeJS.ErrnoException): void; + } + export interface Http2Stream extends stream.Duplex { + /** + * Set to `true` if the `Http2Stream` instance was aborted abnormally. When set, + * the `'aborted'` event will have been emitted. + * @since v8.4.0 + */ + readonly aborted: boolean; + /** + * This property shows the number of characters currently buffered to be written. + * See `net.Socket.bufferSize` for details. + * @since v11.2.0, v10.16.0 + */ + readonly bufferSize: number; + /** + * Set to `true` if the `Http2Stream` instance has been closed. + * @since v9.4.0 + */ + readonly closed: boolean; + /** + * Set to `true` if the `Http2Stream` instance has been destroyed and is no longer + * usable. + * @since v8.4.0 + */ + readonly destroyed: boolean; + /** + * Set to `true` if the `END_STREAM` flag was set in the request or response + * HEADERS frame received, indicating that no additional data should be received + * and the readable side of the `Http2Stream` will be closed. + * @since v10.11.0 + */ + readonly endAfterHeaders: boolean; + /** + * The numeric stream identifier of this `Http2Stream` instance. Set to `undefined` if the stream identifier has not yet been assigned. + * @since v8.4.0 + */ + readonly id?: number | undefined; + /** + * Set to `true` if the `Http2Stream` instance has not yet been assigned a + * numeric stream identifier. + * @since v9.4.0 + */ + readonly pending: boolean; + /** + * Set to the `RST_STREAM` `error code` reported when the `Http2Stream` is + * destroyed after either receiving an `RST_STREAM` frame from the connected peer, + * calling `http2stream.close()`, or `http2stream.destroy()`. Will be `undefined` if the `Http2Stream` has not been closed. + * @since v8.4.0 + */ + readonly rstCode: number; + /** + * An object containing the outbound headers sent for this `Http2Stream`. + * @since v9.5.0 + */ + readonly sentHeaders: OutgoingHttpHeaders; + /** + * An array of objects containing the outbound informational (additional) headers + * sent for this `Http2Stream`. + * @since v9.5.0 + */ + readonly sentInfoHeaders?: OutgoingHttpHeaders[] | undefined; + /** + * An object containing the outbound trailers sent for this `HttpStream`. + * @since v9.5.0 + */ + readonly sentTrailers?: OutgoingHttpHeaders | undefined; + /** + * A reference to the `Http2Session` instance that owns this `Http2Stream`. The + * value will be `undefined` after the `Http2Stream` instance is destroyed. + * @since v8.4.0 + */ + readonly session: Http2Session | undefined; + /** + * Provides miscellaneous information about the current state of the `Http2Stream`. + * + * A current state of this `Http2Stream`. + * @since v8.4.0 + */ + readonly state: StreamState; + /** + * Closes the `Http2Stream` instance by sending an `RST_STREAM` frame to the + * connected HTTP/2 peer. + * @since v8.4.0 + * @param [code=http2.constants.NGHTTP2_NO_ERROR] Unsigned 32-bit integer identifying the error code. + * @param callback An optional function registered to listen for the `'close'` event. + */ + close(code?: number, callback?: () => void): void; + /** + * Updates the priority for this `Http2Stream` instance. + * @since v8.4.0 + */ + priority(options: StreamPriorityOptions): void; + /** + * ```js + * const http2 = require('node:http2'); + * const client = http2.connect('http://example.org:8000'); + * const { NGHTTP2_CANCEL } = http2.constants; + * const req = client.request({ ':path': '/' }); + * + * // Cancel the stream if there's no activity after 5 seconds + * req.setTimeout(5000, () => req.close(NGHTTP2_CANCEL)); + * ``` + * @since v8.4.0 + */ + setTimeout(msecs: number, callback?: () => void): void; + /** + * Sends a trailing `HEADERS` frame to the connected HTTP/2 peer. This method + * will cause the `Http2Stream` to be immediately closed and must only be + * called after the `'wantTrailers'` event has been emitted. When sending a + * request or sending a response, the `options.waitForTrailers` option must be set + * in order to keep the `Http2Stream` open after the final `DATA` frame so that + * trailers can be sent. + * + * ```js + * const http2 = require('node:http2'); + * const server = http2.createServer(); + * server.on('stream', (stream) => { + * stream.respond(undefined, { waitForTrailers: true }); + * stream.on('wantTrailers', () => { + * stream.sendTrailers({ xyz: 'abc' }); + * }); + * stream.end('Hello World'); + * }); + * ``` + * + * The HTTP/1 specification forbids trailers from containing HTTP/2 pseudo-header + * fields (e.g. `':method'`, `':path'`, etc). + * @since v10.0.0 + */ + sendTrailers(headers: OutgoingHttpHeaders): void; + addListener(event: "aborted", listener: () => void): this; + addListener(event: "close", listener: () => void): this; + addListener(event: "data", listener: (chunk: Buffer | string) => void): this; + addListener(event: "drain", listener: () => void): this; + addListener(event: "end", listener: () => void): this; + addListener(event: "error", listener: (err: Error) => void): this; + addListener(event: "finish", listener: () => void): this; + addListener(event: "frameError", listener: (frameType: number, errorCode: number) => void): this; + addListener(event: "pipe", listener: (src: stream.Readable) => void): this; + addListener(event: "unpipe", listener: (src: stream.Readable) => void): this; + addListener(event: "streamClosed", listener: (code: number) => void): this; + addListener(event: "timeout", listener: () => void): this; + addListener(event: "trailers", listener: (trailers: IncomingHttpHeaders, flags: number) => void): this; + addListener(event: "wantTrailers", listener: () => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + emit(event: "aborted"): boolean; + emit(event: "close"): boolean; + emit(event: "data", chunk: Buffer | string): boolean; + emit(event: "drain"): boolean; + emit(event: "end"): boolean; + emit(event: "error", err: Error): boolean; + emit(event: "finish"): boolean; + emit(event: "frameError", frameType: number, errorCode: number): boolean; + emit(event: "pipe", src: stream.Readable): boolean; + emit(event: "unpipe", src: stream.Readable): boolean; + emit(event: "streamClosed", code: number): boolean; + emit(event: "timeout"): boolean; + emit(event: "trailers", trailers: IncomingHttpHeaders, flags: number): boolean; + emit(event: "wantTrailers"): boolean; + emit(event: string | symbol, ...args: any[]): boolean; + on(event: "aborted", listener: () => void): this; + on(event: "close", listener: () => void): this; + on(event: "data", listener: (chunk: Buffer | string) => void): this; + on(event: "drain", listener: () => void): this; + on(event: "end", listener: () => void): this; + on(event: "error", listener: (err: Error) => void): this; + on(event: "finish", listener: () => void): this; + on(event: "frameError", listener: (frameType: number, errorCode: number) => void): this; + on(event: "pipe", listener: (src: stream.Readable) => void): this; + on(event: "unpipe", listener: (src: stream.Readable) => void): this; + on(event: "streamClosed", listener: (code: number) => void): this; + on(event: "timeout", listener: () => void): this; + on(event: "trailers", listener: (trailers: IncomingHttpHeaders, flags: number) => void): this; + on(event: "wantTrailers", listener: () => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + once(event: "aborted", listener: () => void): this; + once(event: "close", listener: () => void): this; + once(event: "data", listener: (chunk: Buffer | string) => void): this; + once(event: "drain", listener: () => void): this; + once(event: "end", listener: () => void): this; + once(event: "error", listener: (err: Error) => void): this; + once(event: "finish", listener: () => void): this; + once(event: "frameError", listener: (frameType: number, errorCode: number) => void): this; + once(event: "pipe", listener: (src: stream.Readable) => void): this; + once(event: "unpipe", listener: (src: stream.Readable) => void): this; + once(event: "streamClosed", listener: (code: number) => void): this; + once(event: "timeout", listener: () => void): this; + once(event: "trailers", listener: (trailers: IncomingHttpHeaders, flags: number) => void): this; + once(event: "wantTrailers", listener: () => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + prependListener(event: "aborted", listener: () => void): this; + prependListener(event: "close", listener: () => void): this; + prependListener(event: "data", listener: (chunk: Buffer | string) => void): this; + prependListener(event: "drain", listener: () => void): this; + prependListener(event: "end", listener: () => void): this; + prependListener(event: "error", listener: (err: Error) => void): this; + prependListener(event: "finish", listener: () => void): this; + prependListener(event: "frameError", listener: (frameType: number, errorCode: number) => void): this; + prependListener(event: "pipe", listener: (src: stream.Readable) => void): this; + prependListener(event: "unpipe", listener: (src: stream.Readable) => void): this; + prependListener(event: "streamClosed", listener: (code: number) => void): this; + prependListener(event: "timeout", listener: () => void): this; + prependListener(event: "trailers", listener: (trailers: IncomingHttpHeaders, flags: number) => void): this; + prependListener(event: "wantTrailers", listener: () => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener(event: "aborted", listener: () => void): this; + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "data", listener: (chunk: Buffer | string) => void): this; + prependOnceListener(event: "drain", listener: () => void): this; + prependOnceListener(event: "end", listener: () => void): this; + prependOnceListener(event: "error", listener: (err: Error) => void): this; + prependOnceListener(event: "finish", listener: () => void): this; + prependOnceListener(event: "frameError", listener: (frameType: number, errorCode: number) => void): this; + prependOnceListener(event: "pipe", listener: (src: stream.Readable) => void): this; + prependOnceListener(event: "unpipe", listener: (src: stream.Readable) => void): this; + prependOnceListener(event: "streamClosed", listener: (code: number) => void): this; + prependOnceListener(event: "timeout", listener: () => void): this; + prependOnceListener(event: "trailers", listener: (trailers: IncomingHttpHeaders, flags: number) => void): this; + prependOnceListener(event: "wantTrailers", listener: () => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + } + export interface ClientHttp2Stream extends Http2Stream { + addListener(event: "continue", listener: () => {}): this; + addListener( + event: "headers", + listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void, + ): this; + addListener(event: "push", listener: (headers: IncomingHttpHeaders, flags: number) => void): this; + addListener( + event: "response", + listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void, + ): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + emit(event: "continue"): boolean; + emit(event: "headers", headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number): boolean; + emit(event: "push", headers: IncomingHttpHeaders, flags: number): boolean; + emit(event: "response", headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number): boolean; + emit(event: string | symbol, ...args: any[]): boolean; + on(event: "continue", listener: () => {}): this; + on( + event: "headers", + listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void, + ): this; + on(event: "push", listener: (headers: IncomingHttpHeaders, flags: number) => void): this; + on( + event: "response", + listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void, + ): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + once(event: "continue", listener: () => {}): this; + once( + event: "headers", + listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void, + ): this; + once(event: "push", listener: (headers: IncomingHttpHeaders, flags: number) => void): this; + once( + event: "response", + listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void, + ): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + prependListener(event: "continue", listener: () => {}): this; + prependListener( + event: "headers", + listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void, + ): this; + prependListener(event: "push", listener: (headers: IncomingHttpHeaders, flags: number) => void): this; + prependListener( + event: "response", + listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void, + ): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener(event: "continue", listener: () => {}): this; + prependOnceListener( + event: "headers", + listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void, + ): this; + prependOnceListener(event: "push", listener: (headers: IncomingHttpHeaders, flags: number) => void): this; + prependOnceListener( + event: "response", + listener: (headers: IncomingHttpHeaders & IncomingHttpStatusHeader, flags: number) => void, + ): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + } + export interface ServerHttp2Stream extends Http2Stream { + /** + * True if headers were sent, false otherwise (read-only). + * @since v8.4.0 + */ + readonly headersSent: boolean; + /** + * Read-only property mapped to the `SETTINGS_ENABLE_PUSH` flag of the remote + * client's most recent `SETTINGS` frame. Will be `true` if the remote peer + * accepts push streams, `false` otherwise. Settings are the same for every `Http2Stream` in the same `Http2Session`. + * @since v8.4.0 + */ + readonly pushAllowed: boolean; + /** + * Sends an additional informational `HEADERS` frame to the connected HTTP/2 peer. + * @since v8.4.0 + */ + additionalHeaders(headers: OutgoingHttpHeaders): void; + /** + * Initiates a push stream. The callback is invoked with the new `Http2Stream` instance created for the push stream passed as the second argument, or an `Error` passed as the first argument. + * + * ```js + * const http2 = require('node:http2'); + * const server = http2.createServer(); + * server.on('stream', (stream) => { + * stream.respond({ ':status': 200 }); + * stream.pushStream({ ':path': '/' }, (err, pushStream, headers) => { + * if (err) throw err; + * pushStream.respond({ ':status': 200 }); + * pushStream.end('some pushed data'); + * }); + * stream.end('some data'); + * }); + * ``` + * + * Setting the weight of a push stream is not allowed in the `HEADERS` frame. Pass + * a `weight` value to `http2stream.priority` with the `silent` option set to `true` to enable server-side bandwidth balancing between concurrent streams. + * + * Calling `http2stream.pushStream()` from within a pushed stream is not permitted + * and will throw an error. + * @since v8.4.0 + * @param callback Callback that is called once the push stream has been initiated. + */ + pushStream( + headers: OutgoingHttpHeaders, + callback?: (err: Error | null, pushStream: ServerHttp2Stream, headers: OutgoingHttpHeaders) => void, + ): void; + pushStream( + headers: OutgoingHttpHeaders, + options?: StreamPriorityOptions, + callback?: (err: Error | null, pushStream: ServerHttp2Stream, headers: OutgoingHttpHeaders) => void, + ): void; + /** + * ```js + * const http2 = require('node:http2'); + * const server = http2.createServer(); + * server.on('stream', (stream) => { + * stream.respond({ ':status': 200 }); + * stream.end('some data'); + * }); + * ``` + * + * Initiates a response. When the `options.waitForTrailers` option is set, the`'wantTrailers'` event will be emitted immediately after queuing the last chunk + * of payload data to be sent. The `http2stream.sendTrailers()` method can then be + * used to sent trailing header fields to the peer. + * + * When `options.waitForTrailers` is set, the `Http2Stream` will not automatically + * close when the final `DATA` frame is transmitted. User code must call either `http2stream.sendTrailers()` or `http2stream.close()` to close the `Http2Stream`. + * + * ```js + * const http2 = require('node:http2'); + * const server = http2.createServer(); + * server.on('stream', (stream) => { + * stream.respond({ ':status': 200 }, { waitForTrailers: true }); + * stream.on('wantTrailers', () => { + * stream.sendTrailers({ ABC: 'some value to send' }); + * }); + * stream.end('some data'); + * }); + * ``` + * @since v8.4.0 + */ + respond(headers?: OutgoingHttpHeaders, options?: ServerStreamResponseOptions): void; + /** + * Initiates a response whose data is read from the given file descriptor. No + * validation is performed on the given file descriptor. If an error occurs while + * attempting to read data using the file descriptor, the `Http2Stream` will be + * closed using an `RST_STREAM` frame using the standard `INTERNAL_ERROR` code. + * + * When used, the `Http2Stream` object's `Duplex` interface will be closed + * automatically. + * + * ```js + * const http2 = require('node:http2'); + * const fs = require('node:fs'); + * + * const server = http2.createServer(); + * server.on('stream', (stream) => { + * const fd = fs.openSync('/some/file', 'r'); + * + * const stat = fs.fstatSync(fd); + * const headers = { + * 'content-length': stat.size, + * 'last-modified': stat.mtime.toUTCString(), + * 'content-type': 'text/plain; charset=utf-8', + * }; + * stream.respondWithFD(fd, headers); + * stream.on('close', () => fs.closeSync(fd)); + * }); + * ``` + * + * The optional `options.statCheck` function may be specified to give user code + * an opportunity to set additional content headers based on the `fs.Stat` details + * of the given fd. If the `statCheck` function is provided, the `http2stream.respondWithFD()` method will perform an `fs.fstat()` call to + * collect details on the provided file descriptor. + * + * The `offset` and `length` options may be used to limit the response to a + * specific range subset. This can be used, for instance, to support HTTP Range + * requests. + * + * The file descriptor or `FileHandle` is not closed when the stream is closed, + * so it will need to be closed manually once it is no longer needed. + * Using the same file descriptor concurrently for multiple streams + * is not supported and may result in data loss. Re-using a file descriptor + * after a stream has finished is supported. + * + * When the `options.waitForTrailers` option is set, the `'wantTrailers'` event + * will be emitted immediately after queuing the last chunk of payload data to be + * sent. The `http2stream.sendTrailers()` method can then be used to sent trailing + * header fields to the peer. + * + * When `options.waitForTrailers` is set, the `Http2Stream` will not automatically + * close when the final `DATA` frame is transmitted. User code _must_ call either `http2stream.sendTrailers()` or `http2stream.close()` to close the `Http2Stream`. + * + * ```js + * const http2 = require('node:http2'); + * const fs = require('node:fs'); + * + * const server = http2.createServer(); + * server.on('stream', (stream) => { + * const fd = fs.openSync('/some/file', 'r'); + * + * const stat = fs.fstatSync(fd); + * const headers = { + * 'content-length': stat.size, + * 'last-modified': stat.mtime.toUTCString(), + * 'content-type': 'text/plain; charset=utf-8', + * }; + * stream.respondWithFD(fd, headers, { waitForTrailers: true }); + * stream.on('wantTrailers', () => { + * stream.sendTrailers({ ABC: 'some value to send' }); + * }); + * + * stream.on('close', () => fs.closeSync(fd)); + * }); + * ``` + * @since v8.4.0 + * @param fd A readable file descriptor. + */ + respondWithFD( + fd: number | fs.promises.FileHandle, + headers?: OutgoingHttpHeaders, + options?: ServerStreamFileResponseOptions, + ): void; + /** + * Sends a regular file as the response. The `path` must specify a regular file + * or an `'error'` event will be emitted on the `Http2Stream` object. + * + * When used, the `Http2Stream` object's `Duplex` interface will be closed + * automatically. + * + * The optional `options.statCheck` function may be specified to give user code + * an opportunity to set additional content headers based on the `fs.Stat` details + * of the given file: + * + * If an error occurs while attempting to read the file data, the `Http2Stream` will be closed using an `RST_STREAM` frame using the standard `INTERNAL_ERROR` code. If the `onError` callback is + * defined, then it will be called. Otherwise + * the stream will be destroyed. + * + * Example using a file path: + * + * ```js + * const http2 = require('node:http2'); + * const server = http2.createServer(); + * server.on('stream', (stream) => { + * function statCheck(stat, headers) { + * headers['last-modified'] = stat.mtime.toUTCString(); + * } + * + * function onError(err) { + * // stream.respond() can throw if the stream has been destroyed by + * // the other side. + * try { + * if (err.code === 'ENOENT') { + * stream.respond({ ':status': 404 }); + * } else { + * stream.respond({ ':status': 500 }); + * } + * } catch (err) { + * // Perform actual error handling. + * console.error(err); + * } + * stream.end(); + * } + * + * stream.respondWithFile('/some/file', + * { 'content-type': 'text/plain; charset=utf-8' }, + * { statCheck, onError }); + * }); + * ``` + * + * The `options.statCheck` function may also be used to cancel the send operation + * by returning `false`. For instance, a conditional request may check the stat + * results to determine if the file has been modified to return an appropriate `304` response: + * + * ```js + * const http2 = require('node:http2'); + * const server = http2.createServer(); + * server.on('stream', (stream) => { + * function statCheck(stat, headers) { + * // Check the stat here... + * stream.respond({ ':status': 304 }); + * return false; // Cancel the send operation + * } + * stream.respondWithFile('/some/file', + * { 'content-type': 'text/plain; charset=utf-8' }, + * { statCheck }); + * }); + * ``` + * + * The `content-length` header field will be automatically set. + * + * The `offset` and `length` options may be used to limit the response to a + * specific range subset. This can be used, for instance, to support HTTP Range + * requests. + * + * The `options.onError` function may also be used to handle all the errors + * that could happen before the delivery of the file is initiated. The + * default behavior is to destroy the stream. + * + * When the `options.waitForTrailers` option is set, the `'wantTrailers'` event + * will be emitted immediately after queuing the last chunk of payload data to be + * sent. The `http2stream.sendTrailers()` method can then be used to sent trailing + * header fields to the peer. + * + * When `options.waitForTrailers` is set, the `Http2Stream` will not automatically + * close when the final `DATA` frame is transmitted. User code must call either`http2stream.sendTrailers()` or `http2stream.close()` to close the`Http2Stream`. + * + * ```js + * const http2 = require('node:http2'); + * const server = http2.createServer(); + * server.on('stream', (stream) => { + * stream.respondWithFile('/some/file', + * { 'content-type': 'text/plain; charset=utf-8' }, + * { waitForTrailers: true }); + * stream.on('wantTrailers', () => { + * stream.sendTrailers({ ABC: 'some value to send' }); + * }); + * }); + * ``` + * @since v8.4.0 + */ + respondWithFile( + path: string, + headers?: OutgoingHttpHeaders, + options?: ServerStreamFileResponseOptionsWithError, + ): void; + } + // Http2Session + export interface Settings { + headerTableSize?: number | undefined; + enablePush?: boolean | undefined; + initialWindowSize?: number | undefined; + maxFrameSize?: number | undefined; + maxConcurrentStreams?: number | undefined; + maxHeaderListSize?: number | undefined; + enableConnectProtocol?: boolean | undefined; + } + export interface ClientSessionRequestOptions { + endStream?: boolean | undefined; + exclusive?: boolean | undefined; + parent?: number | undefined; + weight?: number | undefined; + waitForTrailers?: boolean | undefined; + signal?: AbortSignal | undefined; + } + export interface SessionState { + effectiveLocalWindowSize?: number | undefined; + effectiveRecvDataLength?: number | undefined; + nextStreamID?: number | undefined; + localWindowSize?: number | undefined; + lastProcStreamID?: number | undefined; + remoteWindowSize?: number | undefined; + outboundQueueSize?: number | undefined; + deflateDynamicTableSize?: number | undefined; + inflateDynamicTableSize?: number | undefined; + } + export interface Http2Session extends EventEmitter { + /** + * Value will be `undefined` if the `Http2Session` is not yet connected to a + * socket, `h2c` if the `Http2Session` is not connected to a `TLSSocket`, or + * will return the value of the connected `TLSSocket`'s own `alpnProtocol` property. + * @since v9.4.0 + */ + readonly alpnProtocol?: string | undefined; + /** + * Will be `true` if this `Http2Session` instance has been closed, otherwise `false`. + * @since v9.4.0 + */ + readonly closed: boolean; + /** + * Will be `true` if this `Http2Session` instance is still connecting, will be set + * to `false` before emitting `connect` event and/or calling the `http2.connect` callback. + * @since v10.0.0 + */ + readonly connecting: boolean; + /** + * Will be `true` if this `Http2Session` instance has been destroyed and must no + * longer be used, otherwise `false`. + * @since v8.4.0 + */ + readonly destroyed: boolean; + /** + * Value is `undefined` if the `Http2Session` session socket has not yet been + * connected, `true` if the `Http2Session` is connected with a `TLSSocket`, + * and `false` if the `Http2Session` is connected to any other kind of socket + * or stream. + * @since v9.4.0 + */ + readonly encrypted?: boolean | undefined; + /** + * A prototype-less object describing the current local settings of this `Http2Session`. The local settings are local to _this_`Http2Session` instance. + * @since v8.4.0 + */ + readonly localSettings: Settings; + /** + * If the `Http2Session` is connected to a `TLSSocket`, the `originSet` property + * will return an `Array` of origins for which the `Http2Session` may be + * considered authoritative. + * + * The `originSet` property is only available when using a secure TLS connection. + * @since v9.4.0 + */ + readonly originSet?: string[] | undefined; + /** + * Indicates whether the `Http2Session` is currently waiting for acknowledgment of + * a sent `SETTINGS` frame. Will be `true` after calling the `http2session.settings()` method. Will be `false` once all sent `SETTINGS` frames have been acknowledged. + * @since v8.4.0 + */ + readonly pendingSettingsAck: boolean; + /** + * A prototype-less object describing the current remote settings of this`Http2Session`. The remote settings are set by the _connected_ HTTP/2 peer. + * @since v8.4.0 + */ + readonly remoteSettings: Settings; + /** + * Returns a `Proxy` object that acts as a `net.Socket` (or `tls.TLSSocket`) but + * limits available methods to ones safe to use with HTTP/2. + * + * `destroy`, `emit`, `end`, `pause`, `read`, `resume`, and `write` will throw + * an error with code `ERR_HTTP2_NO_SOCKET_MANIPULATION`. See `Http2Session and Sockets` for more information. + * + * `setTimeout` method will be called on this `Http2Session`. + * + * All other interactions will be routed directly to the socket. + * @since v8.4.0 + */ + readonly socket: net.Socket | tls.TLSSocket; + /** + * Provides miscellaneous information about the current state of the`Http2Session`. + * + * An object describing the current status of this `Http2Session`. + * @since v8.4.0 + */ + readonly state: SessionState; + /** + * The `http2session.type` will be equal to `http2.constants.NGHTTP2_SESSION_SERVER` if this `Http2Session` instance is a + * server, and `http2.constants.NGHTTP2_SESSION_CLIENT` if the instance is a + * client. + * @since v8.4.0 + */ + readonly type: number; + /** + * Gracefully closes the `Http2Session`, allowing any existing streams to + * complete on their own and preventing new `Http2Stream` instances from being + * created. Once closed, `http2session.destroy()`_might_ be called if there + * are no open `Http2Stream` instances. + * + * If specified, the `callback` function is registered as a handler for the`'close'` event. + * @since v9.4.0 + */ + close(callback?: () => void): void; + /** + * Immediately terminates the `Http2Session` and the associated `net.Socket` or `tls.TLSSocket`. + * + * Once destroyed, the `Http2Session` will emit the `'close'` event. If `error` is not undefined, an `'error'` event will be emitted immediately before the `'close'` event. + * + * If there are any remaining open `Http2Streams` associated with the `Http2Session`, those will also be destroyed. + * @since v8.4.0 + * @param error An `Error` object if the `Http2Session` is being destroyed due to an error. + * @param code The HTTP/2 error code to send in the final `GOAWAY` frame. If unspecified, and `error` is not undefined, the default is `INTERNAL_ERROR`, otherwise defaults to `NO_ERROR`. + */ + destroy(error?: Error, code?: number): void; + /** + * Transmits a `GOAWAY` frame to the connected peer _without_ shutting down the`Http2Session`. + * @since v9.4.0 + * @param code An HTTP/2 error code + * @param lastStreamID The numeric ID of the last processed `Http2Stream` + * @param opaqueData A `TypedArray` or `DataView` instance containing additional data to be carried within the `GOAWAY` frame. + */ + goaway(code?: number, lastStreamID?: number, opaqueData?: NodeJS.ArrayBufferView): void; + /** + * Sends a `PING` frame to the connected HTTP/2 peer. A `callback` function must + * be provided. The method will return `true` if the `PING` was sent, `false` otherwise. + * + * The maximum number of outstanding (unacknowledged) pings is determined by the `maxOutstandingPings` configuration option. The default maximum is 10. + * + * If provided, the `payload` must be a `Buffer`, `TypedArray`, or `DataView` containing 8 bytes of data that will be transmitted with the `PING` and + * returned with the ping acknowledgment. + * + * The callback will be invoked with three arguments: an error argument that will + * be `null` if the `PING` was successfully acknowledged, a `duration` argument + * that reports the number of milliseconds elapsed since the ping was sent and the + * acknowledgment was received, and a `Buffer` containing the 8-byte `PING` payload. + * + * ```js + * session.ping(Buffer.from('abcdefgh'), (err, duration, payload) => { + * if (!err) { + * console.log(`Ping acknowledged in ${duration} milliseconds`); + * console.log(`With payload '${payload.toString()}'`); + * } + * }); + * ``` + * + * If the `payload` argument is not specified, the default payload will be the + * 64-bit timestamp (little endian) marking the start of the `PING` duration. + * @since v8.9.3 + * @param payload Optional ping payload. + */ + ping(callback: (err: Error | null, duration: number, payload: Buffer) => void): boolean; + ping( + payload: NodeJS.ArrayBufferView, + callback: (err: Error | null, duration: number, payload: Buffer) => void, + ): boolean; + /** + * Calls `ref()` on this `Http2Session` instance's underlying `net.Socket`. + * @since v9.4.0 + */ + ref(): void; + /** + * Sets the local endpoint's window size. + * The `windowSize` is the total window size to set, not + * the delta. + * + * ```js + * const http2 = require('node:http2'); + * + * const server = http2.createServer(); + * const expectedWindowSize = 2 ** 20; + * server.on('connect', (session) => { + * + * // Set local window size to be 2 ** 20 + * session.setLocalWindowSize(expectedWindowSize); + * }); + * ``` + * @since v15.3.0, v14.18.0 + */ + setLocalWindowSize(windowSize: number): void; + /** + * Used to set a callback function that is called when there is no activity on + * the `Http2Session` after `msecs` milliseconds. The given `callback` is + * registered as a listener on the `'timeout'` event. + * @since v8.4.0 + */ + setTimeout(msecs: number, callback?: () => void): void; + /** + * Updates the current local settings for this `Http2Session` and sends a new `SETTINGS` frame to the connected HTTP/2 peer. + * + * Once called, the `http2session.pendingSettingsAck` property will be `true` while the session is waiting for the remote peer to acknowledge the new + * settings. + * + * The new settings will not become effective until the `SETTINGS` acknowledgment + * is received and the `'localSettings'` event is emitted. It is possible to send + * multiple `SETTINGS` frames while acknowledgment is still pending. + * @since v8.4.0 + * @param callback Callback that is called once the session is connected or right away if the session is already connected. + */ + settings( + settings: Settings, + callback?: (err: Error | null, settings: Settings, duration: number) => void, + ): void; + /** + * Calls `unref()` on this `Http2Session`instance's underlying `net.Socket`. + * @since v9.4.0 + */ + unref(): void; + addListener(event: "close", listener: () => void): this; + addListener(event: "error", listener: (err: Error) => void): this; + addListener( + event: "frameError", + listener: (frameType: number, errorCode: number, streamID: number) => void, + ): this; + addListener( + event: "goaway", + listener: (errorCode: number, lastStreamID: number, opaqueData?: Buffer) => void, + ): this; + addListener(event: "localSettings", listener: (settings: Settings) => void): this; + addListener(event: "ping", listener: () => void): this; + addListener(event: "remoteSettings", listener: (settings: Settings) => void): this; + addListener(event: "timeout", listener: () => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + emit(event: "close"): boolean; + emit(event: "error", err: Error): boolean; + emit(event: "frameError", frameType: number, errorCode: number, streamID: number): boolean; + emit(event: "goaway", errorCode: number, lastStreamID: number, opaqueData?: Buffer): boolean; + emit(event: "localSettings", settings: Settings): boolean; + emit(event: "ping"): boolean; + emit(event: "remoteSettings", settings: Settings): boolean; + emit(event: "timeout"): boolean; + emit(event: string | symbol, ...args: any[]): boolean; + on(event: "close", listener: () => void): this; + on(event: "error", listener: (err: Error) => void): this; + on(event: "frameError", listener: (frameType: number, errorCode: number, streamID: number) => void): this; + on(event: "goaway", listener: (errorCode: number, lastStreamID: number, opaqueData?: Buffer) => void): this; + on(event: "localSettings", listener: (settings: Settings) => void): this; + on(event: "ping", listener: () => void): this; + on(event: "remoteSettings", listener: (settings: Settings) => void): this; + on(event: "timeout", listener: () => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + once(event: "close", listener: () => void): this; + once(event: "error", listener: (err: Error) => void): this; + once(event: "frameError", listener: (frameType: number, errorCode: number, streamID: number) => void): this; + once(event: "goaway", listener: (errorCode: number, lastStreamID: number, opaqueData?: Buffer) => void): this; + once(event: "localSettings", listener: (settings: Settings) => void): this; + once(event: "ping", listener: () => void): this; + once(event: "remoteSettings", listener: (settings: Settings) => void): this; + once(event: "timeout", listener: () => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + prependListener(event: "close", listener: () => void): this; + prependListener(event: "error", listener: (err: Error) => void): this; + prependListener( + event: "frameError", + listener: (frameType: number, errorCode: number, streamID: number) => void, + ): this; + prependListener( + event: "goaway", + listener: (errorCode: number, lastStreamID: number, opaqueData?: Buffer) => void, + ): this; + prependListener(event: "localSettings", listener: (settings: Settings) => void): this; + prependListener(event: "ping", listener: () => void): this; + prependListener(event: "remoteSettings", listener: (settings: Settings) => void): this; + prependListener(event: "timeout", listener: () => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "error", listener: (err: Error) => void): this; + prependOnceListener( + event: "frameError", + listener: (frameType: number, errorCode: number, streamID: number) => void, + ): this; + prependOnceListener( + event: "goaway", + listener: (errorCode: number, lastStreamID: number, opaqueData?: Buffer) => void, + ): this; + prependOnceListener(event: "localSettings", listener: (settings: Settings) => void): this; + prependOnceListener(event: "ping", listener: () => void): this; + prependOnceListener(event: "remoteSettings", listener: (settings: Settings) => void): this; + prependOnceListener(event: "timeout", listener: () => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + } + export interface ClientHttp2Session extends Http2Session { + /** + * For HTTP/2 Client `Http2Session` instances only, the `http2session.request()` creates and returns an `Http2Stream` instance that can be used to send an + * HTTP/2 request to the connected server. + * + * When a `ClientHttp2Session` is first created, the socket may not yet be + * connected. if `clienthttp2session.request()` is called during this time, the + * actual request will be deferred until the socket is ready to go. + * If the `session` is closed before the actual request be executed, an `ERR_HTTP2_GOAWAY_SESSION` is thrown. + * + * This method is only available if `http2session.type` is equal to `http2.constants.NGHTTP2_SESSION_CLIENT`. + * + * ```js + * const http2 = require('node:http2'); + * const clientSession = http2.connect('https://localhost:1234'); + * const { + * HTTP2_HEADER_PATH, + * HTTP2_HEADER_STATUS, + * } = http2.constants; + * + * const req = clientSession.request({ [HTTP2_HEADER_PATH]: '/' }); + * req.on('response', (headers) => { + * console.log(headers[HTTP2_HEADER_STATUS]); + * req.on('data', (chunk) => { // .. }); + * req.on('end', () => { // .. }); + * }); + * ``` + * + * When the `options.waitForTrailers` option is set, the `'wantTrailers'` event + * is emitted immediately after queuing the last chunk of payload data to be sent. + * The `http2stream.sendTrailers()` method can then be called to send trailing + * headers to the peer. + * + * When `options.waitForTrailers` is set, the `Http2Stream` will not automatically + * close when the final `DATA` frame is transmitted. User code must call either`http2stream.sendTrailers()` or `http2stream.close()` to close the`Http2Stream`. + * + * When `options.signal` is set with an `AbortSignal` and then `abort` on the + * corresponding `AbortController` is called, the request will emit an `'error'`event with an `AbortError` error. + * + * The `:method` and `:path` pseudo-headers are not specified within `headers`, + * they respectively default to: + * + * * `:method` \= `'GET'` + * * `:path` \= `/` + * @since v8.4.0 + */ + request(headers?: OutgoingHttpHeaders, options?: ClientSessionRequestOptions): ClientHttp2Stream; + addListener(event: "altsvc", listener: (alt: string, origin: string, stream: number) => void): this; + addListener(event: "origin", listener: (origins: string[]) => void): this; + addListener( + event: "connect", + listener: (session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket) => void, + ): this; + addListener( + event: "stream", + listener: ( + stream: ClientHttp2Stream, + headers: IncomingHttpHeaders & IncomingHttpStatusHeader, + flags: number, + ) => void, + ): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + emit(event: "altsvc", alt: string, origin: string, stream: number): boolean; + emit(event: "origin", origins: readonly string[]): boolean; + emit(event: "connect", session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket): boolean; + emit( + event: "stream", + stream: ClientHttp2Stream, + headers: IncomingHttpHeaders & IncomingHttpStatusHeader, + flags: number, + ): boolean; + emit(event: string | symbol, ...args: any[]): boolean; + on(event: "altsvc", listener: (alt: string, origin: string, stream: number) => void): this; + on(event: "origin", listener: (origins: string[]) => void): this; + on(event: "connect", listener: (session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket) => void): this; + on( + event: "stream", + listener: ( + stream: ClientHttp2Stream, + headers: IncomingHttpHeaders & IncomingHttpStatusHeader, + flags: number, + ) => void, + ): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + once(event: "altsvc", listener: (alt: string, origin: string, stream: number) => void): this; + once(event: "origin", listener: (origins: string[]) => void): this; + once( + event: "connect", + listener: (session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket) => void, + ): this; + once( + event: "stream", + listener: ( + stream: ClientHttp2Stream, + headers: IncomingHttpHeaders & IncomingHttpStatusHeader, + flags: number, + ) => void, + ): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + prependListener(event: "altsvc", listener: (alt: string, origin: string, stream: number) => void): this; + prependListener(event: "origin", listener: (origins: string[]) => void): this; + prependListener( + event: "connect", + listener: (session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket) => void, + ): this; + prependListener( + event: "stream", + listener: ( + stream: ClientHttp2Stream, + headers: IncomingHttpHeaders & IncomingHttpStatusHeader, + flags: number, + ) => void, + ): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener(event: "altsvc", listener: (alt: string, origin: string, stream: number) => void): this; + prependOnceListener(event: "origin", listener: (origins: string[]) => void): this; + prependOnceListener( + event: "connect", + listener: (session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket) => void, + ): this; + prependOnceListener( + event: "stream", + listener: ( + stream: ClientHttp2Stream, + headers: IncomingHttpHeaders & IncomingHttpStatusHeader, + flags: number, + ) => void, + ): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + } + export interface AlternativeServiceOptions { + origin: number | string | url.URL; + } + export interface ServerHttp2Session extends Http2Session { + readonly server: Http2Server | Http2SecureServer; + /** + * Submits an `ALTSVC` frame (as defined by [RFC 7838](https://tools.ietf.org/html/rfc7838)) to the connected client. + * + * ```js + * const http2 = require('node:http2'); + * + * const server = http2.createServer(); + * server.on('session', (session) => { + * // Set altsvc for origin https://example.org:80 + * session.altsvc('h2=":8000"', 'https://example.org:80'); + * }); + * + * server.on('stream', (stream) => { + * // Set altsvc for a specific stream + * stream.session.altsvc('h2=":8000"', stream.id); + * }); + * ``` + * + * Sending an `ALTSVC` frame with a specific stream ID indicates that the alternate + * service is associated with the origin of the given `Http2Stream`. + * + * The `alt` and origin string _must_ contain only ASCII bytes and are + * strictly interpreted as a sequence of ASCII bytes. The special value `'clear'`may be passed to clear any previously set alternative service for a given + * domain. + * + * When a string is passed for the `originOrStream` argument, it will be parsed as + * a URL and the origin will be derived. For instance, the origin for the + * HTTP URL `'https://example.org/foo/bar'` is the ASCII string`'https://example.org'`. An error will be thrown if either the given string + * cannot be parsed as a URL or if a valid origin cannot be derived. + * + * A `URL` object, or any object with an `origin` property, may be passed as`originOrStream`, in which case the value of the `origin` property will be + * used. The value of the `origin` property _must_ be a properly serialized + * ASCII origin. + * @since v9.4.0 + * @param alt A description of the alternative service configuration as defined by `RFC 7838`. + * @param originOrStream Either a URL string specifying the origin (or an `Object` with an `origin` property) or the numeric identifier of an active `Http2Stream` as given by the + * `http2stream.id` property. + */ + altsvc(alt: string, originOrStream: number | string | url.URL | AlternativeServiceOptions): void; + /** + * Submits an `ORIGIN` frame (as defined by [RFC 8336](https://tools.ietf.org/html/rfc8336)) to the connected client + * to advertise the set of origins for which the server is capable of providing + * authoritative responses. + * + * ```js + * const http2 = require('node:http2'); + * const options = getSecureOptionsSomehow(); + * const server = http2.createSecureServer(options); + * server.on('stream', (stream) => { + * stream.respond(); + * stream.end('ok'); + * }); + * server.on('session', (session) => { + * session.origin('https://example.com', 'https://example.org'); + * }); + * ``` + * + * When a string is passed as an `origin`, it will be parsed as a URL and the + * origin will be derived. For instance, the origin for the HTTP URL `'https://example.org/foo/bar'` is the ASCII string` 'https://example.org'`. An error will be thrown if either the given + * string + * cannot be parsed as a URL or if a valid origin cannot be derived. + * + * A `URL` object, or any object with an `origin` property, may be passed as + * an `origin`, in which case the value of the `origin` property will be + * used. The value of the `origin` property _must_ be a properly serialized + * ASCII origin. + * + * Alternatively, the `origins` option may be used when creating a new HTTP/2 + * server using the `http2.createSecureServer()` method: + * + * ```js + * const http2 = require('node:http2'); + * const options = getSecureOptionsSomehow(); + * options.origins = ['https://example.com', 'https://example.org']; + * const server = http2.createSecureServer(options); + * server.on('stream', (stream) => { + * stream.respond(); + * stream.end('ok'); + * }); + * ``` + * @since v10.12.0 + * @param origins One or more URL Strings passed as separate arguments. + */ + origin( + ...origins: Array< + | string + | url.URL + | { + origin: string; + } + > + ): void; + addListener( + event: "connect", + listener: (session: ServerHttp2Session, socket: net.Socket | tls.TLSSocket) => void, + ): this; + addListener( + event: "stream", + listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void, + ): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + emit(event: "connect", session: ServerHttp2Session, socket: net.Socket | tls.TLSSocket): boolean; + emit(event: "stream", stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number): boolean; + emit(event: string | symbol, ...args: any[]): boolean; + on(event: "connect", listener: (session: ServerHttp2Session, socket: net.Socket | tls.TLSSocket) => void): this; + on( + event: "stream", + listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void, + ): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + once( + event: "connect", + listener: (session: ServerHttp2Session, socket: net.Socket | tls.TLSSocket) => void, + ): this; + once( + event: "stream", + listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void, + ): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + prependListener( + event: "connect", + listener: (session: ServerHttp2Session, socket: net.Socket | tls.TLSSocket) => void, + ): this; + prependListener( + event: "stream", + listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void, + ): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener( + event: "connect", + listener: (session: ServerHttp2Session, socket: net.Socket | tls.TLSSocket) => void, + ): this; + prependOnceListener( + event: "stream", + listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void, + ): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + } + // Http2Server + export interface SessionOptions { + maxDeflateDynamicTableSize?: number | undefined; + maxSessionMemory?: number | undefined; + maxHeaderListPairs?: number | undefined; + maxOutstandingPings?: number | undefined; + maxSendHeaderBlockLength?: number | undefined; + paddingStrategy?: number | undefined; + peerMaxConcurrentStreams?: number | undefined; + settings?: Settings | undefined; + remoteCustomSettings?: number[] | undefined; + /** + * Specifies a timeout in milliseconds that + * a server should wait when an [`'unknownProtocol'`][] is emitted. If the + * socket has not been destroyed by that time the server will destroy it. + * @default 100000 + */ + unknownProtocolTimeout?: number | undefined; + selectPadding?(frameLen: number, maxFrameLen: number): number; + } + export interface ClientSessionOptions extends SessionOptions { + maxReservedRemoteStreams?: number | undefined; + createConnection?: ((authority: url.URL, option: SessionOptions) => stream.Duplex) | undefined; + protocol?: "http:" | "https:" | undefined; + } + export interface ServerSessionOptions extends SessionOptions { + Http1IncomingMessage?: typeof IncomingMessage | undefined; + Http1ServerResponse?: typeof ServerResponse | undefined; + Http2ServerRequest?: typeof Http2ServerRequest | undefined; + Http2ServerResponse?: typeof Http2ServerResponse | undefined; + } + export interface SecureClientSessionOptions extends ClientSessionOptions, tls.ConnectionOptions {} + export interface SecureServerSessionOptions extends ServerSessionOptions, tls.TlsOptions {} + export interface ServerOptions extends ServerSessionOptions {} + export interface SecureServerOptions extends SecureServerSessionOptions { + allowHTTP1?: boolean | undefined; + origins?: string[] | undefined; + } + interface HTTP2ServerCommon { + setTimeout(msec?: number, callback?: () => void): this; + /** + * Throws ERR_HTTP2_INVALID_SETTING_VALUE for invalid settings values. + * Throws ERR_INVALID_ARG_TYPE for invalid settings argument. + */ + updateSettings(settings: Settings): void; + } + export interface Http2Server extends net.Server, HTTP2ServerCommon { + addListener( + event: "checkContinue", + listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void, + ): this; + addListener( + event: "request", + listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void, + ): this; + addListener(event: "session", listener: (session: ServerHttp2Session) => void): this; + addListener(event: "sessionError", listener: (err: Error) => void): this; + addListener( + event: "stream", + listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void, + ): this; + addListener(event: "timeout", listener: () => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + emit(event: "checkContinue", request: Http2ServerRequest, response: Http2ServerResponse): boolean; + emit(event: "request", request: Http2ServerRequest, response: Http2ServerResponse): boolean; + emit(event: "session", session: ServerHttp2Session): boolean; + emit(event: "sessionError", err: Error): boolean; + emit(event: "stream", stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number): boolean; + emit(event: "timeout"): boolean; + emit(event: string | symbol, ...args: any[]): boolean; + on( + event: "checkContinue", + listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void, + ): this; + on(event: "request", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + on(event: "session", listener: (session: ServerHttp2Session) => void): this; + on(event: "sessionError", listener: (err: Error) => void): this; + on( + event: "stream", + listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void, + ): this; + on(event: "timeout", listener: () => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + once( + event: "checkContinue", + listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void, + ): this; + once(event: "request", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + once(event: "session", listener: (session: ServerHttp2Session) => void): this; + once(event: "sessionError", listener: (err: Error) => void): this; + once( + event: "stream", + listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void, + ): this; + once(event: "timeout", listener: () => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + prependListener( + event: "checkContinue", + listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void, + ): this; + prependListener( + event: "request", + listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void, + ): this; + prependListener(event: "session", listener: (session: ServerHttp2Session) => void): this; + prependListener(event: "sessionError", listener: (err: Error) => void): this; + prependListener( + event: "stream", + listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void, + ): this; + prependListener(event: "timeout", listener: () => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener( + event: "checkContinue", + listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void, + ): this; + prependOnceListener( + event: "request", + listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void, + ): this; + prependOnceListener(event: "session", listener: (session: ServerHttp2Session) => void): this; + prependOnceListener(event: "sessionError", listener: (err: Error) => void): this; + prependOnceListener( + event: "stream", + listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void, + ): this; + prependOnceListener(event: "timeout", listener: () => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + } + export interface Http2SecureServer extends tls.Server, HTTP2ServerCommon { + addListener( + event: "checkContinue", + listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void, + ): this; + addListener( + event: "request", + listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void, + ): this; + addListener(event: "session", listener: (session: ServerHttp2Session) => void): this; + addListener(event: "sessionError", listener: (err: Error) => void): this; + addListener( + event: "stream", + listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void, + ): this; + addListener(event: "timeout", listener: () => void): this; + addListener(event: "unknownProtocol", listener: (socket: tls.TLSSocket) => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + emit(event: "checkContinue", request: Http2ServerRequest, response: Http2ServerResponse): boolean; + emit(event: "request", request: Http2ServerRequest, response: Http2ServerResponse): boolean; + emit(event: "session", session: ServerHttp2Session): boolean; + emit(event: "sessionError", err: Error): boolean; + emit(event: "stream", stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number): boolean; + emit(event: "timeout"): boolean; + emit(event: "unknownProtocol", socket: tls.TLSSocket): boolean; + emit(event: string | symbol, ...args: any[]): boolean; + on( + event: "checkContinue", + listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void, + ): this; + on(event: "request", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + on(event: "session", listener: (session: ServerHttp2Session) => void): this; + on(event: "sessionError", listener: (err: Error) => void): this; + on( + event: "stream", + listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void, + ): this; + on(event: "timeout", listener: () => void): this; + on(event: "unknownProtocol", listener: (socket: tls.TLSSocket) => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + once( + event: "checkContinue", + listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void, + ): this; + once(event: "request", listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void): this; + once(event: "session", listener: (session: ServerHttp2Session) => void): this; + once(event: "sessionError", listener: (err: Error) => void): this; + once( + event: "stream", + listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void, + ): this; + once(event: "timeout", listener: () => void): this; + once(event: "unknownProtocol", listener: (socket: tls.TLSSocket) => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + prependListener( + event: "checkContinue", + listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void, + ): this; + prependListener( + event: "request", + listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void, + ): this; + prependListener(event: "session", listener: (session: ServerHttp2Session) => void): this; + prependListener(event: "sessionError", listener: (err: Error) => void): this; + prependListener( + event: "stream", + listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void, + ): this; + prependListener(event: "timeout", listener: () => void): this; + prependListener(event: "unknownProtocol", listener: (socket: tls.TLSSocket) => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener( + event: "checkContinue", + listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void, + ): this; + prependOnceListener( + event: "request", + listener: (request: Http2ServerRequest, response: Http2ServerResponse) => void, + ): this; + prependOnceListener(event: "session", listener: (session: ServerHttp2Session) => void): this; + prependOnceListener(event: "sessionError", listener: (err: Error) => void): this; + prependOnceListener( + event: "stream", + listener: (stream: ServerHttp2Stream, headers: IncomingHttpHeaders, flags: number) => void, + ): this; + prependOnceListener(event: "timeout", listener: () => void): this; + prependOnceListener(event: "unknownProtocol", listener: (socket: tls.TLSSocket) => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + } + /** + * A `Http2ServerRequest` object is created by {@link Server} or {@link SecureServer} and passed as the first argument to the `'request'` event. It may be used to access a request status, + * headers, and + * data. + * @since v8.4.0 + */ + export class Http2ServerRequest extends stream.Readable { + constructor( + stream: ServerHttp2Stream, + headers: IncomingHttpHeaders, + options: stream.ReadableOptions, + rawHeaders: readonly string[], + ); + /** + * The `request.aborted` property will be `true` if the request has + * been aborted. + * @since v10.1.0 + */ + readonly aborted: boolean; + /** + * The request authority pseudo header field. Because HTTP/2 allows requests + * to set either `:authority` or `host`, this value is derived from `req.headers[':authority']` if present. Otherwise, it is derived from `req.headers['host']`. + * @since v8.4.0 + */ + readonly authority: string; + /** + * See `request.socket`. + * @since v8.4.0 + * @deprecated Since v13.0.0 - Use `socket`. + */ + readonly connection: net.Socket | tls.TLSSocket; + /** + * The `request.complete` property will be `true` if the request has + * been completed, aborted, or destroyed. + * @since v12.10.0 + */ + readonly complete: boolean; + /** + * The request/response headers object. + * + * Key-value pairs of header names and values. Header names are lower-cased. + * + * ```js + * // Prints something like: + * // + * // { 'user-agent': 'curl/7.22.0', + * // host: '127.0.0.1:8000', + * // accept: '*' } + * console.log(request.headers); + * ``` + * + * See `HTTP/2 Headers Object`. + * + * In HTTP/2, the request path, host name, protocol, and method are represented as + * special headers prefixed with the `:` character (e.g. `':path'`). These special + * headers will be included in the `request.headers` object. Care must be taken not + * to inadvertently modify these special headers or errors may occur. For instance, + * removing all headers from the request will cause errors to occur: + * + * ```js + * removeAllHeaders(request.headers); + * assert(request.url); // Fails because the :path header has been removed + * ``` + * @since v8.4.0 + */ + readonly headers: IncomingHttpHeaders; + /** + * In case of server request, the HTTP version sent by the client. In the case of + * client response, the HTTP version of the connected-to server. Returns `'2.0'`. + * + * Also `message.httpVersionMajor` is the first integer and `message.httpVersionMinor` is the second. + * @since v8.4.0 + */ + readonly httpVersion: string; + readonly httpVersionMinor: number; + readonly httpVersionMajor: number; + /** + * The request method as a string. Read-only. Examples: `'GET'`, `'DELETE'`. + * @since v8.4.0 + */ + readonly method: string; + /** + * The raw request/response headers list exactly as they were received. + * + * The keys and values are in the same list. It is _not_ a + * list of tuples. So, the even-numbered offsets are key values, and the + * odd-numbered offsets are the associated values. + * + * Header names are not lowercased, and duplicates are not merged. + * + * ```js + * // Prints something like: + * // + * // [ 'user-agent', + * // 'this is invalid because there can be only one', + * // 'User-Agent', + * // 'curl/7.22.0', + * // 'Host', + * // '127.0.0.1:8000', + * // 'ACCEPT', + * // '*' ] + * console.log(request.rawHeaders); + * ``` + * @since v8.4.0 + */ + readonly rawHeaders: string[]; + /** + * The raw request/response trailer keys and values exactly as they were + * received. Only populated at the `'end'` event. + * @since v8.4.0 + */ + readonly rawTrailers: string[]; + /** + * The request scheme pseudo header field indicating the scheme + * portion of the target URL. + * @since v8.4.0 + */ + readonly scheme: string; + /** + * Returns a `Proxy` object that acts as a `net.Socket` (or `tls.TLSSocket`) but + * applies getters, setters, and methods based on HTTP/2 logic. + * + * `destroyed`, `readable`, and `writable` properties will be retrieved from and + * set on `request.stream`. + * + * `destroy`, `emit`, `end`, `on` and `once` methods will be called on `request.stream`. + * + * `setTimeout` method will be called on `request.stream.session`. + * + * `pause`, `read`, `resume`, and `write` will throw an error with code `ERR_HTTP2_NO_SOCKET_MANIPULATION`. See `Http2Session and Sockets` for + * more information. + * + * All other interactions will be routed directly to the socket. With TLS support, + * use `request.socket.getPeerCertificate()` to obtain the client's + * authentication details. + * @since v8.4.0 + */ + readonly socket: net.Socket | tls.TLSSocket; + /** + * The `Http2Stream` object backing the request. + * @since v8.4.0 + */ + readonly stream: ServerHttp2Stream; + /** + * The request/response trailers object. Only populated at the `'end'` event. + * @since v8.4.0 + */ + readonly trailers: IncomingHttpHeaders; + /** + * Request URL string. This contains only the URL that is present in the actual + * HTTP request. If the request is: + * + * ```http + * GET /status?name=ryan HTTP/1.1 + * Accept: text/plain + * ``` + * + * Then `request.url` will be: + * + * ```js + * '/status?name=ryan' + * ``` + * + * To parse the url into its parts, `new URL()` can be used: + * + * ```console + * $ node + * > new URL('/status?name=ryan', 'http://example.com') + * URL { + * href: 'http://example.com/status?name=ryan', + * origin: 'http://example.com', + * protocol: 'http:', + * username: '', + * password: '', + * host: 'example.com', + * hostname: 'example.com', + * port: '', + * pathname: '/status', + * search: '?name=ryan', + * searchParams: URLSearchParams { 'name' => 'ryan' }, + * hash: '' + * } + * ``` + * @since v8.4.0 + */ + url: string; + /** + * Sets the `Http2Stream`'s timeout value to `msecs`. If a callback is + * provided, then it is added as a listener on the `'timeout'` event on + * the response object. + * + * If no `'timeout'` listener is added to the request, the response, or + * the server, then `Http2Stream`s are destroyed when they time out. If a + * handler is assigned to the request, the response, or the server's `'timeout'`events, timed out sockets must be handled explicitly. + * @since v8.4.0 + */ + setTimeout(msecs: number, callback?: () => void): void; + read(size?: number): Buffer | string | null; + addListener(event: "aborted", listener: (hadError: boolean, code: number) => void): this; + addListener(event: "close", listener: () => void): this; + addListener(event: "data", listener: (chunk: Buffer | string) => void): this; + addListener(event: "end", listener: () => void): this; + addListener(event: "readable", listener: () => void): this; + addListener(event: "error", listener: (err: Error) => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + emit(event: "aborted", hadError: boolean, code: number): boolean; + emit(event: "close"): boolean; + emit(event: "data", chunk: Buffer | string): boolean; + emit(event: "end"): boolean; + emit(event: "readable"): boolean; + emit(event: "error", err: Error): boolean; + emit(event: string | symbol, ...args: any[]): boolean; + on(event: "aborted", listener: (hadError: boolean, code: number) => void): this; + on(event: "close", listener: () => void): this; + on(event: "data", listener: (chunk: Buffer | string) => void): this; + on(event: "end", listener: () => void): this; + on(event: "readable", listener: () => void): this; + on(event: "error", listener: (err: Error) => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + once(event: "aborted", listener: (hadError: boolean, code: number) => void): this; + once(event: "close", listener: () => void): this; + once(event: "data", listener: (chunk: Buffer | string) => void): this; + once(event: "end", listener: () => void): this; + once(event: "readable", listener: () => void): this; + once(event: "error", listener: (err: Error) => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + prependListener(event: "aborted", listener: (hadError: boolean, code: number) => void): this; + prependListener(event: "close", listener: () => void): this; + prependListener(event: "data", listener: (chunk: Buffer | string) => void): this; + prependListener(event: "end", listener: () => void): this; + prependListener(event: "readable", listener: () => void): this; + prependListener(event: "error", listener: (err: Error) => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener(event: "aborted", listener: (hadError: boolean, code: number) => void): this; + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "data", listener: (chunk: Buffer | string) => void): this; + prependOnceListener(event: "end", listener: () => void): this; + prependOnceListener(event: "readable", listener: () => void): this; + prependOnceListener(event: "error", listener: (err: Error) => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + } + /** + * This object is created internally by an HTTP server, not by the user. It is + * passed as the second parameter to the `'request'` event. + * @since v8.4.0 + */ + export class Http2ServerResponse extends stream.Writable { + constructor(stream: ServerHttp2Stream); + /** + * See `response.socket`. + * @since v8.4.0 + * @deprecated Since v13.0.0 - Use `socket`. + */ + readonly connection: net.Socket | tls.TLSSocket; + /** + * Append a single header value to the header object. + * + * If the value is an array, this is equivalent to calling this method multiple times. + * + * If there were no previous values for the header, this is equivalent to calling {@link setHeader}. + * + * Attempting to set a header field name or value that contains invalid characters will result in a + * [TypeError](https://nodejs.org/docs/latest-v20.x/api/errors.html#class-typeerror) being thrown. + * + * ```js + * // Returns headers including "set-cookie: a" and "set-cookie: b" + * const server = http2.createServer((req, res) => { + * res.setHeader('set-cookie', 'a'); + * res.appendHeader('set-cookie', 'b'); + * res.writeHead(200); + * res.end('ok'); + * }); + * ``` + * @since v20.12.0 + */ + appendHeader(name: string, value: string | string[]): void; + /** + * Boolean value that indicates whether the response has completed. Starts + * as `false`. After `response.end()` executes, the value will be `true`. + * @since v8.4.0 + * @deprecated Since v13.4.0,v12.16.0 - Use `writableEnded`. + */ + readonly finished: boolean; + /** + * True if headers were sent, false otherwise (read-only). + * @since v8.4.0 + */ + readonly headersSent: boolean; + /** + * A reference to the original HTTP2 `request` object. + * @since v15.7.0 + */ + readonly req: Http2ServerRequest; + /** + * Returns a `Proxy` object that acts as a `net.Socket` (or `tls.TLSSocket`) but + * applies getters, setters, and methods based on HTTP/2 logic. + * + * `destroyed`, `readable`, and `writable` properties will be retrieved from and + * set on `response.stream`. + * + * `destroy`, `emit`, `end`, `on` and `once` methods will be called on `response.stream`. + * + * `setTimeout` method will be called on `response.stream.session`. + * + * `pause`, `read`, `resume`, and `write` will throw an error with code `ERR_HTTP2_NO_SOCKET_MANIPULATION`. See `Http2Session and Sockets` for + * more information. + * + * All other interactions will be routed directly to the socket. + * + * ```js + * const http2 = require('node:http2'); + * const server = http2.createServer((req, res) => { + * const ip = req.socket.remoteAddress; + * const port = req.socket.remotePort; + * res.end(`Your IP address is ${ip} and your source port is ${port}.`); + * }).listen(3000); + * ``` + * @since v8.4.0 + */ + readonly socket: net.Socket | tls.TLSSocket; + /** + * The `Http2Stream` object backing the response. + * @since v8.4.0 + */ + readonly stream: ServerHttp2Stream; + /** + * When true, the Date header will be automatically generated and sent in + * the response if it is not already present in the headers. Defaults to true. + * + * This should only be disabled for testing; HTTP requires the Date header + * in responses. + * @since v8.4.0 + */ + sendDate: boolean; + /** + * When using implicit headers (not calling `response.writeHead()` explicitly), + * this property controls the status code that will be sent to the client when + * the headers get flushed. + * + * ```js + * response.statusCode = 404; + * ``` + * + * After response header was sent to the client, this property indicates the + * status code which was sent out. + * @since v8.4.0 + */ + statusCode: number; + /** + * Status message is not supported by HTTP/2 (RFC 7540 8.1.2.4). It returns + * an empty string. + * @since v8.4.0 + */ + statusMessage: ""; + /** + * This method adds HTTP trailing headers (a header but at the end of the + * message) to the response. + * + * Attempting to set a header field name or value that contains invalid characters + * will result in a `TypeError` being thrown. + * @since v8.4.0 + */ + addTrailers(trailers: OutgoingHttpHeaders): void; + /** + * This method signals to the server that all of the response headers and body + * have been sent; that server should consider this message complete. + * The method, `response.end()`, MUST be called on each response. + * + * If `data` is specified, it is equivalent to calling `response.write(data, encoding)` followed by `response.end(callback)`. + * + * If `callback` is specified, it will be called when the response stream + * is finished. + * @since v8.4.0 + */ + end(callback?: () => void): this; + end(data: string | Uint8Array, callback?: () => void): this; + end(data: string | Uint8Array, encoding: BufferEncoding, callback?: () => void): this; + /** + * Reads out a header that has already been queued but not sent to the client. + * The name is case-insensitive. + * + * ```js + * const contentType = response.getHeader('content-type'); + * ``` + * @since v8.4.0 + */ + getHeader(name: string): string; + /** + * Returns an array containing the unique names of the current outgoing headers. + * All header names are lowercase. + * + * ```js + * response.setHeader('Foo', 'bar'); + * response.setHeader('Set-Cookie', ['foo=bar', 'bar=baz']); + * + * const headerNames = response.getHeaderNames(); + * // headerNames === ['foo', 'set-cookie'] + * ``` + * @since v8.4.0 + */ + getHeaderNames(): string[]; + /** + * Returns a shallow copy of the current outgoing headers. Since a shallow copy + * is used, array values may be mutated without additional calls to various + * header-related http module methods. The keys of the returned object are the + * header names and the values are the respective header values. All header names + * are lowercase. + * + * The object returned by the `response.getHeaders()` method _does not_ prototypically inherit from the JavaScript `Object`. This means that typical `Object` methods such as `obj.toString()`, + * `obj.hasOwnProperty()`, and others + * are not defined and _will not work_. + * + * ```js + * response.setHeader('Foo', 'bar'); + * response.setHeader('Set-Cookie', ['foo=bar', 'bar=baz']); + * + * const headers = response.getHeaders(); + * // headers === { foo: 'bar', 'set-cookie': ['foo=bar', 'bar=baz'] } + * ``` + * @since v8.4.0 + */ + getHeaders(): OutgoingHttpHeaders; + /** + * Returns `true` if the header identified by `name` is currently set in the + * outgoing headers. The header name matching is case-insensitive. + * + * ```js + * const hasContentType = response.hasHeader('content-type'); + * ``` + * @since v8.4.0 + */ + hasHeader(name: string): boolean; + /** + * Removes a header that has been queued for implicit sending. + * + * ```js + * response.removeHeader('Content-Encoding'); + * ``` + * @since v8.4.0 + */ + removeHeader(name: string): void; + /** + * Sets a single header value for implicit headers. If this header already exists + * in the to-be-sent headers, its value will be replaced. Use an array of strings + * here to send multiple headers with the same name. + * + * ```js + * response.setHeader('Content-Type', 'text/html; charset=utf-8'); + * ``` + * + * or + * + * ```js + * response.setHeader('Set-Cookie', ['type=ninja', 'language=javascript']); + * ``` + * + * Attempting to set a header field name or value that contains invalid characters + * will result in a `TypeError` being thrown. + * + * When headers have been set with `response.setHeader()`, they will be merged + * with any headers passed to `response.writeHead()`, with the headers passed + * to `response.writeHead()` given precedence. + * + * ```js + * // Returns content-type = text/plain + * const server = http2.createServer((req, res) => { + * res.setHeader('Content-Type', 'text/html; charset=utf-8'); + * res.setHeader('X-Foo', 'bar'); + * res.writeHead(200, { 'Content-Type': 'text/plain; charset=utf-8' }); + * res.end('ok'); + * }); + * ``` + * @since v8.4.0 + */ + setHeader(name: string, value: number | string | readonly string[]): void; + /** + * Sets the `Http2Stream`'s timeout value to `msecs`. If a callback is + * provided, then it is added as a listener on the `'timeout'` event on + * the response object. + * + * If no `'timeout'` listener is added to the request, the response, or + * the server, then `Http2Stream` s are destroyed when they time out. If a + * handler is assigned to the request, the response, or the server's `'timeout'` events, timed out sockets must be handled explicitly. + * @since v8.4.0 + */ + setTimeout(msecs: number, callback?: () => void): void; + /** + * If this method is called and `response.writeHead()` has not been called, + * it will switch to implicit header mode and flush the implicit headers. + * + * This sends a chunk of the response body. This method may + * be called multiple times to provide successive parts of the body. + * + * In the `node:http` module, the response body is omitted when the + * request is a HEAD request. Similarly, the `204` and `304` responses _must not_ include a message body. + * + * `chunk` can be a string or a buffer. If `chunk` is a string, + * the second parameter specifies how to encode it into a byte stream. + * By default the `encoding` is `'utf8'`. `callback` will be called when this chunk + * of data is flushed. + * + * This is the raw HTTP body and has nothing to do with higher-level multi-part + * body encodings that may be used. + * + * The first time `response.write()` is called, it will send the buffered + * header information and the first chunk of the body to the client. The second + * time `response.write()` is called, Node.js assumes data will be streamed, + * and sends the new data separately. That is, the response is buffered up to the + * first chunk of the body. + * + * Returns `true` if the entire data was flushed successfully to the kernel + * buffer. Returns `false` if all or part of the data was queued in user memory.`'drain'` will be emitted when the buffer is free again. + * @since v8.4.0 + */ + write(chunk: string | Uint8Array, callback?: (err: Error) => void): boolean; + write(chunk: string | Uint8Array, encoding: BufferEncoding, callback?: (err: Error) => void): boolean; + /** + * Sends a status `100 Continue` to the client, indicating that the request body + * should be sent. See the `'checkContinue'` event on `Http2Server` and `Http2SecureServer`. + * @since v8.4.0 + */ + writeContinue(): void; + /** + * Sends a status `103 Early Hints` to the client with a Link header, + * indicating that the user agent can preload/preconnect the linked resources. + * The `hints` is an object containing the values of headers to be sent with + * early hints message. + * + * **Example** + * + * ```js + * const earlyHintsLink = '; rel=preload; as=style'; + * response.writeEarlyHints({ + * 'link': earlyHintsLink, + * }); + * + * const earlyHintsLinks = [ + * '; rel=preload; as=style', + * '; rel=preload; as=script', + * ]; + * response.writeEarlyHints({ + * 'link': earlyHintsLinks, + * }); + * ``` + * @since v18.11.0 + */ + writeEarlyHints(hints: Record): void; + /** + * Sends a response header to the request. The status code is a 3-digit HTTP + * status code, like `404`. The last argument, `headers`, are the response headers. + * + * Returns a reference to the `Http2ServerResponse`, so that calls can be chained. + * + * For compatibility with `HTTP/1`, a human-readable `statusMessage` may be + * passed as the second argument. However, because the `statusMessage` has no + * meaning within HTTP/2, the argument will have no effect and a process warning + * will be emitted. + * + * ```js + * const body = 'hello world'; + * response.writeHead(200, { + * 'Content-Length': Buffer.byteLength(body), + * 'Content-Type': 'text/plain; charset=utf-8', + * }); + * ``` + * + * `Content-Length` is given in bytes not characters. The`Buffer.byteLength()` API may be used to determine the number of bytes in a + * given encoding. On outbound messages, Node.js does not check if Content-Length + * and the length of the body being transmitted are equal or not. However, when + * receiving messages, Node.js will automatically reject messages when the `Content-Length` does not match the actual payload size. + * + * This method may be called at most one time on a message before `response.end()` is called. + * + * If `response.write()` or `response.end()` are called before calling + * this, the implicit/mutable headers will be calculated and call this function. + * + * When headers have been set with `response.setHeader()`, they will be merged + * with any headers passed to `response.writeHead()`, with the headers passed + * to `response.writeHead()` given precedence. + * + * ```js + * // Returns content-type = text/plain + * const server = http2.createServer((req, res) => { + * res.setHeader('Content-Type', 'text/html; charset=utf-8'); + * res.setHeader('X-Foo', 'bar'); + * res.writeHead(200, { 'Content-Type': 'text/plain; charset=utf-8' }); + * res.end('ok'); + * }); + * ``` + * + * Attempting to set a header field name or value that contains invalid characters + * will result in a `TypeError` being thrown. + * @since v8.4.0 + */ + writeHead(statusCode: number, headers?: OutgoingHttpHeaders): this; + writeHead(statusCode: number, statusMessage: string, headers?: OutgoingHttpHeaders): this; + /** + * Call `http2stream.pushStream()` with the given headers, and wrap the + * given `Http2Stream` on a newly created `Http2ServerResponse` as the callback + * parameter if successful. When `Http2ServerRequest` is closed, the callback is + * called with an error `ERR_HTTP2_INVALID_STREAM`. + * @since v8.4.0 + * @param headers An object describing the headers + * @param callback Called once `http2stream.pushStream()` is finished, or either when the attempt to create the pushed `Http2Stream` has failed or has been rejected, or the state of + * `Http2ServerRequest` is closed prior to calling the `http2stream.pushStream()` method + */ + createPushResponse( + headers: OutgoingHttpHeaders, + callback: (err: Error | null, res: Http2ServerResponse) => void, + ): void; + addListener(event: "close", listener: () => void): this; + addListener(event: "drain", listener: () => void): this; + addListener(event: "error", listener: (error: Error) => void): this; + addListener(event: "finish", listener: () => void): this; + addListener(event: "pipe", listener: (src: stream.Readable) => void): this; + addListener(event: "unpipe", listener: (src: stream.Readable) => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + emit(event: "close"): boolean; + emit(event: "drain"): boolean; + emit(event: "error", error: Error): boolean; + emit(event: "finish"): boolean; + emit(event: "pipe", src: stream.Readable): boolean; + emit(event: "unpipe", src: stream.Readable): boolean; + emit(event: string | symbol, ...args: any[]): boolean; + on(event: "close", listener: () => void): this; + on(event: "drain", listener: () => void): this; + on(event: "error", listener: (error: Error) => void): this; + on(event: "finish", listener: () => void): this; + on(event: "pipe", listener: (src: stream.Readable) => void): this; + on(event: "unpipe", listener: (src: stream.Readable) => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + once(event: "close", listener: () => void): this; + once(event: "drain", listener: () => void): this; + once(event: "error", listener: (error: Error) => void): this; + once(event: "finish", listener: () => void): this; + once(event: "pipe", listener: (src: stream.Readable) => void): this; + once(event: "unpipe", listener: (src: stream.Readable) => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + prependListener(event: "close", listener: () => void): this; + prependListener(event: "drain", listener: () => void): this; + prependListener(event: "error", listener: (error: Error) => void): this; + prependListener(event: "finish", listener: () => void): this; + prependListener(event: "pipe", listener: (src: stream.Readable) => void): this; + prependListener(event: "unpipe", listener: (src: stream.Readable) => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "drain", listener: () => void): this; + prependOnceListener(event: "error", listener: (error: Error) => void): this; + prependOnceListener(event: "finish", listener: () => void): this; + prependOnceListener(event: "pipe", listener: (src: stream.Readable) => void): this; + prependOnceListener(event: "unpipe", listener: (src: stream.Readable) => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + } + export namespace constants { + const NGHTTP2_SESSION_SERVER: number; + const NGHTTP2_SESSION_CLIENT: number; + const NGHTTP2_STREAM_STATE_IDLE: number; + const NGHTTP2_STREAM_STATE_OPEN: number; + const NGHTTP2_STREAM_STATE_RESERVED_LOCAL: number; + const NGHTTP2_STREAM_STATE_RESERVED_REMOTE: number; + const NGHTTP2_STREAM_STATE_HALF_CLOSED_LOCAL: number; + const NGHTTP2_STREAM_STATE_HALF_CLOSED_REMOTE: number; + const NGHTTP2_STREAM_STATE_CLOSED: number; + const NGHTTP2_NO_ERROR: number; + const NGHTTP2_PROTOCOL_ERROR: number; + const NGHTTP2_INTERNAL_ERROR: number; + const NGHTTP2_FLOW_CONTROL_ERROR: number; + const NGHTTP2_SETTINGS_TIMEOUT: number; + const NGHTTP2_STREAM_CLOSED: number; + const NGHTTP2_FRAME_SIZE_ERROR: number; + const NGHTTP2_REFUSED_STREAM: number; + const NGHTTP2_CANCEL: number; + const NGHTTP2_COMPRESSION_ERROR: number; + const NGHTTP2_CONNECT_ERROR: number; + const NGHTTP2_ENHANCE_YOUR_CALM: number; + const NGHTTP2_INADEQUATE_SECURITY: number; + const NGHTTP2_HTTP_1_1_REQUIRED: number; + const NGHTTP2_ERR_FRAME_SIZE_ERROR: number; + const NGHTTP2_FLAG_NONE: number; + const NGHTTP2_FLAG_END_STREAM: number; + const NGHTTP2_FLAG_END_HEADERS: number; + const NGHTTP2_FLAG_ACK: number; + const NGHTTP2_FLAG_PADDED: number; + const NGHTTP2_FLAG_PRIORITY: number; + const DEFAULT_SETTINGS_HEADER_TABLE_SIZE: number; + const DEFAULT_SETTINGS_ENABLE_PUSH: number; + const DEFAULT_SETTINGS_INITIAL_WINDOW_SIZE: number; + const DEFAULT_SETTINGS_MAX_FRAME_SIZE: number; + const MAX_MAX_FRAME_SIZE: number; + const MIN_MAX_FRAME_SIZE: number; + const MAX_INITIAL_WINDOW_SIZE: number; + const NGHTTP2_DEFAULT_WEIGHT: number; + const NGHTTP2_SETTINGS_HEADER_TABLE_SIZE: number; + const NGHTTP2_SETTINGS_ENABLE_PUSH: number; + const NGHTTP2_SETTINGS_MAX_CONCURRENT_STREAMS: number; + const NGHTTP2_SETTINGS_INITIAL_WINDOW_SIZE: number; + const NGHTTP2_SETTINGS_MAX_FRAME_SIZE: number; + const NGHTTP2_SETTINGS_MAX_HEADER_LIST_SIZE: number; + const PADDING_STRATEGY_NONE: number; + const PADDING_STRATEGY_MAX: number; + const PADDING_STRATEGY_CALLBACK: number; + const HTTP2_HEADER_STATUS: string; + const HTTP2_HEADER_METHOD: string; + const HTTP2_HEADER_AUTHORITY: string; + const HTTP2_HEADER_SCHEME: string; + const HTTP2_HEADER_PATH: string; + const HTTP2_HEADER_ACCEPT_CHARSET: string; + const HTTP2_HEADER_ACCEPT_ENCODING: string; + const HTTP2_HEADER_ACCEPT_LANGUAGE: string; + const HTTP2_HEADER_ACCEPT_RANGES: string; + const HTTP2_HEADER_ACCEPT: string; + const HTTP2_HEADER_ACCESS_CONTROL_ALLOW_CREDENTIALS: string; + const HTTP2_HEADER_ACCESS_CONTROL_ALLOW_HEADERS: string; + const HTTP2_HEADER_ACCESS_CONTROL_ALLOW_METHODS: string; + const HTTP2_HEADER_ACCESS_CONTROL_ALLOW_ORIGIN: string; + const HTTP2_HEADER_ACCESS_CONTROL_EXPOSE_HEADERS: string; + const HTTP2_HEADER_ACCESS_CONTROL_REQUEST_HEADERS: string; + const HTTP2_HEADER_ACCESS_CONTROL_REQUEST_METHOD: string; + const HTTP2_HEADER_AGE: string; + const HTTP2_HEADER_ALLOW: string; + const HTTP2_HEADER_AUTHORIZATION: string; + const HTTP2_HEADER_CACHE_CONTROL: string; + const HTTP2_HEADER_CONNECTION: string; + const HTTP2_HEADER_CONTENT_DISPOSITION: string; + const HTTP2_HEADER_CONTENT_ENCODING: string; + const HTTP2_HEADER_CONTENT_LANGUAGE: string; + const HTTP2_HEADER_CONTENT_LENGTH: string; + const HTTP2_HEADER_CONTENT_LOCATION: string; + const HTTP2_HEADER_CONTENT_MD5: string; + const HTTP2_HEADER_CONTENT_RANGE: string; + const HTTP2_HEADER_CONTENT_TYPE: string; + const HTTP2_HEADER_COOKIE: string; + const HTTP2_HEADER_DATE: string; + const HTTP2_HEADER_ETAG: string; + const HTTP2_HEADER_EXPECT: string; + const HTTP2_HEADER_EXPIRES: string; + const HTTP2_HEADER_FROM: string; + const HTTP2_HEADER_HOST: string; + const HTTP2_HEADER_IF_MATCH: string; + const HTTP2_HEADER_IF_MODIFIED_SINCE: string; + const HTTP2_HEADER_IF_NONE_MATCH: string; + const HTTP2_HEADER_IF_RANGE: string; + const HTTP2_HEADER_IF_UNMODIFIED_SINCE: string; + const HTTP2_HEADER_LAST_MODIFIED: string; + const HTTP2_HEADER_LINK: string; + const HTTP2_HEADER_LOCATION: string; + const HTTP2_HEADER_MAX_FORWARDS: string; + const HTTP2_HEADER_PREFER: string; + const HTTP2_HEADER_PROXY_AUTHENTICATE: string; + const HTTP2_HEADER_PROXY_AUTHORIZATION: string; + const HTTP2_HEADER_RANGE: string; + const HTTP2_HEADER_REFERER: string; + const HTTP2_HEADER_REFRESH: string; + const HTTP2_HEADER_RETRY_AFTER: string; + const HTTP2_HEADER_SERVER: string; + const HTTP2_HEADER_SET_COOKIE: string; + const HTTP2_HEADER_STRICT_TRANSPORT_SECURITY: string; + const HTTP2_HEADER_TRANSFER_ENCODING: string; + const HTTP2_HEADER_TE: string; + const HTTP2_HEADER_UPGRADE: string; + const HTTP2_HEADER_USER_AGENT: string; + const HTTP2_HEADER_VARY: string; + const HTTP2_HEADER_VIA: string; + const HTTP2_HEADER_WWW_AUTHENTICATE: string; + const HTTP2_HEADER_HTTP2_SETTINGS: string; + const HTTP2_HEADER_KEEP_ALIVE: string; + const HTTP2_HEADER_PROXY_CONNECTION: string; + const HTTP2_METHOD_ACL: string; + const HTTP2_METHOD_BASELINE_CONTROL: string; + const HTTP2_METHOD_BIND: string; + const HTTP2_METHOD_CHECKIN: string; + const HTTP2_METHOD_CHECKOUT: string; + const HTTP2_METHOD_CONNECT: string; + const HTTP2_METHOD_COPY: string; + const HTTP2_METHOD_DELETE: string; + const HTTP2_METHOD_GET: string; + const HTTP2_METHOD_HEAD: string; + const HTTP2_METHOD_LABEL: string; + const HTTP2_METHOD_LINK: string; + const HTTP2_METHOD_LOCK: string; + const HTTP2_METHOD_MERGE: string; + const HTTP2_METHOD_MKACTIVITY: string; + const HTTP2_METHOD_MKCALENDAR: string; + const HTTP2_METHOD_MKCOL: string; + const HTTP2_METHOD_MKREDIRECTREF: string; + const HTTP2_METHOD_MKWORKSPACE: string; + const HTTP2_METHOD_MOVE: string; + const HTTP2_METHOD_OPTIONS: string; + const HTTP2_METHOD_ORDERPATCH: string; + const HTTP2_METHOD_PATCH: string; + const HTTP2_METHOD_POST: string; + const HTTP2_METHOD_PRI: string; + const HTTP2_METHOD_PROPFIND: string; + const HTTP2_METHOD_PROPPATCH: string; + const HTTP2_METHOD_PUT: string; + const HTTP2_METHOD_REBIND: string; + const HTTP2_METHOD_REPORT: string; + const HTTP2_METHOD_SEARCH: string; + const HTTP2_METHOD_TRACE: string; + const HTTP2_METHOD_UNBIND: string; + const HTTP2_METHOD_UNCHECKOUT: string; + const HTTP2_METHOD_UNLINK: string; + const HTTP2_METHOD_UNLOCK: string; + const HTTP2_METHOD_UPDATE: string; + const HTTP2_METHOD_UPDATEREDIRECTREF: string; + const HTTP2_METHOD_VERSION_CONTROL: string; + const HTTP_STATUS_CONTINUE: number; + const HTTP_STATUS_SWITCHING_PROTOCOLS: number; + const HTTP_STATUS_PROCESSING: number; + const HTTP_STATUS_OK: number; + const HTTP_STATUS_CREATED: number; + const HTTP_STATUS_ACCEPTED: number; + const HTTP_STATUS_NON_AUTHORITATIVE_INFORMATION: number; + const HTTP_STATUS_NO_CONTENT: number; + const HTTP_STATUS_RESET_CONTENT: number; + const HTTP_STATUS_PARTIAL_CONTENT: number; + const HTTP_STATUS_MULTI_STATUS: number; + const HTTP_STATUS_ALREADY_REPORTED: number; + const HTTP_STATUS_IM_USED: number; + const HTTP_STATUS_MULTIPLE_CHOICES: number; + const HTTP_STATUS_MOVED_PERMANENTLY: number; + const HTTP_STATUS_FOUND: number; + const HTTP_STATUS_SEE_OTHER: number; + const HTTP_STATUS_NOT_MODIFIED: number; + const HTTP_STATUS_USE_PROXY: number; + const HTTP_STATUS_TEMPORARY_REDIRECT: number; + const HTTP_STATUS_PERMANENT_REDIRECT: number; + const HTTP_STATUS_BAD_REQUEST: number; + const HTTP_STATUS_UNAUTHORIZED: number; + const HTTP_STATUS_PAYMENT_REQUIRED: number; + const HTTP_STATUS_FORBIDDEN: number; + const HTTP_STATUS_NOT_FOUND: number; + const HTTP_STATUS_METHOD_NOT_ALLOWED: number; + const HTTP_STATUS_NOT_ACCEPTABLE: number; + const HTTP_STATUS_PROXY_AUTHENTICATION_REQUIRED: number; + const HTTP_STATUS_REQUEST_TIMEOUT: number; + const HTTP_STATUS_CONFLICT: number; + const HTTP_STATUS_GONE: number; + const HTTP_STATUS_LENGTH_REQUIRED: number; + const HTTP_STATUS_PRECONDITION_FAILED: number; + const HTTP_STATUS_PAYLOAD_TOO_LARGE: number; + const HTTP_STATUS_URI_TOO_LONG: number; + const HTTP_STATUS_UNSUPPORTED_MEDIA_TYPE: number; + const HTTP_STATUS_RANGE_NOT_SATISFIABLE: number; + const HTTP_STATUS_EXPECTATION_FAILED: number; + const HTTP_STATUS_TEAPOT: number; + const HTTP_STATUS_MISDIRECTED_REQUEST: number; + const HTTP_STATUS_UNPROCESSABLE_ENTITY: number; + const HTTP_STATUS_LOCKED: number; + const HTTP_STATUS_FAILED_DEPENDENCY: number; + const HTTP_STATUS_UNORDERED_COLLECTION: number; + const HTTP_STATUS_UPGRADE_REQUIRED: number; + const HTTP_STATUS_PRECONDITION_REQUIRED: number; + const HTTP_STATUS_TOO_MANY_REQUESTS: number; + const HTTP_STATUS_REQUEST_HEADER_FIELDS_TOO_LARGE: number; + const HTTP_STATUS_UNAVAILABLE_FOR_LEGAL_REASONS: number; + const HTTP_STATUS_INTERNAL_SERVER_ERROR: number; + const HTTP_STATUS_NOT_IMPLEMENTED: number; + const HTTP_STATUS_BAD_GATEWAY: number; + const HTTP_STATUS_SERVICE_UNAVAILABLE: number; + const HTTP_STATUS_GATEWAY_TIMEOUT: number; + const HTTP_STATUS_HTTP_VERSION_NOT_SUPPORTED: number; + const HTTP_STATUS_VARIANT_ALSO_NEGOTIATES: number; + const HTTP_STATUS_INSUFFICIENT_STORAGE: number; + const HTTP_STATUS_LOOP_DETECTED: number; + const HTTP_STATUS_BANDWIDTH_LIMIT_EXCEEDED: number; + const HTTP_STATUS_NOT_EXTENDED: number; + const HTTP_STATUS_NETWORK_AUTHENTICATION_REQUIRED: number; + } + /** + * This symbol can be set as a property on the HTTP/2 headers object with + * an array value in order to provide a list of headers considered sensitive. + */ + export const sensitiveHeaders: symbol; + /** + * Returns an object containing the default settings for an `Http2Session` instance. This method returns a new object instance every time it is called + * so instances returned may be safely modified for use. + * @since v8.4.0 + */ + export function getDefaultSettings(): Settings; + /** + * Returns a `Buffer` instance containing serialized representation of the given + * HTTP/2 settings as specified in the [HTTP/2](https://tools.ietf.org/html/rfc7540) specification. This is intended + * for use with the `HTTP2-Settings` header field. + * + * ```js + * const http2 = require('node:http2'); + * + * const packed = http2.getPackedSettings({ enablePush: false }); + * + * console.log(packed.toString('base64')); + * // Prints: AAIAAAAA + * ``` + * @since v8.4.0 + */ + export function getPackedSettings(settings: Settings): Buffer; + /** + * Returns a `HTTP/2 Settings Object` containing the deserialized settings from + * the given `Buffer` as generated by `http2.getPackedSettings()`. + * @since v8.4.0 + * @param buf The packed settings. + */ + export function getUnpackedSettings(buf: Uint8Array): Settings; + /** + * Returns a `net.Server` instance that creates and manages `Http2Session` instances. + * + * Since there are no browsers known that support [unencrypted HTTP/2](https://http2.github.io/faq/#does-http2-require-encryption), the use of {@link createSecureServer} is necessary when + * communicating + * with browser clients. + * + * ```js + * const http2 = require('node:http2'); + * + * // Create an unencrypted HTTP/2 server. + * // Since there are no browsers known that support + * // unencrypted HTTP/2, the use of `http2.createSecureServer()` + * // is necessary when communicating with browser clients. + * const server = http2.createServer(); + * + * server.on('stream', (stream, headers) => { + * stream.respond({ + * 'content-type': 'text/html; charset=utf-8', + * ':status': 200, + * }); + * stream.end('

Hello World

'); + * }); + * + * server.listen(8000); + * ``` + * @since v8.4.0 + * @param onRequestHandler See `Compatibility API` + */ + export function createServer( + onRequestHandler?: (request: Http2ServerRequest, response: Http2ServerResponse) => void, + ): Http2Server; + export function createServer( + options: ServerOptions, + onRequestHandler?: (request: Http2ServerRequest, response: Http2ServerResponse) => void, + ): Http2Server; + /** + * Returns a `tls.Server` instance that creates and manages `Http2Session` instances. + * + * ```js + * const http2 = require('node:http2'); + * const fs = require('node:fs'); + * + * const options = { + * key: fs.readFileSync('server-key.pem'), + * cert: fs.readFileSync('server-cert.pem'), + * }; + * + * // Create a secure HTTP/2 server + * const server = http2.createSecureServer(options); + * + * server.on('stream', (stream, headers) => { + * stream.respond({ + * 'content-type': 'text/html; charset=utf-8', + * ':status': 200, + * }); + * stream.end('

Hello World

'); + * }); + * + * server.listen(8443); + * ``` + * @since v8.4.0 + * @param onRequestHandler See `Compatibility API` + */ + export function createSecureServer( + onRequestHandler?: (request: Http2ServerRequest, response: Http2ServerResponse) => void, + ): Http2SecureServer; + export function createSecureServer( + options: SecureServerOptions, + onRequestHandler?: (request: Http2ServerRequest, response: Http2ServerResponse) => void, + ): Http2SecureServer; + /** + * Returns a `ClientHttp2Session` instance. + * + * ```js + * const http2 = require('node:http2'); + * const client = http2.connect('https://localhost:1234'); + * + * // Use the client + * + * client.close(); + * ``` + * @since v8.4.0 + * @param authority The remote HTTP/2 server to connect to. This must be in the form of a minimal, valid URL with the `http://` or `https://` prefix, host name, and IP port (if a non-default port + * is used). Userinfo (user ID and password), path, querystring, and fragment details in the URL will be ignored. + * @param listener Will be registered as a one-time listener of the {@link 'connect'} event. + */ + export function connect( + authority: string | url.URL, + listener: (session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket) => void, + ): ClientHttp2Session; + export function connect( + authority: string | url.URL, + options?: ClientSessionOptions | SecureClientSessionOptions, + listener?: (session: ClientHttp2Session, socket: net.Socket | tls.TLSSocket) => void, + ): ClientHttp2Session; + /** + * Create an HTTP/2 server session from an existing socket. + * @param socket A Duplex Stream + * @param options Any `{@link createServer}` options can be provided. + * @since v20.12.0 + */ + export function performServerHandshake(socket: stream.Duplex, options?: ServerOptions): ServerHttp2Session; +} +declare module "node:http2" { + export * from "http2"; +} diff --git a/node_modules/@types/node/https.d.ts b/node_modules/@types/node/https.d.ts new file mode 100644 index 0000000..76c6d73 --- /dev/null +++ b/node_modules/@types/node/https.d.ts @@ -0,0 +1,550 @@ +/** + * HTTPS is the HTTP protocol over TLS/SSL. In Node.js this is implemented as a + * separate module. + * @see [source](https://github.com/nodejs/node/blob/v20.13.1/lib/https.js) + */ +declare module "https" { + import { Duplex } from "node:stream"; + import * as tls from "node:tls"; + import * as http from "node:http"; + import { URL } from "node:url"; + type ServerOptions< + Request extends typeof http.IncomingMessage = typeof http.IncomingMessage, + Response extends typeof http.ServerResponse = typeof http.ServerResponse, + > = tls.SecureContextOptions & tls.TlsOptions & http.ServerOptions; + type RequestOptions = + & http.RequestOptions + & tls.SecureContextOptions + & { + checkServerIdentity?: typeof tls.checkServerIdentity | undefined; + rejectUnauthorized?: boolean | undefined; // Defaults to true + servername?: string | undefined; // SNI TLS Extension + }; + interface AgentOptions extends http.AgentOptions, tls.ConnectionOptions { + rejectUnauthorized?: boolean | undefined; + maxCachedSessions?: number | undefined; + } + /** + * An `Agent` object for HTTPS similar to `http.Agent`. See {@link request} for more information. + * @since v0.4.5 + */ + class Agent extends http.Agent { + constructor(options?: AgentOptions); + options: AgentOptions; + } + interface Server< + Request extends typeof http.IncomingMessage = typeof http.IncomingMessage, + Response extends typeof http.ServerResponse = typeof http.ServerResponse, + > extends http.Server {} + /** + * See `http.Server` for more information. + * @since v0.3.4 + */ + class Server< + Request extends typeof http.IncomingMessage = typeof http.IncomingMessage, + Response extends typeof http.ServerResponse = typeof http.ServerResponse, + > extends tls.Server { + constructor(requestListener?: http.RequestListener); + constructor( + options: ServerOptions, + requestListener?: http.RequestListener, + ); + /** + * Closes all connections connected to this server. + * @since v18.2.0 + */ + closeAllConnections(): void; + /** + * Closes all connections connected to this server which are not sending a request or waiting for a response. + * @since v18.2.0 + */ + closeIdleConnections(): void; + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "keylog", listener: (line: Buffer, tlsSocket: tls.TLSSocket) => void): this; + addListener( + event: "newSession", + listener: (sessionId: Buffer, sessionData: Buffer, callback: (err: Error, resp: Buffer) => void) => void, + ): this; + addListener( + event: "OCSPRequest", + listener: ( + certificate: Buffer, + issuer: Buffer, + callback: (err: Error | null, resp: Buffer) => void, + ) => void, + ): this; + addListener( + event: "resumeSession", + listener: (sessionId: Buffer, callback: (err: Error, sessionData: Buffer) => void) => void, + ): this; + addListener(event: "secureConnection", listener: (tlsSocket: tls.TLSSocket) => void): this; + addListener(event: "tlsClientError", listener: (err: Error, tlsSocket: tls.TLSSocket) => void): this; + addListener(event: "close", listener: () => void): this; + addListener(event: "connection", listener: (socket: Duplex) => void): this; + addListener(event: "error", listener: (err: Error) => void): this; + addListener(event: "listening", listener: () => void): this; + addListener(event: "checkContinue", listener: http.RequestListener): this; + addListener(event: "checkExpectation", listener: http.RequestListener): this; + addListener(event: "clientError", listener: (err: Error, socket: Duplex) => void): this; + addListener( + event: "connect", + listener: (req: InstanceType, socket: Duplex, head: Buffer) => void, + ): this; + addListener(event: "request", listener: http.RequestListener): this; + addListener( + event: "upgrade", + listener: (req: InstanceType, socket: Duplex, head: Buffer) => void, + ): this; + emit(event: string, ...args: any[]): boolean; + emit(event: "keylog", line: Buffer, tlsSocket: tls.TLSSocket): boolean; + emit( + event: "newSession", + sessionId: Buffer, + sessionData: Buffer, + callback: (err: Error, resp: Buffer) => void, + ): boolean; + emit( + event: "OCSPRequest", + certificate: Buffer, + issuer: Buffer, + callback: (err: Error | null, resp: Buffer) => void, + ): boolean; + emit(event: "resumeSession", sessionId: Buffer, callback: (err: Error, sessionData: Buffer) => void): boolean; + emit(event: "secureConnection", tlsSocket: tls.TLSSocket): boolean; + emit(event: "tlsClientError", err: Error, tlsSocket: tls.TLSSocket): boolean; + emit(event: "close"): boolean; + emit(event: "connection", socket: Duplex): boolean; + emit(event: "error", err: Error): boolean; + emit(event: "listening"): boolean; + emit( + event: "checkContinue", + req: InstanceType, + res: InstanceType & { + req: InstanceType; + }, + ): boolean; + emit( + event: "checkExpectation", + req: InstanceType, + res: InstanceType & { + req: InstanceType; + }, + ): boolean; + emit(event: "clientError", err: Error, socket: Duplex): boolean; + emit(event: "connect", req: InstanceType, socket: Duplex, head: Buffer): boolean; + emit( + event: "request", + req: InstanceType, + res: InstanceType & { + req: InstanceType; + }, + ): boolean; + emit(event: "upgrade", req: InstanceType, socket: Duplex, head: Buffer): boolean; + on(event: string, listener: (...args: any[]) => void): this; + on(event: "keylog", listener: (line: Buffer, tlsSocket: tls.TLSSocket) => void): this; + on( + event: "newSession", + listener: (sessionId: Buffer, sessionData: Buffer, callback: (err: Error, resp: Buffer) => void) => void, + ): this; + on( + event: "OCSPRequest", + listener: ( + certificate: Buffer, + issuer: Buffer, + callback: (err: Error | null, resp: Buffer) => void, + ) => void, + ): this; + on( + event: "resumeSession", + listener: (sessionId: Buffer, callback: (err: Error, sessionData: Buffer) => void) => void, + ): this; + on(event: "secureConnection", listener: (tlsSocket: tls.TLSSocket) => void): this; + on(event: "tlsClientError", listener: (err: Error, tlsSocket: tls.TLSSocket) => void): this; + on(event: "close", listener: () => void): this; + on(event: "connection", listener: (socket: Duplex) => void): this; + on(event: "error", listener: (err: Error) => void): this; + on(event: "listening", listener: () => void): this; + on(event: "checkContinue", listener: http.RequestListener): this; + on(event: "checkExpectation", listener: http.RequestListener): this; + on(event: "clientError", listener: (err: Error, socket: Duplex) => void): this; + on(event: "connect", listener: (req: InstanceType, socket: Duplex, head: Buffer) => void): this; + on(event: "request", listener: http.RequestListener): this; + on(event: "upgrade", listener: (req: InstanceType, socket: Duplex, head: Buffer) => void): this; + once(event: string, listener: (...args: any[]) => void): this; + once(event: "keylog", listener: (line: Buffer, tlsSocket: tls.TLSSocket) => void): this; + once( + event: "newSession", + listener: (sessionId: Buffer, sessionData: Buffer, callback: (err: Error, resp: Buffer) => void) => void, + ): this; + once( + event: "OCSPRequest", + listener: ( + certificate: Buffer, + issuer: Buffer, + callback: (err: Error | null, resp: Buffer) => void, + ) => void, + ): this; + once( + event: "resumeSession", + listener: (sessionId: Buffer, callback: (err: Error, sessionData: Buffer) => void) => void, + ): this; + once(event: "secureConnection", listener: (tlsSocket: tls.TLSSocket) => void): this; + once(event: "tlsClientError", listener: (err: Error, tlsSocket: tls.TLSSocket) => void): this; + once(event: "close", listener: () => void): this; + once(event: "connection", listener: (socket: Duplex) => void): this; + once(event: "error", listener: (err: Error) => void): this; + once(event: "listening", listener: () => void): this; + once(event: "checkContinue", listener: http.RequestListener): this; + once(event: "checkExpectation", listener: http.RequestListener): this; + once(event: "clientError", listener: (err: Error, socket: Duplex) => void): this; + once(event: "connect", listener: (req: InstanceType, socket: Duplex, head: Buffer) => void): this; + once(event: "request", listener: http.RequestListener): this; + once(event: "upgrade", listener: (req: InstanceType, socket: Duplex, head: Buffer) => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "keylog", listener: (line: Buffer, tlsSocket: tls.TLSSocket) => void): this; + prependListener( + event: "newSession", + listener: (sessionId: Buffer, sessionData: Buffer, callback: (err: Error, resp: Buffer) => void) => void, + ): this; + prependListener( + event: "OCSPRequest", + listener: ( + certificate: Buffer, + issuer: Buffer, + callback: (err: Error | null, resp: Buffer) => void, + ) => void, + ): this; + prependListener( + event: "resumeSession", + listener: (sessionId: Buffer, callback: (err: Error, sessionData: Buffer) => void) => void, + ): this; + prependListener(event: "secureConnection", listener: (tlsSocket: tls.TLSSocket) => void): this; + prependListener(event: "tlsClientError", listener: (err: Error, tlsSocket: tls.TLSSocket) => void): this; + prependListener(event: "close", listener: () => void): this; + prependListener(event: "connection", listener: (socket: Duplex) => void): this; + prependListener(event: "error", listener: (err: Error) => void): this; + prependListener(event: "listening", listener: () => void): this; + prependListener(event: "checkContinue", listener: http.RequestListener): this; + prependListener(event: "checkExpectation", listener: http.RequestListener): this; + prependListener(event: "clientError", listener: (err: Error, socket: Duplex) => void): this; + prependListener( + event: "connect", + listener: (req: InstanceType, socket: Duplex, head: Buffer) => void, + ): this; + prependListener(event: "request", listener: http.RequestListener): this; + prependListener( + event: "upgrade", + listener: (req: InstanceType, socket: Duplex, head: Buffer) => void, + ): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "keylog", listener: (line: Buffer, tlsSocket: tls.TLSSocket) => void): this; + prependOnceListener( + event: "newSession", + listener: (sessionId: Buffer, sessionData: Buffer, callback: (err: Error, resp: Buffer) => void) => void, + ): this; + prependOnceListener( + event: "OCSPRequest", + listener: ( + certificate: Buffer, + issuer: Buffer, + callback: (err: Error | null, resp: Buffer) => void, + ) => void, + ): this; + prependOnceListener( + event: "resumeSession", + listener: (sessionId: Buffer, callback: (err: Error, sessionData: Buffer) => void) => void, + ): this; + prependOnceListener(event: "secureConnection", listener: (tlsSocket: tls.TLSSocket) => void): this; + prependOnceListener(event: "tlsClientError", listener: (err: Error, tlsSocket: tls.TLSSocket) => void): this; + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "connection", listener: (socket: Duplex) => void): this; + prependOnceListener(event: "error", listener: (err: Error) => void): this; + prependOnceListener(event: "listening", listener: () => void): this; + prependOnceListener(event: "checkContinue", listener: http.RequestListener): this; + prependOnceListener(event: "checkExpectation", listener: http.RequestListener): this; + prependOnceListener(event: "clientError", listener: (err: Error, socket: Duplex) => void): this; + prependOnceListener( + event: "connect", + listener: (req: InstanceType, socket: Duplex, head: Buffer) => void, + ): this; + prependOnceListener(event: "request", listener: http.RequestListener): this; + prependOnceListener( + event: "upgrade", + listener: (req: InstanceType, socket: Duplex, head: Buffer) => void, + ): this; + } + /** + * ```js + * // curl -k https://localhost:8000/ + * const https = require('node:https'); + * const fs = require('node:fs'); + * + * const options = { + * key: fs.readFileSync('test/fixtures/keys/agent2-key.pem'), + * cert: fs.readFileSync('test/fixtures/keys/agent2-cert.pem'), + * }; + * + * https.createServer(options, (req, res) => { + * res.writeHead(200); + * res.end('hello world\n'); + * }).listen(8000); + * ``` + * + * Or + * + * ```js + * const https = require('node:https'); + * const fs = require('node:fs'); + * + * const options = { + * pfx: fs.readFileSync('test/fixtures/test_cert.pfx'), + * passphrase: 'sample', + * }; + * + * https.createServer(options, (req, res) => { + * res.writeHead(200); + * res.end('hello world\n'); + * }).listen(8000); + * ``` + * @since v0.3.4 + * @param options Accepts `options` from `createServer`, `createSecureContext` and `createServer`. + * @param requestListener A listener to be added to the `'request'` event. + */ + function createServer< + Request extends typeof http.IncomingMessage = typeof http.IncomingMessage, + Response extends typeof http.ServerResponse = typeof http.ServerResponse, + >(requestListener?: http.RequestListener): Server; + function createServer< + Request extends typeof http.IncomingMessage = typeof http.IncomingMessage, + Response extends typeof http.ServerResponse = typeof http.ServerResponse, + >( + options: ServerOptions, + requestListener?: http.RequestListener, + ): Server; + /** + * Makes a request to a secure web server. + * + * The following additional `options` from `tls.connect()` are also accepted: `ca`, `cert`, `ciphers`, `clientCertEngine`, `crl`, `dhparam`, `ecdhCurve`, `honorCipherOrder`, `key`, `passphrase`, + * `pfx`, `rejectUnauthorized`, `secureOptions`, `secureProtocol`, `servername`, `sessionIdContext`, `highWaterMark`. + * + * `options` can be an object, a string, or a `URL` object. If `options` is a + * string, it is automatically parsed with `new URL()`. If it is a `URL` object, it will be automatically converted to an ordinary `options` object. + * + * `https.request()` returns an instance of the `http.ClientRequest` class. The `ClientRequest` instance is a writable stream. If one needs to + * upload a file with a POST request, then write to the `ClientRequest` object. + * + * ```js + * const https = require('node:https'); + * + * const options = { + * hostname: 'encrypted.google.com', + * port: 443, + * path: '/', + * method: 'GET', + * }; + * + * const req = https.request(options, (res) => { + * console.log('statusCode:', res.statusCode); + * console.log('headers:', res.headers); + * + * res.on('data', (d) => { + * process.stdout.write(d); + * }); + * }); + * + * req.on('error', (e) => { + * console.error(e); + * }); + * req.end(); + * ``` + * + * Example using options from `tls.connect()`: + * + * ```js + * const options = { + * hostname: 'encrypted.google.com', + * port: 443, + * path: '/', + * method: 'GET', + * key: fs.readFileSync('test/fixtures/keys/agent2-key.pem'), + * cert: fs.readFileSync('test/fixtures/keys/agent2-cert.pem'), + * }; + * options.agent = new https.Agent(options); + * + * const req = https.request(options, (res) => { + * // ... + * }); + * ``` + * + * Alternatively, opt out of connection pooling by not using an `Agent`. + * + * ```js + * const options = { + * hostname: 'encrypted.google.com', + * port: 443, + * path: '/', + * method: 'GET', + * key: fs.readFileSync('test/fixtures/keys/agent2-key.pem'), + * cert: fs.readFileSync('test/fixtures/keys/agent2-cert.pem'), + * agent: false, + * }; + * + * const req = https.request(options, (res) => { + * // ... + * }); + * ``` + * + * Example using a `URL` as `options`: + * + * ```js + * const options = new URL('https://abc:xyz@example.com'); + * + * const req = https.request(options, (res) => { + * // ... + * }); + * ``` + * + * Example pinning on certificate fingerprint, or the public key (similar to`pin-sha256`): + * + * ```js + * const tls = require('node:tls'); + * const https = require('node:https'); + * const crypto = require('node:crypto'); + * + * function sha256(s) { + * return crypto.createHash('sha256').update(s).digest('base64'); + * } + * const options = { + * hostname: 'github.com', + * port: 443, + * path: '/', + * method: 'GET', + * checkServerIdentity: function(host, cert) { + * // Make sure the certificate is issued to the host we are connected to + * const err = tls.checkServerIdentity(host, cert); + * if (err) { + * return err; + * } + * + * // Pin the public key, similar to HPKP pin-sha256 pinning + * const pubkey256 = 'pL1+qb9HTMRZJmuC/bB/ZI9d302BYrrqiVuRyW+DGrU='; + * if (sha256(cert.pubkey) !== pubkey256) { + * const msg = 'Certificate verification error: ' + + * `The public key of '${cert.subject.CN}' ` + + * 'does not match our pinned fingerprint'; + * return new Error(msg); + * } + * + * // Pin the exact certificate, rather than the pub key + * const cert256 = '25:FE:39:32:D9:63:8C:8A:FC:A1:9A:29:87:' + + * 'D8:3E:4C:1D:98:DB:71:E4:1A:48:03:98:EA:22:6A:BD:8B:93:16'; + * if (cert.fingerprint256 !== cert256) { + * const msg = 'Certificate verification error: ' + + * `The certificate of '${cert.subject.CN}' ` + + * 'does not match our pinned fingerprint'; + * return new Error(msg); + * } + * + * // This loop is informational only. + * // Print the certificate and public key fingerprints of all certs in the + * // chain. Its common to pin the public key of the issuer on the public + * // internet, while pinning the public key of the service in sensitive + * // environments. + * do { + * console.log('Subject Common Name:', cert.subject.CN); + * console.log(' Certificate SHA256 fingerprint:', cert.fingerprint256); + * + * hash = crypto.createHash('sha256'); + * console.log(' Public key ping-sha256:', sha256(cert.pubkey)); + * + * lastprint256 = cert.fingerprint256; + * cert = cert.issuerCertificate; + * } while (cert.fingerprint256 !== lastprint256); + * + * }, + * }; + * + * options.agent = new https.Agent(options); + * const req = https.request(options, (res) => { + * console.log('All OK. Server matched our pinned cert or public key'); + * console.log('statusCode:', res.statusCode); + * // Print the HPKP values + * console.log('headers:', res.headers['public-key-pins']); + * + * res.on('data', (d) => {}); + * }); + * + * req.on('error', (e) => { + * console.error(e.message); + * }); + * req.end(); + * ``` + * + * Outputs for example: + * + * ```text + * Subject Common Name: github.com + * Certificate SHA256 fingerprint: 25:FE:39:32:D9:63:8C:8A:FC:A1:9A:29:87:D8:3E:4C:1D:98:DB:71:E4:1A:48:03:98:EA:22:6A:BD:8B:93:16 + * Public key ping-sha256: pL1+qb9HTMRZJmuC/bB/ZI9d302BYrrqiVuRyW+DGrU= + * Subject Common Name: DigiCert SHA2 Extended Validation Server CA + * Certificate SHA256 fingerprint: 40:3E:06:2A:26:53:05:91:13:28:5B:AF:80:A0:D4:AE:42:2C:84:8C:9F:78:FA:D0:1F:C9:4B:C5:B8:7F:EF:1A + * Public key ping-sha256: RRM1dGqnDFsCJXBTHky16vi1obOlCgFFn/yOhI/y+ho= + * Subject Common Name: DigiCert High Assurance EV Root CA + * Certificate SHA256 fingerprint: 74:31:E5:F4:C3:C1:CE:46:90:77:4F:0B:61:E0:54:40:88:3B:A9:A0:1E:D0:0B:A6:AB:D7:80:6E:D3:B1:18:CF + * Public key ping-sha256: WoiWRyIOVNa9ihaBciRSC7XHjliYS9VwUGOIud4PB18= + * All OK. Server matched our pinned cert or public key + * statusCode: 200 + * headers: max-age=0; pin-sha256="WoiWRyIOVNa9ihaBciRSC7XHjliYS9VwUGOIud4PB18="; pin-sha256="RRM1dGqnDFsCJXBTHky16vi1obOlCgFFn/yOhI/y+ho="; + * pin-sha256="k2v657xBsOVe1PQRwOsHsw3bsGT2VzIqz5K+59sNQws="; pin-sha256="K87oWBWM9UZfyddvDfoxL+8lpNyoUB2ptGtn0fv6G2Q="; pin-sha256="IQBnNBEiFuhj+8x6X8XLgh01V9Ic5/V3IRQLNFFc7v4="; + * pin-sha256="iie1VXtL7HzAMF+/PVPR9xzT80kQxdZeJ+zduCB3uj0="; pin-sha256="LvRiGEjRqfzurezaWuj8Wie2gyHMrW5Q06LspMnox7A="; includeSubDomains + * ``` + * @since v0.3.6 + * @param options Accepts all `options` from `request`, with some differences in default values: + */ + function request( + options: RequestOptions | string | URL, + callback?: (res: http.IncomingMessage) => void, + ): http.ClientRequest; + function request( + url: string | URL, + options: RequestOptions, + callback?: (res: http.IncomingMessage) => void, + ): http.ClientRequest; + /** + * Like `http.get()` but for HTTPS. + * + * `options` can be an object, a string, or a `URL` object. If `options` is a + * string, it is automatically parsed with `new URL()`. If it is a `URL` object, it will be automatically converted to an ordinary `options` object. + * + * ```js + * const https = require('node:https'); + * + * https.get('https://encrypted.google.com/', (res) => { + * console.log('statusCode:', res.statusCode); + * console.log('headers:', res.headers); + * + * res.on('data', (d) => { + * process.stdout.write(d); + * }); + * + * }).on('error', (e) => { + * console.error(e); + * }); + * ``` + * @since v0.3.6 + * @param options Accepts the same `options` as {@link request}, with the `method` always set to `GET`. + */ + function get( + options: RequestOptions | string | URL, + callback?: (res: http.IncomingMessage) => void, + ): http.ClientRequest; + function get( + url: string | URL, + options: RequestOptions, + callback?: (res: http.IncomingMessage) => void, + ): http.ClientRequest; + let globalAgent: Agent; +} +declare module "node:https" { + export * from "https"; +} diff --git a/node_modules/@types/node/index.d.ts b/node_modules/@types/node/index.d.ts new file mode 100644 index 0000000..f043abe --- /dev/null +++ b/node_modules/@types/node/index.d.ts @@ -0,0 +1,89 @@ +/** + * License for programmatically and manually incorporated + * documentation aka. `JSDoc` from https://github.com/nodejs/node/tree/master/doc + * + * Copyright Node.js contributors. All rights reserved. + * Permission is hereby granted, free of charge, to any person obtaining a copy + * of this software and associated documentation files (the "Software"), to + * deal in the Software without restriction, including without limitation the + * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or + * sell copies of the Software, and to permit persons to whom the Software is + * furnished to do so, subject to the following conditions: + * + * The above copyright notice and this permission notice shall be included in + * all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING + * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS + * IN THE SOFTWARE. + */ + +// NOTE: These definitions support NodeJS and TypeScript 4.9+. + +// Reference required types from the default lib: +/// +/// +/// +/// + +// Base definitions for all NodeJS modules that are not specific to any version of TypeScript: +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// +/// + +/// diff --git a/node_modules/@types/node/inspector.d.ts b/node_modules/@types/node/inspector.d.ts new file mode 100644 index 0000000..012eb74 --- /dev/null +++ b/node_modules/@types/node/inspector.d.ts @@ -0,0 +1,2746 @@ +// Type definitions for inspector + +// These definitions are auto-generated. +// Please see https://github.com/DefinitelyTyped/DefinitelyTyped/pull/19330 +// for more information. + + +/** + * The `node:inspector` module provides an API for interacting with the V8 + * inspector. + * + * It can be accessed using: + * + * ```js + * import * as inspector from 'node:inspector/promises'; + * ``` + * + * or + * + * ```js + * import * as inspector from 'node:inspector'; + * ``` + * @see [source](https://github.com/nodejs/node/blob/v20.13.1/lib/inspector.js) + */ +declare module 'inspector' { + import EventEmitter = require('node:events'); + interface InspectorNotification { + method: string; + params: T; + } + namespace Schema { + /** + * Description of the protocol domain. + */ + interface Domain { + /** + * Domain name. + */ + name: string; + /** + * Domain version. + */ + version: string; + } + interface GetDomainsReturnType { + /** + * List of supported domains. + */ + domains: Domain[]; + } + } + namespace Runtime { + /** + * Unique script identifier. + */ + type ScriptId = string; + /** + * Unique object identifier. + */ + type RemoteObjectId = string; + /** + * Primitive value which cannot be JSON-stringified. + */ + type UnserializableValue = string; + /** + * Mirror object referencing original JavaScript object. + */ + interface RemoteObject { + /** + * Object type. + */ + type: string; + /** + * Object subtype hint. Specified for object type values only. + */ + subtype?: string | undefined; + /** + * Object class (constructor) name. Specified for object type values only. + */ + className?: string | undefined; + /** + * Remote object value in case of primitive values or JSON values (if it was requested). + */ + value?: any; + /** + * Primitive value which can not be JSON-stringified does not have value, but gets this property. + */ + unserializableValue?: UnserializableValue | undefined; + /** + * String representation of the object. + */ + description?: string | undefined; + /** + * Unique object identifier (for non-primitive values). + */ + objectId?: RemoteObjectId | undefined; + /** + * Preview containing abbreviated property values. Specified for object type values only. + * @experimental + */ + preview?: ObjectPreview | undefined; + /** + * @experimental + */ + customPreview?: CustomPreview | undefined; + } + /** + * @experimental + */ + interface CustomPreview { + header: string; + hasBody: boolean; + formatterObjectId: RemoteObjectId; + bindRemoteObjectFunctionId: RemoteObjectId; + configObjectId?: RemoteObjectId | undefined; + } + /** + * Object containing abbreviated remote object value. + * @experimental + */ + interface ObjectPreview { + /** + * Object type. + */ + type: string; + /** + * Object subtype hint. Specified for object type values only. + */ + subtype?: string | undefined; + /** + * String representation of the object. + */ + description?: string | undefined; + /** + * True iff some of the properties or entries of the original object did not fit. + */ + overflow: boolean; + /** + * List of the properties. + */ + properties: PropertyPreview[]; + /** + * List of the entries. Specified for map and set subtype values only. + */ + entries?: EntryPreview[] | undefined; + } + /** + * @experimental + */ + interface PropertyPreview { + /** + * Property name. + */ + name: string; + /** + * Object type. Accessor means that the property itself is an accessor property. + */ + type: string; + /** + * User-friendly property value string. + */ + value?: string | undefined; + /** + * Nested value preview. + */ + valuePreview?: ObjectPreview | undefined; + /** + * Object subtype hint. Specified for object type values only. + */ + subtype?: string | undefined; + } + /** + * @experimental + */ + interface EntryPreview { + /** + * Preview of the key. Specified for map-like collection entries. + */ + key?: ObjectPreview | undefined; + /** + * Preview of the value. + */ + value: ObjectPreview; + } + /** + * Object property descriptor. + */ + interface PropertyDescriptor { + /** + * Property name or symbol description. + */ + name: string; + /** + * The value associated with the property. + */ + value?: RemoteObject | undefined; + /** + * True if the value associated with the property may be changed (data descriptors only). + */ + writable?: boolean | undefined; + /** + * A function which serves as a getter for the property, or undefined if there is no getter (accessor descriptors only). + */ + get?: RemoteObject | undefined; + /** + * A function which serves as a setter for the property, or undefined if there is no setter (accessor descriptors only). + */ + set?: RemoteObject | undefined; + /** + * True if the type of this property descriptor may be changed and if the property may be deleted from the corresponding object. + */ + configurable: boolean; + /** + * True if this property shows up during enumeration of the properties on the corresponding object. + */ + enumerable: boolean; + /** + * True if the result was thrown during the evaluation. + */ + wasThrown?: boolean | undefined; + /** + * True if the property is owned for the object. + */ + isOwn?: boolean | undefined; + /** + * Property symbol object, if the property is of the symbol type. + */ + symbol?: RemoteObject | undefined; + } + /** + * Object internal property descriptor. This property isn't normally visible in JavaScript code. + */ + interface InternalPropertyDescriptor { + /** + * Conventional property name. + */ + name: string; + /** + * The value associated with the property. + */ + value?: RemoteObject | undefined; + } + /** + * Represents function call argument. Either remote object id objectId, primitive value, unserializable primitive value or neither of (for undefined) them should be specified. + */ + interface CallArgument { + /** + * Primitive value or serializable javascript object. + */ + value?: any; + /** + * Primitive value which can not be JSON-stringified. + */ + unserializableValue?: UnserializableValue | undefined; + /** + * Remote object handle. + */ + objectId?: RemoteObjectId | undefined; + } + /** + * Id of an execution context. + */ + type ExecutionContextId = number; + /** + * Description of an isolated world. + */ + interface ExecutionContextDescription { + /** + * Unique id of the execution context. It can be used to specify in which execution context script evaluation should be performed. + */ + id: ExecutionContextId; + /** + * Execution context origin. + */ + origin: string; + /** + * Human readable name describing given context. + */ + name: string; + /** + * Embedder-specific auxiliary data. + */ + auxData?: {} | undefined; + } + /** + * Detailed information about exception (or error) that was thrown during script compilation or execution. + */ + interface ExceptionDetails { + /** + * Exception id. + */ + exceptionId: number; + /** + * Exception text, which should be used together with exception object when available. + */ + text: string; + /** + * Line number of the exception location (0-based). + */ + lineNumber: number; + /** + * Column number of the exception location (0-based). + */ + columnNumber: number; + /** + * Script ID of the exception location. + */ + scriptId?: ScriptId | undefined; + /** + * URL of the exception location, to be used when the script was not reported. + */ + url?: string | undefined; + /** + * JavaScript stack trace if available. + */ + stackTrace?: StackTrace | undefined; + /** + * Exception object if available. + */ + exception?: RemoteObject | undefined; + /** + * Identifier of the context where exception happened. + */ + executionContextId?: ExecutionContextId | undefined; + } + /** + * Number of milliseconds since epoch. + */ + type Timestamp = number; + /** + * Stack entry for runtime errors and assertions. + */ + interface CallFrame { + /** + * JavaScript function name. + */ + functionName: string; + /** + * JavaScript script id. + */ + scriptId: ScriptId; + /** + * JavaScript script name or url. + */ + url: string; + /** + * JavaScript script line number (0-based). + */ + lineNumber: number; + /** + * JavaScript script column number (0-based). + */ + columnNumber: number; + } + /** + * Call frames for assertions or error messages. + */ + interface StackTrace { + /** + * String label of this stack trace. For async traces this may be a name of the function that initiated the async call. + */ + description?: string | undefined; + /** + * JavaScript function name. + */ + callFrames: CallFrame[]; + /** + * Asynchronous JavaScript stack trace that preceded this stack, if available. + */ + parent?: StackTrace | undefined; + /** + * Asynchronous JavaScript stack trace that preceded this stack, if available. + * @experimental + */ + parentId?: StackTraceId | undefined; + } + /** + * Unique identifier of current debugger. + * @experimental + */ + type UniqueDebuggerId = string; + /** + * If debuggerId is set stack trace comes from another debugger and can be resolved there. This allows to track cross-debugger calls. See Runtime.StackTrace and Debugger.paused for usages. + * @experimental + */ + interface StackTraceId { + id: string; + debuggerId?: UniqueDebuggerId | undefined; + } + interface EvaluateParameterType { + /** + * Expression to evaluate. + */ + expression: string; + /** + * Symbolic group name that can be used to release multiple objects. + */ + objectGroup?: string | undefined; + /** + * Determines whether Command Line API should be available during the evaluation. + */ + includeCommandLineAPI?: boolean | undefined; + /** + * In silent mode exceptions thrown during evaluation are not reported and do not pause execution. Overrides setPauseOnException state. + */ + silent?: boolean | undefined; + /** + * Specifies in which execution context to perform evaluation. If the parameter is omitted the evaluation will be performed in the context of the inspected page. + */ + contextId?: ExecutionContextId | undefined; + /** + * Whether the result is expected to be a JSON object that should be sent by value. + */ + returnByValue?: boolean | undefined; + /** + * Whether preview should be generated for the result. + * @experimental + */ + generatePreview?: boolean | undefined; + /** + * Whether execution should be treated as initiated by user in the UI. + */ + userGesture?: boolean | undefined; + /** + * Whether execution should await for resulting value and return once awaited promise is resolved. + */ + awaitPromise?: boolean | undefined; + } + interface AwaitPromiseParameterType { + /** + * Identifier of the promise. + */ + promiseObjectId: RemoteObjectId; + /** + * Whether the result is expected to be a JSON object that should be sent by value. + */ + returnByValue?: boolean | undefined; + /** + * Whether preview should be generated for the result. + */ + generatePreview?: boolean | undefined; + } + interface CallFunctionOnParameterType { + /** + * Declaration of the function to call. + */ + functionDeclaration: string; + /** + * Identifier of the object to call function on. Either objectId or executionContextId should be specified. + */ + objectId?: RemoteObjectId | undefined; + /** + * Call arguments. All call arguments must belong to the same JavaScript world as the target object. + */ + arguments?: CallArgument[] | undefined; + /** + * In silent mode exceptions thrown during evaluation are not reported and do not pause execution. Overrides setPauseOnException state. + */ + silent?: boolean | undefined; + /** + * Whether the result is expected to be a JSON object which should be sent by value. + */ + returnByValue?: boolean | undefined; + /** + * Whether preview should be generated for the result. + * @experimental + */ + generatePreview?: boolean | undefined; + /** + * Whether execution should be treated as initiated by user in the UI. + */ + userGesture?: boolean | undefined; + /** + * Whether execution should await for resulting value and return once awaited promise is resolved. + */ + awaitPromise?: boolean | undefined; + /** + * Specifies execution context which global object will be used to call function on. Either executionContextId or objectId should be specified. + */ + executionContextId?: ExecutionContextId | undefined; + /** + * Symbolic group name that can be used to release multiple objects. If objectGroup is not specified and objectId is, objectGroup will be inherited from object. + */ + objectGroup?: string | undefined; + } + interface GetPropertiesParameterType { + /** + * Identifier of the object to return properties for. + */ + objectId: RemoteObjectId; + /** + * If true, returns properties belonging only to the element itself, not to its prototype chain. + */ + ownProperties?: boolean | undefined; + /** + * If true, returns accessor properties (with getter/setter) only; internal properties are not returned either. + * @experimental + */ + accessorPropertiesOnly?: boolean | undefined; + /** + * Whether preview should be generated for the results. + * @experimental + */ + generatePreview?: boolean | undefined; + } + interface ReleaseObjectParameterType { + /** + * Identifier of the object to release. + */ + objectId: RemoteObjectId; + } + interface ReleaseObjectGroupParameterType { + /** + * Symbolic object group name. + */ + objectGroup: string; + } + interface SetCustomObjectFormatterEnabledParameterType { + enabled: boolean; + } + interface CompileScriptParameterType { + /** + * Expression to compile. + */ + expression: string; + /** + * Source url to be set for the script. + */ + sourceURL: string; + /** + * Specifies whether the compiled script should be persisted. + */ + persistScript: boolean; + /** + * Specifies in which execution context to perform script run. If the parameter is omitted the evaluation will be performed in the context of the inspected page. + */ + executionContextId?: ExecutionContextId | undefined; + } + interface RunScriptParameterType { + /** + * Id of the script to run. + */ + scriptId: ScriptId; + /** + * Specifies in which execution context to perform script run. If the parameter is omitted the evaluation will be performed in the context of the inspected page. + */ + executionContextId?: ExecutionContextId | undefined; + /** + * Symbolic group name that can be used to release multiple objects. + */ + objectGroup?: string | undefined; + /** + * In silent mode exceptions thrown during evaluation are not reported and do not pause execution. Overrides setPauseOnException state. + */ + silent?: boolean | undefined; + /** + * Determines whether Command Line API should be available during the evaluation. + */ + includeCommandLineAPI?: boolean | undefined; + /** + * Whether the result is expected to be a JSON object which should be sent by value. + */ + returnByValue?: boolean | undefined; + /** + * Whether preview should be generated for the result. + */ + generatePreview?: boolean | undefined; + /** + * Whether execution should await for resulting value and return once awaited promise is resolved. + */ + awaitPromise?: boolean | undefined; + } + interface QueryObjectsParameterType { + /** + * Identifier of the prototype to return objects for. + */ + prototypeObjectId: RemoteObjectId; + } + interface GlobalLexicalScopeNamesParameterType { + /** + * Specifies in which execution context to lookup global scope variables. + */ + executionContextId?: ExecutionContextId | undefined; + } + interface EvaluateReturnType { + /** + * Evaluation result. + */ + result: RemoteObject; + /** + * Exception details. + */ + exceptionDetails?: ExceptionDetails | undefined; + } + interface AwaitPromiseReturnType { + /** + * Promise result. Will contain rejected value if promise was rejected. + */ + result: RemoteObject; + /** + * Exception details if stack strace is available. + */ + exceptionDetails?: ExceptionDetails | undefined; + } + interface CallFunctionOnReturnType { + /** + * Call result. + */ + result: RemoteObject; + /** + * Exception details. + */ + exceptionDetails?: ExceptionDetails | undefined; + } + interface GetPropertiesReturnType { + /** + * Object properties. + */ + result: PropertyDescriptor[]; + /** + * Internal object properties (only of the element itself). + */ + internalProperties?: InternalPropertyDescriptor[] | undefined; + /** + * Exception details. + */ + exceptionDetails?: ExceptionDetails | undefined; + } + interface CompileScriptReturnType { + /** + * Id of the script. + */ + scriptId?: ScriptId | undefined; + /** + * Exception details. + */ + exceptionDetails?: ExceptionDetails | undefined; + } + interface RunScriptReturnType { + /** + * Run result. + */ + result: RemoteObject; + /** + * Exception details. + */ + exceptionDetails?: ExceptionDetails | undefined; + } + interface QueryObjectsReturnType { + /** + * Array with objects. + */ + objects: RemoteObject; + } + interface GlobalLexicalScopeNamesReturnType { + names: string[]; + } + interface ExecutionContextCreatedEventDataType { + /** + * A newly created execution context. + */ + context: ExecutionContextDescription; + } + interface ExecutionContextDestroyedEventDataType { + /** + * Id of the destroyed context + */ + executionContextId: ExecutionContextId; + } + interface ExceptionThrownEventDataType { + /** + * Timestamp of the exception. + */ + timestamp: Timestamp; + exceptionDetails: ExceptionDetails; + } + interface ExceptionRevokedEventDataType { + /** + * Reason describing why exception was revoked. + */ + reason: string; + /** + * The id of revoked exception, as reported in exceptionThrown. + */ + exceptionId: number; + } + interface ConsoleAPICalledEventDataType { + /** + * Type of the call. + */ + type: string; + /** + * Call arguments. + */ + args: RemoteObject[]; + /** + * Identifier of the context where the call was made. + */ + executionContextId: ExecutionContextId; + /** + * Call timestamp. + */ + timestamp: Timestamp; + /** + * Stack trace captured when the call was made. + */ + stackTrace?: StackTrace | undefined; + /** + * Console context descriptor for calls on non-default console context (not console.*): 'anonymous#unique-logger-id' for call on unnamed context, 'name#unique-logger-id' for call on named context. + * @experimental + */ + context?: string | undefined; + } + interface InspectRequestedEventDataType { + object: RemoteObject; + hints: {}; + } + } + namespace Debugger { + /** + * Breakpoint identifier. + */ + type BreakpointId = string; + /** + * Call frame identifier. + */ + type CallFrameId = string; + /** + * Location in the source code. + */ + interface Location { + /** + * Script identifier as reported in the Debugger.scriptParsed. + */ + scriptId: Runtime.ScriptId; + /** + * Line number in the script (0-based). + */ + lineNumber: number; + /** + * Column number in the script (0-based). + */ + columnNumber?: number | undefined; + } + /** + * Location in the source code. + * @experimental + */ + interface ScriptPosition { + lineNumber: number; + columnNumber: number; + } + /** + * JavaScript call frame. Array of call frames form the call stack. + */ + interface CallFrame { + /** + * Call frame identifier. This identifier is only valid while the virtual machine is paused. + */ + callFrameId: CallFrameId; + /** + * Name of the JavaScript function called on this call frame. + */ + functionName: string; + /** + * Location in the source code. + */ + functionLocation?: Location | undefined; + /** + * Location in the source code. + */ + location: Location; + /** + * JavaScript script name or url. + */ + url: string; + /** + * Scope chain for this call frame. + */ + scopeChain: Scope[]; + /** + * this object for this call frame. + */ + this: Runtime.RemoteObject; + /** + * The value being returned, if the function is at return point. + */ + returnValue?: Runtime.RemoteObject | undefined; + } + /** + * Scope description. + */ + interface Scope { + /** + * Scope type. + */ + type: string; + /** + * Object representing the scope. For global and with scopes it represents the actual object; for the rest of the scopes, it is artificial transient object enumerating scope variables as its properties. + */ + object: Runtime.RemoteObject; + name?: string | undefined; + /** + * Location in the source code where scope starts + */ + startLocation?: Location | undefined; + /** + * Location in the source code where scope ends + */ + endLocation?: Location | undefined; + } + /** + * Search match for resource. + */ + interface SearchMatch { + /** + * Line number in resource content. + */ + lineNumber: number; + /** + * Line with match content. + */ + lineContent: string; + } + interface BreakLocation { + /** + * Script identifier as reported in the Debugger.scriptParsed. + */ + scriptId: Runtime.ScriptId; + /** + * Line number in the script (0-based). + */ + lineNumber: number; + /** + * Column number in the script (0-based). + */ + columnNumber?: number | undefined; + type?: string | undefined; + } + interface SetBreakpointsActiveParameterType { + /** + * New value for breakpoints active state. + */ + active: boolean; + } + interface SetSkipAllPausesParameterType { + /** + * New value for skip pauses state. + */ + skip: boolean; + } + interface SetBreakpointByUrlParameterType { + /** + * Line number to set breakpoint at. + */ + lineNumber: number; + /** + * URL of the resources to set breakpoint on. + */ + url?: string | undefined; + /** + * Regex pattern for the URLs of the resources to set breakpoints on. Either url or urlRegex must be specified. + */ + urlRegex?: string | undefined; + /** + * Script hash of the resources to set breakpoint on. + */ + scriptHash?: string | undefined; + /** + * Offset in the line to set breakpoint at. + */ + columnNumber?: number | undefined; + /** + * Expression to use as a breakpoint condition. When specified, debugger will only stop on the breakpoint if this expression evaluates to true. + */ + condition?: string | undefined; + } + interface SetBreakpointParameterType { + /** + * Location to set breakpoint in. + */ + location: Location; + /** + * Expression to use as a breakpoint condition. When specified, debugger will only stop on the breakpoint if this expression evaluates to true. + */ + condition?: string | undefined; + } + interface RemoveBreakpointParameterType { + breakpointId: BreakpointId; + } + interface GetPossibleBreakpointsParameterType { + /** + * Start of range to search possible breakpoint locations in. + */ + start: Location; + /** + * End of range to search possible breakpoint locations in (excluding). When not specified, end of scripts is used as end of range. + */ + end?: Location | undefined; + /** + * Only consider locations which are in the same (non-nested) function as start. + */ + restrictToFunction?: boolean | undefined; + } + interface ContinueToLocationParameterType { + /** + * Location to continue to. + */ + location: Location; + targetCallFrames?: string | undefined; + } + interface PauseOnAsyncCallParameterType { + /** + * Debugger will pause when async call with given stack trace is started. + */ + parentStackTraceId: Runtime.StackTraceId; + } + interface StepIntoParameterType { + /** + * Debugger will issue additional Debugger.paused notification if any async task is scheduled before next pause. + * @experimental + */ + breakOnAsyncCall?: boolean | undefined; + } + interface GetStackTraceParameterType { + stackTraceId: Runtime.StackTraceId; + } + interface SearchInContentParameterType { + /** + * Id of the script to search in. + */ + scriptId: Runtime.ScriptId; + /** + * String to search for. + */ + query: string; + /** + * If true, search is case sensitive. + */ + caseSensitive?: boolean | undefined; + /** + * If true, treats string parameter as regex. + */ + isRegex?: boolean | undefined; + } + interface SetScriptSourceParameterType { + /** + * Id of the script to edit. + */ + scriptId: Runtime.ScriptId; + /** + * New content of the script. + */ + scriptSource: string; + /** + * If true the change will not actually be applied. Dry run may be used to get result description without actually modifying the code. + */ + dryRun?: boolean | undefined; + } + interface RestartFrameParameterType { + /** + * Call frame identifier to evaluate on. + */ + callFrameId: CallFrameId; + } + interface GetScriptSourceParameterType { + /** + * Id of the script to get source for. + */ + scriptId: Runtime.ScriptId; + } + interface SetPauseOnExceptionsParameterType { + /** + * Pause on exceptions mode. + */ + state: string; + } + interface EvaluateOnCallFrameParameterType { + /** + * Call frame identifier to evaluate on. + */ + callFrameId: CallFrameId; + /** + * Expression to evaluate. + */ + expression: string; + /** + * String object group name to put result into (allows rapid releasing resulting object handles using releaseObjectGroup). + */ + objectGroup?: string | undefined; + /** + * Specifies whether command line API should be available to the evaluated expression, defaults to false. + */ + includeCommandLineAPI?: boolean | undefined; + /** + * In silent mode exceptions thrown during evaluation are not reported and do not pause execution. Overrides setPauseOnException state. + */ + silent?: boolean | undefined; + /** + * Whether the result is expected to be a JSON object that should be sent by value. + */ + returnByValue?: boolean | undefined; + /** + * Whether preview should be generated for the result. + * @experimental + */ + generatePreview?: boolean | undefined; + /** + * Whether to throw an exception if side effect cannot be ruled out during evaluation. + */ + throwOnSideEffect?: boolean | undefined; + } + interface SetVariableValueParameterType { + /** + * 0-based number of scope as was listed in scope chain. Only 'local', 'closure' and 'catch' scope types are allowed. Other scopes could be manipulated manually. + */ + scopeNumber: number; + /** + * Variable name. + */ + variableName: string; + /** + * New variable value. + */ + newValue: Runtime.CallArgument; + /** + * Id of callframe that holds variable. + */ + callFrameId: CallFrameId; + } + interface SetReturnValueParameterType { + /** + * New return value. + */ + newValue: Runtime.CallArgument; + } + interface SetAsyncCallStackDepthParameterType { + /** + * Maximum depth of async call stacks. Setting to 0 will effectively disable collecting async call stacks (default). + */ + maxDepth: number; + } + interface SetBlackboxPatternsParameterType { + /** + * Array of regexps that will be used to check script url for blackbox state. + */ + patterns: string[]; + } + interface SetBlackboxedRangesParameterType { + /** + * Id of the script. + */ + scriptId: Runtime.ScriptId; + positions: ScriptPosition[]; + } + interface EnableReturnType { + /** + * Unique identifier of the debugger. + * @experimental + */ + debuggerId: Runtime.UniqueDebuggerId; + } + interface SetBreakpointByUrlReturnType { + /** + * Id of the created breakpoint for further reference. + */ + breakpointId: BreakpointId; + /** + * List of the locations this breakpoint resolved into upon addition. + */ + locations: Location[]; + } + interface SetBreakpointReturnType { + /** + * Id of the created breakpoint for further reference. + */ + breakpointId: BreakpointId; + /** + * Location this breakpoint resolved into. + */ + actualLocation: Location; + } + interface GetPossibleBreakpointsReturnType { + /** + * List of the possible breakpoint locations. + */ + locations: BreakLocation[]; + } + interface GetStackTraceReturnType { + stackTrace: Runtime.StackTrace; + } + interface SearchInContentReturnType { + /** + * List of search matches. + */ + result: SearchMatch[]; + } + interface SetScriptSourceReturnType { + /** + * New stack trace in case editing has happened while VM was stopped. + */ + callFrames?: CallFrame[] | undefined; + /** + * Whether current call stack was modified after applying the changes. + */ + stackChanged?: boolean | undefined; + /** + * Async stack trace, if any. + */ + asyncStackTrace?: Runtime.StackTrace | undefined; + /** + * Async stack trace, if any. + * @experimental + */ + asyncStackTraceId?: Runtime.StackTraceId | undefined; + /** + * Exception details if any. + */ + exceptionDetails?: Runtime.ExceptionDetails | undefined; + } + interface RestartFrameReturnType { + /** + * New stack trace. + */ + callFrames: CallFrame[]; + /** + * Async stack trace, if any. + */ + asyncStackTrace?: Runtime.StackTrace | undefined; + /** + * Async stack trace, if any. + * @experimental + */ + asyncStackTraceId?: Runtime.StackTraceId | undefined; + } + interface GetScriptSourceReturnType { + /** + * Script source. + */ + scriptSource: string; + } + interface EvaluateOnCallFrameReturnType { + /** + * Object wrapper for the evaluation result. + */ + result: Runtime.RemoteObject; + /** + * Exception details. + */ + exceptionDetails?: Runtime.ExceptionDetails | undefined; + } + interface ScriptParsedEventDataType { + /** + * Identifier of the script parsed. + */ + scriptId: Runtime.ScriptId; + /** + * URL or name of the script parsed (if any). + */ + url: string; + /** + * Line offset of the script within the resource with given URL (for script tags). + */ + startLine: number; + /** + * Column offset of the script within the resource with given URL. + */ + startColumn: number; + /** + * Last line of the script. + */ + endLine: number; + /** + * Length of the last line of the script. + */ + endColumn: number; + /** + * Specifies script creation context. + */ + executionContextId: Runtime.ExecutionContextId; + /** + * Content hash of the script. + */ + hash: string; + /** + * Embedder-specific auxiliary data. + */ + executionContextAuxData?: {} | undefined; + /** + * True, if this script is generated as a result of the live edit operation. + * @experimental + */ + isLiveEdit?: boolean | undefined; + /** + * URL of source map associated with script (if any). + */ + sourceMapURL?: string | undefined; + /** + * True, if this script has sourceURL. + */ + hasSourceURL?: boolean | undefined; + /** + * True, if this script is ES6 module. + */ + isModule?: boolean | undefined; + /** + * This script length. + */ + length?: number | undefined; + /** + * JavaScript top stack frame of where the script parsed event was triggered if available. + * @experimental + */ + stackTrace?: Runtime.StackTrace | undefined; + } + interface ScriptFailedToParseEventDataType { + /** + * Identifier of the script parsed. + */ + scriptId: Runtime.ScriptId; + /** + * URL or name of the script parsed (if any). + */ + url: string; + /** + * Line offset of the script within the resource with given URL (for script tags). + */ + startLine: number; + /** + * Column offset of the script within the resource with given URL. + */ + startColumn: number; + /** + * Last line of the script. + */ + endLine: number; + /** + * Length of the last line of the script. + */ + endColumn: number; + /** + * Specifies script creation context. + */ + executionContextId: Runtime.ExecutionContextId; + /** + * Content hash of the script. + */ + hash: string; + /** + * Embedder-specific auxiliary data. + */ + executionContextAuxData?: {} | undefined; + /** + * URL of source map associated with script (if any). + */ + sourceMapURL?: string | undefined; + /** + * True, if this script has sourceURL. + */ + hasSourceURL?: boolean | undefined; + /** + * True, if this script is ES6 module. + */ + isModule?: boolean | undefined; + /** + * This script length. + */ + length?: number | undefined; + /** + * JavaScript top stack frame of where the script parsed event was triggered if available. + * @experimental + */ + stackTrace?: Runtime.StackTrace | undefined; + } + interface BreakpointResolvedEventDataType { + /** + * Breakpoint unique identifier. + */ + breakpointId: BreakpointId; + /** + * Actual breakpoint location. + */ + location: Location; + } + interface PausedEventDataType { + /** + * Call stack the virtual machine stopped on. + */ + callFrames: CallFrame[]; + /** + * Pause reason. + */ + reason: string; + /** + * Object containing break-specific auxiliary properties. + */ + data?: {} | undefined; + /** + * Hit breakpoints IDs + */ + hitBreakpoints?: string[] | undefined; + /** + * Async stack trace, if any. + */ + asyncStackTrace?: Runtime.StackTrace | undefined; + /** + * Async stack trace, if any. + * @experimental + */ + asyncStackTraceId?: Runtime.StackTraceId | undefined; + /** + * Just scheduled async call will have this stack trace as parent stack during async execution. This field is available only after Debugger.stepInto call with breakOnAsynCall flag. + * @experimental + */ + asyncCallStackTraceId?: Runtime.StackTraceId | undefined; + } + } + namespace Console { + /** + * Console message. + */ + interface ConsoleMessage { + /** + * Message source. + */ + source: string; + /** + * Message severity. + */ + level: string; + /** + * Message text. + */ + text: string; + /** + * URL of the message origin. + */ + url?: string | undefined; + /** + * Line number in the resource that generated this message (1-based). + */ + line?: number | undefined; + /** + * Column number in the resource that generated this message (1-based). + */ + column?: number | undefined; + } + interface MessageAddedEventDataType { + /** + * Console message that has been added. + */ + message: ConsoleMessage; + } + } + namespace Profiler { + /** + * Profile node. Holds callsite information, execution statistics and child nodes. + */ + interface ProfileNode { + /** + * Unique id of the node. + */ + id: number; + /** + * Function location. + */ + callFrame: Runtime.CallFrame; + /** + * Number of samples where this node was on top of the call stack. + */ + hitCount?: number | undefined; + /** + * Child node ids. + */ + children?: number[] | undefined; + /** + * The reason of being not optimized. The function may be deoptimized or marked as don't optimize. + */ + deoptReason?: string | undefined; + /** + * An array of source position ticks. + */ + positionTicks?: PositionTickInfo[] | undefined; + } + /** + * Profile. + */ + interface Profile { + /** + * The list of profile nodes. First item is the root node. + */ + nodes: ProfileNode[]; + /** + * Profiling start timestamp in microseconds. + */ + startTime: number; + /** + * Profiling end timestamp in microseconds. + */ + endTime: number; + /** + * Ids of samples top nodes. + */ + samples?: number[] | undefined; + /** + * Time intervals between adjacent samples in microseconds. The first delta is relative to the profile startTime. + */ + timeDeltas?: number[] | undefined; + } + /** + * Specifies a number of samples attributed to a certain source position. + */ + interface PositionTickInfo { + /** + * Source line number (1-based). + */ + line: number; + /** + * Number of samples attributed to the source line. + */ + ticks: number; + } + /** + * Coverage data for a source range. + */ + interface CoverageRange { + /** + * JavaScript script source offset for the range start. + */ + startOffset: number; + /** + * JavaScript script source offset for the range end. + */ + endOffset: number; + /** + * Collected execution count of the source range. + */ + count: number; + } + /** + * Coverage data for a JavaScript function. + */ + interface FunctionCoverage { + /** + * JavaScript function name. + */ + functionName: string; + /** + * Source ranges inside the function with coverage data. + */ + ranges: CoverageRange[]; + /** + * Whether coverage data for this function has block granularity. + */ + isBlockCoverage: boolean; + } + /** + * Coverage data for a JavaScript script. + */ + interface ScriptCoverage { + /** + * JavaScript script id. + */ + scriptId: Runtime.ScriptId; + /** + * JavaScript script name or url. + */ + url: string; + /** + * Functions contained in the script that has coverage data. + */ + functions: FunctionCoverage[]; + } + /** + * Describes a type collected during runtime. + * @experimental + */ + interface TypeObject { + /** + * Name of a type collected with type profiling. + */ + name: string; + } + /** + * Source offset and types for a parameter or return value. + * @experimental + */ + interface TypeProfileEntry { + /** + * Source offset of the parameter or end of function for return values. + */ + offset: number; + /** + * The types for this parameter or return value. + */ + types: TypeObject[]; + } + /** + * Type profile data collected during runtime for a JavaScript script. + * @experimental + */ + interface ScriptTypeProfile { + /** + * JavaScript script id. + */ + scriptId: Runtime.ScriptId; + /** + * JavaScript script name or url. + */ + url: string; + /** + * Type profile entries for parameters and return values of the functions in the script. + */ + entries: TypeProfileEntry[]; + } + interface SetSamplingIntervalParameterType { + /** + * New sampling interval in microseconds. + */ + interval: number; + } + interface StartPreciseCoverageParameterType { + /** + * Collect accurate call counts beyond simple 'covered' or 'not covered'. + */ + callCount?: boolean | undefined; + /** + * Collect block-based coverage. + */ + detailed?: boolean | undefined; + } + interface StopReturnType { + /** + * Recorded profile. + */ + profile: Profile; + } + interface TakePreciseCoverageReturnType { + /** + * Coverage data for the current isolate. + */ + result: ScriptCoverage[]; + } + interface GetBestEffortCoverageReturnType { + /** + * Coverage data for the current isolate. + */ + result: ScriptCoverage[]; + } + interface TakeTypeProfileReturnType { + /** + * Type profile for all scripts since startTypeProfile() was turned on. + */ + result: ScriptTypeProfile[]; + } + interface ConsoleProfileStartedEventDataType { + id: string; + /** + * Location of console.profile(). + */ + location: Debugger.Location; + /** + * Profile title passed as an argument to console.profile(). + */ + title?: string | undefined; + } + interface ConsoleProfileFinishedEventDataType { + id: string; + /** + * Location of console.profileEnd(). + */ + location: Debugger.Location; + profile: Profile; + /** + * Profile title passed as an argument to console.profile(). + */ + title?: string | undefined; + } + } + namespace HeapProfiler { + /** + * Heap snapshot object id. + */ + type HeapSnapshotObjectId = string; + /** + * Sampling Heap Profile node. Holds callsite information, allocation statistics and child nodes. + */ + interface SamplingHeapProfileNode { + /** + * Function location. + */ + callFrame: Runtime.CallFrame; + /** + * Allocations size in bytes for the node excluding children. + */ + selfSize: number; + /** + * Child nodes. + */ + children: SamplingHeapProfileNode[]; + } + /** + * Profile. + */ + interface SamplingHeapProfile { + head: SamplingHeapProfileNode; + } + interface StartTrackingHeapObjectsParameterType { + trackAllocations?: boolean | undefined; + } + interface StopTrackingHeapObjectsParameterType { + /** + * If true 'reportHeapSnapshotProgress' events will be generated while snapshot is being taken when the tracking is stopped. + */ + reportProgress?: boolean | undefined; + } + interface TakeHeapSnapshotParameterType { + /** + * If true 'reportHeapSnapshotProgress' events will be generated while snapshot is being taken. + */ + reportProgress?: boolean | undefined; + } + interface GetObjectByHeapObjectIdParameterType { + objectId: HeapSnapshotObjectId; + /** + * Symbolic group name that can be used to release multiple objects. + */ + objectGroup?: string | undefined; + } + interface AddInspectedHeapObjectParameterType { + /** + * Heap snapshot object id to be accessible by means of $x command line API. + */ + heapObjectId: HeapSnapshotObjectId; + } + interface GetHeapObjectIdParameterType { + /** + * Identifier of the object to get heap object id for. + */ + objectId: Runtime.RemoteObjectId; + } + interface StartSamplingParameterType { + /** + * Average sample interval in bytes. Poisson distribution is used for the intervals. The default value is 32768 bytes. + */ + samplingInterval?: number | undefined; + } + interface GetObjectByHeapObjectIdReturnType { + /** + * Evaluation result. + */ + result: Runtime.RemoteObject; + } + interface GetHeapObjectIdReturnType { + /** + * Id of the heap snapshot object corresponding to the passed remote object id. + */ + heapSnapshotObjectId: HeapSnapshotObjectId; + } + interface StopSamplingReturnType { + /** + * Recorded sampling heap profile. + */ + profile: SamplingHeapProfile; + } + interface GetSamplingProfileReturnType { + /** + * Return the sampling profile being collected. + */ + profile: SamplingHeapProfile; + } + interface AddHeapSnapshotChunkEventDataType { + chunk: string; + } + interface ReportHeapSnapshotProgressEventDataType { + done: number; + total: number; + finished?: boolean | undefined; + } + interface LastSeenObjectIdEventDataType { + lastSeenObjectId: number; + timestamp: number; + } + interface HeapStatsUpdateEventDataType { + /** + * An array of triplets. Each triplet describes a fragment. The first integer is the fragment index, the second integer is a total count of objects for the fragment, the third integer is a total size of the objects for the fragment. + */ + statsUpdate: number[]; + } + } + namespace NodeTracing { + interface TraceConfig { + /** + * Controls how the trace buffer stores data. + */ + recordMode?: string | undefined; + /** + * Included category filters. + */ + includedCategories: string[]; + } + interface StartParameterType { + traceConfig: TraceConfig; + } + interface GetCategoriesReturnType { + /** + * A list of supported tracing categories. + */ + categories: string[]; + } + interface DataCollectedEventDataType { + value: Array<{}>; + } + } + namespace NodeWorker { + type WorkerID = string; + /** + * Unique identifier of attached debugging session. + */ + type SessionID = string; + interface WorkerInfo { + workerId: WorkerID; + type: string; + title: string; + url: string; + } + interface SendMessageToWorkerParameterType { + message: string; + /** + * Identifier of the session. + */ + sessionId: SessionID; + } + interface EnableParameterType { + /** + * Whether to new workers should be paused until the frontend sends `Runtime.runIfWaitingForDebugger` + * message to run them. + */ + waitForDebuggerOnStart: boolean; + } + interface DetachParameterType { + sessionId: SessionID; + } + interface AttachedToWorkerEventDataType { + /** + * Identifier assigned to the session used to send/receive messages. + */ + sessionId: SessionID; + workerInfo: WorkerInfo; + waitingForDebugger: boolean; + } + interface DetachedFromWorkerEventDataType { + /** + * Detached session identifier. + */ + sessionId: SessionID; + } + interface ReceivedMessageFromWorkerEventDataType { + /** + * Identifier of a session which sends a message. + */ + sessionId: SessionID; + message: string; + } + } + namespace NodeRuntime { + interface NotifyWhenWaitingForDisconnectParameterType { + enabled: boolean; + } + } + /** + * The `inspector.Session` is used for dispatching messages to the V8 inspector + * back-end and receiving message responses and notifications. + */ + class Session extends EventEmitter { + /** + * Create a new instance of the inspector.Session class. + * The inspector session needs to be connected through session.connect() before the messages can be dispatched to the inspector backend. + */ + constructor(); + /** + * Connects a session to the inspector back-end. + * @since v8.0.0 + */ + connect(): void; + /** + * Immediately close the session. All pending message callbacks will be called + * with an error. `session.connect()` will need to be called to be able to send + * messages again. Reconnected session will lose all inspector state, such as + * enabled agents or configured breakpoints. + * @since v8.0.0 + */ + disconnect(): void; + /** + * Posts a message to the inspector back-end. `callback` will be notified when + * a response is received. `callback` is a function that accepts two optional + * arguments: error and message-specific result. + * + * ```js + * session.post('Runtime.evaluate', { expression: '2 + 2' }, + * (error, { result }) => console.log(result)); + * // Output: { type: 'number', value: 4, description: '4' } + * ``` + * + * The latest version of the V8 inspector protocol is published on the [Chrome DevTools Protocol Viewer](https://chromedevtools.github.io/devtools-protocol/v8/). + * + * Node.js inspector supports all the Chrome DevTools Protocol domains declared + * by V8\. Chrome DevTools Protocol domain provides an interface for interacting + * with one of the runtime agents used to inspect the application state and listen + * to the run-time events. + * + * ## Example usage + * + * Apart from the debugger, various V8 Profilers are available through the DevTools + * protocol. + * @since v8.0.0 + */ + post(method: string, params?: {}, callback?: (err: Error | null, params?: {}) => void): void; + post(method: string, callback?: (err: Error | null, params?: {}) => void): void; + /** + * Returns supported domains. + */ + post(method: 'Schema.getDomains', callback?: (err: Error | null, params: Schema.GetDomainsReturnType) => void): void; + /** + * Evaluates expression on global object. + */ + post(method: 'Runtime.evaluate', params?: Runtime.EvaluateParameterType, callback?: (err: Error | null, params: Runtime.EvaluateReturnType) => void): void; + post(method: 'Runtime.evaluate', callback?: (err: Error | null, params: Runtime.EvaluateReturnType) => void): void; + /** + * Add handler to promise with given promise object id. + */ + post(method: 'Runtime.awaitPromise', params?: Runtime.AwaitPromiseParameterType, callback?: (err: Error | null, params: Runtime.AwaitPromiseReturnType) => void): void; + post(method: 'Runtime.awaitPromise', callback?: (err: Error | null, params: Runtime.AwaitPromiseReturnType) => void): void; + /** + * Calls function with given declaration on the given object. Object group of the result is inherited from the target object. + */ + post(method: 'Runtime.callFunctionOn', params?: Runtime.CallFunctionOnParameterType, callback?: (err: Error | null, params: Runtime.CallFunctionOnReturnType) => void): void; + post(method: 'Runtime.callFunctionOn', callback?: (err: Error | null, params: Runtime.CallFunctionOnReturnType) => void): void; + /** + * Returns properties of a given object. Object group of the result is inherited from the target object. + */ + post(method: 'Runtime.getProperties', params?: Runtime.GetPropertiesParameterType, callback?: (err: Error | null, params: Runtime.GetPropertiesReturnType) => void): void; + post(method: 'Runtime.getProperties', callback?: (err: Error | null, params: Runtime.GetPropertiesReturnType) => void): void; + /** + * Releases remote object with given id. + */ + post(method: 'Runtime.releaseObject', params?: Runtime.ReleaseObjectParameterType, callback?: (err: Error | null) => void): void; + post(method: 'Runtime.releaseObject', callback?: (err: Error | null) => void): void; + /** + * Releases all remote objects that belong to a given group. + */ + post(method: 'Runtime.releaseObjectGroup', params?: Runtime.ReleaseObjectGroupParameterType, callback?: (err: Error | null) => void): void; + post(method: 'Runtime.releaseObjectGroup', callback?: (err: Error | null) => void): void; + /** + * Tells inspected instance to run if it was waiting for debugger to attach. + */ + post(method: 'Runtime.runIfWaitingForDebugger', callback?: (err: Error | null) => void): void; + /** + * Enables reporting of execution contexts creation by means of executionContextCreated event. When the reporting gets enabled the event will be sent immediately for each existing execution context. + */ + post(method: 'Runtime.enable', callback?: (err: Error | null) => void): void; + /** + * Disables reporting of execution contexts creation. + */ + post(method: 'Runtime.disable', callback?: (err: Error | null) => void): void; + /** + * Discards collected exceptions and console API calls. + */ + post(method: 'Runtime.discardConsoleEntries', callback?: (err: Error | null) => void): void; + /** + * @experimental + */ + post(method: 'Runtime.setCustomObjectFormatterEnabled', params?: Runtime.SetCustomObjectFormatterEnabledParameterType, callback?: (err: Error | null) => void): void; + post(method: 'Runtime.setCustomObjectFormatterEnabled', callback?: (err: Error | null) => void): void; + /** + * Compiles expression. + */ + post(method: 'Runtime.compileScript', params?: Runtime.CompileScriptParameterType, callback?: (err: Error | null, params: Runtime.CompileScriptReturnType) => void): void; + post(method: 'Runtime.compileScript', callback?: (err: Error | null, params: Runtime.CompileScriptReturnType) => void): void; + /** + * Runs script with given id in a given context. + */ + post(method: 'Runtime.runScript', params?: Runtime.RunScriptParameterType, callback?: (err: Error | null, params: Runtime.RunScriptReturnType) => void): void; + post(method: 'Runtime.runScript', callback?: (err: Error | null, params: Runtime.RunScriptReturnType) => void): void; + post(method: 'Runtime.queryObjects', params?: Runtime.QueryObjectsParameterType, callback?: (err: Error | null, params: Runtime.QueryObjectsReturnType) => void): void; + post(method: 'Runtime.queryObjects', callback?: (err: Error | null, params: Runtime.QueryObjectsReturnType) => void): void; + /** + * Returns all let, const and class variables from global scope. + */ + post( + method: 'Runtime.globalLexicalScopeNames', + params?: Runtime.GlobalLexicalScopeNamesParameterType, + callback?: (err: Error | null, params: Runtime.GlobalLexicalScopeNamesReturnType) => void + ): void; + post(method: 'Runtime.globalLexicalScopeNames', callback?: (err: Error | null, params: Runtime.GlobalLexicalScopeNamesReturnType) => void): void; + /** + * Enables debugger for the given page. Clients should not assume that the debugging has been enabled until the result for this command is received. + */ + post(method: 'Debugger.enable', callback?: (err: Error | null, params: Debugger.EnableReturnType) => void): void; + /** + * Disables debugger for given page. + */ + post(method: 'Debugger.disable', callback?: (err: Error | null) => void): void; + /** + * Activates / deactivates all breakpoints on the page. + */ + post(method: 'Debugger.setBreakpointsActive', params?: Debugger.SetBreakpointsActiveParameterType, callback?: (err: Error | null) => void): void; + post(method: 'Debugger.setBreakpointsActive', callback?: (err: Error | null) => void): void; + /** + * Makes page not interrupt on any pauses (breakpoint, exception, dom exception etc). + */ + post(method: 'Debugger.setSkipAllPauses', params?: Debugger.SetSkipAllPausesParameterType, callback?: (err: Error | null) => void): void; + post(method: 'Debugger.setSkipAllPauses', callback?: (err: Error | null) => void): void; + /** + * Sets JavaScript breakpoint at given location specified either by URL or URL regex. Once this command is issued, all existing parsed scripts will have breakpoints resolved and returned in locations property. Further matching script parsing will result in subsequent breakpointResolved events issued. This logical breakpoint will survive page reloads. + */ + post(method: 'Debugger.setBreakpointByUrl', params?: Debugger.SetBreakpointByUrlParameterType, callback?: (err: Error | null, params: Debugger.SetBreakpointByUrlReturnType) => void): void; + post(method: 'Debugger.setBreakpointByUrl', callback?: (err: Error | null, params: Debugger.SetBreakpointByUrlReturnType) => void): void; + /** + * Sets JavaScript breakpoint at a given location. + */ + post(method: 'Debugger.setBreakpoint', params?: Debugger.SetBreakpointParameterType, callback?: (err: Error | null, params: Debugger.SetBreakpointReturnType) => void): void; + post(method: 'Debugger.setBreakpoint', callback?: (err: Error | null, params: Debugger.SetBreakpointReturnType) => void): void; + /** + * Removes JavaScript breakpoint. + */ + post(method: 'Debugger.removeBreakpoint', params?: Debugger.RemoveBreakpointParameterType, callback?: (err: Error | null) => void): void; + post(method: 'Debugger.removeBreakpoint', callback?: (err: Error | null) => void): void; + /** + * Returns possible locations for breakpoint. scriptId in start and end range locations should be the same. + */ + post( + method: 'Debugger.getPossibleBreakpoints', + params?: Debugger.GetPossibleBreakpointsParameterType, + callback?: (err: Error | null, params: Debugger.GetPossibleBreakpointsReturnType) => void + ): void; + post(method: 'Debugger.getPossibleBreakpoints', callback?: (err: Error | null, params: Debugger.GetPossibleBreakpointsReturnType) => void): void; + /** + * Continues execution until specific location is reached. + */ + post(method: 'Debugger.continueToLocation', params?: Debugger.ContinueToLocationParameterType, callback?: (err: Error | null) => void): void; + post(method: 'Debugger.continueToLocation', callback?: (err: Error | null) => void): void; + /** + * @experimental + */ + post(method: 'Debugger.pauseOnAsyncCall', params?: Debugger.PauseOnAsyncCallParameterType, callback?: (err: Error | null) => void): void; + post(method: 'Debugger.pauseOnAsyncCall', callback?: (err: Error | null) => void): void; + /** + * Steps over the statement. + */ + post(method: 'Debugger.stepOver', callback?: (err: Error | null) => void): void; + /** + * Steps into the function call. + */ + post(method: 'Debugger.stepInto', params?: Debugger.StepIntoParameterType, callback?: (err: Error | null) => void): void; + post(method: 'Debugger.stepInto', callback?: (err: Error | null) => void): void; + /** + * Steps out of the function call. + */ + post(method: 'Debugger.stepOut', callback?: (err: Error | null) => void): void; + /** + * Stops on the next JavaScript statement. + */ + post(method: 'Debugger.pause', callback?: (err: Error | null) => void): void; + /** + * This method is deprecated - use Debugger.stepInto with breakOnAsyncCall and Debugger.pauseOnAsyncTask instead. Steps into next scheduled async task if any is scheduled before next pause. Returns success when async task is actually scheduled, returns error if no task were scheduled or another scheduleStepIntoAsync was called. + * @experimental + */ + post(method: 'Debugger.scheduleStepIntoAsync', callback?: (err: Error | null) => void): void; + /** + * Resumes JavaScript execution. + */ + post(method: 'Debugger.resume', callback?: (err: Error | null) => void): void; + /** + * Returns stack trace with given stackTraceId. + * @experimental + */ + post(method: 'Debugger.getStackTrace', params?: Debugger.GetStackTraceParameterType, callback?: (err: Error | null, params: Debugger.GetStackTraceReturnType) => void): void; + post(method: 'Debugger.getStackTrace', callback?: (err: Error | null, params: Debugger.GetStackTraceReturnType) => void): void; + /** + * Searches for given string in script content. + */ + post(method: 'Debugger.searchInContent', params?: Debugger.SearchInContentParameterType, callback?: (err: Error | null, params: Debugger.SearchInContentReturnType) => void): void; + post(method: 'Debugger.searchInContent', callback?: (err: Error | null, params: Debugger.SearchInContentReturnType) => void): void; + /** + * Edits JavaScript source live. + */ + post(method: 'Debugger.setScriptSource', params?: Debugger.SetScriptSourceParameterType, callback?: (err: Error | null, params: Debugger.SetScriptSourceReturnType) => void): void; + post(method: 'Debugger.setScriptSource', callback?: (err: Error | null, params: Debugger.SetScriptSourceReturnType) => void): void; + /** + * Restarts particular call frame from the beginning. + */ + post(method: 'Debugger.restartFrame', params?: Debugger.RestartFrameParameterType, callback?: (err: Error | null, params: Debugger.RestartFrameReturnType) => void): void; + post(method: 'Debugger.restartFrame', callback?: (err: Error | null, params: Debugger.RestartFrameReturnType) => void): void; + /** + * Returns source for the script with given id. + */ + post(method: 'Debugger.getScriptSource', params?: Debugger.GetScriptSourceParameterType, callback?: (err: Error | null, params: Debugger.GetScriptSourceReturnType) => void): void; + post(method: 'Debugger.getScriptSource', callback?: (err: Error | null, params: Debugger.GetScriptSourceReturnType) => void): void; + /** + * Defines pause on exceptions state. Can be set to stop on all exceptions, uncaught exceptions or no exceptions. Initial pause on exceptions state is none. + */ + post(method: 'Debugger.setPauseOnExceptions', params?: Debugger.SetPauseOnExceptionsParameterType, callback?: (err: Error | null) => void): void; + post(method: 'Debugger.setPauseOnExceptions', callback?: (err: Error | null) => void): void; + /** + * Evaluates expression on a given call frame. + */ + post(method: 'Debugger.evaluateOnCallFrame', params?: Debugger.EvaluateOnCallFrameParameterType, callback?: (err: Error | null, params: Debugger.EvaluateOnCallFrameReturnType) => void): void; + post(method: 'Debugger.evaluateOnCallFrame', callback?: (err: Error | null, params: Debugger.EvaluateOnCallFrameReturnType) => void): void; + /** + * Changes value of variable in a callframe. Object-based scopes are not supported and must be mutated manually. + */ + post(method: 'Debugger.setVariableValue', params?: Debugger.SetVariableValueParameterType, callback?: (err: Error | null) => void): void; + post(method: 'Debugger.setVariableValue', callback?: (err: Error | null) => void): void; + /** + * Changes return value in top frame. Available only at return break position. + * @experimental + */ + post(method: 'Debugger.setReturnValue', params?: Debugger.SetReturnValueParameterType, callback?: (err: Error | null) => void): void; + post(method: 'Debugger.setReturnValue', callback?: (err: Error | null) => void): void; + /** + * Enables or disables async call stacks tracking. + */ + post(method: 'Debugger.setAsyncCallStackDepth', params?: Debugger.SetAsyncCallStackDepthParameterType, callback?: (err: Error | null) => void): void; + post(method: 'Debugger.setAsyncCallStackDepth', callback?: (err: Error | null) => void): void; + /** + * Replace previous blackbox patterns with passed ones. Forces backend to skip stepping/pausing in scripts with url matching one of the patterns. VM will try to leave blackboxed script by performing 'step in' several times, finally resorting to 'step out' if unsuccessful. + * @experimental + */ + post(method: 'Debugger.setBlackboxPatterns', params?: Debugger.SetBlackboxPatternsParameterType, callback?: (err: Error | null) => void): void; + post(method: 'Debugger.setBlackboxPatterns', callback?: (err: Error | null) => void): void; + /** + * Makes backend skip steps in the script in blackboxed ranges. VM will try leave blacklisted scripts by performing 'step in' several times, finally resorting to 'step out' if unsuccessful. Positions array contains positions where blackbox state is changed. First interval isn't blackboxed. Array should be sorted. + * @experimental + */ + post(method: 'Debugger.setBlackboxedRanges', params?: Debugger.SetBlackboxedRangesParameterType, callback?: (err: Error | null) => void): void; + post(method: 'Debugger.setBlackboxedRanges', callback?: (err: Error | null) => void): void; + /** + * Enables console domain, sends the messages collected so far to the client by means of the messageAdded notification. + */ + post(method: 'Console.enable', callback?: (err: Error | null) => void): void; + /** + * Disables console domain, prevents further console messages from being reported to the client. + */ + post(method: 'Console.disable', callback?: (err: Error | null) => void): void; + /** + * Does nothing. + */ + post(method: 'Console.clearMessages', callback?: (err: Error | null) => void): void; + post(method: 'Profiler.enable', callback?: (err: Error | null) => void): void; + post(method: 'Profiler.disable', callback?: (err: Error | null) => void): void; + /** + * Changes CPU profiler sampling interval. Must be called before CPU profiles recording started. + */ + post(method: 'Profiler.setSamplingInterval', params?: Profiler.SetSamplingIntervalParameterType, callback?: (err: Error | null) => void): void; + post(method: 'Profiler.setSamplingInterval', callback?: (err: Error | null) => void): void; + post(method: 'Profiler.start', callback?: (err: Error | null) => void): void; + post(method: 'Profiler.stop', callback?: (err: Error | null, params: Profiler.StopReturnType) => void): void; + /** + * Enable precise code coverage. Coverage data for JavaScript executed before enabling precise code coverage may be incomplete. Enabling prevents running optimized code and resets execution counters. + */ + post(method: 'Profiler.startPreciseCoverage', params?: Profiler.StartPreciseCoverageParameterType, callback?: (err: Error | null) => void): void; + post(method: 'Profiler.startPreciseCoverage', callback?: (err: Error | null) => void): void; + /** + * Disable precise code coverage. Disabling releases unnecessary execution count records and allows executing optimized code. + */ + post(method: 'Profiler.stopPreciseCoverage', callback?: (err: Error | null) => void): void; + /** + * Collect coverage data for the current isolate, and resets execution counters. Precise code coverage needs to have started. + */ + post(method: 'Profiler.takePreciseCoverage', callback?: (err: Error | null, params: Profiler.TakePreciseCoverageReturnType) => void): void; + /** + * Collect coverage data for the current isolate. The coverage data may be incomplete due to garbage collection. + */ + post(method: 'Profiler.getBestEffortCoverage', callback?: (err: Error | null, params: Profiler.GetBestEffortCoverageReturnType) => void): void; + /** + * Enable type profile. + * @experimental + */ + post(method: 'Profiler.startTypeProfile', callback?: (err: Error | null) => void): void; + /** + * Disable type profile. Disabling releases type profile data collected so far. + * @experimental + */ + post(method: 'Profiler.stopTypeProfile', callback?: (err: Error | null) => void): void; + /** + * Collect type profile. + * @experimental + */ + post(method: 'Profiler.takeTypeProfile', callback?: (err: Error | null, params: Profiler.TakeTypeProfileReturnType) => void): void; + post(method: 'HeapProfiler.enable', callback?: (err: Error | null) => void): void; + post(method: 'HeapProfiler.disable', callback?: (err: Error | null) => void): void; + post(method: 'HeapProfiler.startTrackingHeapObjects', params?: HeapProfiler.StartTrackingHeapObjectsParameterType, callback?: (err: Error | null) => void): void; + post(method: 'HeapProfiler.startTrackingHeapObjects', callback?: (err: Error | null) => void): void; + post(method: 'HeapProfiler.stopTrackingHeapObjects', params?: HeapProfiler.StopTrackingHeapObjectsParameterType, callback?: (err: Error | null) => void): void; + post(method: 'HeapProfiler.stopTrackingHeapObjects', callback?: (err: Error | null) => void): void; + post(method: 'HeapProfiler.takeHeapSnapshot', params?: HeapProfiler.TakeHeapSnapshotParameterType, callback?: (err: Error | null) => void): void; + post(method: 'HeapProfiler.takeHeapSnapshot', callback?: (err: Error | null) => void): void; + post(method: 'HeapProfiler.collectGarbage', callback?: (err: Error | null) => void): void; + post( + method: 'HeapProfiler.getObjectByHeapObjectId', + params?: HeapProfiler.GetObjectByHeapObjectIdParameterType, + callback?: (err: Error | null, params: HeapProfiler.GetObjectByHeapObjectIdReturnType) => void + ): void; + post(method: 'HeapProfiler.getObjectByHeapObjectId', callback?: (err: Error | null, params: HeapProfiler.GetObjectByHeapObjectIdReturnType) => void): void; + /** + * Enables console to refer to the node with given id via $x (see Command Line API for more details $x functions). + */ + post(method: 'HeapProfiler.addInspectedHeapObject', params?: HeapProfiler.AddInspectedHeapObjectParameterType, callback?: (err: Error | null) => void): void; + post(method: 'HeapProfiler.addInspectedHeapObject', callback?: (err: Error | null) => void): void; + post(method: 'HeapProfiler.getHeapObjectId', params?: HeapProfiler.GetHeapObjectIdParameterType, callback?: (err: Error | null, params: HeapProfiler.GetHeapObjectIdReturnType) => void): void; + post(method: 'HeapProfiler.getHeapObjectId', callback?: (err: Error | null, params: HeapProfiler.GetHeapObjectIdReturnType) => void): void; + post(method: 'HeapProfiler.startSampling', params?: HeapProfiler.StartSamplingParameterType, callback?: (err: Error | null) => void): void; + post(method: 'HeapProfiler.startSampling', callback?: (err: Error | null) => void): void; + post(method: 'HeapProfiler.stopSampling', callback?: (err: Error | null, params: HeapProfiler.StopSamplingReturnType) => void): void; + post(method: 'HeapProfiler.getSamplingProfile', callback?: (err: Error | null, params: HeapProfiler.GetSamplingProfileReturnType) => void): void; + /** + * Gets supported tracing categories. + */ + post(method: 'NodeTracing.getCategories', callback?: (err: Error | null, params: NodeTracing.GetCategoriesReturnType) => void): void; + /** + * Start trace events collection. + */ + post(method: 'NodeTracing.start', params?: NodeTracing.StartParameterType, callback?: (err: Error | null) => void): void; + post(method: 'NodeTracing.start', callback?: (err: Error | null) => void): void; + /** + * Stop trace events collection. Remaining collected events will be sent as a sequence of + * dataCollected events followed by tracingComplete event. + */ + post(method: 'NodeTracing.stop', callback?: (err: Error | null) => void): void; + /** + * Sends protocol message over session with given id. + */ + post(method: 'NodeWorker.sendMessageToWorker', params?: NodeWorker.SendMessageToWorkerParameterType, callback?: (err: Error | null) => void): void; + post(method: 'NodeWorker.sendMessageToWorker', callback?: (err: Error | null) => void): void; + /** + * Instructs the inspector to attach to running workers. Will also attach to new workers + * as they start + */ + post(method: 'NodeWorker.enable', params?: NodeWorker.EnableParameterType, callback?: (err: Error | null) => void): void; + post(method: 'NodeWorker.enable', callback?: (err: Error | null) => void): void; + /** + * Detaches from all running workers and disables attaching to new workers as they are started. + */ + post(method: 'NodeWorker.disable', callback?: (err: Error | null) => void): void; + /** + * Detached from the worker with given sessionId. + */ + post(method: 'NodeWorker.detach', params?: NodeWorker.DetachParameterType, callback?: (err: Error | null) => void): void; + post(method: 'NodeWorker.detach', callback?: (err: Error | null) => void): void; + /** + * Enable the `NodeRuntime.waitingForDisconnect`. + */ + post(method: 'NodeRuntime.notifyWhenWaitingForDisconnect', params?: NodeRuntime.NotifyWhenWaitingForDisconnectParameterType, callback?: (err: Error | null) => void): void; + post(method: 'NodeRuntime.notifyWhenWaitingForDisconnect', callback?: (err: Error | null) => void): void; + // Events + addListener(event: string, listener: (...args: any[]) => void): this; + /** + * Emitted when any notification from the V8 Inspector is received. + */ + addListener(event: 'inspectorNotification', listener: (message: InspectorNotification<{}>) => void): this; + /** + * Issued when new execution context is created. + */ + addListener(event: 'Runtime.executionContextCreated', listener: (message: InspectorNotification) => void): this; + /** + * Issued when execution context is destroyed. + */ + addListener(event: 'Runtime.executionContextDestroyed', listener: (message: InspectorNotification) => void): this; + /** + * Issued when all executionContexts were cleared in browser + */ + addListener(event: 'Runtime.executionContextsCleared', listener: () => void): this; + /** + * Issued when exception was thrown and unhandled. + */ + addListener(event: 'Runtime.exceptionThrown', listener: (message: InspectorNotification) => void): this; + /** + * Issued when unhandled exception was revoked. + */ + addListener(event: 'Runtime.exceptionRevoked', listener: (message: InspectorNotification) => void): this; + /** + * Issued when console API was called. + */ + addListener(event: 'Runtime.consoleAPICalled', listener: (message: InspectorNotification) => void): this; + /** + * Issued when object should be inspected (for example, as a result of inspect() command line API call). + */ + addListener(event: 'Runtime.inspectRequested', listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine parses script. This event is also fired for all known and uncollected scripts upon enabling debugger. + */ + addListener(event: 'Debugger.scriptParsed', listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine fails to parse the script. + */ + addListener(event: 'Debugger.scriptFailedToParse', listener: (message: InspectorNotification) => void): this; + /** + * Fired when breakpoint is resolved to an actual script and location. + */ + addListener(event: 'Debugger.breakpointResolved', listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine stopped on breakpoint or exception or any other stop criteria. + */ + addListener(event: 'Debugger.paused', listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine resumed execution. + */ + addListener(event: 'Debugger.resumed', listener: () => void): this; + /** + * Issued when new console message is added. + */ + addListener(event: 'Console.messageAdded', listener: (message: InspectorNotification) => void): this; + /** + * Sent when new profile recording is started using console.profile() call. + */ + addListener(event: 'Profiler.consoleProfileStarted', listener: (message: InspectorNotification) => void): this; + addListener(event: 'Profiler.consoleProfileFinished', listener: (message: InspectorNotification) => void): this; + addListener(event: 'HeapProfiler.addHeapSnapshotChunk', listener: (message: InspectorNotification) => void): this; + addListener(event: 'HeapProfiler.resetProfiles', listener: () => void): this; + addListener(event: 'HeapProfiler.reportHeapSnapshotProgress', listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend regularly sends a current value for last seen object id and corresponding timestamp. If the were changes in the heap since last event then one or more heapStatsUpdate events will be sent before a new lastSeenObjectId event. + */ + addListener(event: 'HeapProfiler.lastSeenObjectId', listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend may send update for one or more fragments + */ + addListener(event: 'HeapProfiler.heapStatsUpdate', listener: (message: InspectorNotification) => void): this; + /** + * Contains an bucket of collected trace events. + */ + addListener(event: 'NodeTracing.dataCollected', listener: (message: InspectorNotification) => void): this; + /** + * Signals that tracing is stopped and there is no trace buffers pending flush, all data were + * delivered via dataCollected events. + */ + addListener(event: 'NodeTracing.tracingComplete', listener: () => void): this; + /** + * Issued when attached to a worker. + */ + addListener(event: 'NodeWorker.attachedToWorker', listener: (message: InspectorNotification) => void): this; + /** + * Issued when detached from the worker. + */ + addListener(event: 'NodeWorker.detachedFromWorker', listener: (message: InspectorNotification) => void): this; + /** + * Notifies about a new protocol message received from the session + * (session ID is provided in attachedToWorker notification). + */ + addListener(event: 'NodeWorker.receivedMessageFromWorker', listener: (message: InspectorNotification) => void): this; + /** + * This event is fired instead of `Runtime.executionContextDestroyed` when + * enabled. + * It is fired when the Node process finished all code execution and is + * waiting for all frontends to disconnect. + */ + addListener(event: 'NodeRuntime.waitingForDisconnect', listener: () => void): this; + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: 'inspectorNotification', message: InspectorNotification<{}>): boolean; + emit(event: 'Runtime.executionContextCreated', message: InspectorNotification): boolean; + emit(event: 'Runtime.executionContextDestroyed', message: InspectorNotification): boolean; + emit(event: 'Runtime.executionContextsCleared'): boolean; + emit(event: 'Runtime.exceptionThrown', message: InspectorNotification): boolean; + emit(event: 'Runtime.exceptionRevoked', message: InspectorNotification): boolean; + emit(event: 'Runtime.consoleAPICalled', message: InspectorNotification): boolean; + emit(event: 'Runtime.inspectRequested', message: InspectorNotification): boolean; + emit(event: 'Debugger.scriptParsed', message: InspectorNotification): boolean; + emit(event: 'Debugger.scriptFailedToParse', message: InspectorNotification): boolean; + emit(event: 'Debugger.breakpointResolved', message: InspectorNotification): boolean; + emit(event: 'Debugger.paused', message: InspectorNotification): boolean; + emit(event: 'Debugger.resumed'): boolean; + emit(event: 'Console.messageAdded', message: InspectorNotification): boolean; + emit(event: 'Profiler.consoleProfileStarted', message: InspectorNotification): boolean; + emit(event: 'Profiler.consoleProfileFinished', message: InspectorNotification): boolean; + emit(event: 'HeapProfiler.addHeapSnapshotChunk', message: InspectorNotification): boolean; + emit(event: 'HeapProfiler.resetProfiles'): boolean; + emit(event: 'HeapProfiler.reportHeapSnapshotProgress', message: InspectorNotification): boolean; + emit(event: 'HeapProfiler.lastSeenObjectId', message: InspectorNotification): boolean; + emit(event: 'HeapProfiler.heapStatsUpdate', message: InspectorNotification): boolean; + emit(event: 'NodeTracing.dataCollected', message: InspectorNotification): boolean; + emit(event: 'NodeTracing.tracingComplete'): boolean; + emit(event: 'NodeWorker.attachedToWorker', message: InspectorNotification): boolean; + emit(event: 'NodeWorker.detachedFromWorker', message: InspectorNotification): boolean; + emit(event: 'NodeWorker.receivedMessageFromWorker', message: InspectorNotification): boolean; + emit(event: 'NodeRuntime.waitingForDisconnect'): boolean; + on(event: string, listener: (...args: any[]) => void): this; + /** + * Emitted when any notification from the V8 Inspector is received. + */ + on(event: 'inspectorNotification', listener: (message: InspectorNotification<{}>) => void): this; + /** + * Issued when new execution context is created. + */ + on(event: 'Runtime.executionContextCreated', listener: (message: InspectorNotification) => void): this; + /** + * Issued when execution context is destroyed. + */ + on(event: 'Runtime.executionContextDestroyed', listener: (message: InspectorNotification) => void): this; + /** + * Issued when all executionContexts were cleared in browser + */ + on(event: 'Runtime.executionContextsCleared', listener: () => void): this; + /** + * Issued when exception was thrown and unhandled. + */ + on(event: 'Runtime.exceptionThrown', listener: (message: InspectorNotification) => void): this; + /** + * Issued when unhandled exception was revoked. + */ + on(event: 'Runtime.exceptionRevoked', listener: (message: InspectorNotification) => void): this; + /** + * Issued when console API was called. + */ + on(event: 'Runtime.consoleAPICalled', listener: (message: InspectorNotification) => void): this; + /** + * Issued when object should be inspected (for example, as a result of inspect() command line API call). + */ + on(event: 'Runtime.inspectRequested', listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine parses script. This event is also fired for all known and uncollected scripts upon enabling debugger. + */ + on(event: 'Debugger.scriptParsed', listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine fails to parse the script. + */ + on(event: 'Debugger.scriptFailedToParse', listener: (message: InspectorNotification) => void): this; + /** + * Fired when breakpoint is resolved to an actual script and location. + */ + on(event: 'Debugger.breakpointResolved', listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine stopped on breakpoint or exception or any other stop criteria. + */ + on(event: 'Debugger.paused', listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine resumed execution. + */ + on(event: 'Debugger.resumed', listener: () => void): this; + /** + * Issued when new console message is added. + */ + on(event: 'Console.messageAdded', listener: (message: InspectorNotification) => void): this; + /** + * Sent when new profile recording is started using console.profile() call. + */ + on(event: 'Profiler.consoleProfileStarted', listener: (message: InspectorNotification) => void): this; + on(event: 'Profiler.consoleProfileFinished', listener: (message: InspectorNotification) => void): this; + on(event: 'HeapProfiler.addHeapSnapshotChunk', listener: (message: InspectorNotification) => void): this; + on(event: 'HeapProfiler.resetProfiles', listener: () => void): this; + on(event: 'HeapProfiler.reportHeapSnapshotProgress', listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend regularly sends a current value for last seen object id and corresponding timestamp. If the were changes in the heap since last event then one or more heapStatsUpdate events will be sent before a new lastSeenObjectId event. + */ + on(event: 'HeapProfiler.lastSeenObjectId', listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend may send update for one or more fragments + */ + on(event: 'HeapProfiler.heapStatsUpdate', listener: (message: InspectorNotification) => void): this; + /** + * Contains an bucket of collected trace events. + */ + on(event: 'NodeTracing.dataCollected', listener: (message: InspectorNotification) => void): this; + /** + * Signals that tracing is stopped and there is no trace buffers pending flush, all data were + * delivered via dataCollected events. + */ + on(event: 'NodeTracing.tracingComplete', listener: () => void): this; + /** + * Issued when attached to a worker. + */ + on(event: 'NodeWorker.attachedToWorker', listener: (message: InspectorNotification) => void): this; + /** + * Issued when detached from the worker. + */ + on(event: 'NodeWorker.detachedFromWorker', listener: (message: InspectorNotification) => void): this; + /** + * Notifies about a new protocol message received from the session + * (session ID is provided in attachedToWorker notification). + */ + on(event: 'NodeWorker.receivedMessageFromWorker', listener: (message: InspectorNotification) => void): this; + /** + * This event is fired instead of `Runtime.executionContextDestroyed` when + * enabled. + * It is fired when the Node process finished all code execution and is + * waiting for all frontends to disconnect. + */ + on(event: 'NodeRuntime.waitingForDisconnect', listener: () => void): this; + once(event: string, listener: (...args: any[]) => void): this; + /** + * Emitted when any notification from the V8 Inspector is received. + */ + once(event: 'inspectorNotification', listener: (message: InspectorNotification<{}>) => void): this; + /** + * Issued when new execution context is created. + */ + once(event: 'Runtime.executionContextCreated', listener: (message: InspectorNotification) => void): this; + /** + * Issued when execution context is destroyed. + */ + once(event: 'Runtime.executionContextDestroyed', listener: (message: InspectorNotification) => void): this; + /** + * Issued when all executionContexts were cleared in browser + */ + once(event: 'Runtime.executionContextsCleared', listener: () => void): this; + /** + * Issued when exception was thrown and unhandled. + */ + once(event: 'Runtime.exceptionThrown', listener: (message: InspectorNotification) => void): this; + /** + * Issued when unhandled exception was revoked. + */ + once(event: 'Runtime.exceptionRevoked', listener: (message: InspectorNotification) => void): this; + /** + * Issued when console API was called. + */ + once(event: 'Runtime.consoleAPICalled', listener: (message: InspectorNotification) => void): this; + /** + * Issued when object should be inspected (for example, as a result of inspect() command line API call). + */ + once(event: 'Runtime.inspectRequested', listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine parses script. This event is also fired for all known and uncollected scripts upon enabling debugger. + */ + once(event: 'Debugger.scriptParsed', listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine fails to parse the script. + */ + once(event: 'Debugger.scriptFailedToParse', listener: (message: InspectorNotification) => void): this; + /** + * Fired when breakpoint is resolved to an actual script and location. + */ + once(event: 'Debugger.breakpointResolved', listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine stopped on breakpoint or exception or any other stop criteria. + */ + once(event: 'Debugger.paused', listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine resumed execution. + */ + once(event: 'Debugger.resumed', listener: () => void): this; + /** + * Issued when new console message is added. + */ + once(event: 'Console.messageAdded', listener: (message: InspectorNotification) => void): this; + /** + * Sent when new profile recording is started using console.profile() call. + */ + once(event: 'Profiler.consoleProfileStarted', listener: (message: InspectorNotification) => void): this; + once(event: 'Profiler.consoleProfileFinished', listener: (message: InspectorNotification) => void): this; + once(event: 'HeapProfiler.addHeapSnapshotChunk', listener: (message: InspectorNotification) => void): this; + once(event: 'HeapProfiler.resetProfiles', listener: () => void): this; + once(event: 'HeapProfiler.reportHeapSnapshotProgress', listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend regularly sends a current value for last seen object id and corresponding timestamp. If the were changes in the heap since last event then one or more heapStatsUpdate events will be sent before a new lastSeenObjectId event. + */ + once(event: 'HeapProfiler.lastSeenObjectId', listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend may send update for one or more fragments + */ + once(event: 'HeapProfiler.heapStatsUpdate', listener: (message: InspectorNotification) => void): this; + /** + * Contains an bucket of collected trace events. + */ + once(event: 'NodeTracing.dataCollected', listener: (message: InspectorNotification) => void): this; + /** + * Signals that tracing is stopped and there is no trace buffers pending flush, all data were + * delivered via dataCollected events. + */ + once(event: 'NodeTracing.tracingComplete', listener: () => void): this; + /** + * Issued when attached to a worker. + */ + once(event: 'NodeWorker.attachedToWorker', listener: (message: InspectorNotification) => void): this; + /** + * Issued when detached from the worker. + */ + once(event: 'NodeWorker.detachedFromWorker', listener: (message: InspectorNotification) => void): this; + /** + * Notifies about a new protocol message received from the session + * (session ID is provided in attachedToWorker notification). + */ + once(event: 'NodeWorker.receivedMessageFromWorker', listener: (message: InspectorNotification) => void): this; + /** + * This event is fired instead of `Runtime.executionContextDestroyed` when + * enabled. + * It is fired when the Node process finished all code execution and is + * waiting for all frontends to disconnect. + */ + once(event: 'NodeRuntime.waitingForDisconnect', listener: () => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + /** + * Emitted when any notification from the V8 Inspector is received. + */ + prependListener(event: 'inspectorNotification', listener: (message: InspectorNotification<{}>) => void): this; + /** + * Issued when new execution context is created. + */ + prependListener(event: 'Runtime.executionContextCreated', listener: (message: InspectorNotification) => void): this; + /** + * Issued when execution context is destroyed. + */ + prependListener(event: 'Runtime.executionContextDestroyed', listener: (message: InspectorNotification) => void): this; + /** + * Issued when all executionContexts were cleared in browser + */ + prependListener(event: 'Runtime.executionContextsCleared', listener: () => void): this; + /** + * Issued when exception was thrown and unhandled. + */ + prependListener(event: 'Runtime.exceptionThrown', listener: (message: InspectorNotification) => void): this; + /** + * Issued when unhandled exception was revoked. + */ + prependListener(event: 'Runtime.exceptionRevoked', listener: (message: InspectorNotification) => void): this; + /** + * Issued when console API was called. + */ + prependListener(event: 'Runtime.consoleAPICalled', listener: (message: InspectorNotification) => void): this; + /** + * Issued when object should be inspected (for example, as a result of inspect() command line API call). + */ + prependListener(event: 'Runtime.inspectRequested', listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine parses script. This event is also fired for all known and uncollected scripts upon enabling debugger. + */ + prependListener(event: 'Debugger.scriptParsed', listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine fails to parse the script. + */ + prependListener(event: 'Debugger.scriptFailedToParse', listener: (message: InspectorNotification) => void): this; + /** + * Fired when breakpoint is resolved to an actual script and location. + */ + prependListener(event: 'Debugger.breakpointResolved', listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine stopped on breakpoint or exception or any other stop criteria. + */ + prependListener(event: 'Debugger.paused', listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine resumed execution. + */ + prependListener(event: 'Debugger.resumed', listener: () => void): this; + /** + * Issued when new console message is added. + */ + prependListener(event: 'Console.messageAdded', listener: (message: InspectorNotification) => void): this; + /** + * Sent when new profile recording is started using console.profile() call. + */ + prependListener(event: 'Profiler.consoleProfileStarted', listener: (message: InspectorNotification) => void): this; + prependListener(event: 'Profiler.consoleProfileFinished', listener: (message: InspectorNotification) => void): this; + prependListener(event: 'HeapProfiler.addHeapSnapshotChunk', listener: (message: InspectorNotification) => void): this; + prependListener(event: 'HeapProfiler.resetProfiles', listener: () => void): this; + prependListener(event: 'HeapProfiler.reportHeapSnapshotProgress', listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend regularly sends a current value for last seen object id and corresponding timestamp. If the were changes in the heap since last event then one or more heapStatsUpdate events will be sent before a new lastSeenObjectId event. + */ + prependListener(event: 'HeapProfiler.lastSeenObjectId', listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend may send update for one or more fragments + */ + prependListener(event: 'HeapProfiler.heapStatsUpdate', listener: (message: InspectorNotification) => void): this; + /** + * Contains an bucket of collected trace events. + */ + prependListener(event: 'NodeTracing.dataCollected', listener: (message: InspectorNotification) => void): this; + /** + * Signals that tracing is stopped and there is no trace buffers pending flush, all data were + * delivered via dataCollected events. + */ + prependListener(event: 'NodeTracing.tracingComplete', listener: () => void): this; + /** + * Issued when attached to a worker. + */ + prependListener(event: 'NodeWorker.attachedToWorker', listener: (message: InspectorNotification) => void): this; + /** + * Issued when detached from the worker. + */ + prependListener(event: 'NodeWorker.detachedFromWorker', listener: (message: InspectorNotification) => void): this; + /** + * Notifies about a new protocol message received from the session + * (session ID is provided in attachedToWorker notification). + */ + prependListener(event: 'NodeWorker.receivedMessageFromWorker', listener: (message: InspectorNotification) => void): this; + /** + * This event is fired instead of `Runtime.executionContextDestroyed` when + * enabled. + * It is fired when the Node process finished all code execution and is + * waiting for all frontends to disconnect. + */ + prependListener(event: 'NodeRuntime.waitingForDisconnect', listener: () => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + /** + * Emitted when any notification from the V8 Inspector is received. + */ + prependOnceListener(event: 'inspectorNotification', listener: (message: InspectorNotification<{}>) => void): this; + /** + * Issued when new execution context is created. + */ + prependOnceListener(event: 'Runtime.executionContextCreated', listener: (message: InspectorNotification) => void): this; + /** + * Issued when execution context is destroyed. + */ + prependOnceListener(event: 'Runtime.executionContextDestroyed', listener: (message: InspectorNotification) => void): this; + /** + * Issued when all executionContexts were cleared in browser + */ + prependOnceListener(event: 'Runtime.executionContextsCleared', listener: () => void): this; + /** + * Issued when exception was thrown and unhandled. + */ + prependOnceListener(event: 'Runtime.exceptionThrown', listener: (message: InspectorNotification) => void): this; + /** + * Issued when unhandled exception was revoked. + */ + prependOnceListener(event: 'Runtime.exceptionRevoked', listener: (message: InspectorNotification) => void): this; + /** + * Issued when console API was called. + */ + prependOnceListener(event: 'Runtime.consoleAPICalled', listener: (message: InspectorNotification) => void): this; + /** + * Issued when object should be inspected (for example, as a result of inspect() command line API call). + */ + prependOnceListener(event: 'Runtime.inspectRequested', listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine parses script. This event is also fired for all known and uncollected scripts upon enabling debugger. + */ + prependOnceListener(event: 'Debugger.scriptParsed', listener: (message: InspectorNotification) => void): this; + /** + * Fired when virtual machine fails to parse the script. + */ + prependOnceListener(event: 'Debugger.scriptFailedToParse', listener: (message: InspectorNotification) => void): this; + /** + * Fired when breakpoint is resolved to an actual script and location. + */ + prependOnceListener(event: 'Debugger.breakpointResolved', listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine stopped on breakpoint or exception or any other stop criteria. + */ + prependOnceListener(event: 'Debugger.paused', listener: (message: InspectorNotification) => void): this; + /** + * Fired when the virtual machine resumed execution. + */ + prependOnceListener(event: 'Debugger.resumed', listener: () => void): this; + /** + * Issued when new console message is added. + */ + prependOnceListener(event: 'Console.messageAdded', listener: (message: InspectorNotification) => void): this; + /** + * Sent when new profile recording is started using console.profile() call. + */ + prependOnceListener(event: 'Profiler.consoleProfileStarted', listener: (message: InspectorNotification) => void): this; + prependOnceListener(event: 'Profiler.consoleProfileFinished', listener: (message: InspectorNotification) => void): this; + prependOnceListener(event: 'HeapProfiler.addHeapSnapshotChunk', listener: (message: InspectorNotification) => void): this; + prependOnceListener(event: 'HeapProfiler.resetProfiles', listener: () => void): this; + prependOnceListener(event: 'HeapProfiler.reportHeapSnapshotProgress', listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend regularly sends a current value for last seen object id and corresponding timestamp. If the were changes in the heap since last event then one or more heapStatsUpdate events will be sent before a new lastSeenObjectId event. + */ + prependOnceListener(event: 'HeapProfiler.lastSeenObjectId', listener: (message: InspectorNotification) => void): this; + /** + * If heap objects tracking has been started then backend may send update for one or more fragments + */ + prependOnceListener(event: 'HeapProfiler.heapStatsUpdate', listener: (message: InspectorNotification) => void): this; + /** + * Contains an bucket of collected trace events. + */ + prependOnceListener(event: 'NodeTracing.dataCollected', listener: (message: InspectorNotification) => void): this; + /** + * Signals that tracing is stopped and there is no trace buffers pending flush, all data were + * delivered via dataCollected events. + */ + prependOnceListener(event: 'NodeTracing.tracingComplete', listener: () => void): this; + /** + * Issued when attached to a worker. + */ + prependOnceListener(event: 'NodeWorker.attachedToWorker', listener: (message: InspectorNotification) => void): this; + /** + * Issued when detached from the worker. + */ + prependOnceListener(event: 'NodeWorker.detachedFromWorker', listener: (message: InspectorNotification) => void): this; + /** + * Notifies about a new protocol message received from the session + * (session ID is provided in attachedToWorker notification). + */ + prependOnceListener(event: 'NodeWorker.receivedMessageFromWorker', listener: (message: InspectorNotification) => void): this; + /** + * This event is fired instead of `Runtime.executionContextDestroyed` when + * enabled. + * It is fired when the Node process finished all code execution and is + * waiting for all frontends to disconnect. + */ + prependOnceListener(event: 'NodeRuntime.waitingForDisconnect', listener: () => void): this; + } + /** + * Activate inspector on host and port. Equivalent to `node --inspect=[[host:]port]`, but can be done programmatically after node has + * started. + * + * If wait is `true`, will block until a client has connected to the inspect port + * and flow control has been passed to the debugger client. + * + * See the `security warning` regarding the `host` parameter usage. + * @param [port='what was specified on the CLI'] Port to listen on for inspector connections. Optional. + * @param [host='what was specified on the CLI'] Host to listen on for inspector connections. Optional. + * @param [wait=false] Block until a client has connected. Optional. + * @returns Disposable that calls `inspector.close()`. + */ + function open(port?: number, host?: string, wait?: boolean): Disposable; + /** + * Deactivate the inspector. Blocks until there are no active connections. + */ + function close(): void; + /** + * Return the URL of the active inspector, or `undefined` if there is none. + * + * ```console + * $ node --inspect -p 'inspector.url()' + * Debugger listening on ws://127.0.0.1:9229/166e272e-7a30-4d09-97ce-f1c012b43c34 + * For help, see: https://nodejs.org/en/docs/inspector + * ws://127.0.0.1:9229/166e272e-7a30-4d09-97ce-f1c012b43c34 + * + * $ node --inspect=localhost:3000 -p 'inspector.url()' + * Debugger listening on ws://localhost:3000/51cf8d0e-3c36-4c59-8efd-54519839e56a + * For help, see: https://nodejs.org/en/docs/inspector + * ws://localhost:3000/51cf8d0e-3c36-4c59-8efd-54519839e56a + * + * $ node -p 'inspector.url()' + * undefined + * ``` + */ + function url(): string | undefined; + /** + * Blocks until a client (existing or connected later) has sent `Runtime.runIfWaitingForDebugger` command. + * + * An exception will be thrown if there is no active inspector. + * @since v12.7.0 + */ + function waitForDebugger(): void; +} +/** + * The inspector module provides an API for interacting with the V8 inspector. + */ +declare module 'node:inspector' { + export * from 'inspector'; +} diff --git a/node_modules/@types/node/module.d.ts b/node_modules/@types/node/module.d.ts new file mode 100644 index 0000000..c38a9b8 --- /dev/null +++ b/node_modules/@types/node/module.d.ts @@ -0,0 +1,315 @@ +/** + * @since v0.3.7 + * @experimental + */ +declare module "module" { + import { URL } from "node:url"; + import { MessagePort } from "node:worker_threads"; + namespace Module { + /** + * The `module.syncBuiltinESMExports()` method updates all the live bindings for + * builtin `ES Modules` to match the properties of the `CommonJS` exports. It + * does not add or remove exported names from the `ES Modules`. + * + * ```js + * const fs = require('node:fs'); + * const assert = require('node:assert'); + * const { syncBuiltinESMExports } = require('node:module'); + * + * fs.readFile = newAPI; + * + * delete fs.readFileSync; + * + * function newAPI() { + * // ... + * } + * + * fs.newAPI = newAPI; + * + * syncBuiltinESMExports(); + * + * import('node:fs').then((esmFS) => { + * // It syncs the existing readFile property with the new value + * assert.strictEqual(esmFS.readFile, newAPI); + * // readFileSync has been deleted from the required fs + * assert.strictEqual('readFileSync' in fs, false); + * // syncBuiltinESMExports() does not remove readFileSync from esmFS + * assert.strictEqual('readFileSync' in esmFS, true); + * // syncBuiltinESMExports() does not add names + * assert.strictEqual(esmFS.newAPI, undefined); + * }); + * ``` + * @since v12.12.0 + */ + function syncBuiltinESMExports(): void; + /** + * `path` is the resolved path for the file for which a corresponding source map + * should be fetched. + * @since v13.7.0, v12.17.0 + * @return Returns `module.SourceMap` if a source map is found, `undefined` otherwise. + */ + function findSourceMap(path: string, error?: Error): SourceMap; + interface SourceMapPayload { + file: string; + version: number; + sources: string[]; + sourcesContent: string[]; + names: string[]; + mappings: string; + sourceRoot: string; + } + interface SourceMapping { + generatedLine: number; + generatedColumn: number; + originalSource: string; + originalLine: number; + originalColumn: number; + } + interface SourceOrigin { + /** + * The name of the range in the source map, if one was provided + */ + name?: string; + /** + * The file name of the original source, as reported in the SourceMap + */ + fileName: string; + /** + * The 1-indexed lineNumber of the corresponding call site in the original source + */ + lineNumber: number; + /** + * The 1-indexed columnNumber of the corresponding call site in the original source + */ + columnNumber: number; + } + /** + * @since v13.7.0, v12.17.0 + */ + class SourceMap { + /** + * Getter for the payload used to construct the `SourceMap` instance. + */ + readonly payload: SourceMapPayload; + constructor(payload: SourceMapPayload); + /** + * Given a line offset and column offset in the generated source + * file, returns an object representing the SourceMap range in the + * original file if found, or an empty object if not. + * + * The object returned contains the following keys: + * + * The returned value represents the raw range as it appears in the + * SourceMap, based on zero-indexed offsets, _not_ 1-indexed line and + * column numbers as they appear in Error messages and CallSite + * objects. + * + * To get the corresponding 1-indexed line and column numbers from a + * lineNumber and columnNumber as they are reported by Error stacks + * and CallSite objects, use `sourceMap.findOrigin(lineNumber, columnNumber)` + * @param lineOffset The zero-indexed line number offset in the generated source + * @param columnOffset The zero-indexed column number offset in the generated source + */ + findEntry(lineOffset: number, columnOffset: number): SourceMapping; + /** + * Given a 1-indexed `lineNumber` and `columnNumber` from a call site in the generated source, + * find the corresponding call site location in the original source. + * + * If the `lineNumber` and `columnNumber` provided are not found in any source map, + * then an empty object is returned. + * @param lineNumber The 1-indexed line number of the call site in the generated source + * @param columnNumber The 1-indexed column number of the call site in the generated source + */ + findOrigin(lineNumber: number, columnNumber: number): SourceOrigin | {}; + } + /** @deprecated Use `ImportAttributes` instead */ + interface ImportAssertions extends ImportAttributes {} + interface ImportAttributes extends NodeJS.Dict { + type?: string | undefined; + } + type ModuleFormat = "builtin" | "commonjs" | "json" | "module" | "wasm"; + type ModuleSource = string | ArrayBuffer | NodeJS.TypedArray; + interface GlobalPreloadContext { + port: MessagePort; + } + /** + * @deprecated This hook will be removed in a future version. + * Use `initialize` instead. When a loader has an `initialize` export, `globalPreload` will be ignored. + * + * Sometimes it might be necessary to run some code inside of the same global scope that the application runs in. + * This hook allows the return of a string that is run as a sloppy-mode script on startup. + * + * @param context Information to assist the preload code + * @return Code to run before application startup + */ + type GlobalPreloadHook = (context: GlobalPreloadContext) => string; + /** + * The `initialize` hook provides a way to define a custom function that runs in the hooks thread + * when the hooks module is initialized. Initialization happens when the hooks module is registered via `register`. + * + * This hook can receive data from a `register` invocation, including ports and other transferrable objects. + * The return value of `initialize` can be a `Promise`, in which case it will be awaited before the main application thread execution resumes. + */ + type InitializeHook = (data: Data) => void | Promise; + interface ResolveHookContext { + /** + * Export conditions of the relevant `package.json` + */ + conditions: string[]; + /** + * @deprecated Use `importAttributes` instead + */ + importAssertions: ImportAttributes; + /** + * An object whose key-value pairs represent the assertions for the module to import + */ + importAttributes: ImportAttributes; + /** + * The module importing this one, or undefined if this is the Node.js entry point + */ + parentURL: string | undefined; + } + interface ResolveFnOutput { + /** + * A hint to the load hook (it might be ignored) + */ + format?: ModuleFormat | null | undefined; + /** + * @deprecated Use `importAttributes` instead + */ + importAssertions?: ImportAttributes | undefined; + /** + * The import attributes to use when caching the module (optional; if excluded the input will be used) + */ + importAttributes?: ImportAttributes | undefined; + /** + * A signal that this hook intends to terminate the chain of `resolve` hooks. + * @default false + */ + shortCircuit?: boolean | undefined; + /** + * The absolute URL to which this input resolves + */ + url: string; + } + /** + * The `resolve` hook chain is responsible for resolving file URL for a given module specifier and parent URL, and optionally its format (such as `'module'`) as a hint to the `load` hook. + * If a format is specified, the load hook is ultimately responsible for providing the final `format` value (and it is free to ignore the hint provided by `resolve`); + * if `resolve` provides a format, a custom `load` hook is required even if only to pass the value to the Node.js default `load` hook. + * + * @param specifier The specified URL path of the module to be resolved + * @param context + * @param nextResolve The subsequent `resolve` hook in the chain, or the Node.js default `resolve` hook after the last user-supplied resolve hook + */ + type ResolveHook = ( + specifier: string, + context: ResolveHookContext, + nextResolve: ( + specifier: string, + context?: ResolveHookContext, + ) => ResolveFnOutput | Promise, + ) => ResolveFnOutput | Promise; + interface LoadHookContext { + /** + * Export conditions of the relevant `package.json` + */ + conditions: string[]; + /** + * The format optionally supplied by the `resolve` hook chain + */ + format: ModuleFormat; + /** + * @deprecated Use `importAttributes` instead + */ + importAssertions: ImportAttributes; + /** + * An object whose key-value pairs represent the assertions for the module to import + */ + importAttributes: ImportAttributes; + } + interface LoadFnOutput { + format: ModuleFormat; + /** + * A signal that this hook intends to terminate the chain of `resolve` hooks. + * @default false + */ + shortCircuit?: boolean | undefined; + /** + * The source for Node.js to evaluate + */ + source?: ModuleSource; + } + /** + * The `load` hook provides a way to define a custom method of determining how a URL should be interpreted, retrieved, and parsed. + * It is also in charge of validating the import assertion. + * + * @param url The URL/path of the module to be loaded + * @param context Metadata about the module + * @param nextLoad The subsequent `load` hook in the chain, or the Node.js default `load` hook after the last user-supplied `load` hook + */ + type LoadHook = ( + url: string, + context: LoadHookContext, + nextLoad: (url: string, context?: LoadHookContext) => LoadFnOutput | Promise, + ) => LoadFnOutput | Promise; + } + interface RegisterOptions { + parentURL: string | URL; + data?: Data | undefined; + transferList?: any[] | undefined; + } + interface Module extends NodeModule {} + class Module { + static runMain(): void; + static wrap(code: string): string; + static createRequire(path: string | URL): NodeRequire; + static builtinModules: string[]; + static isBuiltin(moduleName: string): boolean; + static Module: typeof Module; + static register( + specifier: string | URL, + parentURL?: string | URL, + options?: RegisterOptions, + ): void; + static register(specifier: string | URL, options?: RegisterOptions): void; + constructor(id: string, parent?: Module); + } + global { + interface ImportMeta { + /** + * The directory name of the current module. This is the same as the `path.dirname()` of the `import.meta.filename`. + * **Caveat:** only present on `file:` modules. + */ + dirname: string; + /** + * The full absolute path and filename of the current module, with symlinks resolved. + * This is the same as the `url.fileURLToPath()` of the `import.meta.url`. + * **Caveat:** only local modules support this property. Modules not using the `file:` protocol will not provide it. + */ + filename: string; + /** + * The absolute `file:` URL of the module. + */ + url: string; + /** + * Provides a module-relative resolution function scoped to each module, returning + * the URL string. + * + * Second `parent` parameter is only used when the `--experimental-import-meta-resolve` + * command flag enabled. + * + * @since v20.6.0 + * + * @param specifier The module specifier to resolve relative to `parent`. + * @param parent The absolute parent module URL to resolve from. + * @returns The absolute (`file:`) URL string for the resolved module. + */ + resolve(specifier: string, parent?: string | URL | undefined): string; + } + } + export = Module; +} +declare module "node:module" { + import module = require("module"); + export = module; +} diff --git a/node_modules/@types/node/net.d.ts b/node_modules/@types/node/net.d.ts new file mode 100644 index 0000000..238c6a6 --- /dev/null +++ b/node_modules/@types/node/net.d.ts @@ -0,0 +1,999 @@ +/** + * > Stability: 2 - Stable + * + * The `node:net` module provides an asynchronous network API for creating stream-based + * TCP or `IPC` servers ({@link createServer}) and clients + * ({@link createConnection}). + * + * It can be accessed using: + * + * ```js + * const net = require('node:net'); + * ``` + * @see [source](https://github.com/nodejs/node/blob/v20.13.1/lib/net.js) + */ +declare module "net" { + import * as stream from "node:stream"; + import { Abortable, EventEmitter } from "node:events"; + import * as dns from "node:dns"; + type LookupFunction = ( + hostname: string, + options: dns.LookupOptions, + callback: (err: NodeJS.ErrnoException | null, address: string | dns.LookupAddress[], family?: number) => void, + ) => void; + interface AddressInfo { + address: string; + family: string; + port: number; + } + interface SocketConstructorOpts { + fd?: number | undefined; + allowHalfOpen?: boolean | undefined; + readable?: boolean | undefined; + writable?: boolean | undefined; + signal?: AbortSignal; + } + interface OnReadOpts { + buffer: Uint8Array | (() => Uint8Array); + /** + * This function is called for every chunk of incoming data. + * Two arguments are passed to it: the number of bytes written to buffer and a reference to buffer. + * Return false from this function to implicitly pause() the socket. + */ + callback(bytesWritten: number, buf: Uint8Array): boolean; + } + interface ConnectOpts { + /** + * If specified, incoming data is stored in a single buffer and passed to the supplied callback when data arrives on the socket. + * Note: this will cause the streaming functionality to not provide any data, however events like 'error', 'end', and 'close' will + * still be emitted as normal and methods like pause() and resume() will also behave as expected. + */ + onread?: OnReadOpts | undefined; + } + interface TcpSocketConnectOpts extends ConnectOpts { + port: number; + host?: string | undefined; + localAddress?: string | undefined; + localPort?: number | undefined; + hints?: number | undefined; + family?: number | undefined; + lookup?: LookupFunction | undefined; + noDelay?: boolean | undefined; + keepAlive?: boolean | undefined; + keepAliveInitialDelay?: number | undefined; + /** + * @since v18.13.0 + */ + autoSelectFamily?: boolean | undefined; + /** + * @since v18.13.0 + */ + autoSelectFamilyAttemptTimeout?: number | undefined; + } + interface IpcSocketConnectOpts extends ConnectOpts { + path: string; + } + type SocketConnectOpts = TcpSocketConnectOpts | IpcSocketConnectOpts; + type SocketReadyState = "opening" | "open" | "readOnly" | "writeOnly" | "closed"; + /** + * This class is an abstraction of a TCP socket or a streaming `IPC` endpoint + * (uses named pipes on Windows, and Unix domain sockets otherwise). It is also + * an `EventEmitter`. + * + * A `net.Socket` can be created by the user and used directly to interact with + * a server. For example, it is returned by {@link createConnection}, + * so the user can use it to talk to the server. + * + * It can also be created by Node.js and passed to the user when a connection + * is received. For example, it is passed to the listeners of a `'connection'` event emitted on a {@link Server}, so the user can use + * it to interact with the client. + * @since v0.3.4 + */ + class Socket extends stream.Duplex { + constructor(options?: SocketConstructorOpts); + /** + * Destroys the socket after all data is written. If the `finish` event was already emitted the socket is destroyed immediately. + * If the socket is still writable it implicitly calls `socket.end()`. + * @since v0.3.4 + */ + destroySoon(): void; + /** + * Sends data on the socket. The second parameter specifies the encoding in the + * case of a string. It defaults to UTF8 encoding. + * + * Returns `true` if the entire data was flushed successfully to the kernel + * buffer. Returns `false` if all or part of the data was queued in user memory.`'drain'` will be emitted when the buffer is again free. + * + * The optional `callback` parameter will be executed when the data is finally + * written out, which may not be immediately. + * + * See `Writable` stream `write()` method for more + * information. + * @since v0.1.90 + * @param [encoding='utf8'] Only used when data is `string`. + */ + write(buffer: Uint8Array | string, cb?: (err?: Error) => void): boolean; + write(str: Uint8Array | string, encoding?: BufferEncoding, cb?: (err?: Error) => void): boolean; + /** + * Initiate a connection on a given socket. + * + * Possible signatures: + * + * * `socket.connect(options[, connectListener])` + * * `socket.connect(path[, connectListener])` for `IPC` connections. + * * `socket.connect(port[, host][, connectListener])` for TCP connections. + * * Returns: `net.Socket` The socket itself. + * + * This function is asynchronous. When the connection is established, the `'connect'` event will be emitted. If there is a problem connecting, + * instead of a `'connect'` event, an `'error'` event will be emitted with + * the error passed to the `'error'` listener. + * The last parameter `connectListener`, if supplied, will be added as a listener + * for the `'connect'` event **once**. + * + * This function should only be used for reconnecting a socket after`'close'` has been emitted or otherwise it may lead to undefined + * behavior. + */ + connect(options: SocketConnectOpts, connectionListener?: () => void): this; + connect(port: number, host: string, connectionListener?: () => void): this; + connect(port: number, connectionListener?: () => void): this; + connect(path: string, connectionListener?: () => void): this; + /** + * Set the encoding for the socket as a `Readable Stream`. See `readable.setEncoding()` for more information. + * @since v0.1.90 + * @return The socket itself. + */ + setEncoding(encoding?: BufferEncoding): this; + /** + * Pauses the reading of data. That is, `'data'` events will not be emitted. + * Useful to throttle back an upload. + * @return The socket itself. + */ + pause(): this; + /** + * Close the TCP connection by sending an RST packet and destroy the stream. + * If this TCP socket is in connecting status, it will send an RST packet and destroy this TCP socket once it is connected. + * Otherwise, it will call `socket.destroy` with an `ERR_SOCKET_CLOSED` Error. + * If this is not a TCP socket (for example, a pipe), calling this method will immediately throw an `ERR_INVALID_HANDLE_TYPE` Error. + * @since v18.3.0, v16.17.0 + */ + resetAndDestroy(): this; + /** + * Resumes reading after a call to `socket.pause()`. + * @return The socket itself. + */ + resume(): this; + /** + * Sets the socket to timeout after `timeout` milliseconds of inactivity on + * the socket. By default `net.Socket` do not have a timeout. + * + * When an idle timeout is triggered the socket will receive a `'timeout'` event but the connection will not be severed. The user must manually call `socket.end()` or `socket.destroy()` to + * end the connection. + * + * ```js + * socket.setTimeout(3000); + * socket.on('timeout', () => { + * console.log('socket timeout'); + * socket.end(); + * }); + * ``` + * + * If `timeout` is 0, then the existing idle timeout is disabled. + * + * The optional `callback` parameter will be added as a one-time listener for the `'timeout'` event. + * @since v0.1.90 + * @return The socket itself. + */ + setTimeout(timeout: number, callback?: () => void): this; + /** + * Enable/disable the use of Nagle's algorithm. + * + * When a TCP connection is created, it will have Nagle's algorithm enabled. + * + * Nagle's algorithm delays data before it is sent via the network. It attempts + * to optimize throughput at the expense of latency. + * + * Passing `true` for `noDelay` or not passing an argument will disable Nagle's + * algorithm for the socket. Passing `false` for `noDelay` will enable Nagle's + * algorithm. + * @since v0.1.90 + * @param [noDelay=true] + * @return The socket itself. + */ + setNoDelay(noDelay?: boolean): this; + /** + * Enable/disable keep-alive functionality, and optionally set the initial + * delay before the first keepalive probe is sent on an idle socket. + * + * Set `initialDelay` (in milliseconds) to set the delay between the last + * data packet received and the first keepalive probe. Setting `0` for`initialDelay` will leave the value unchanged from the default + * (or previous) setting. + * + * Enabling the keep-alive functionality will set the following socket options: + * + * * `SO_KEEPALIVE=1` + * * `TCP_KEEPIDLE=initialDelay` + * * `TCP_KEEPCNT=10` + * * `TCP_KEEPINTVL=1` + * @since v0.1.92 + * @param [enable=false] + * @param [initialDelay=0] + * @return The socket itself. + */ + setKeepAlive(enable?: boolean, initialDelay?: number): this; + /** + * Returns the bound `address`, the address `family` name and `port` of the + * socket as reported by the operating system:`{ port: 12346, family: 'IPv4', address: '127.0.0.1' }` + * @since v0.1.90 + */ + address(): AddressInfo | {}; + /** + * Calling `unref()` on a socket will allow the program to exit if this is the only + * active socket in the event system. If the socket is already `unref`ed calling`unref()` again will have no effect. + * @since v0.9.1 + * @return The socket itself. + */ + unref(): this; + /** + * Opposite of `unref()`, calling `ref()` on a previously `unref`ed socket will _not_ let the program exit if it's the only socket left (the default behavior). + * If the socket is `ref`ed calling `ref` again will have no effect. + * @since v0.9.1 + * @return The socket itself. + */ + ref(): this; + /** + * This property is only present if the family autoselection algorithm is enabled in `socket.connect(options)` + * and it is an array of the addresses that have been attempted. + * + * Each address is a string in the form of `$IP:$PORT`. + * If the connection was successful, then the last address is the one that the socket is currently connected to. + * @since v19.4.0 + */ + readonly autoSelectFamilyAttemptedAddresses: string[]; + /** + * This property shows the number of characters buffered for writing. The buffer + * may contain strings whose length after encoding is not yet known. So this number + * is only an approximation of the number of bytes in the buffer. + * + * `net.Socket` has the property that `socket.write()` always works. This is to + * help users get up and running quickly. The computer cannot always keep up + * with the amount of data that is written to a socket. The network connection + * simply might be too slow. Node.js will internally queue up the data written to a + * socket and send it out over the wire when it is possible. + * + * The consequence of this internal buffering is that memory may grow. + * Users who experience large or growing `bufferSize` should attempt to + * "throttle" the data flows in their program with `socket.pause()` and `socket.resume()`. + * @since v0.3.8 + * @deprecated Since v14.6.0 - Use `writableLength` instead. + */ + readonly bufferSize: number; + /** + * The amount of received bytes. + * @since v0.5.3 + */ + readonly bytesRead: number; + /** + * The amount of bytes sent. + * @since v0.5.3 + */ + readonly bytesWritten: number; + /** + * If `true`, `socket.connect(options[, connectListener])` was + * called and has not yet finished. It will stay `true` until the socket becomes + * connected, then it is set to `false` and the `'connect'` event is emitted. Note + * that the `socket.connect(options[, connectListener])` callback is a listener for the `'connect'` event. + * @since v6.1.0 + */ + readonly connecting: boolean; + /** + * This is `true` if the socket is not connected yet, either because `.connect()`has not yet been called or because it is still in the process of connecting + * (see `socket.connecting`). + * @since v11.2.0, v10.16.0 + */ + readonly pending: boolean; + /** + * See `writable.destroyed` for further details. + */ + readonly destroyed: boolean; + /** + * The string representation of the local IP address the remote client is + * connecting on. For example, in a server listening on `'0.0.0.0'`, if a client + * connects on `'192.168.1.1'`, the value of `socket.localAddress` would be`'192.168.1.1'`. + * @since v0.9.6 + */ + readonly localAddress?: string; + /** + * The numeric representation of the local port. For example, `80` or `21`. + * @since v0.9.6 + */ + readonly localPort?: number; + /** + * The string representation of the local IP family. `'IPv4'` or `'IPv6'`. + * @since v18.8.0, v16.18.0 + */ + readonly localFamily?: string; + /** + * This property represents the state of the connection as a string. + * + * * If the stream is connecting `socket.readyState` is `opening`. + * * If the stream is readable and writable, it is `open`. + * * If the stream is readable and not writable, it is `readOnly`. + * * If the stream is not readable and writable, it is `writeOnly`. + * @since v0.5.0 + */ + readonly readyState: SocketReadyState; + /** + * The string representation of the remote IP address. For example,`'74.125.127.100'` or `'2001:4860:a005::68'`. Value may be `undefined` if + * the socket is destroyed (for example, if the client disconnected). + * @since v0.5.10 + */ + readonly remoteAddress?: string | undefined; + /** + * The string representation of the remote IP family. `'IPv4'` or `'IPv6'`. Value may be `undefined` if + * the socket is destroyed (for example, if the client disconnected). + * @since v0.11.14 + */ + readonly remoteFamily?: string | undefined; + /** + * The numeric representation of the remote port. For example, `80` or `21`. Value may be `undefined` if + * the socket is destroyed (for example, if the client disconnected). + * @since v0.5.10 + */ + readonly remotePort?: number | undefined; + /** + * The socket timeout in milliseconds as set by `socket.setTimeout()`. + * It is `undefined` if a timeout has not been set. + * @since v10.7.0 + */ + readonly timeout?: number | undefined; + /** + * Half-closes the socket. i.e., it sends a FIN packet. It is possible the + * server will still send some data. + * + * See `writable.end()` for further details. + * @since v0.1.90 + * @param [encoding='utf8'] Only used when data is `string`. + * @param callback Optional callback for when the socket is finished. + * @return The socket itself. + */ + end(callback?: () => void): this; + end(buffer: Uint8Array | string, callback?: () => void): this; + end(str: Uint8Array | string, encoding?: BufferEncoding, callback?: () => void): this; + /** + * events.EventEmitter + * 1. close + * 2. connect + * 3. connectionAttempt + * 4. connectionAttemptFailed + * 5. connectionAttemptTimeout + * 6. data + * 7. drain + * 8. end + * 9. error + * 10. lookup + * 11. ready + * 12. timeout + */ + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "close", listener: (hadError: boolean) => void): this; + addListener(event: "connect", listener: () => void): this; + addListener(event: "connectionAttempt", listener: (ip: string, port: number, family: number) => void): this; + addListener( + event: "connectionAttemptFailed", + listener: (ip: string, port: number, family: number) => void, + ): this; + addListener( + event: "connectionAttemptTimeout", + listener: (ip: string, port: number, family: number) => void, + ): this; + addListener(event: "data", listener: (data: Buffer) => void): this; + addListener(event: "drain", listener: () => void): this; + addListener(event: "end", listener: () => void): this; + addListener(event: "error", listener: (err: Error) => void): this; + addListener( + event: "lookup", + listener: (err: Error, address: string, family: string | number, host: string) => void, + ): this; + addListener(event: "ready", listener: () => void): this; + addListener(event: "timeout", listener: () => void): this; + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: "close", hadError: boolean): boolean; + emit(event: "connect"): boolean; + emit(event: "connectionAttempt", ip: string, port: number, family: number): boolean; + emit(event: "connectionAttemptFailed", ip: string, port: number, family: number): boolean; + emit(event: "connectionAttemptTimeout", ip: string, port: number, family: number): boolean; + emit(event: "data", data: Buffer): boolean; + emit(event: "drain"): boolean; + emit(event: "end"): boolean; + emit(event: "error", err: Error): boolean; + emit(event: "lookup", err: Error, address: string, family: string | number, host: string): boolean; + emit(event: "ready"): boolean; + emit(event: "timeout"): boolean; + on(event: string, listener: (...args: any[]) => void): this; + on(event: "close", listener: (hadError: boolean) => void): this; + on(event: "connect", listener: () => void): this; + on(event: "connectionAttempt", listener: (ip: string, port: number, family: number) => void): this; + on(event: "connectionAttemptFailed", listener: (ip: string, port: number, family: number) => void): this; + on(event: "connectionAttemptTimeout", listener: (ip: string, port: number, family: number) => void): this; + on(event: "data", listener: (data: Buffer) => void): this; + on(event: "drain", listener: () => void): this; + on(event: "end", listener: () => void): this; + on(event: "error", listener: (err: Error) => void): this; + on( + event: "lookup", + listener: (err: Error, address: string, family: string | number, host: string) => void, + ): this; + on(event: "ready", listener: () => void): this; + on(event: "timeout", listener: () => void): this; + once(event: string, listener: (...args: any[]) => void): this; + once(event: "close", listener: (hadError: boolean) => void): this; + once(event: "connectionAttempt", listener: (ip: string, port: number, family: number) => void): this; + once(event: "connectionAttemptFailed", listener: (ip: string, port: number, family: number) => void): this; + once(event: "connectionAttemptTimeout", listener: (ip: string, port: number, family: number) => void): this; + once(event: "connect", listener: () => void): this; + once(event: "data", listener: (data: Buffer) => void): this; + once(event: "drain", listener: () => void): this; + once(event: "end", listener: () => void): this; + once(event: "error", listener: (err: Error) => void): this; + once( + event: "lookup", + listener: (err: Error, address: string, family: string | number, host: string) => void, + ): this; + once(event: "ready", listener: () => void): this; + once(event: "timeout", listener: () => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "close", listener: (hadError: boolean) => void): this; + prependListener(event: "connect", listener: () => void): this; + prependListener(event: "connectionAttempt", listener: (ip: string, port: number, family: number) => void): this; + prependListener( + event: "connectionAttemptFailed", + listener: (ip: string, port: number, family: number) => void, + ): this; + prependListener( + event: "connectionAttemptTimeout", + listener: (ip: string, port: number, family: number) => void, + ): this; + prependListener(event: "data", listener: (data: Buffer) => void): this; + prependListener(event: "drain", listener: () => void): this; + prependListener(event: "end", listener: () => void): this; + prependListener(event: "error", listener: (err: Error) => void): this; + prependListener( + event: "lookup", + listener: (err: Error, address: string, family: string | number, host: string) => void, + ): this; + prependListener(event: "ready", listener: () => void): this; + prependListener(event: "timeout", listener: () => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "close", listener: (hadError: boolean) => void): this; + prependOnceListener(event: "connect", listener: () => void): this; + prependOnceListener( + event: "connectionAttempt", + listener: (ip: string, port: number, family: number) => void, + ): this; + prependOnceListener( + event: "connectionAttemptFailed", + listener: (ip: string, port: number, family: number) => void, + ): this; + prependOnceListener( + event: "connectionAttemptTimeout", + listener: (ip: string, port: number, family: number) => void, + ): this; + prependOnceListener(event: "data", listener: (data: Buffer) => void): this; + prependOnceListener(event: "drain", listener: () => void): this; + prependOnceListener(event: "end", listener: () => void): this; + prependOnceListener(event: "error", listener: (err: Error) => void): this; + prependOnceListener( + event: "lookup", + listener: (err: Error, address: string, family: string | number, host: string) => void, + ): this; + prependOnceListener(event: "ready", listener: () => void): this; + prependOnceListener(event: "timeout", listener: () => void): this; + } + interface ListenOptions extends Abortable { + port?: number | undefined; + host?: string | undefined; + backlog?: number | undefined; + path?: string | undefined; + exclusive?: boolean | undefined; + readableAll?: boolean | undefined; + writableAll?: boolean | undefined; + /** + * @default false + */ + ipv6Only?: boolean | undefined; + } + interface ServerOpts { + /** + * Indicates whether half-opened TCP connections are allowed. + * @default false + */ + allowHalfOpen?: boolean | undefined; + /** + * Indicates whether the socket should be paused on incoming connections. + * @default false + */ + pauseOnConnect?: boolean | undefined; + /** + * If set to `true`, it disables the use of Nagle's algorithm immediately after a new incoming connection is received. + * @default false + * @since v16.5.0 + */ + noDelay?: boolean | undefined; + /** + * If set to `true`, it enables keep-alive functionality on the socket immediately after a new incoming connection is received, + * similarly on what is done in `socket.setKeepAlive([enable][, initialDelay])`. + * @default false + * @since v16.5.0 + */ + keepAlive?: boolean | undefined; + /** + * If set to a positive number, it sets the initial delay before the first keepalive probe is sent on an idle socket. + * @default 0 + * @since v16.5.0 + */ + keepAliveInitialDelay?: number | undefined; + } + interface DropArgument { + localAddress?: string; + localPort?: number; + localFamily?: string; + remoteAddress?: string; + remotePort?: number; + remoteFamily?: string; + } + /** + * This class is used to create a TCP or `IPC` server. + * @since v0.1.90 + */ + class Server extends EventEmitter { + constructor(connectionListener?: (socket: Socket) => void); + constructor(options?: ServerOpts, connectionListener?: (socket: Socket) => void); + /** + * Start a server listening for connections. A `net.Server` can be a TCP or + * an `IPC` server depending on what it listens to. + * + * Possible signatures: + * + * * `server.listen(handle[, backlog][, callback])` + * * `server.listen(options[, callback])` + * * `server.listen(path[, backlog][, callback])` for `IPC` servers + * * `server.listen([port[, host[, backlog]]][, callback])` for TCP servers + * + * This function is asynchronous. When the server starts listening, the `'listening'` event will be emitted. The last parameter `callback`will be added as a listener for the `'listening'` + * event. + * + * All `listen()` methods can take a `backlog` parameter to specify the maximum + * length of the queue of pending connections. The actual length will be determined + * by the OS through sysctl settings such as `tcp_max_syn_backlog` and `somaxconn` on Linux. The default value of this parameter is 511 (not 512). + * + * All {@link Socket} are set to `SO_REUSEADDR` (see [`socket(7)`](https://man7.org/linux/man-pages/man7/socket.7.html) for + * details). + * + * The `server.listen()` method can be called again if and only if there was an + * error during the first `server.listen()` call or `server.close()` has been + * called. Otherwise, an `ERR_SERVER_ALREADY_LISTEN` error will be thrown. + * + * One of the most common errors raised when listening is `EADDRINUSE`. + * This happens when another server is already listening on the requested`port`/`path`/`handle`. One way to handle this would be to retry + * after a certain amount of time: + * + * ```js + * server.on('error', (e) => { + * if (e.code === 'EADDRINUSE') { + * console.error('Address in use, retrying...'); + * setTimeout(() => { + * server.close(); + * server.listen(PORT, HOST); + * }, 1000); + * } + * }); + * ``` + */ + listen(port?: number, hostname?: string, backlog?: number, listeningListener?: () => void): this; + listen(port?: number, hostname?: string, listeningListener?: () => void): this; + listen(port?: number, backlog?: number, listeningListener?: () => void): this; + listen(port?: number, listeningListener?: () => void): this; + listen(path: string, backlog?: number, listeningListener?: () => void): this; + listen(path: string, listeningListener?: () => void): this; + listen(options: ListenOptions, listeningListener?: () => void): this; + listen(handle: any, backlog?: number, listeningListener?: () => void): this; + listen(handle: any, listeningListener?: () => void): this; + /** + * Stops the server from accepting new connections and keeps existing + * connections. This function is asynchronous, the server is finally closed + * when all connections are ended and the server emits a `'close'` event. + * The optional `callback` will be called once the `'close'` event occurs. Unlike + * that event, it will be called with an `Error` as its only argument if the server + * was not open when it was closed. + * @since v0.1.90 + * @param callback Called when the server is closed. + */ + close(callback?: (err?: Error) => void): this; + /** + * Returns the bound `address`, the address `family` name, and `port` of the server + * as reported by the operating system if listening on an IP socket + * (useful to find which port was assigned when getting an OS-assigned address):`{ port: 12346, family: 'IPv4', address: '127.0.0.1' }`. + * + * For a server listening on a pipe or Unix domain socket, the name is returned + * as a string. + * + * ```js + * const server = net.createServer((socket) => { + * socket.end('goodbye\n'); + * }).on('error', (err) => { + * // Handle errors here. + * throw err; + * }); + * + * // Grab an arbitrary unused port. + * server.listen(() => { + * console.log('opened server on', server.address()); + * }); + * ``` + * + * `server.address()` returns `null` before the `'listening'` event has been + * emitted or after calling `server.close()`. + * @since v0.1.90 + */ + address(): AddressInfo | string | null; + /** + * Asynchronously get the number of concurrent connections on the server. Works + * when sockets were sent to forks. + * + * Callback should take two arguments `err` and `count`. + * @since v0.9.7 + */ + getConnections(cb: (error: Error | null, count: number) => void): void; + /** + * Opposite of `unref()`, calling `ref()` on a previously `unref`ed server will _not_ let the program exit if it's the only server left (the default behavior). + * If the server is `ref`ed calling `ref()` again will have no effect. + * @since v0.9.1 + */ + ref(): this; + /** + * Calling `unref()` on a server will allow the program to exit if this is the only + * active server in the event system. If the server is already `unref`ed calling`unref()` again will have no effect. + * @since v0.9.1 + */ + unref(): this; + /** + * Set this property to reject connections when the server's connection count gets + * high. + * + * It is not recommended to use this option once a socket has been sent to a child + * with `child_process.fork()`. + * @since v0.2.0 + */ + maxConnections: number; + connections: number; + /** + * Indicates whether or not the server is listening for connections. + * @since v5.7.0 + */ + readonly listening: boolean; + /** + * events.EventEmitter + * 1. close + * 2. connection + * 3. error + * 4. listening + * 5. drop + */ + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "close", listener: () => void): this; + addListener(event: "connection", listener: (socket: Socket) => void): this; + addListener(event: "error", listener: (err: Error) => void): this; + addListener(event: "listening", listener: () => void): this; + addListener(event: "drop", listener: (data?: DropArgument) => void): this; + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: "close"): boolean; + emit(event: "connection", socket: Socket): boolean; + emit(event: "error", err: Error): boolean; + emit(event: "listening"): boolean; + emit(event: "drop", data?: DropArgument): boolean; + on(event: string, listener: (...args: any[]) => void): this; + on(event: "close", listener: () => void): this; + on(event: "connection", listener: (socket: Socket) => void): this; + on(event: "error", listener: (err: Error) => void): this; + on(event: "listening", listener: () => void): this; + on(event: "drop", listener: (data?: DropArgument) => void): this; + once(event: string, listener: (...args: any[]) => void): this; + once(event: "close", listener: () => void): this; + once(event: "connection", listener: (socket: Socket) => void): this; + once(event: "error", listener: (err: Error) => void): this; + once(event: "listening", listener: () => void): this; + once(event: "drop", listener: (data?: DropArgument) => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "close", listener: () => void): this; + prependListener(event: "connection", listener: (socket: Socket) => void): this; + prependListener(event: "error", listener: (err: Error) => void): this; + prependListener(event: "listening", listener: () => void): this; + prependListener(event: "drop", listener: (data?: DropArgument) => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "connection", listener: (socket: Socket) => void): this; + prependOnceListener(event: "error", listener: (err: Error) => void): this; + prependOnceListener(event: "listening", listener: () => void): this; + prependOnceListener(event: "drop", listener: (data?: DropArgument) => void): this; + /** + * Calls {@link Server.close()} and returns a promise that fulfills when the server has closed. + * @since v20.5.0 + */ + [Symbol.asyncDispose](): Promise; + } + type IPVersion = "ipv4" | "ipv6"; + /** + * The `BlockList` object can be used with some network APIs to specify rules for + * disabling inbound or outbound access to specific IP addresses, IP ranges, or + * IP subnets. + * @since v15.0.0, v14.18.0 + */ + class BlockList { + /** + * Adds a rule to block the given IP address. + * @since v15.0.0, v14.18.0 + * @param address An IPv4 or IPv6 address. + * @param [type='ipv4'] Either `'ipv4'` or `'ipv6'`. + */ + addAddress(address: string, type?: IPVersion): void; + addAddress(address: SocketAddress): void; + /** + * Adds a rule to block a range of IP addresses from `start` (inclusive) to`end` (inclusive). + * @since v15.0.0, v14.18.0 + * @param start The starting IPv4 or IPv6 address in the range. + * @param end The ending IPv4 or IPv6 address in the range. + * @param [type='ipv4'] Either `'ipv4'` or `'ipv6'`. + */ + addRange(start: string, end: string, type?: IPVersion): void; + addRange(start: SocketAddress, end: SocketAddress): void; + /** + * Adds a rule to block a range of IP addresses specified as a subnet mask. + * @since v15.0.0, v14.18.0 + * @param net The network IPv4 or IPv6 address. + * @param prefix The number of CIDR prefix bits. For IPv4, this must be a value between `0` and `32`. For IPv6, this must be between `0` and `128`. + * @param [type='ipv4'] Either `'ipv4'` or `'ipv6'`. + */ + addSubnet(net: SocketAddress, prefix: number): void; + addSubnet(net: string, prefix: number, type?: IPVersion): void; + /** + * Returns `true` if the given IP address matches any of the rules added to the`BlockList`. + * + * ```js + * const blockList = new net.BlockList(); + * blockList.addAddress('123.123.123.123'); + * blockList.addRange('10.0.0.1', '10.0.0.10'); + * blockList.addSubnet('8592:757c:efae:4e45::', 64, 'ipv6'); + * + * console.log(blockList.check('123.123.123.123')); // Prints: true + * console.log(blockList.check('10.0.0.3')); // Prints: true + * console.log(blockList.check('222.111.111.222')); // Prints: false + * + * // IPv6 notation for IPv4 addresses works: + * console.log(blockList.check('::ffff:7b7b:7b7b', 'ipv6')); // Prints: true + * console.log(blockList.check('::ffff:123.123.123.123', 'ipv6')); // Prints: true + * ``` + * @since v15.0.0, v14.18.0 + * @param address The IP address to check + * @param [type='ipv4'] Either `'ipv4'` or `'ipv6'`. + */ + check(address: SocketAddress): boolean; + check(address: string, type?: IPVersion): boolean; + /** + * The list of rules added to the blocklist. + * @since v15.0.0, v14.18.0 + */ + rules: readonly string[]; + } + interface TcpNetConnectOpts extends TcpSocketConnectOpts, SocketConstructorOpts { + timeout?: number | undefined; + } + interface IpcNetConnectOpts extends IpcSocketConnectOpts, SocketConstructorOpts { + timeout?: number | undefined; + } + type NetConnectOpts = TcpNetConnectOpts | IpcNetConnectOpts; + /** + * Creates a new TCP or `IPC` server. + * + * If `allowHalfOpen` is set to `true`, when the other end of the socket + * signals the end of transmission, the server will only send back the end of + * transmission when `socket.end()` is explicitly called. For example, in the + * context of TCP, when a FIN packed is received, a FIN packed is sent + * back only when `socket.end()` is explicitly called. Until then the + * connection is half-closed (non-readable but still writable). See `'end'` event and [RFC 1122](https://tools.ietf.org/html/rfc1122) (section 4.2.2.13) for more information. + * + * If `pauseOnConnect` is set to `true`, then the socket associated with each + * incoming connection will be paused, and no data will be read from its handle. + * This allows connections to be passed between processes without any data being + * read by the original process. To begin reading data from a paused socket, call `socket.resume()`. + * + * The server can be a TCP server or an `IPC` server, depending on what it `listen()` to. + * + * Here is an example of a TCP echo server which listens for connections + * on port 8124: + * + * ```js + * const net = require('node:net'); + * const server = net.createServer((c) => { + * // 'connection' listener. + * console.log('client connected'); + * c.on('end', () => { + * console.log('client disconnected'); + * }); + * c.write('hello\r\n'); + * c.pipe(c); + * }); + * server.on('error', (err) => { + * throw err; + * }); + * server.listen(8124, () => { + * console.log('server bound'); + * }); + * ``` + * + * Test this by using `telnet`: + * + * ```bash + * telnet localhost 8124 + * ``` + * + * To listen on the socket `/tmp/echo.sock`: + * + * ```js + * server.listen('/tmp/echo.sock', () => { + * console.log('server bound'); + * }); + * ``` + * + * Use `nc` to connect to a Unix domain socket server: + * + * ```bash + * nc -U /tmp/echo.sock + * ``` + * @since v0.5.0 + * @param connectionListener Automatically set as a listener for the {@link 'connection'} event. + */ + function createServer(connectionListener?: (socket: Socket) => void): Server; + function createServer(options?: ServerOpts, connectionListener?: (socket: Socket) => void): Server; + /** + * Aliases to {@link createConnection}. + * + * Possible signatures: + * + * * {@link connect} + * * {@link connect} for `IPC` connections. + * * {@link connect} for TCP connections. + */ + function connect(options: NetConnectOpts, connectionListener?: () => void): Socket; + function connect(port: number, host?: string, connectionListener?: () => void): Socket; + function connect(path: string, connectionListener?: () => void): Socket; + /** + * A factory function, which creates a new {@link Socket}, + * immediately initiates connection with `socket.connect()`, + * then returns the `net.Socket` that starts the connection. + * + * When the connection is established, a `'connect'` event will be emitted + * on the returned socket. The last parameter `connectListener`, if supplied, + * will be added as a listener for the `'connect'` event **once**. + * + * Possible signatures: + * + * * {@link createConnection} + * * {@link createConnection} for `IPC` connections. + * * {@link createConnection} for TCP connections. + * + * The {@link connect} function is an alias to this function. + */ + function createConnection(options: NetConnectOpts, connectionListener?: () => void): Socket; + function createConnection(port: number, host?: string, connectionListener?: () => void): Socket; + function createConnection(path: string, connectionListener?: () => void): Socket; + /** + * Gets the current default value of the `autoSelectFamily` option of `socket.connect(options)`. + * The initial default value is `true`, unless the command line option`--no-network-family-autoselection` is provided. + * @since v19.4.0 + */ + function getDefaultAutoSelectFamily(): boolean; + /** + * Sets the default value of the `autoSelectFamily` option of `socket.connect(options)`. + * @since v19.4.0 + */ + function setDefaultAutoSelectFamily(value: boolean): void; + /** + * Gets the current default value of the `autoSelectFamilyAttemptTimeout` option of `socket.connect(options)`. + * The initial default value is `250` or the value specified via the command line option `--network-family-autoselection-attempt-timeout`. + * @returns The current default value of the `autoSelectFamilyAttemptTimeout` option. + * @since v19.8.0, v18.8.0 + */ + function getDefaultAutoSelectFamilyAttemptTimeout(): number; + /** + * Sets the default value of the `autoSelectFamilyAttemptTimeout` option of `socket.connect(options)`. + * @param value The new default value, which must be a positive number. If the number is less than `10`, the value `10` is used instead. The initial default value is `250` or the value specified via the command line + * option `--network-family-autoselection-attempt-timeout`. + * @since v19.8.0, v18.8.0 + */ + function setDefaultAutoSelectFamilyAttemptTimeout(value: number): void; + /** + * Returns `6` if `input` is an IPv6 address. Returns `4` if `input` is an IPv4 + * address in [dot-decimal notation](https://en.wikipedia.org/wiki/Dot-decimal_notation) with no leading zeroes. Otherwise, returns`0`. + * + * ```js + * net.isIP('::1'); // returns 6 + * net.isIP('127.0.0.1'); // returns 4 + * net.isIP('127.000.000.001'); // returns 0 + * net.isIP('127.0.0.1/24'); // returns 0 + * net.isIP('fhqwhgads'); // returns 0 + * ``` + * @since v0.3.0 + */ + function isIP(input: string): number; + /** + * Returns `true` if `input` is an IPv4 address in [dot-decimal notation](https://en.wikipedia.org/wiki/Dot-decimal_notation) with no + * leading zeroes. Otherwise, returns `false`. + * + * ```js + * net.isIPv4('127.0.0.1'); // returns true + * net.isIPv4('127.000.000.001'); // returns false + * net.isIPv4('127.0.0.1/24'); // returns false + * net.isIPv4('fhqwhgads'); // returns false + * ``` + * @since v0.3.0 + */ + function isIPv4(input: string): boolean; + /** + * Returns `true` if `input` is an IPv6 address. Otherwise, returns `false`. + * + * ```js + * net.isIPv6('::1'); // returns true + * net.isIPv6('fhqwhgads'); // returns false + * ``` + * @since v0.3.0 + */ + function isIPv6(input: string): boolean; + interface SocketAddressInitOptions { + /** + * The network address as either an IPv4 or IPv6 string. + * @default 127.0.0.1 + */ + address?: string | undefined; + /** + * @default `'ipv4'` + */ + family?: IPVersion | undefined; + /** + * An IPv6 flow-label used only if `family` is `'ipv6'`. + * @default 0 + */ + flowlabel?: number | undefined; + /** + * An IP port. + * @default 0 + */ + port?: number | undefined; + } + /** + * @since v15.14.0, v14.18.0 + */ + class SocketAddress { + constructor(options: SocketAddressInitOptions); + /** + * Either \`'ipv4'\` or \`'ipv6'\`. + * @since v15.14.0, v14.18.0 + */ + readonly address: string; + /** + * Either \`'ipv4'\` or \`'ipv6'\`. + * @since v15.14.0, v14.18.0 + */ + readonly family: IPVersion; + /** + * @since v15.14.0, v14.18.0 + */ + readonly port: number; + /** + * @since v15.14.0, v14.18.0 + */ + readonly flowlabel: number; + } +} +declare module "node:net" { + export * from "net"; +} diff --git a/node_modules/@types/node/os.d.ts b/node_modules/@types/node/os.d.ts new file mode 100644 index 0000000..0b9a68c --- /dev/null +++ b/node_modules/@types/node/os.d.ts @@ -0,0 +1,495 @@ +/** + * The `node:os` module provides operating system-related utility methods and + * properties. It can be accessed using: + * + * ```js + * const os = require('node:os'); + * ``` + * @see [source](https://github.com/nodejs/node/blob/v20.13.1/lib/os.js) + */ +declare module "os" { + interface CpuInfo { + model: string; + speed: number; + times: { + /** The number of milliseconds the CPU has spent in user mode. */ + user: number; + /** The number of milliseconds the CPU has spent in nice mode. */ + nice: number; + /** The number of milliseconds the CPU has spent in sys mode. */ + sys: number; + /** The number of milliseconds the CPU has spent in idle mode. */ + idle: number; + /** The number of milliseconds the CPU has spent in irq mode. */ + irq: number; + }; + } + interface NetworkInterfaceBase { + address: string; + netmask: string; + mac: string; + internal: boolean; + cidr: string | null; + } + interface NetworkInterfaceInfoIPv4 extends NetworkInterfaceBase { + family: "IPv4"; + scopeid?: undefined; + } + interface NetworkInterfaceInfoIPv6 extends NetworkInterfaceBase { + family: "IPv6"; + scopeid: number; + } + interface UserInfo { + username: T; + uid: number; + gid: number; + shell: T | null; + homedir: T; + } + type NetworkInterfaceInfo = NetworkInterfaceInfoIPv4 | NetworkInterfaceInfoIPv6; + /** + * Returns the host name of the operating system as a string. + * @since v0.3.3 + */ + function hostname(): string; + /** + * Returns an array containing the 1, 5, and 15 minute load averages. + * + * The load average is a measure of system activity calculated by the operating + * system and expressed as a fractional number. + * + * The load average is a Unix-specific concept. On Windows, the return value is + * always `[0, 0, 0]`. + * @since v0.3.3 + */ + function loadavg(): number[]; + /** + * Returns the system uptime in number of seconds. + * @since v0.3.3 + */ + function uptime(): number; + /** + * Returns the amount of free system memory in bytes as an integer. + * @since v0.3.3 + */ + function freemem(): number; + /** + * Returns the total amount of system memory in bytes as an integer. + * @since v0.3.3 + */ + function totalmem(): number; + /** + * Returns an array of objects containing information about each logical CPU core. + * The array will be empty if no CPU information is available, such as if the `/proc` file system is unavailable. + * + * The properties included on each object include: + * + * ```js + * [ + * { + * model: 'Intel(R) Core(TM) i7 CPU 860 @ 2.80GHz', + * speed: 2926, + * times: { + * user: 252020, + * nice: 0, + * sys: 30340, + * idle: 1070356870, + * irq: 0, + * }, + * }, + * { + * model: 'Intel(R) Core(TM) i7 CPU 860 @ 2.80GHz', + * speed: 2926, + * times: { + * user: 306960, + * nice: 0, + * sys: 26980, + * idle: 1071569080, + * irq: 0, + * }, + * }, + * { + * model: 'Intel(R) Core(TM) i7 CPU 860 @ 2.80GHz', + * speed: 2926, + * times: { + * user: 248450, + * nice: 0, + * sys: 21750, + * idle: 1070919370, + * irq: 0, + * }, + * }, + * { + * model: 'Intel(R) Core(TM) i7 CPU 860 @ 2.80GHz', + * speed: 2926, + * times: { + * user: 256880, + * nice: 0, + * sys: 19430, + * idle: 1070905480, + * irq: 20, + * }, + * }, + * ] + * ``` + * + * `nice` values are POSIX-only. On Windows, the `nice` values of all processors + * are always 0. + * + * `os.cpus().length` should not be used to calculate the amount of parallelism + * available to an application. Use {@link availableParallelism} for this purpose. + * @since v0.3.3 + */ + function cpus(): CpuInfo[]; + /** + * Returns an estimate of the default amount of parallelism a program should use. + * Always returns a value greater than zero. + * + * This function is a small wrapper about libuv's [`uv_available_parallelism()`](https://docs.libuv.org/en/v1.x/misc.html#c.uv_available_parallelism). + * @since v19.4.0, v18.14.0 + */ + function availableParallelism(): number; + /** + * Returns the operating system name as returned by [`uname(3)`](https://linux.die.net/man/3/uname). For example, it + * returns `'Linux'` on Linux, `'Darwin'` on macOS, and `'Windows_NT'` on Windows. + * + * See [https://en.wikipedia.org/wiki/Uname#Examples](https://en.wikipedia.org/wiki/Uname#Examples) for additional information + * about the output of running [`uname(3)`](https://linux.die.net/man/3/uname) on various operating systems. + * @since v0.3.3 + */ + function type(): string; + /** + * Returns the operating system as a string. + * + * On POSIX systems, the operating system release is determined by calling [`uname(3)`](https://linux.die.net/man/3/uname). On Windows, `GetVersionExW()` is used. See + * [https://en.wikipedia.org/wiki/Uname#Examples](https://en.wikipedia.org/wiki/Uname#Examples) for more information. + * @since v0.3.3 + */ + function release(): string; + /** + * Returns an object containing network interfaces that have been assigned a + * network address. + * + * Each key on the returned object identifies a network interface. The associated + * value is an array of objects that each describe an assigned network address. + * + * The properties available on the assigned network address object include: + * + * ```js + * { + * lo: [ + * { + * address: '127.0.0.1', + * netmask: '255.0.0.0', + * family: 'IPv4', + * mac: '00:00:00:00:00:00', + * internal: true, + * cidr: '127.0.0.1/8' + * }, + * { + * address: '::1', + * netmask: 'ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff', + * family: 'IPv6', + * mac: '00:00:00:00:00:00', + * scopeid: 0, + * internal: true, + * cidr: '::1/128' + * } + * ], + * eth0: [ + * { + * address: '192.168.1.108', + * netmask: '255.255.255.0', + * family: 'IPv4', + * mac: '01:02:03:0a:0b:0c', + * internal: false, + * cidr: '192.168.1.108/24' + * }, + * { + * address: 'fe80::a00:27ff:fe4e:66a1', + * netmask: 'ffff:ffff:ffff:ffff::', + * family: 'IPv6', + * mac: '01:02:03:0a:0b:0c', + * scopeid: 1, + * internal: false, + * cidr: 'fe80::a00:27ff:fe4e:66a1/64' + * } + * ] + * } + * ``` + * @since v0.6.0 + */ + function networkInterfaces(): NodeJS.Dict; + /** + * Returns the string path of the current user's home directory. + * + * On POSIX, it uses the `$HOME` environment variable if defined. Otherwise it + * uses the [effective UID](https://en.wikipedia.org/wiki/User_identifier#Effective_user_ID) to look up the user's home directory. + * + * On Windows, it uses the `USERPROFILE` environment variable if defined. + * Otherwise it uses the path to the profile directory of the current user. + * @since v2.3.0 + */ + function homedir(): string; + /** + * Returns information about the currently effective user. On POSIX platforms, + * this is typically a subset of the password file. The returned object includes + * the `username`, `uid`, `gid`, `shell`, and `homedir`. On Windows, the `uid` and `gid` fields are `-1`, and `shell` is `null`. + * + * The value of `homedir` returned by `os.userInfo()` is provided by the operating + * system. This differs from the result of `os.homedir()`, which queries + * environment variables for the home directory before falling back to the + * operating system response. + * + * Throws a [`SystemError`](https://nodejs.org/docs/latest-v20.x/api/errors.html#class-systemerror) if a user has no `username` or `homedir`. + * @since v6.0.0 + */ + function userInfo(options: { encoding: "buffer" }): UserInfo; + function userInfo(options?: { encoding: BufferEncoding }): UserInfo; + type SignalConstants = { + [key in NodeJS.Signals]: number; + }; + namespace constants { + const UV_UDP_REUSEADDR: number; + namespace signals {} + const signals: SignalConstants; + namespace errno { + const E2BIG: number; + const EACCES: number; + const EADDRINUSE: number; + const EADDRNOTAVAIL: number; + const EAFNOSUPPORT: number; + const EAGAIN: number; + const EALREADY: number; + const EBADF: number; + const EBADMSG: number; + const EBUSY: number; + const ECANCELED: number; + const ECHILD: number; + const ECONNABORTED: number; + const ECONNREFUSED: number; + const ECONNRESET: number; + const EDEADLK: number; + const EDESTADDRREQ: number; + const EDOM: number; + const EDQUOT: number; + const EEXIST: number; + const EFAULT: number; + const EFBIG: number; + const EHOSTUNREACH: number; + const EIDRM: number; + const EILSEQ: number; + const EINPROGRESS: number; + const EINTR: number; + const EINVAL: number; + const EIO: number; + const EISCONN: number; + const EISDIR: number; + const ELOOP: number; + const EMFILE: number; + const EMLINK: number; + const EMSGSIZE: number; + const EMULTIHOP: number; + const ENAMETOOLONG: number; + const ENETDOWN: number; + const ENETRESET: number; + const ENETUNREACH: number; + const ENFILE: number; + const ENOBUFS: number; + const ENODATA: number; + const ENODEV: number; + const ENOENT: number; + const ENOEXEC: number; + const ENOLCK: number; + const ENOLINK: number; + const ENOMEM: number; + const ENOMSG: number; + const ENOPROTOOPT: number; + const ENOSPC: number; + const ENOSR: number; + const ENOSTR: number; + const ENOSYS: number; + const ENOTCONN: number; + const ENOTDIR: number; + const ENOTEMPTY: number; + const ENOTSOCK: number; + const ENOTSUP: number; + const ENOTTY: number; + const ENXIO: number; + const EOPNOTSUPP: number; + const EOVERFLOW: number; + const EPERM: number; + const EPIPE: number; + const EPROTO: number; + const EPROTONOSUPPORT: number; + const EPROTOTYPE: number; + const ERANGE: number; + const EROFS: number; + const ESPIPE: number; + const ESRCH: number; + const ESTALE: number; + const ETIME: number; + const ETIMEDOUT: number; + const ETXTBSY: number; + const EWOULDBLOCK: number; + const EXDEV: number; + const WSAEINTR: number; + const WSAEBADF: number; + const WSAEACCES: number; + const WSAEFAULT: number; + const WSAEINVAL: number; + const WSAEMFILE: number; + const WSAEWOULDBLOCK: number; + const WSAEINPROGRESS: number; + const WSAEALREADY: number; + const WSAENOTSOCK: number; + const WSAEDESTADDRREQ: number; + const WSAEMSGSIZE: number; + const WSAEPROTOTYPE: number; + const WSAENOPROTOOPT: number; + const WSAEPROTONOSUPPORT: number; + const WSAESOCKTNOSUPPORT: number; + const WSAEOPNOTSUPP: number; + const WSAEPFNOSUPPORT: number; + const WSAEAFNOSUPPORT: number; + const WSAEADDRINUSE: number; + const WSAEADDRNOTAVAIL: number; + const WSAENETDOWN: number; + const WSAENETUNREACH: number; + const WSAENETRESET: number; + const WSAECONNABORTED: number; + const WSAECONNRESET: number; + const WSAENOBUFS: number; + const WSAEISCONN: number; + const WSAENOTCONN: number; + const WSAESHUTDOWN: number; + const WSAETOOMANYREFS: number; + const WSAETIMEDOUT: number; + const WSAECONNREFUSED: number; + const WSAELOOP: number; + const WSAENAMETOOLONG: number; + const WSAEHOSTDOWN: number; + const WSAEHOSTUNREACH: number; + const WSAENOTEMPTY: number; + const WSAEPROCLIM: number; + const WSAEUSERS: number; + const WSAEDQUOT: number; + const WSAESTALE: number; + const WSAEREMOTE: number; + const WSASYSNOTREADY: number; + const WSAVERNOTSUPPORTED: number; + const WSANOTINITIALISED: number; + const WSAEDISCON: number; + const WSAENOMORE: number; + const WSAECANCELLED: number; + const WSAEINVALIDPROCTABLE: number; + const WSAEINVALIDPROVIDER: number; + const WSAEPROVIDERFAILEDINIT: number; + const WSASYSCALLFAILURE: number; + const WSASERVICE_NOT_FOUND: number; + const WSATYPE_NOT_FOUND: number; + const WSA_E_NO_MORE: number; + const WSA_E_CANCELLED: number; + const WSAEREFUSED: number; + } + namespace dlopen { + const RTLD_LAZY: number; + const RTLD_NOW: number; + const RTLD_GLOBAL: number; + const RTLD_LOCAL: number; + const RTLD_DEEPBIND: number; + } + namespace priority { + const PRIORITY_LOW: number; + const PRIORITY_BELOW_NORMAL: number; + const PRIORITY_NORMAL: number; + const PRIORITY_ABOVE_NORMAL: number; + const PRIORITY_HIGH: number; + const PRIORITY_HIGHEST: number; + } + } + const devNull: string; + /** + * The operating system-specific end-of-line marker. + * * `\n` on POSIX + * * `\r\n` on Windows + */ + const EOL: string; + /** + * Returns the operating system CPU architecture for which the Node.js binary was + * compiled. Possible values are `'arm'`, `'arm64'`, `'ia32'`, `'loong64'`, `'mips'`, `'mipsel'`, `'ppc'`, `'ppc64'`, `'riscv64'`, `'s390'`, `'s390x'`, + * and `'x64'`. + * + * The return value is equivalent to [process.arch](https://nodejs.org/docs/latest-v20.x/api/process.html#processarch). + * @since v0.5.0 + */ + function arch(): string; + /** + * Returns a string identifying the kernel version. + * + * On POSIX systems, the operating system release is determined by calling [`uname(3)`](https://linux.die.net/man/3/uname). On Windows, `RtlGetVersion()` is used, and if it is not + * available, `GetVersionExW()` will be used. See [https://en.wikipedia.org/wiki/Uname#Examples](https://en.wikipedia.org/wiki/Uname#Examples) for more information. + * @since v13.11.0, v12.17.0 + */ + function version(): string; + /** + * Returns a string identifying the operating system platform for which + * the Node.js binary was compiled. The value is set at compile time. + * Possible values are `'aix'`, `'darwin'`, `'freebsd'`, `'linux'`, `'openbsd'`, `'sunos'`, and `'win32'`. + * + * The return value is equivalent to `process.platform`. + * + * The value `'android'` may also be returned if Node.js is built on the Android + * operating system. [Android support is experimental](https://github.com/nodejs/node/blob/HEAD/BUILDING.md#androidandroid-based-devices-eg-firefox-os). + * @since v0.5.0 + */ + function platform(): NodeJS.Platform; + /** + * Returns the machine type as a string, such as `arm`, `arm64`, `aarch64`, `mips`, `mips64`, `ppc64`, `ppc64le`, `s390`, `s390x`, `i386`, `i686`, `x86_64`. + * + * On POSIX systems, the machine type is determined by calling [`uname(3)`](https://linux.die.net/man/3/uname). On Windows, `RtlGetVersion()` is used, and if it is not + * available, `GetVersionExW()` will be used. See [https://en.wikipedia.org/wiki/Uname#Examples](https://en.wikipedia.org/wiki/Uname#Examples) for more information. + * @since v18.9.0, v16.18.0 + */ + function machine(): string; + /** + * Returns the operating system's default directory for temporary files as a + * string. + * @since v0.9.9 + */ + function tmpdir(): string; + /** + * Returns a string identifying the endianness of the CPU for which the Node.js + * binary was compiled. + * + * Possible values are `'BE'` for big endian and `'LE'` for little endian. + * @since v0.9.4 + */ + function endianness(): "BE" | "LE"; + /** + * Returns the scheduling priority for the process specified by `pid`. If `pid` is + * not provided or is `0`, the priority of the current process is returned. + * @since v10.10.0 + * @param [pid=0] The process ID to retrieve scheduling priority for. + */ + function getPriority(pid?: number): number; + /** + * Attempts to set the scheduling priority for the process specified by `pid`. If `pid` is not provided or is `0`, the process ID of the current process is used. + * + * The `priority` input must be an integer between `-20` (high priority) and `19` (low priority). Due to differences between Unix priority levels and Windows + * priority classes, `priority` is mapped to one of six priority constants in `os.constants.priority`. When retrieving a process priority level, this range + * mapping may cause the return value to be slightly different on Windows. To avoid + * confusion, set `priority` to one of the priority constants. + * + * On Windows, setting priority to `PRIORITY_HIGHEST` requires elevated user + * privileges. Otherwise the set priority will be silently reduced to `PRIORITY_HIGH`. + * @since v10.10.0 + * @param [pid=0] The process ID to set scheduling priority for. + * @param priority The scheduling priority to assign to the process. + */ + function setPriority(priority: number): void; + function setPriority(pid: number, priority: number): void; +} +declare module "node:os" { + export * from "os"; +} diff --git a/node_modules/@types/node/package.json b/node_modules/@types/node/package.json new file mode 100644 index 0000000..c1de485 --- /dev/null +++ b/node_modules/@types/node/package.json @@ -0,0 +1,217 @@ +{ + "name": "@types/node", + "version": "20.14.1", + "description": "TypeScript definitions for node", + "homepage": "https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/node", + "license": "MIT", + "contributors": [ + { + "name": "Microsoft TypeScript", + "githubUsername": "Microsoft", + "url": "https://github.com/Microsoft" + }, + { + "name": "Alberto Schiabel", + "githubUsername": "jkomyno", + "url": "https://github.com/jkomyno" + }, + { + "name": "Alvis HT Tang", + "githubUsername": "alvis", + "url": "https://github.com/alvis" + }, + { + "name": "Andrew Makarov", + "githubUsername": "r3nya", + "url": "https://github.com/r3nya" + }, + { + "name": "Benjamin Toueg", + "githubUsername": "btoueg", + "url": "https://github.com/btoueg" + }, + { + "name": "Chigozirim C.", + "githubUsername": "smac89", + "url": "https://github.com/smac89" + }, + { + "name": "David Junger", + "githubUsername": "touffy", + "url": "https://github.com/touffy" + }, + { + "name": "Deividas Bakanas", + "githubUsername": "DeividasBakanas", + "url": "https://github.com/DeividasBakanas" + }, + { + "name": "Eugene Y. Q. Shen", + "githubUsername": "eyqs", + "url": "https://github.com/eyqs" + }, + { + "name": "Hannes Magnusson", + "githubUsername": "Hannes-Magnusson-CK", + "url": "https://github.com/Hannes-Magnusson-CK" + }, + { + "name": "Huw", + "githubUsername": "hoo29", + "url": "https://github.com/hoo29" + }, + { + "name": "Kelvin Jin", + "githubUsername": "kjin", + "url": "https://github.com/kjin" + }, + { + "name": "Klaus Meinhardt", + "githubUsername": "ajafff", + "url": "https://github.com/ajafff" + }, + { + "name": "Lishude", + "githubUsername": "islishude", + "url": "https://github.com/islishude" + }, + { + "name": "Mariusz Wiktorczyk", + "githubUsername": "mwiktorczyk", + "url": "https://github.com/mwiktorczyk" + }, + { + "name": "Mohsen Azimi", + "githubUsername": "mohsen1", + "url": "https://github.com/mohsen1" + }, + { + "name": "Nikita Galkin", + "githubUsername": "galkin", + "url": "https://github.com/galkin" + }, + { + "name": "Parambir Singh", + "githubUsername": "parambirs", + "url": "https://github.com/parambirs" + }, + { + "name": "Sebastian Silbermann", + "githubUsername": "eps1lon", + "url": "https://github.com/eps1lon" + }, + { + "name": "Thomas den Hollander", + "githubUsername": "ThomasdenH", + "url": "https://github.com/ThomasdenH" + }, + { + "name": "Wilco Bakker", + "githubUsername": "WilcoBakker", + "url": "https://github.com/WilcoBakker" + }, + { + "name": "wwwy3y3", + "githubUsername": "wwwy3y3", + "url": "https://github.com/wwwy3y3" + }, + { + "name": "Samuel Ainsworth", + "githubUsername": "samuela", + "url": "https://github.com/samuela" + }, + { + "name": "Kyle Uehlein", + "githubUsername": "kuehlein", + "url": "https://github.com/kuehlein" + }, + { + "name": "Thanik Bhongbhibhat", + "githubUsername": "bhongy", + "url": "https://github.com/bhongy" + }, + { + "name": "Marcin Kopacz", + "githubUsername": "chyzwar", + "url": "https://github.com/chyzwar" + }, + { + "name": "Trivikram Kamat", + "githubUsername": "trivikr", + "url": "https://github.com/trivikr" + }, + { + "name": "Junxiao Shi", + "githubUsername": "yoursunny", + "url": "https://github.com/yoursunny" + }, + { + "name": "Ilia Baryshnikov", + "githubUsername": "qwelias", + "url": "https://github.com/qwelias" + }, + { + "name": "ExE Boss", + "githubUsername": "ExE-Boss", + "url": "https://github.com/ExE-Boss" + }, + { + "name": "Piotr Błażejewicz", + "githubUsername": "peterblazejewicz", + "url": "https://github.com/peterblazejewicz" + }, + { + "name": "Anna Henningsen", + "githubUsername": "addaleax", + "url": "https://github.com/addaleax" + }, + { + "name": "Victor Perin", + "githubUsername": "victorperin", + "url": "https://github.com/victorperin" + }, + { + "name": "Yongsheng Zhang", + "githubUsername": "ZYSzys", + "url": "https://github.com/ZYSzys" + }, + { + "name": "NodeJS Contributors", + "githubUsername": "NodeJS", + "url": "https://github.com/NodeJS" + }, + { + "name": "Linus Unnebäck", + "githubUsername": "LinusU", + "url": "https://github.com/LinusU" + }, + { + "name": "wafuwafu13", + "githubUsername": "wafuwafu13", + "url": "https://github.com/wafuwafu13" + }, + { + "name": "Matteo Collina", + "githubUsername": "mcollina", + "url": "https://github.com/mcollina" + }, + { + "name": "Dmitry Semigradsky", + "githubUsername": "Semigradsky", + "url": "https://github.com/Semigradsky" + } + ], + "main": "", + "types": "index.d.ts", + "repository": { + "type": "git", + "url": "https://github.com/DefinitelyTyped/DefinitelyTyped.git", + "directory": "types/node" + }, + "scripts": {}, + "dependencies": { + "undici-types": "~5.26.4" + }, + "typesPublisherContentHash": "455abc0b2a6d72d7977aaab5e4b453a7b36fbd90d6f0024b019fa63926420f36", + "typeScriptVersion": "4.7" +} \ No newline at end of file diff --git a/node_modules/@types/node/path.d.ts b/node_modules/@types/node/path.d.ts new file mode 100644 index 0000000..0c6b46d --- /dev/null +++ b/node_modules/@types/node/path.d.ts @@ -0,0 +1,191 @@ +declare module "path/posix" { + import path = require("path"); + export = path; +} +declare module "path/win32" { + import path = require("path"); + export = path; +} +/** + * The `node:path` module provides utilities for working with file and directory + * paths. It can be accessed using: + * + * ```js + * const path = require('node:path'); + * ``` + * @see [source](https://github.com/nodejs/node/blob/v20.13.1/lib/path.js) + */ +declare module "path" { + namespace path { + /** + * A parsed path object generated by path.parse() or consumed by path.format(). + */ + interface ParsedPath { + /** + * The root of the path such as '/' or 'c:\' + */ + root: string; + /** + * The full directory path such as '/home/user/dir' or 'c:\path\dir' + */ + dir: string; + /** + * The file name including extension (if any) such as 'index.html' + */ + base: string; + /** + * The file extension (if any) such as '.html' + */ + ext: string; + /** + * The file name without extension (if any) such as 'index' + */ + name: string; + } + interface FormatInputPathObject { + /** + * The root of the path such as '/' or 'c:\' + */ + root?: string | undefined; + /** + * The full directory path such as '/home/user/dir' or 'c:\path\dir' + */ + dir?: string | undefined; + /** + * The file name including extension (if any) such as 'index.html' + */ + base?: string | undefined; + /** + * The file extension (if any) such as '.html' + */ + ext?: string | undefined; + /** + * The file name without extension (if any) such as 'index' + */ + name?: string | undefined; + } + interface PlatformPath { + /** + * Normalize a string path, reducing '..' and '.' parts. + * When multiple slashes are found, they're replaced by a single one; when the path contains a trailing slash, it is preserved. On Windows backslashes are used. + * + * @param path string path to normalize. + * @throws {TypeError} if `path` is not a string. + */ + normalize(path: string): string; + /** + * Join all arguments together and normalize the resulting path. + * + * @param paths paths to join. + * @throws {TypeError} if any of the path segments is not a string. + */ + join(...paths: string[]): string; + /** + * The right-most parameter is considered {to}. Other parameters are considered an array of {from}. + * + * Starting from leftmost {from} parameter, resolves {to} to an absolute path. + * + * If {to} isn't already absolute, {from} arguments are prepended in right to left order, + * until an absolute path is found. If after using all {from} paths still no absolute path is found, + * the current working directory is used as well. The resulting path is normalized, + * and trailing slashes are removed unless the path gets resolved to the root directory. + * + * @param paths A sequence of paths or path segments. + * @throws {TypeError} if any of the arguments is not a string. + */ + resolve(...paths: string[]): string; + /** + * Determines whether {path} is an absolute path. An absolute path will always resolve to the same location, regardless of the working directory. + * + * If the given {path} is a zero-length string, `false` will be returned. + * + * @param path path to test. + * @throws {TypeError} if `path` is not a string. + */ + isAbsolute(path: string): boolean; + /** + * Solve the relative path from {from} to {to} based on the current working directory. + * At times we have two absolute paths, and we need to derive the relative path from one to the other. This is actually the reverse transform of path.resolve. + * + * @throws {TypeError} if either `from` or `to` is not a string. + */ + relative(from: string, to: string): string; + /** + * Return the directory name of a path. Similar to the Unix dirname command. + * + * @param path the path to evaluate. + * @throws {TypeError} if `path` is not a string. + */ + dirname(path: string): string; + /** + * Return the last portion of a path. Similar to the Unix basename command. + * Often used to extract the file name from a fully qualified path. + * + * @param path the path to evaluate. + * @param suffix optionally, an extension to remove from the result. + * @throws {TypeError} if `path` is not a string or if `ext` is given and is not a string. + */ + basename(path: string, suffix?: string): string; + /** + * Return the extension of the path, from the last '.' to end of string in the last portion of the path. + * If there is no '.' in the last portion of the path or the first character of it is '.', then it returns an empty string. + * + * @param path the path to evaluate. + * @throws {TypeError} if `path` is not a string. + */ + extname(path: string): string; + /** + * The platform-specific file separator. '\\' or '/'. + */ + readonly sep: "\\" | "/"; + /** + * The platform-specific file delimiter. ';' or ':'. + */ + readonly delimiter: ";" | ":"; + /** + * Returns an object from a path string - the opposite of format(). + * + * @param path path to evaluate. + * @throws {TypeError} if `path` is not a string. + */ + parse(path: string): ParsedPath; + /** + * Returns a path string from an object - the opposite of parse(). + * + * @param pathObject path to evaluate. + */ + format(pathObject: FormatInputPathObject): string; + /** + * On Windows systems only, returns an equivalent namespace-prefixed path for the given path. + * If path is not a string, path will be returned without modifications. + * This method is meaningful only on Windows system. + * On POSIX systems, the method is non-operational and always returns path without modifications. + */ + toNamespacedPath(path: string): string; + /** + * Posix specific pathing. + * Same as parent object on posix. + */ + readonly posix: PlatformPath; + /** + * Windows specific pathing. + * Same as parent object on windows + */ + readonly win32: PlatformPath; + } + } + const path: path.PlatformPath; + export = path; +} +declare module "node:path" { + import path = require("path"); + export = path; +} +declare module "node:path/posix" { + import path = require("path/posix"); + export = path; +} +declare module "node:path/win32" { + import path = require("path/win32"); + export = path; +} diff --git a/node_modules/@types/node/perf_hooks.d.ts b/node_modules/@types/node/perf_hooks.d.ts new file mode 100644 index 0000000..5ce7fca --- /dev/null +++ b/node_modules/@types/node/perf_hooks.d.ts @@ -0,0 +1,905 @@ +/** + * This module provides an implementation of a subset of the W3C [Web Performance APIs](https://w3c.github.io/perf-timing-primer/) as well as additional APIs for + * Node.js-specific performance measurements. + * + * Node.js supports the following [Web Performance APIs](https://w3c.github.io/perf-timing-primer/): + * + * * [High Resolution Time](https://www.w3.org/TR/hr-time-2) + * * [Performance Timeline](https://w3c.github.io/performance-timeline/) + * * [User Timing](https://www.w3.org/TR/user-timing/) + * * [Resource Timing](https://www.w3.org/TR/resource-timing-2/) + * + * ```js + * const { PerformanceObserver, performance } = require('node:perf_hooks'); + * + * const obs = new PerformanceObserver((items) => { + * console.log(items.getEntries()[0].duration); + * performance.clearMarks(); + * }); + * obs.observe({ type: 'measure' }); + * performance.measure('Start to Now'); + * + * performance.mark('A'); + * doSomeLongRunningProcess(() => { + * performance.measure('A to Now', 'A'); + * + * performance.mark('B'); + * performance.measure('A to B', 'A', 'B'); + * }); + * ``` + * @see [source](https://github.com/nodejs/node/blob/v20.13.1/lib/perf_hooks.js) + */ +declare module "perf_hooks" { + import { AsyncResource } from "node:async_hooks"; + type EntryType = "node" | "mark" | "measure" | "gc" | "function" | "http2" | "http" | "dns" | "net"; + interface NodeGCPerformanceDetail { + /** + * When `performanceEntry.entryType` is equal to 'gc', the `performance.kind` property identifies + * the type of garbage collection operation that occurred. + * See perf_hooks.constants for valid values. + */ + readonly kind?: number | undefined; + /** + * When `performanceEntry.entryType` is equal to 'gc', the `performance.flags` + * property contains additional information about garbage collection operation. + * See perf_hooks.constants for valid values. + */ + readonly flags?: number | undefined; + } + /** + * The constructor of this class is not exposed to users directly. + * @since v8.5.0 + */ + class PerformanceEntry { + protected constructor(); + /** + * The total number of milliseconds elapsed for this entry. This value will not + * be meaningful for all Performance Entry types. + * @since v8.5.0 + */ + readonly duration: number; + /** + * The name of the performance entry. + * @since v8.5.0 + */ + readonly name: string; + /** + * The high resolution millisecond timestamp marking the starting time of the + * Performance Entry. + * @since v8.5.0 + */ + readonly startTime: number; + /** + * The type of the performance entry. It may be one of: + * + * * `'node'` (Node.js only) + * * `'mark'` (available on the Web) + * * `'measure'` (available on the Web) + * * `'gc'` (Node.js only) + * * `'function'` (Node.js only) + * * `'http2'` (Node.js only) + * * `'http'` (Node.js only) + * @since v8.5.0 + */ + readonly entryType: EntryType; + /** + * Additional detail specific to the `entryType`. + * @since v16.0.0 + */ + readonly detail?: NodeGCPerformanceDetail | unknown | undefined; // TODO: Narrow this based on entry type. + toJSON(): any; + } + /** + * Exposes marks created via the `Performance.mark()` method. + * @since v18.2.0, v16.17.0 + */ + class PerformanceMark extends PerformanceEntry { + readonly duration: 0; + readonly entryType: "mark"; + } + /** + * Exposes measures created via the `Performance.measure()` method. + * + * The constructor of this class is not exposed to users directly. + * @since v18.2.0, v16.17.0 + */ + class PerformanceMeasure extends PerformanceEntry { + readonly entryType: "measure"; + } + /** + * _This property is an extension by Node.js. It is not available in Web browsers._ + * + * Provides timing details for Node.js itself. The constructor of this class + * is not exposed to users. + * @since v8.5.0 + */ + class PerformanceNodeTiming extends PerformanceEntry { + /** + * The high resolution millisecond timestamp at which the Node.js process + * completed bootstrapping. If bootstrapping has not yet finished, the property + * has the value of -1. + * @since v8.5.0 + */ + readonly bootstrapComplete: number; + /** + * The high resolution millisecond timestamp at which the Node.js environment was + * initialized. + * @since v8.5.0 + */ + readonly environment: number; + /** + * The high resolution millisecond timestamp of the amount of time the event loop + * has been idle within the event loop's event provider (e.g. `epoll_wait`). This + * does not take CPU usage into consideration. If the event loop has not yet + * started (e.g., in the first tick of the main script), the property has the + * value of 0. + * @since v14.10.0, v12.19.0 + */ + readonly idleTime: number; + /** + * The high resolution millisecond timestamp at which the Node.js event loop + * exited. If the event loop has not yet exited, the property has the value of -1\. + * It can only have a value of not -1 in a handler of the `'exit'` event. + * @since v8.5.0 + */ + readonly loopExit: number; + /** + * The high resolution millisecond timestamp at which the Node.js event loop + * started. If the event loop has not yet started (e.g., in the first tick of the + * main script), the property has the value of -1. + * @since v8.5.0 + */ + readonly loopStart: number; + /** + * The high resolution millisecond timestamp at which the Node.js process was initialized. + * @since v8.5.0 + */ + readonly nodeStart: number; + /** + * The high resolution millisecond timestamp at which the V8 platform was + * initialized. + * @since v8.5.0 + */ + readonly v8Start: number; + } + interface EventLoopUtilization { + idle: number; + active: number; + utilization: number; + } + /** + * @param utilization1 The result of a previous call to `eventLoopUtilization()`. + * @param utilization2 The result of a previous call to `eventLoopUtilization()` prior to `utilization1`. + */ + type EventLoopUtilityFunction = ( + utilization1?: EventLoopUtilization, + utilization2?: EventLoopUtilization, + ) => EventLoopUtilization; + interface MarkOptions { + /** + * Additional optional detail to include with the mark. + */ + detail?: unknown | undefined; + /** + * An optional timestamp to be used as the mark time. + * @default `performance.now()` + */ + startTime?: number | undefined; + } + interface MeasureOptions { + /** + * Additional optional detail to include with the mark. + */ + detail?: unknown | undefined; + /** + * Duration between start and end times. + */ + duration?: number | undefined; + /** + * Timestamp to be used as the end time, or a string identifying a previously recorded mark. + */ + end?: number | string | undefined; + /** + * Timestamp to be used as the start time, or a string identifying a previously recorded mark. + */ + start?: number | string | undefined; + } + interface TimerifyOptions { + /** + * A histogram object created using `perf_hooks.createHistogram()` that will record runtime + * durations in nanoseconds. + */ + histogram?: RecordableHistogram | undefined; + } + interface Performance { + /** + * If `name` is not provided, removes all `PerformanceMark` objects from the Performance Timeline. + * If `name` is provided, removes only the named mark. + * @since v8.5.0 + */ + clearMarks(name?: string): void; + /** + * If `name` is not provided, removes all `PerformanceMeasure` objects from the Performance Timeline. + * If `name` is provided, removes only the named measure. + * @since v16.7.0 + */ + clearMeasures(name?: string): void; + /** + * If `name` is not provided, removes all `PerformanceResourceTiming` objects from the Resource Timeline. + * If `name` is provided, removes only the named resource. + * @since v18.2.0, v16.17.0 + */ + clearResourceTimings(name?: string): void; + /** + * eventLoopUtilization is similar to CPU utilization except that it is calculated using high precision wall-clock time. + * It represents the percentage of time the event loop has spent outside the event loop's event provider (e.g. epoll_wait). + * No other CPU idle time is taken into consideration. + */ + eventLoopUtilization: EventLoopUtilityFunction; + /** + * Returns a list of `PerformanceEntry` objects in chronological order with respect to `performanceEntry.startTime`. + * If you are only interested in performance entries of certain types or that have certain names, see + * `performance.getEntriesByType()` and `performance.getEntriesByName()`. + * @since v16.7.0 + */ + getEntries(): PerformanceEntry[]; + /** + * Returns a list of `PerformanceEntry` objects in chronological order with respect to `performanceEntry.startTime` + * whose `performanceEntry.name` is equal to `name`, and optionally, whose `performanceEntry.entryType` is equal to `type`. + * @param name + * @param type + * @since v16.7.0 + */ + getEntriesByName(name: string, type?: EntryType): PerformanceEntry[]; + /** + * Returns a list of `PerformanceEntry` objects in chronological order with respect to `performanceEntry.startTime` + * whose `performanceEntry.entryType` is equal to `type`. + * @param type + * @since v16.7.0 + */ + getEntriesByType(type: EntryType): PerformanceEntry[]; + /** + * Creates a new `PerformanceMark` entry in the Performance Timeline. + * A `PerformanceMark` is a subclass of `PerformanceEntry` whose `performanceEntry.entryType` is always `'mark'`, + * and whose `performanceEntry.duration` is always `0`. + * Performance marks are used to mark specific significant moments in the Performance Timeline. + * + * The created `PerformanceMark` entry is put in the global Performance Timeline and can be queried with + * `performance.getEntries`, `performance.getEntriesByName`, and `performance.getEntriesByType`. When the observation is + * performed, the entries should be cleared from the global Performance Timeline manually with `performance.clearMarks`. + * @param name + */ + mark(name: string, options?: MarkOptions): PerformanceMark; + /** + * Creates a new PerformanceMeasure entry in the Performance Timeline. + * A PerformanceMeasure is a subclass of PerformanceEntry whose performanceEntry.entryType is always 'measure', + * and whose performanceEntry.duration measures the number of milliseconds elapsed since startMark and endMark. + * + * The startMark argument may identify any existing PerformanceMark in the the Performance Timeline, or may identify + * any of the timestamp properties provided by the PerformanceNodeTiming class. If the named startMark does not exist, + * then startMark is set to timeOrigin by default. + * + * The endMark argument must identify any existing PerformanceMark in the the Performance Timeline or any of the timestamp + * properties provided by the PerformanceNodeTiming class. If the named endMark does not exist, an error will be thrown. + * @param name + * @param startMark + * @param endMark + * @return The PerformanceMeasure entry that was created + */ + measure(name: string, startMark?: string, endMark?: string): PerformanceMeasure; + measure(name: string, options: MeasureOptions): PerformanceMeasure; + /** + * _This property is an extension by Node.js. It is not available in Web browsers._ + * + * An instance of the `PerformanceNodeTiming` class that provides performance metrics for specific Node.js operational milestones. + * @since v8.5.0 + */ + readonly nodeTiming: PerformanceNodeTiming; + /** + * Returns the current high resolution millisecond timestamp, where 0 represents the start of the current `node` process. + * @since v8.5.0 + */ + now(): number; + /** + * Sets the global performance resource timing buffer size to the specified number of "resource" type performance entry objects. + * + * By default the max buffer size is set to 250. + * @since v18.8.0 + */ + setResourceTimingBufferSize(maxSize: number): void; + /** + * The [`timeOrigin`](https://w3c.github.io/hr-time/#dom-performance-timeorigin) specifies the high resolution millisecond timestamp + * at which the current `node` process began, measured in Unix time. + * @since v8.5.0 + */ + readonly timeOrigin: number; + /** + * _This property is an extension by Node.js. It is not available in Web browsers._ + * + * Wraps a function within a new function that measures the running time of the wrapped function. + * A `PerformanceObserver` must be subscribed to the `'function'` event type in order for the timing details to be accessed. + * + * ```js + * const { + * performance, + * PerformanceObserver, + * } = require('node:perf_hooks'); + * + * function someFunction() { + * console.log('hello world'); + * } + * + * const wrapped = performance.timerify(someFunction); + * + * const obs = new PerformanceObserver((list) => { + * console.log(list.getEntries()[0].duration); + * + * performance.clearMarks(); + * performance.clearMeasures(); + * obs.disconnect(); + * }); + * obs.observe({ entryTypes: ['function'] }); + * + * // A performance timeline entry will be created + * wrapped(); + * ``` + * + * If the wrapped function returns a promise, a finally handler will be attached to the promise and the duration will be reported + * once the finally handler is invoked. + * @param fn + */ + timerify any>(fn: T, options?: TimerifyOptions): T; + /** + * An object which is JSON representation of the performance object. It is similar to + * [`window.performance.toJSON`](https://developer.mozilla.org/en-US/docs/Web/API/Performance/toJSON) in browsers. + * @since v16.1.0 + */ + toJSON(): any; + } + class PerformanceObserverEntryList { + /** + * Returns a list of `PerformanceEntry` objects in chronological order + * with respect to `performanceEntry.startTime`. + * + * ```js + * const { + * performance, + * PerformanceObserver, + * } = require('node:perf_hooks'); + * + * const obs = new PerformanceObserver((perfObserverList, observer) => { + * console.log(perfObserverList.getEntries()); + * + * * [ + * * PerformanceEntry { + * * name: 'test', + * * entryType: 'mark', + * * startTime: 81.465639, + * * duration: 0, + * * detail: null + * * }, + * * PerformanceEntry { + * * name: 'meow', + * * entryType: 'mark', + * * startTime: 81.860064, + * * duration: 0, + * * detail: null + * * } + * * ] + * + * performance.clearMarks(); + * performance.clearMeasures(); + * observer.disconnect(); + * }); + * obs.observe({ type: 'mark' }); + * + * performance.mark('test'); + * performance.mark('meow'); + * ``` + * @since v8.5.0 + */ + getEntries(): PerformanceEntry[]; + /** + * Returns a list of `PerformanceEntry` objects in chronological order + * with respect to `performanceEntry.startTime` whose `performanceEntry.name` is + * equal to `name`, and optionally, whose `performanceEntry.entryType` is equal to`type`. + * + * ```js + * const { + * performance, + * PerformanceObserver, + * } = require('node:perf_hooks'); + * + * const obs = new PerformanceObserver((perfObserverList, observer) => { + * console.log(perfObserverList.getEntriesByName('meow')); + * + * * [ + * * PerformanceEntry { + * * name: 'meow', + * * entryType: 'mark', + * * startTime: 98.545991, + * * duration: 0, + * * detail: null + * * } + * * ] + * + * console.log(perfObserverList.getEntriesByName('nope')); // [] + * + * console.log(perfObserverList.getEntriesByName('test', 'mark')); + * + * * [ + * * PerformanceEntry { + * * name: 'test', + * * entryType: 'mark', + * * startTime: 63.518931, + * * duration: 0, + * * detail: null + * * } + * * ] + * + * console.log(perfObserverList.getEntriesByName('test', 'measure')); // [] + * + * performance.clearMarks(); + * performance.clearMeasures(); + * observer.disconnect(); + * }); + * obs.observe({ entryTypes: ['mark', 'measure'] }); + * + * performance.mark('test'); + * performance.mark('meow'); + * ``` + * @since v8.5.0 + */ + getEntriesByName(name: string, type?: EntryType): PerformanceEntry[]; + /** + * Returns a list of `PerformanceEntry` objects in chronological order + * with respect to `performanceEntry.startTime` whose `performanceEntry.entryType` is equal to `type`. + * + * ```js + * const { + * performance, + * PerformanceObserver, + * } = require('node:perf_hooks'); + * + * const obs = new PerformanceObserver((perfObserverList, observer) => { + * console.log(perfObserverList.getEntriesByType('mark')); + * + * * [ + * * PerformanceEntry { + * * name: 'test', + * * entryType: 'mark', + * * startTime: 55.897834, + * * duration: 0, + * * detail: null + * * }, + * * PerformanceEntry { + * * name: 'meow', + * * entryType: 'mark', + * * startTime: 56.350146, + * * duration: 0, + * * detail: null + * * } + * * ] + * + * performance.clearMarks(); + * performance.clearMeasures(); + * observer.disconnect(); + * }); + * obs.observe({ type: 'mark' }); + * + * performance.mark('test'); + * performance.mark('meow'); + * ``` + * @since v8.5.0 + */ + getEntriesByType(type: EntryType): PerformanceEntry[]; + } + type PerformanceObserverCallback = (list: PerformanceObserverEntryList, observer: PerformanceObserver) => void; + /** + * @since v8.5.0 + */ + class PerformanceObserver extends AsyncResource { + constructor(callback: PerformanceObserverCallback); + /** + * Disconnects the `PerformanceObserver` instance from all notifications. + * @since v8.5.0 + */ + disconnect(): void; + /** + * Subscribes the `PerformanceObserver` instance to notifications of new `PerformanceEntry` instances identified either by `options.entryTypes` or `options.type`: + * + * ```js + * const { + * performance, + * PerformanceObserver, + * } = require('node:perf_hooks'); + * + * const obs = new PerformanceObserver((list, observer) => { + * // Called once asynchronously. `list` contains three items. + * }); + * obs.observe({ type: 'mark' }); + * + * for (let n = 0; n < 3; n++) + * performance.mark(`test${n}`); + * ``` + * @since v8.5.0 + */ + observe( + options: + | { + entryTypes: readonly EntryType[]; + buffered?: boolean | undefined; + } + | { + type: EntryType; + buffered?: boolean | undefined; + }, + ): void; + } + /** + * Provides detailed network timing data regarding the loading of an application's resources. + * + * The constructor of this class is not exposed to users directly. + * @since v18.2.0, v16.17.0 + */ + class PerformanceResourceTiming extends PerformanceEntry { + protected constructor(); + /** + * The high resolution millisecond timestamp at immediately before dispatching the `fetch` + * request. If the resource is not intercepted by a worker the property will always return 0. + * @since v18.2.0, v16.17.0 + */ + readonly workerStart: number; + /** + * The high resolution millisecond timestamp that represents the start time of the fetch which + * initiates the redirect. + * @since v18.2.0, v16.17.0 + */ + readonly redirectStart: number; + /** + * The high resolution millisecond timestamp that will be created immediately after receiving + * the last byte of the response of the last redirect. + * @since v18.2.0, v16.17.0 + */ + readonly redirectEnd: number; + /** + * The high resolution millisecond timestamp immediately before the Node.js starts to fetch the resource. + * @since v18.2.0, v16.17.0 + */ + readonly fetchStart: number; + /** + * The high resolution millisecond timestamp immediately before the Node.js starts the domain name lookup + * for the resource. + * @since v18.2.0, v16.17.0 + */ + readonly domainLookupStart: number; + /** + * The high resolution millisecond timestamp representing the time immediately after the Node.js finished + * the domain name lookup for the resource. + * @since v18.2.0, v16.17.0 + */ + readonly domainLookupEnd: number; + /** + * The high resolution millisecond timestamp representing the time immediately before Node.js starts to + * establish the connection to the server to retrieve the resource. + * @since v18.2.0, v16.17.0 + */ + readonly connectStart: number; + /** + * The high resolution millisecond timestamp representing the time immediately after Node.js finishes + * establishing the connection to the server to retrieve the resource. + * @since v18.2.0, v16.17.0 + */ + readonly connectEnd: number; + /** + * The high resolution millisecond timestamp representing the time immediately before Node.js starts the + * handshake process to secure the current connection. + * @since v18.2.0, v16.17.0 + */ + readonly secureConnectionStart: number; + /** + * The high resolution millisecond timestamp representing the time immediately before Node.js receives the + * first byte of the response from the server. + * @since v18.2.0, v16.17.0 + */ + readonly requestStart: number; + /** + * The high resolution millisecond timestamp representing the time immediately after Node.js receives the + * last byte of the resource or immediately before the transport connection is closed, whichever comes first. + * @since v18.2.0, v16.17.0 + */ + readonly responseEnd: number; + /** + * A number representing the size (in octets) of the fetched resource. The size includes the response header + * fields plus the response payload body. + * @since v18.2.0, v16.17.0 + */ + readonly transferSize: number; + /** + * A number representing the size (in octets) received from the fetch (HTTP or cache), of the payload body, before + * removing any applied content-codings. + * @since v18.2.0, v16.17.0 + */ + readonly encodedBodySize: number; + /** + * A number representing the size (in octets) received from the fetch (HTTP or cache), of the message body, after + * removing any applied content-codings. + * @since v18.2.0, v16.17.0 + */ + readonly decodedBodySize: number; + /** + * Returns a `object` that is the JSON representation of the `PerformanceResourceTiming` object + * @since v18.2.0, v16.17.0 + */ + toJSON(): any; + } + namespace constants { + const NODE_PERFORMANCE_GC_MAJOR: number; + const NODE_PERFORMANCE_GC_MINOR: number; + const NODE_PERFORMANCE_GC_INCREMENTAL: number; + const NODE_PERFORMANCE_GC_WEAKCB: number; + const NODE_PERFORMANCE_GC_FLAGS_NO: number; + const NODE_PERFORMANCE_GC_FLAGS_CONSTRUCT_RETAINED: number; + const NODE_PERFORMANCE_GC_FLAGS_FORCED: number; + const NODE_PERFORMANCE_GC_FLAGS_SYNCHRONOUS_PHANTOM_PROCESSING: number; + const NODE_PERFORMANCE_GC_FLAGS_ALL_AVAILABLE_GARBAGE: number; + const NODE_PERFORMANCE_GC_FLAGS_ALL_EXTERNAL_MEMORY: number; + const NODE_PERFORMANCE_GC_FLAGS_SCHEDULE_IDLE: number; + } + const performance: Performance; + interface EventLoopMonitorOptions { + /** + * The sampling rate in milliseconds. + * Must be greater than zero. + * @default 10 + */ + resolution?: number | undefined; + } + interface Histogram { + /** + * The number of samples recorded by the histogram. + * @since v17.4.0, v16.14.0 + */ + readonly count: number; + /** + * The number of samples recorded by the histogram. + * v17.4.0, v16.14.0 + */ + readonly countBigInt: bigint; + /** + * The number of times the event loop delay exceeded the maximum 1 hour event + * loop delay threshold. + * @since v11.10.0 + */ + readonly exceeds: number; + /** + * The number of times the event loop delay exceeded the maximum 1 hour event loop delay threshold. + * @since v17.4.0, v16.14.0 + */ + readonly exceedsBigInt: bigint; + /** + * The maximum recorded event loop delay. + * @since v11.10.0 + */ + readonly max: number; + /** + * The maximum recorded event loop delay. + * v17.4.0, v16.14.0 + */ + readonly maxBigInt: number; + /** + * The mean of the recorded event loop delays. + * @since v11.10.0 + */ + readonly mean: number; + /** + * The minimum recorded event loop delay. + * @since v11.10.0 + */ + readonly min: number; + /** + * The minimum recorded event loop delay. + * v17.4.0, v16.14.0 + */ + readonly minBigInt: bigint; + /** + * Returns the value at the given percentile. + * @since v11.10.0 + * @param percentile A percentile value in the range (0, 100]. + */ + percentile(percentile: number): number; + /** + * Returns the value at the given percentile. + * @since v17.4.0, v16.14.0 + * @param percentile A percentile value in the range (0, 100]. + */ + percentileBigInt(percentile: number): bigint; + /** + * Returns a `Map` object detailing the accumulated percentile distribution. + * @since v11.10.0 + */ + readonly percentiles: Map; + /** + * Returns a `Map` object detailing the accumulated percentile distribution. + * @since v17.4.0, v16.14.0 + */ + readonly percentilesBigInt: Map; + /** + * Resets the collected histogram data. + * @since v11.10.0 + */ + reset(): void; + /** + * The standard deviation of the recorded event loop delays. + * @since v11.10.0 + */ + readonly stddev: number; + } + interface IntervalHistogram extends Histogram { + /** + * Enables the update interval timer. Returns `true` if the timer was + * started, `false` if it was already started. + * @since v11.10.0 + */ + enable(): boolean; + /** + * Disables the update interval timer. Returns `true` if the timer was + * stopped, `false` if it was already stopped. + * @since v11.10.0 + */ + disable(): boolean; + } + interface RecordableHistogram extends Histogram { + /** + * @since v15.9.0, v14.18.0 + * @param val The amount to record in the histogram. + */ + record(val: number | bigint): void; + /** + * Calculates the amount of time (in nanoseconds) that has passed since the + * previous call to `recordDelta()` and records that amount in the histogram. + * @since v15.9.0, v14.18.0 + */ + recordDelta(): void; + /** + * Adds the values from `other` to this histogram. + * @since v17.4.0, v16.14.0 + */ + add(other: RecordableHistogram): void; + } + /** + * _This property is an extension by Node.js. It is not available in Web browsers._ + * + * Creates an `IntervalHistogram` object that samples and reports the event loop + * delay over time. The delays will be reported in nanoseconds. + * + * Using a timer to detect approximate event loop delay works because the + * execution of timers is tied specifically to the lifecycle of the libuv + * event loop. That is, a delay in the loop will cause a delay in the execution + * of the timer, and those delays are specifically what this API is intended to + * detect. + * + * ```js + * const { monitorEventLoopDelay } = require('node:perf_hooks'); + * const h = monitorEventLoopDelay({ resolution: 20 }); + * h.enable(); + * // Do something. + * h.disable(); + * console.log(h.min); + * console.log(h.max); + * console.log(h.mean); + * console.log(h.stddev); + * console.log(h.percentiles); + * console.log(h.percentile(50)); + * console.log(h.percentile(99)); + * ``` + * @since v11.10.0 + */ + function monitorEventLoopDelay(options?: EventLoopMonitorOptions): IntervalHistogram; + interface CreateHistogramOptions { + /** + * The minimum recordable value. Must be an integer value greater than 0. + * @default 1 + */ + min?: number | bigint | undefined; + /** + * The maximum recordable value. Must be an integer value greater than min. + * @default Number.MAX_SAFE_INTEGER + */ + max?: number | bigint | undefined; + /** + * The number of accuracy digits. Must be a number between 1 and 5. + * @default 3 + */ + figures?: number | undefined; + } + /** + * Returns a `RecordableHistogram`. + * @since v15.9.0, v14.18.0 + */ + function createHistogram(options?: CreateHistogramOptions): RecordableHistogram; + import { + performance as _performance, + PerformanceEntry as _PerformanceEntry, + PerformanceMark as _PerformanceMark, + PerformanceMeasure as _PerformanceMeasure, + PerformanceObserver as _PerformanceObserver, + PerformanceObserverEntryList as _PerformanceObserverEntryList, + PerformanceResourceTiming as _PerformanceResourceTiming, + } from "perf_hooks"; + global { + /** + * `PerformanceEntry` is a global reference for `require('node:perf_hooks').PerformanceEntry` + * @see https://nodejs.org/docs/latest-v20.x/api/globals.html#performanceentry + * @since v19.0.0 + */ + var PerformanceEntry: typeof globalThis extends { + onmessage: any; + PerformanceEntry: infer T; + } ? T + : typeof _PerformanceEntry; + /** + * `PerformanceMark` is a global reference for `require('node:perf_hooks').PerformanceMark` + * @see https://nodejs.org/docs/latest-v20.x/api/globals.html#performancemark + * @since v19.0.0 + */ + var PerformanceMark: typeof globalThis extends { + onmessage: any; + PerformanceMark: infer T; + } ? T + : typeof _PerformanceMark; + /** + * `PerformanceMeasure` is a global reference for `require('node:perf_hooks').PerformanceMeasure` + * @see https://nodejs.org/docs/latest-v20.x/api/globals.html#performancemeasure + * @since v19.0.0 + */ + var PerformanceMeasure: typeof globalThis extends { + onmessage: any; + PerformanceMeasure: infer T; + } ? T + : typeof _PerformanceMeasure; + /** + * `PerformanceObserver` is a global reference for `require('node:perf_hooks').PerformanceObserver` + * @see https://nodejs.org/docs/latest-v20.x/api/globals.html#performanceobserver + * @since v19.0.0 + */ + var PerformanceObserver: typeof globalThis extends { + onmessage: any; + PerformanceObserver: infer T; + } ? T + : typeof _PerformanceObserver; + /** + * `PerformanceObserverEntryList` is a global reference for `require('node:perf_hooks').PerformanceObserverEntryList` + * @see https://nodejs.org/docs/latest-v20.x/api/globals.html#performanceobserverentrylist + * @since v19.0.0 + */ + var PerformanceObserverEntryList: typeof globalThis extends { + onmessage: any; + PerformanceObserverEntryList: infer T; + } ? T + : typeof _PerformanceObserverEntryList; + /** + * `PerformanceResourceTiming` is a global reference for `require('node:perf_hooks').PerformanceResourceTiming` + * @see https://nodejs.org/docs/latest-v20.x/api/globals.html#performanceresourcetiming + * @since v19.0.0 + */ + var PerformanceResourceTiming: typeof globalThis extends { + onmessage: any; + PerformanceResourceTiming: infer T; + } ? T + : typeof _PerformanceResourceTiming; + /** + * `performance` is a global reference for `require('node:perf_hooks').performance` + * @see https://nodejs.org/docs/latest-v20.x/api/globals.html#performance + * @since v16.0.0 + */ + var performance: typeof globalThis extends { + onmessage: any; + performance: infer T; + } ? T + : typeof _performance; + } +} +declare module "node:perf_hooks" { + export * from "perf_hooks"; +} diff --git a/node_modules/@types/node/process.d.ts b/node_modules/@types/node/process.d.ts new file mode 100644 index 0000000..5f84863 --- /dev/null +++ b/node_modules/@types/node/process.d.ts @@ -0,0 +1,1754 @@ +declare module "process" { + import * as net from "node:net"; + import * as os from "node:os"; + import * as tty from "node:tty"; + import { Worker } from "node:worker_threads"; + global { + var process: NodeJS.Process; + namespace NodeJS { + // this namespace merge is here because these are specifically used + // as the type for process.stdin, process.stdout, and process.stderr. + // they can't live in tty.d.ts because we need to disambiguate the imported name. + interface ReadStream extends tty.ReadStream {} + interface WriteStream extends tty.WriteStream {} + interface MemoryUsageFn { + /** + * The `process.memoryUsage()` method iterate over each page to gather informations about memory + * usage which can be slow depending on the program memory allocations. + */ + (): MemoryUsage; + /** + * method returns an integer representing the Resident Set Size (RSS) in bytes. + */ + rss(): number; + } + interface MemoryUsage { + /** + * Resident Set Size, is the amount of space occupied in the main memory device (that is a subset of the total allocated memory) for the + * process, including all C++ and JavaScript objects and code. + */ + rss: number; + /** + * Refers to V8's memory usage. + */ + heapTotal: number; + /** + * Refers to V8's memory usage. + */ + heapUsed: number; + external: number; + /** + * Refers to memory allocated for `ArrayBuffer`s and `SharedArrayBuffer`s, including all Node.js Buffers. This is also included + * in the external value. When Node.js is used as an embedded library, this value may be `0` because allocations for `ArrayBuffer`s + * may not be tracked in that case. + */ + arrayBuffers: number; + } + interface CpuUsage { + user: number; + system: number; + } + interface ProcessRelease { + name: string; + sourceUrl?: string | undefined; + headersUrl?: string | undefined; + libUrl?: string | undefined; + lts?: string | undefined; + } + interface ProcessVersions extends Dict { + http_parser: string; + node: string; + v8: string; + ares: string; + uv: string; + zlib: string; + modules: string; + openssl: string; + } + type Platform = + | "aix" + | "android" + | "darwin" + | "freebsd" + | "haiku" + | "linux" + | "openbsd" + | "sunos" + | "win32" + | "cygwin" + | "netbsd"; + type Architecture = + | "arm" + | "arm64" + | "ia32" + | "loong64" + | "mips" + | "mipsel" + | "ppc" + | "ppc64" + | "riscv64" + | "s390" + | "s390x" + | "x64"; + type Signals = + | "SIGABRT" + | "SIGALRM" + | "SIGBUS" + | "SIGCHLD" + | "SIGCONT" + | "SIGFPE" + | "SIGHUP" + | "SIGILL" + | "SIGINT" + | "SIGIO" + | "SIGIOT" + | "SIGKILL" + | "SIGPIPE" + | "SIGPOLL" + | "SIGPROF" + | "SIGPWR" + | "SIGQUIT" + | "SIGSEGV" + | "SIGSTKFLT" + | "SIGSTOP" + | "SIGSYS" + | "SIGTERM" + | "SIGTRAP" + | "SIGTSTP" + | "SIGTTIN" + | "SIGTTOU" + | "SIGUNUSED" + | "SIGURG" + | "SIGUSR1" + | "SIGUSR2" + | "SIGVTALRM" + | "SIGWINCH" + | "SIGXCPU" + | "SIGXFSZ" + | "SIGBREAK" + | "SIGLOST" + | "SIGINFO"; + type UncaughtExceptionOrigin = "uncaughtException" | "unhandledRejection"; + type MultipleResolveType = "resolve" | "reject"; + type BeforeExitListener = (code: number) => void; + type DisconnectListener = () => void; + type ExitListener = (code: number) => void; + type RejectionHandledListener = (promise: Promise) => void; + type UncaughtExceptionListener = (error: Error, origin: UncaughtExceptionOrigin) => void; + /** + * Most of the time the unhandledRejection will be an Error, but this should not be relied upon + * as *anything* can be thrown/rejected, it is therefore unsafe to assume that the value is an Error. + */ + type UnhandledRejectionListener = (reason: unknown, promise: Promise) => void; + type WarningListener = (warning: Error) => void; + type MessageListener = (message: unknown, sendHandle: unknown) => void; + type SignalsListener = (signal: Signals) => void; + type MultipleResolveListener = ( + type: MultipleResolveType, + promise: Promise, + value: unknown, + ) => void; + type WorkerListener = (worker: Worker) => void; + interface Socket extends ReadWriteStream { + isTTY?: true | undefined; + } + // Alias for compatibility + interface ProcessEnv extends Dict { + /** + * Can be used to change the default timezone at runtime + */ + TZ?: string; + } + interface HRTime { + (time?: [number, number]): [number, number]; + /** + * The `bigint` version of the `{@link hrtime()}` method returning the current high-resolution real time in nanoseconds as a `bigint`. + * + * Unlike `{@link hrtime()}`, it does not support an additional time argument since the difference can just be computed directly by subtraction of the two `bigint`s. + * ```js + * import { hrtime } from 'node:process'; + * + * const start = hrtime.bigint(); + * // 191051479007711n + * + * setTimeout(() => { + * const end = hrtime.bigint(); + * // 191052633396993n + * + * console.log(`Benchmark took ${end - start} nanoseconds`); + * // Benchmark took 1154389282 nanoseconds + * }, 1000); + * ``` + */ + bigint(): bigint; + } + interface ProcessPermission { + /** + * Verifies that the process is able to access the given scope and reference. + * If no reference is provided, a global scope is assumed, for instance, `process.permission.has('fs.read')` + * will check if the process has ALL file system read permissions. + * + * The reference has a meaning based on the provided scope. For example, the reference when the scope is File System means files and folders. + * + * The available scopes are: + * + * * `fs` - All File System + * * `fs.read` - File System read operations + * * `fs.write` - File System write operations + * * `child` - Child process spawning operations + * * `worker` - Worker thread spawning operation + * + * ```js + * // Check if the process has permission to read the README file + * process.permission.has('fs.read', './README.md'); + * // Check if the process has read permission operations + * process.permission.has('fs.read'); + * ``` + * @since v20.0.0 + */ + has(scope: string, reference?: string): boolean; + } + interface ProcessReport { + /** + * Directory where the report is written. + * working directory of the Node.js process. + * @default '' indicating that reports are written to the current + */ + directory: string; + /** + * Filename where the report is written. + * The default value is the empty string. + * @default '' the output filename will be comprised of a timestamp, + * PID, and sequence number. + */ + filename: string; + /** + * Returns a JSON-formatted diagnostic report for the running process. + * The report's JavaScript stack trace is taken from err, if present. + */ + getReport(err?: Error): string; + /** + * If true, a diagnostic report is generated on fatal errors, + * such as out of memory errors or failed C++ assertions. + * @default false + */ + reportOnFatalError: boolean; + /** + * If true, a diagnostic report is generated when the process + * receives the signal specified by process.report.signal. + * @default false + */ + reportOnSignal: boolean; + /** + * If true, a diagnostic report is generated on uncaught exception. + * @default false + */ + reportOnUncaughtException: boolean; + /** + * The signal used to trigger the creation of a diagnostic report. + * @default 'SIGUSR2' + */ + signal: Signals; + /** + * Writes a diagnostic report to a file. If filename is not provided, the default filename + * includes the date, time, PID, and a sequence number. + * The report's JavaScript stack trace is taken from err, if present. + * + * @param fileName Name of the file where the report is written. + * This should be a relative path, that will be appended to the directory specified in + * `process.report.directory`, or the current working directory of the Node.js process, + * if unspecified. + * @param error A custom error used for reporting the JavaScript stack. + * @return Filename of the generated report. + */ + writeReport(fileName?: string): string; + writeReport(error?: Error): string; + writeReport(fileName?: string, err?: Error): string; + } + interface ResourceUsage { + fsRead: number; + fsWrite: number; + involuntaryContextSwitches: number; + ipcReceived: number; + ipcSent: number; + majorPageFault: number; + maxRSS: number; + minorPageFault: number; + sharedMemorySize: number; + signalsCount: number; + swappedOut: number; + systemCPUTime: number; + unsharedDataSize: number; + unsharedStackSize: number; + userCPUTime: number; + voluntaryContextSwitches: number; + } + interface EmitWarningOptions { + /** + * When `warning` is a `string`, `type` is the name to use for the _type_ of warning being emitted. + * + * @default 'Warning' + */ + type?: string | undefined; + /** + * A unique identifier for the warning instance being emitted. + */ + code?: string | undefined; + /** + * When `warning` is a `string`, `ctor` is an optional function used to limit the generated stack trace. + * + * @default process.emitWarning + */ + ctor?: Function | undefined; + /** + * Additional text to include with the error. + */ + detail?: string | undefined; + } + interface ProcessConfig { + readonly target_defaults: { + readonly cflags: any[]; + readonly default_configuration: string; + readonly defines: string[]; + readonly include_dirs: string[]; + readonly libraries: string[]; + }; + readonly variables: { + readonly clang: number; + readonly host_arch: string; + readonly node_install_npm: boolean; + readonly node_install_waf: boolean; + readonly node_prefix: string; + readonly node_shared_openssl: boolean; + readonly node_shared_v8: boolean; + readonly node_shared_zlib: boolean; + readonly node_use_dtrace: boolean; + readonly node_use_etw: boolean; + readonly node_use_openssl: boolean; + readonly target_arch: string; + readonly v8_no_strict_aliasing: number; + readonly v8_use_snapshot: boolean; + readonly visibility: string; + }; + } + interface Process extends EventEmitter { + /** + * The `process.stdout` property returns a stream connected to`stdout` (fd `1`). It is a `net.Socket` (which is a `Duplex` stream) unless fd `1` refers to a file, in which case it is + * a `Writable` stream. + * + * For example, to copy `process.stdin` to `process.stdout`: + * + * ```js + * import { stdin, stdout } from 'node:process'; + * + * stdin.pipe(stdout); + * ``` + * + * `process.stdout` differs from other Node.js streams in important ways. See `note on process I/O` for more information. + */ + stdout: WriteStream & { + fd: 1; + }; + /** + * The `process.stderr` property returns a stream connected to`stderr` (fd `2`). It is a `net.Socket` (which is a `Duplex` stream) unless fd `2` refers to a file, in which case it is + * a `Writable` stream. + * + * `process.stderr` differs from other Node.js streams in important ways. See `note on process I/O` for more information. + */ + stderr: WriteStream & { + fd: 2; + }; + /** + * The `process.stdin` property returns a stream connected to`stdin` (fd `0`). It is a `net.Socket` (which is a `Duplex` stream) unless fd `0` refers to a file, in which case it is + * a `Readable` stream. + * + * For details of how to read from `stdin` see `readable.read()`. + * + * As a `Duplex` stream, `process.stdin` can also be used in "old" mode that + * is compatible with scripts written for Node.js prior to v0.10\. + * For more information see `Stream compatibility`. + * + * In "old" streams mode the `stdin` stream is paused by default, so one + * must call `process.stdin.resume()` to read from it. Note also that calling `process.stdin.resume()` itself would switch stream to "old" mode. + */ + stdin: ReadStream & { + fd: 0; + }; + /** + * The `process.argv` property returns an array containing the command-line + * arguments passed when the Node.js process was launched. The first element will + * be {@link execPath}. See `process.argv0` if access to the original value + * of `argv[0]` is needed. The second element will be the path to the JavaScript + * file being executed. The remaining elements will be any additional command-line + * arguments. + * + * For example, assuming the following script for `process-args.js`: + * + * ```js + * import { argv } from 'node:process'; + * + * // print process.argv + * argv.forEach((val, index) => { + * console.log(`${index}: ${val}`); + * }); + * ``` + * + * Launching the Node.js process as: + * + * ```bash + * node process-args.js one two=three four + * ``` + * + * Would generate the output: + * + * ```text + * 0: /usr/local/bin/node + * 1: /Users/mjr/work/node/process-args.js + * 2: one + * 3: two=three + * 4: four + * ``` + * @since v0.1.27 + */ + argv: string[]; + /** + * The `process.argv0` property stores a read-only copy of the original value of`argv[0]` passed when Node.js starts. + * + * ```console + * $ bash -c 'exec -a customArgv0 ./node' + * > process.argv[0] + * '/Volumes/code/external/node/out/Release/node' + * > process.argv0 + * 'customArgv0' + * ``` + * @since v6.4.0 + */ + argv0: string; + /** + * The `process.execArgv` property returns the set of Node.js-specific command-line + * options passed when the Node.js process was launched. These options do not + * appear in the array returned by the {@link argv} property, and do not + * include the Node.js executable, the name of the script, or any options following + * the script name. These options are useful in order to spawn child processes with + * the same execution environment as the parent. + * + * ```bash + * node --icu-data-dir=./foo --require ./bar.js script.js --version + * ``` + * + * Results in `process.execArgv`: + * + * ```js + * ["--icu-data-dir=./foo", "--require", "./bar.js"] + * ``` + * + * And `process.argv`: + * + * ```js + * ['/usr/local/bin/node', 'script.js', '--version'] + * ``` + * + * Refer to `Worker constructor` for the detailed behavior of worker + * threads with this property. + * @since v0.7.7 + */ + execArgv: string[]; + /** + * The `process.execPath` property returns the absolute pathname of the executable + * that started the Node.js process. Symbolic links, if any, are resolved. + * + * ```js + * '/usr/local/bin/node' + * ``` + * @since v0.1.100 + */ + execPath: string; + /** + * The `process.abort()` method causes the Node.js process to exit immediately and + * generate a core file. + * + * This feature is not available in `Worker` threads. + * @since v0.7.0 + */ + abort(): never; + /** + * The `process.chdir()` method changes the current working directory of the + * Node.js process or throws an exception if doing so fails (for instance, if + * the specified `directory` does not exist). + * + * ```js + * import { chdir, cwd } from 'node:process'; + * + * console.log(`Starting directory: ${cwd()}`); + * try { + * chdir('/tmp'); + * console.log(`New directory: ${cwd()}`); + * } catch (err) { + * console.error(`chdir: ${err}`); + * } + * ``` + * + * This feature is not available in `Worker` threads. + * @since v0.1.17 + */ + chdir(directory: string): void; + /** + * The `process.cwd()` method returns the current working directory of the Node.js + * process. + * + * ```js + * import { cwd } from 'node:process'; + * + * console.log(`Current directory: ${cwd()}`); + * ``` + * @since v0.1.8 + */ + cwd(): string; + /** + * The port used by the Node.js debugger when enabled. + * + * ```js + * import process from 'node:process'; + * + * process.debugPort = 5858; + * ``` + * @since v0.7.2 + */ + debugPort: number; + /** + * The `process.dlopen()` method allows dynamically loading shared objects. It is primarily used by `require()` to load C++ Addons, and + * should not be used directly, except in special cases. In other words, `require()` should be preferred over `process.dlopen()` + * unless there are specific reasons such as custom dlopen flags or loading from ES modules. + * + * The `flags` argument is an integer that allows to specify dlopen behavior. See the `[os.constants.dlopen](https://nodejs.org/docs/latest-v20.x/api/os.html#dlopen-constants)` + * documentation for details. + * + * An important requirement when calling `process.dlopen()` is that the `module` instance must be passed. Functions exported by the C++ Addon + * are then accessible via `module.exports`. + * + * The example below shows how to load a C++ Addon, named `local.node`, that exports a `foo` function. All the symbols are loaded before the call returns, by passing the `RTLD_NOW` constant. + * In this example the constant is assumed to be available. + * + * ```js + * import { dlopen } from 'node:process'; + * import { constants } from 'node:os'; + * import { fileURLToPath } from 'node:url'; + * + * const module = { exports: {} }; + * dlopen(module, fileURLToPath(new URL('local.node', import.meta.url)), + * constants.dlopen.RTLD_NOW); + * module.exports.foo(); + * ``` + */ + dlopen(module: object, filename: string, flags?: number): void; + /** + * The `process.emitWarning()` method can be used to emit custom or application + * specific process warnings. These can be listened for by adding a handler to the `'warning'` event. + * + * ```js + * import { emitWarning } from 'node:process'; + * + * // Emit a warning using a string. + * emitWarning('Something happened!'); + * // Emits: (node: 56338) Warning: Something happened! + * ``` + * + * ```js + * import { emitWarning } from 'node:process'; + * + * // Emit a warning using a string and a type. + * emitWarning('Something Happened!', 'CustomWarning'); + * // Emits: (node:56338) CustomWarning: Something Happened! + * ``` + * + * ```js + * import { emitWarning } from 'node:process'; + * + * emitWarning('Something happened!', 'CustomWarning', 'WARN001'); + * // Emits: (node:56338) [WARN001] CustomWarning: Something happened! + * ```js + * + * In each of the previous examples, an `Error` object is generated internally by `process.emitWarning()` and passed through to the `'warning'` handler. + * + * ```js + * import process from 'node:process'; + * + * process.on('warning', (warning) => { + * console.warn(warning.name); // 'Warning' + * console.warn(warning.message); // 'Something happened!' + * console.warn(warning.code); // 'MY_WARNING' + * console.warn(warning.stack); // Stack trace + * console.warn(warning.detail); // 'This is some additional information' + * }); + * ``` + * + * If `warning` is passed as an `Error` object, it will be passed through to the `'warning'` event handler + * unmodified (and the optional `type`, `code` and `ctor` arguments will be ignored): + * + * ```js + * import { emitWarning } from 'node:process'; + * + * // Emit a warning using an Error object. + * const myWarning = new Error('Something happened!'); + * // Use the Error name property to specify the type name + * myWarning.name = 'CustomWarning'; + * myWarning.code = 'WARN001'; + * + * emitWarning(myWarning); + * // Emits: (node:56338) [WARN001] CustomWarning: Something happened! + * ``` + * + * A `TypeError` is thrown if `warning` is anything other than a string or `Error` object. + * + * While process warnings use `Error` objects, the process warning mechanism is not a replacement for normal error handling mechanisms. + * + * The following additional handling is implemented if the warning `type` is `'DeprecationWarning'`: + * * If the `--throw-deprecation` command-line flag is used, the deprecation warning is thrown as an exception rather than being emitted as an event. + * * If the `--no-deprecation` command-line flag is used, the deprecation warning is suppressed. + * * If the `--trace-deprecation` command-line flag is used, the deprecation warning is printed to `stderr` along with the full stack trace. + * @since v8.0.0 + * @param warning The warning to emit. + */ + emitWarning(warning: string | Error, ctor?: Function): void; + emitWarning(warning: string | Error, type?: string, ctor?: Function): void; + emitWarning(warning: string | Error, type?: string, code?: string, ctor?: Function): void; + emitWarning(warning: string | Error, options?: EmitWarningOptions): void; + /** + * The `process.env` property returns an object containing the user environment. + * See [`environ(7)`](http://man7.org/linux/man-pages/man7/environ.7.html). + * + * An example of this object looks like: + * + * ```js + * { + * TERM: 'xterm-256color', + * SHELL: '/usr/local/bin/bash', + * USER: 'maciej', + * PATH: '~/.bin/:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin', + * PWD: '/Users/maciej', + * EDITOR: 'vim', + * SHLVL: '1', + * HOME: '/Users/maciej', + * LOGNAME: 'maciej', + * _: '/usr/local/bin/node' + * } + * ``` + * + * It is possible to modify this object, but such modifications will not be + * reflected outside the Node.js process, or (unless explicitly requested) + * to other `Worker` threads. + * In other words, the following example would not work: + * + * ```bash + * node -e 'process.env.foo = "bar"' && echo $foo + * ``` + * + * While the following will: + * + * ```js + * import { env } from 'node:process'; + * + * env.foo = 'bar'; + * console.log(env.foo); + * ``` + * + * Assigning a property on `process.env` will implicitly convert the value + * to a string. **This behavior is deprecated.** Future versions of Node.js may + * throw an error when the value is not a string, number, or boolean. + * + * ```js + * import { env } from 'node:process'; + * + * env.test = null; + * console.log(env.test); + * // => 'null' + * env.test = undefined; + * console.log(env.test); + * // => 'undefined' + * ``` + * + * Use `delete` to delete a property from `process.env`. + * + * ```js + * import { env } from 'node:process'; + * + * env.TEST = 1; + * delete env.TEST; + * console.log(env.TEST); + * // => undefined + * ``` + * + * On Windows operating systems, environment variables are case-insensitive. + * + * ```js + * import { env } from 'node:process'; + * + * env.TEST = 1; + * console.log(env.test); + * // => 1 + * ``` + * + * Unless explicitly specified when creating a `Worker` instance, + * each `Worker` thread has its own copy of `process.env`, based on its + * parent thread's `process.env`, or whatever was specified as the `env` option + * to the `Worker` constructor. Changes to `process.env` will not be visible + * across `Worker` threads, and only the main thread can make changes that + * are visible to the operating system or to native add-ons. On Windows, a copy of `process.env` on a `Worker` instance operates in a case-sensitive manner + * unlike the main thread. + * @since v0.1.27 + */ + env: ProcessEnv; + /** + * The `process.exit()` method instructs Node.js to terminate the process + * synchronously with an exit status of `code`. If `code` is omitted, exit uses + * either the 'success' code `0` or the value of `process.exitCode` if it has been + * set. Node.js will not terminate until all the `'exit'` event listeners are + * called. + * + * To exit with a 'failure' code: + * + * ```js + * import { exit } from 'node:process'; + * + * exit(1); + * ``` + * + * The shell that executed Node.js should see the exit code as `1`. + * + * Calling `process.exit()` will force the process to exit as quickly as possible + * even if there are still asynchronous operations pending that have not yet + * completed fully, including I/O operations to `process.stdout` and `process.stderr`. + * + * In most situations, it is not actually necessary to call `process.exit()` explicitly. The Node.js process will exit on its own _if there is no additional_ + * _work pending_ in the event loop. The `process.exitCode` property can be set to + * tell the process which exit code to use when the process exits gracefully. + * + * For instance, the following example illustrates a _misuse_ of the `process.exit()` method that could lead to data printed to stdout being + * truncated and lost: + * + * ```js + * import { exit } from 'node:process'; + * + * // This is an example of what *not* to do: + * if (someConditionNotMet()) { + * printUsageToStdout(); + * exit(1); + * } + * ``` + * + * The reason this is problematic is because writes to `process.stdout` in Node.js + * are sometimes _asynchronous_ and may occur over multiple ticks of the Node.js + * event loop. Calling `process.exit()`, however, forces the process to exit _before_ those additional writes to `stdout` can be performed. + * + * Rather than calling `process.exit()` directly, the code _should_ set the `process.exitCode` and allow the process to exit naturally by avoiding + * scheduling any additional work for the event loop: + * + * ```js + * import process from 'node:process'; + * + * // How to properly set the exit code while letting + * // the process exit gracefully. + * if (someConditionNotMet()) { + * printUsageToStdout(); + * process.exitCode = 1; + * } + * ``` + * + * If it is necessary to terminate the Node.js process due to an error condition, + * throwing an _uncaught_ error and allowing the process to terminate accordingly + * is safer than calling `process.exit()`. + * + * In `Worker` threads, this function stops the current thread rather + * than the current process. + * @since v0.1.13 + * @param [code=0] The exit code. For string type, only integer strings (e.g.,'1') are allowed. + */ + exit(code?: number | string | null | undefined): never; + /** + * A number which will be the process exit code, when the process either + * exits gracefully, or is exited via {@link exit} without specifying + * a code. + * + * Specifying a code to {@link exit} will override any + * previous setting of `process.exitCode`. + * @default undefined + * @since v0.11.8 + */ + exitCode?: number | string | number | undefined; + /** + * The `process.getActiveResourcesInfo()` method returns an array of strings containing + * the types of the active resources that are currently keeping the event loop alive. + * + * ```js + * import { getActiveResourcesInfo } from 'node:process'; + * import { setTimeout } from 'node:timers'; + + * console.log('Before:', getActiveResourcesInfo()); + * setTimeout(() => {}, 1000); + * console.log('After:', getActiveResourcesInfo()); + * // Prints: + * // Before: [ 'TTYWrap', 'TTYWrap', 'TTYWrap' ] + * // After: [ 'TTYWrap', 'TTYWrap', 'TTYWrap', 'Timeout' ] + * ``` + * @since v17.3.0, v16.14.0 + */ + getActiveResourcesInfo(): string[]; + /** + * The `process.getgid()` method returns the numerical group identity of the + * process. (See [`getgid(2)`](http://man7.org/linux/man-pages/man2/getgid.2.html).) + * + * ```js + * import process from 'node:process'; + * + * if (process.getgid) { + * console.log(`Current gid: ${process.getgid()}`); + * } + * ``` + * + * This function is only available on POSIX platforms (i.e. not Windows or + * Android). + * @since v0.1.31 + */ + getgid?: () => number; + /** + * The `process.setgid()` method sets the group identity of the process. (See [`setgid(2)`](http://man7.org/linux/man-pages/man2/setgid.2.html).) The `id` can be passed as either a + * numeric ID or a group name + * string. If a group name is specified, this method blocks while resolving the + * associated numeric ID. + * + * ```js + * import process from 'node:process'; + * + * if (process.getgid && process.setgid) { + * console.log(`Current gid: ${process.getgid()}`); + * try { + * process.setgid(501); + * console.log(`New gid: ${process.getgid()}`); + * } catch (err) { + * console.log(`Failed to set gid: ${err}`); + * } + * } + * ``` + * + * This function is only available on POSIX platforms (i.e. not Windows or + * Android). + * This feature is not available in `Worker` threads. + * @since v0.1.31 + * @param id The group name or ID + */ + setgid?: (id: number | string) => void; + /** + * The `process.getuid()` method returns the numeric user identity of the process. + * (See [`getuid(2)`](http://man7.org/linux/man-pages/man2/getuid.2.html).) + * + * ```js + * import process from 'node:process'; + * + * if (process.getuid) { + * console.log(`Current uid: ${process.getuid()}`); + * } + * ``` + * + * This function is only available on POSIX platforms (i.e. not Windows or + * Android). + * @since v0.1.28 + */ + getuid?: () => number; + /** + * The `process.setuid(id)` method sets the user identity of the process. (See [`setuid(2)`](http://man7.org/linux/man-pages/man2/setuid.2.html).) The `id` can be passed as either a + * numeric ID or a username string. + * If a username is specified, the method blocks while resolving the associated + * numeric ID. + * + * ```js + * import process from 'node:process'; + * + * if (process.getuid && process.setuid) { + * console.log(`Current uid: ${process.getuid()}`); + * try { + * process.setuid(501); + * console.log(`New uid: ${process.getuid()}`); + * } catch (err) { + * console.log(`Failed to set uid: ${err}`); + * } + * } + * ``` + * + * This function is only available on POSIX platforms (i.e. not Windows or + * Android). + * This feature is not available in `Worker` threads. + * @since v0.1.28 + */ + setuid?: (id: number | string) => void; + /** + * The `process.geteuid()` method returns the numerical effective user identity of + * the process. (See [`geteuid(2)`](http://man7.org/linux/man-pages/man2/geteuid.2.html).) + * + * ```js + * import process from 'node:process'; + * + * if (process.geteuid) { + * console.log(`Current uid: ${process.geteuid()}`); + * } + * ``` + * + * This function is only available on POSIX platforms (i.e. not Windows or + * Android). + * @since v2.0.0 + */ + geteuid?: () => number; + /** + * The `process.seteuid()` method sets the effective user identity of the process. + * (See [`seteuid(2)`](http://man7.org/linux/man-pages/man2/seteuid.2.html).) The `id` can be passed as either a numeric ID or a username + * string. If a username is specified, the method blocks while resolving the + * associated numeric ID. + * + * ```js + * import process from 'node:process'; + * + * if (process.geteuid && process.seteuid) { + * console.log(`Current uid: ${process.geteuid()}`); + * try { + * process.seteuid(501); + * console.log(`New uid: ${process.geteuid()}`); + * } catch (err) { + * console.log(`Failed to set uid: ${err}`); + * } + * } + * ``` + * + * This function is only available on POSIX platforms (i.e. not Windows or + * Android). + * This feature is not available in `Worker` threads. + * @since v2.0.0 + * @param id A user name or ID + */ + seteuid?: (id: number | string) => void; + /** + * The `process.getegid()` method returns the numerical effective group identity + * of the Node.js process. (See [`getegid(2)`](http://man7.org/linux/man-pages/man2/getegid.2.html).) + * + * ```js + * import process from 'node:process'; + * + * if (process.getegid) { + * console.log(`Current gid: ${process.getegid()}`); + * } + * ``` + * + * This function is only available on POSIX platforms (i.e. not Windows or + * Android). + * @since v2.0.0 + */ + getegid?: () => number; + /** + * The `process.setegid()` method sets the effective group identity of the process. + * (See [`setegid(2)`](http://man7.org/linux/man-pages/man2/setegid.2.html).) The `id` can be passed as either a numeric ID or a group + * name string. If a group name is specified, this method blocks while resolving + * the associated a numeric ID. + * + * ```js + * import process from 'node:process'; + * + * if (process.getegid && process.setegid) { + * console.log(`Current gid: ${process.getegid()}`); + * try { + * process.setegid(501); + * console.log(`New gid: ${process.getegid()}`); + * } catch (err) { + * console.log(`Failed to set gid: ${err}`); + * } + * } + * ``` + * + * This function is only available on POSIX platforms (i.e. not Windows or + * Android). + * This feature is not available in `Worker` threads. + * @since v2.0.0 + * @param id A group name or ID + */ + setegid?: (id: number | string) => void; + /** + * The `process.getgroups()` method returns an array with the supplementary group + * IDs. POSIX leaves it unspecified if the effective group ID is included but + * Node.js ensures it always is. + * + * ```js + * import process from 'node:process'; + * + * if (process.getgroups) { + * console.log(process.getgroups()); // [ 16, 21, 297 ] + * } + * ``` + * + * This function is only available on POSIX platforms (i.e. not Windows or + * Android). + * @since v0.9.4 + */ + getgroups?: () => number[]; + /** + * The `process.setgroups()` method sets the supplementary group IDs for the + * Node.js process. This is a privileged operation that requires the Node.js + * process to have `root` or the `CAP_SETGID` capability. + * + * The `groups` array can contain numeric group IDs, group names, or both. + * + * ```js + * import process from 'node:process'; + * + * if (process.getgroups && process.setgroups) { + * try { + * process.setgroups([501]); + * console.log(process.getgroups()); // new groups + * } catch (err) { + * console.log(`Failed to set groups: ${err}`); + * } + * } + * ``` + * + * This function is only available on POSIX platforms (i.e. not Windows or + * Android). + * This feature is not available in `Worker` threads. + * @since v0.9.4 + */ + setgroups?: (groups: ReadonlyArray) => void; + /** + * The `process.setUncaughtExceptionCaptureCallback()` function sets a function + * that will be invoked when an uncaught exception occurs, which will receive the + * exception value itself as its first argument. + * + * If such a function is set, the `'uncaughtException'` event will + * not be emitted. If `--abort-on-uncaught-exception` was passed from the + * command line or set through `v8.setFlagsFromString()`, the process will + * not abort. Actions configured to take place on exceptions such as report + * generations will be affected too + * + * To unset the capture function, `process.setUncaughtExceptionCaptureCallback(null)` may be used. Calling this + * method with a non-`null` argument while another capture function is set will + * throw an error. + * + * Using this function is mutually exclusive with using the deprecated `domain` built-in module. + * @since v9.3.0 + */ + setUncaughtExceptionCaptureCallback(cb: ((err: Error) => void) | null): void; + /** + * Indicates whether a callback has been set using {@link setUncaughtExceptionCaptureCallback}. + * @since v9.3.0 + */ + hasUncaughtExceptionCaptureCallback(): boolean; + /** + * The `process.sourceMapsEnabled` property returns whether the [Source Map v3](https://sourcemaps.info/spec.html) support for stack traces is enabled. + * @since v20.7.0 + * @experimental + */ + readonly sourceMapsEnabled: boolean; + /** + * This function enables or disables the [Source Map v3](https://sourcemaps.info/spec.html) support for + * stack traces. + * + * It provides same features as launching Node.js process with commandline options `--enable-source-maps`. + * + * Only source maps in JavaScript files that are loaded after source maps has been + * enabled will be parsed and loaded. + * @since v16.6.0, v14.18.0 + * @experimental + */ + setSourceMapsEnabled(value: boolean): void; + /** + * The `process.version` property contains the Node.js version string. + * + * ```js + * import { version } from 'node:process'; + * + * console.log(`Version: ${version}`); + * // Version: v14.8.0 + * ``` + * + * To get the version string without the prepended _v_, use`process.versions.node`. + * @since v0.1.3 + */ + readonly version: string; + /** + * The `process.versions` property returns an object listing the version strings of + * Node.js and its dependencies. `process.versions.modules` indicates the current + * ABI version, which is increased whenever a C++ API changes. Node.js will refuse + * to load modules that were compiled against a different module ABI version. + * + * ```js + * import { versions } from 'node:process'; + * + * console.log(versions); + * ``` + * + * Will generate an object similar to: + * + * ```console + * { node: '20.2.0', + * acorn: '8.8.2', + * ada: '2.4.0', + * ares: '1.19.0', + * base64: '0.5.0', + * brotli: '1.0.9', + * cjs_module_lexer: '1.2.2', + * cldr: '43.0', + * icu: '73.1', + * llhttp: '8.1.0', + * modules: '115', + * napi: '8', + * nghttp2: '1.52.0', + * nghttp3: '0.7.0', + * ngtcp2: '0.8.1', + * openssl: '3.0.8+quic', + * simdutf: '3.2.9', + * tz: '2023c', + * undici: '5.22.0', + * unicode: '15.0', + * uv: '1.44.2', + * uvwasi: '0.0.16', + * v8: '11.3.244.8-node.9', + * zlib: '1.2.13' } + * ``` + * @since v0.2.0 + */ + readonly versions: ProcessVersions; + /** + * The `process.config` property returns a frozen `Object` containing the + * JavaScript representation of the configure options used to compile the current + * Node.js executable. This is the same as the `config.gypi` file that was produced + * when running the `./configure` script. + * + * An example of the possible output looks like: + * + * ```js + * { + * target_defaults: + * { cflags: [], + * default_configuration: 'Release', + * defines: [], + * include_dirs: [], + * libraries: [] }, + * variables: + * { + * host_arch: 'x64', + * napi_build_version: 5, + * node_install_npm: 'true', + * node_prefix: '', + * node_shared_cares: 'false', + * node_shared_http_parser: 'false', + * node_shared_libuv: 'false', + * node_shared_zlib: 'false', + * node_use_openssl: 'true', + * node_shared_openssl: 'false', + * strict_aliasing: 'true', + * target_arch: 'x64', + * v8_use_snapshot: 1 + * } + * } + * ``` + * @since v0.7.7 + */ + readonly config: ProcessConfig; + /** + * The `process.kill()` method sends the `signal` to the process identified by`pid`. + * + * Signal names are strings such as `'SIGINT'` or `'SIGHUP'`. See `Signal Events` and [`kill(2)`](http://man7.org/linux/man-pages/man2/kill.2.html) for more information. + * + * This method will throw an error if the target `pid` does not exist. As a special + * case, a signal of `0` can be used to test for the existence of a process. + * Windows platforms will throw an error if the `pid` is used to kill a process + * group. + * + * Even though the name of this function is `process.kill()`, it is really just a + * signal sender, like the `kill` system call. The signal sent may do something + * other than kill the target process. + * + * ```js + * import process, { kill } from 'node:process'; + * + * process.on('SIGHUP', () => { + * console.log('Got SIGHUP signal.'); + * }); + * + * setTimeout(() => { + * console.log('Exiting.'); + * process.exit(0); + * }, 100); + * + * kill(process.pid, 'SIGHUP'); + * ``` + * + * When `SIGUSR1` is received by a Node.js process, Node.js will start the + * debugger. See `Signal Events`. + * @since v0.0.6 + * @param pid A process ID + * @param [signal='SIGTERM'] The signal to send, either as a string or number. + */ + kill(pid: number, signal?: string | number): true; + /** + * Loads the environment configuration from a `.env` file into `process.env`. If + * the file is not found, error will be thrown. + * + * To load a specific .env file by specifying its path, use the following code: + * + * ```js + * import { loadEnvFile } from 'node:process'; + * + * loadEnvFile('./development.env') + * ``` + * @since v20.12.0 + * @param path The path to the .env file + */ + loadEnvFile(path?: string | URL | Buffer): void; + /** + * The `process.pid` property returns the PID of the process. + * + * ```js + * import { pid } from 'node:process'; + * + * console.log(`This process is pid ${pid}`); + * ``` + * @since v0.1.15 + */ + readonly pid: number; + /** + * The `process.ppid` property returns the PID of the parent of the + * current process. + * + * ```js + * import { ppid } from 'node:process'; + * + * console.log(`The parent process is pid ${ppid}`); + * ``` + * @since v9.2.0, v8.10.0, v6.13.0 + */ + readonly ppid: number; + /** + * The `process.title` property returns the current process title (i.e. returns + * the current value of `ps`). Assigning a new value to `process.title` modifies + * the current value of `ps`. + * + * When a new value is assigned, different platforms will impose different maximum + * length restrictions on the title. Usually such restrictions are quite limited. + * For instance, on Linux and macOS, `process.title` is limited to the size of the + * binary name plus the length of the command-line arguments because setting the `process.title` overwrites the `argv` memory of the process. Node.js v0.8 + * allowed for longer process title strings by also overwriting the `environ` memory but that was potentially insecure and confusing in some (rather obscure) + * cases. + * + * Assigning a value to `process.title` might not result in an accurate label + * within process manager applications such as macOS Activity Monitor or Windows + * Services Manager. + * @since v0.1.104 + */ + title: string; + /** + * The operating system CPU architecture for which the Node.js binary was compiled. + * Possible values are: `'arm'`, `'arm64'`, `'ia32'`, `'loong64'`, `'mips'`, `'mipsel'`, `'ppc'`, `'ppc64'`, `'riscv64'`, `'s390'`, `'s390x'`, and `'x64'`. + * + * ```js + * import { arch } from 'node:process'; + * + * console.log(`This processor architecture is ${arch}`); + * ``` + * @since v0.5.0 + */ + readonly arch: Architecture; + /** + * The `process.platform` property returns a string identifying the operating + * system platform for which the Node.js binary was compiled. + * + * Currently possible values are: + * + * * `'aix'` + * * `'darwin'` + * * `'freebsd'` + * * `'linux'` + * * `'openbsd'` + * * `'sunos'` + * * `'win32'` + * + * ```js + * import { platform } from 'node:process'; + * + * console.log(`This platform is ${platform}`); + * ``` + * + * The value `'android'` may also be returned if the Node.js is built on the + * Android operating system. However, Android support in Node.js [is experimental](https://github.com/nodejs/node/blob/HEAD/BUILDING.md#androidandroid-based-devices-eg-firefox-os). + * @since v0.1.16 + */ + readonly platform: Platform; + /** + * The `process.mainModule` property provides an alternative way of retrieving `require.main`. The difference is that if the main module changes at + * runtime, `require.main` may still refer to the original main module in + * modules that were required before the change occurred. Generally, it's + * safe to assume that the two refer to the same module. + * + * As with `require.main`, `process.mainModule` will be `undefined` if there + * is no entry script. + * @since v0.1.17 + * @deprecated Since v14.0.0 - Use `main` instead. + */ + mainModule?: Module | undefined; + memoryUsage: MemoryUsageFn; + /** + * Gets the amount of memory available to the process (in bytes) based on + * limits imposed by the OS. If there is no such constraint, or the constraint + * is unknown, `0` is returned. + * + * See [`uv_get_constrained_memory`](https://docs.libuv.org/en/v1.x/misc.html#c.uv_get_constrained_memory) for more + * information. + * @since v19.6.0, v18.15.0 + * @experimental + */ + constrainedMemory(): number; + /** + * Gets the amount of free memory that is still available to the process (in bytes). + * See [`uv_get_available_memory`](https://nodejs.org/docs/latest-v20.x/api/process.html#processavailablememory) for more information. + * @experimental + * @since v20.13.0 + */ + availableMemory(): number; + /** + * The `process.cpuUsage()` method returns the user and system CPU time usage of + * the current process, in an object with properties `user` and `system`, whose + * values are microsecond values (millionth of a second). These values measure time + * spent in user and system code respectively, and may end up being greater than + * actual elapsed time if multiple CPU cores are performing work for this process. + * + * The result of a previous call to `process.cpuUsage()` can be passed as the + * argument to the function, to get a diff reading. + * + * ```js + * import { cpuUsage } from 'node:process'; + * + * const startUsage = cpuUsage(); + * // { user: 38579, system: 6986 } + * + * // spin the CPU for 500 milliseconds + * const now = Date.now(); + * while (Date.now() - now < 500); + * + * console.log(cpuUsage(startUsage)); + * // { user: 514883, system: 11226 } + * ``` + * @since v6.1.0 + * @param previousValue A previous return value from calling `process.cpuUsage()` + */ + cpuUsage(previousValue?: CpuUsage): CpuUsage; + /** + * `process.nextTick()` adds `callback` to the "next tick queue". This queue is + * fully drained after the current operation on the JavaScript stack runs to + * completion and before the event loop is allowed to continue. It's possible to + * create an infinite loop if one were to recursively call `process.nextTick()`. + * See the [Event Loop](https://nodejs.org/en/docs/guides/event-loop-timers-and-nexttick/#process-nexttick) guide for more background. + * + * ```js + * import { nextTick } from 'node:process'; + * + * console.log('start'); + * nextTick(() => { + * console.log('nextTick callback'); + * }); + * console.log('scheduled'); + * // Output: + * // start + * // scheduled + * // nextTick callback + * ``` + * + * This is important when developing APIs in order to give users the opportunity + * to assign event handlers _after_ an object has been constructed but before any + * I/O has occurred: + * + * ```js + * import { nextTick } from 'node:process'; + * + * function MyThing(options) { + * this.setupOptions(options); + * + * nextTick(() => { + * this.startDoingStuff(); + * }); + * } + * + * const thing = new MyThing(); + * thing.getReadyForStuff(); + * + * // thing.startDoingStuff() gets called now, not before. + * ``` + * + * It is very important for APIs to be either 100% synchronous or 100% + * asynchronous. Consider this example: + * + * ```js + * // WARNING! DO NOT USE! BAD UNSAFE HAZARD! + * function maybeSync(arg, cb) { + * if (arg) { + * cb(); + * return; + * } + * + * fs.stat('file', cb); + * } + * ``` + * + * This API is hazardous because in the following case: + * + * ```js + * const maybeTrue = Math.random() > 0.5; + * + * maybeSync(maybeTrue, () => { + * foo(); + * }); + * + * bar(); + * ``` + * + * It is not clear whether `foo()` or `bar()` will be called first. + * + * The following approach is much better: + * + * ```js + * import { nextTick } from 'node:process'; + * + * function definitelyAsync(arg, cb) { + * if (arg) { + * nextTick(cb); + * return; + * } + * + * fs.stat('file', cb); + * } + * ``` + * @since v0.1.26 + * @param args Additional arguments to pass when invoking the `callback` + */ + nextTick(callback: Function, ...args: any[]): void; + /** + * This API is available through the [--experimental-permission](https://nodejs.org/api/cli.html#--experimental-permission) flag. + * + * `process.permission` is an object whose methods are used to manage permissions for the current process. + * Additional documentation is available in the [Permission Model](https://nodejs.org/api/permissions.html#permission-model). + * @since v20.0.0 + */ + permission: ProcessPermission; + /** + * The `process.release` property returns an `Object` containing metadata related + * to the current release, including URLs for the source tarball and headers-only + * tarball. + * + * `process.release` contains the following properties: + * + * ```js + * { + * name: 'node', + * lts: 'Hydrogen', + * sourceUrl: 'https://nodejs.org/download/release/v18.12.0/node-v18.12.0.tar.gz', + * headersUrl: 'https://nodejs.org/download/release/v18.12.0/node-v18.12.0-headers.tar.gz', + * libUrl: 'https://nodejs.org/download/release/v18.12.0/win-x64/node.lib' + * } + * ``` + * + * In custom builds from non-release versions of the source tree, only the `name` property may be present. The additional properties should not be + * relied upon to exist. + * @since v3.0.0 + */ + readonly release: ProcessRelease; + features: { + inspector: boolean; + debug: boolean; + uv: boolean; + ipv6: boolean; + tls_alpn: boolean; + tls_sni: boolean; + tls_ocsp: boolean; + tls: boolean; + }; + /** + * `process.umask()` returns the Node.js process's file mode creation mask. Child + * processes inherit the mask from the parent process. + * @since v0.1.19 + * @deprecated Calling `process.umask()` with no argument causes the process-wide umask to be written twice. This introduces a race condition between threads, and is a potential + * security vulnerability. There is no safe, cross-platform alternative API. + */ + umask(): number; + /** + * Can only be set if not in worker thread. + */ + umask(mask: string | number): number; + /** + * The `process.uptime()` method returns the number of seconds the current Node.js + * process has been running. + * + * The return value includes fractions of a second. Use `Math.floor()` to get whole + * seconds. + * @since v0.5.0 + */ + uptime(): number; + hrtime: HRTime; + /** + * If the Node.js process was spawned with an IPC channel, the process.channel property is a reference to the IPC channel. + * If no IPC channel exists, this property is undefined. + * @since v7.1.0 + */ + channel?: { + /** + * This method makes the IPC channel keep the event loop of the process running if .unref() has been called before. + * @since v7.1.0 + */ + ref(): void; + /** + * This method makes the IPC channel not keep the event loop of the process running, and lets it finish even while the channel is open. + * @since v7.1.0 + */ + unref(): void; + }; + /** + * If Node.js is spawned with an IPC channel, the `process.send()` method can be + * used to send messages to the parent process. Messages will be received as a `'message'` event on the parent's `ChildProcess` object. + * + * If Node.js was not spawned with an IPC channel, `process.send` will be `undefined`. + * + * The message goes through serialization and parsing. The resulting message might + * not be the same as what is originally sent. + * @since v0.5.9 + * @param options used to parameterize the sending of certain types of handles. `options` supports the following properties: + */ + send?( + message: any, + sendHandle?: any, + options?: { + keepOpen?: boolean | undefined; + }, + callback?: (error: Error | null) => void, + ): boolean; + /** + * If the Node.js process is spawned with an IPC channel (see the `Child Process` and `Cluster` documentation), the `process.disconnect()` method will close the + * IPC channel to the parent process, allowing the child process to exit gracefully + * once there are no other connections keeping it alive. + * + * The effect of calling `process.disconnect()` is the same as calling `ChildProcess.disconnect()` from the parent process. + * + * If the Node.js process was not spawned with an IPC channel, `process.disconnect()` will be `undefined`. + * @since v0.7.2 + */ + disconnect(): void; + /** + * If the Node.js process is spawned with an IPC channel (see the `Child Process` and `Cluster` documentation), the `process.connected` property will return `true` so long as the IPC + * channel is connected and will return `false` after `process.disconnect()` is called. + * + * Once `process.connected` is `false`, it is no longer possible to send messages + * over the IPC channel using `process.send()`. + * @since v0.7.2 + */ + connected: boolean; + /** + * The `process.allowedNodeEnvironmentFlags` property is a special, + * read-only `Set` of flags allowable within the `NODE_OPTIONS` environment variable. + * + * `process.allowedNodeEnvironmentFlags` extends `Set`, but overrides `Set.prototype.has` to recognize several different possible flag + * representations. `process.allowedNodeEnvironmentFlags.has()` will + * return `true` in the following cases: + * + * * Flags may omit leading single (`-`) or double (`--`) dashes; e.g., `inspect-brk` for `--inspect-brk`, or `r` for `-r`. + * * Flags passed through to V8 (as listed in `--v8-options`) may replace + * one or more _non-leading_ dashes for an underscore, or vice-versa; + * e.g., `--perf_basic_prof`, `--perf-basic-prof`, `--perf_basic-prof`, + * etc. + * * Flags may contain one or more equals (`=`) characters; all + * characters after and including the first equals will be ignored; + * e.g., `--stack-trace-limit=100`. + * * Flags _must_ be allowable within `NODE_OPTIONS`. + * + * When iterating over `process.allowedNodeEnvironmentFlags`, flags will + * appear only _once_; each will begin with one or more dashes. Flags + * passed through to V8 will contain underscores instead of non-leading + * dashes: + * + * ```js + * import { allowedNodeEnvironmentFlags } from 'node:process'; + * + * allowedNodeEnvironmentFlags.forEach((flag) => { + * // -r + * // --inspect-brk + * // --abort_on_uncaught_exception + * // ... + * }); + * ``` + * + * The methods `add()`, `clear()`, and `delete()` of`process.allowedNodeEnvironmentFlags` do nothing, and will fail + * silently. + * + * If Node.js was compiled _without_ `NODE_OPTIONS` support (shown in {@link config}), `process.allowedNodeEnvironmentFlags` will + * contain what _would have_ been allowable. + * @since v10.10.0 + */ + allowedNodeEnvironmentFlags: ReadonlySet; + /** + * `process.report` is an object whose methods are used to generate diagnostic + * reports for the current process. Additional documentation is available in the `report documentation`. + * @since v11.8.0 + */ + report?: ProcessReport | undefined; + /** + * ```js + * import { resourceUsage } from 'node:process'; + * + * console.log(resourceUsage()); + * /* + * Will output: + * { + * userCPUTime: 82872, + * systemCPUTime: 4143, + * maxRSS: 33164, + * sharedMemorySize: 0, + * unsharedDataSize: 0, + * unsharedStackSize: 0, + * minorPageFault: 2469, + * majorPageFault: 0, + * swappedOut: 0, + * fsRead: 0, + * fsWrite: 8, + * ipcSent: 0, + * ipcReceived: 0, + * signalsCount: 0, + * voluntaryContextSwitches: 79, + * involuntaryContextSwitches: 1 + * } + * + * ``` + * @since v12.6.0 + * @return the resource usage for the current process. All of these values come from the `uv_getrusage` call which returns a [`uv_rusage_t` struct][uv_rusage_t]. + */ + resourceUsage(): ResourceUsage; + /** + * The initial value of `process.throwDeprecation` indicates whether the `--throw-deprecation` flag is set on the current Node.js process. `process.throwDeprecation` + * is mutable, so whether or not deprecation warnings result in errors may be altered at runtime. See the documentation for the 'warning' event and the emitWarning() + * method for more information. + * + * ```bash + * $ node --throw-deprecation -p "process.throwDeprecation" + * true + * $ node -p "process.throwDeprecation" + * undefined + * $ node + * > process.emitWarning('test', 'DeprecationWarning'); + * undefined + * > (node:26598) DeprecationWarning: test + * > process.throwDeprecation = true; + * true + * > process.emitWarning('test', 'DeprecationWarning'); + * Thrown: + * [DeprecationWarning: test] { name: 'DeprecationWarning' } + * ``` + * @since v0.9.12 + */ + throwDeprecation: boolean; + /** + * The `process.traceDeprecation` property indicates whether the `--trace-deprecation` flag is set on the current Node.js process. See the + * documentation for the `'warning' event` and the `emitWarning() method` for more information about this + * flag's behavior. + * @since v0.8.0 + */ + traceDeprecation: boolean; + /* EventEmitter */ + addListener(event: "beforeExit", listener: BeforeExitListener): this; + addListener(event: "disconnect", listener: DisconnectListener): this; + addListener(event: "exit", listener: ExitListener): this; + addListener(event: "rejectionHandled", listener: RejectionHandledListener): this; + addListener(event: "uncaughtException", listener: UncaughtExceptionListener): this; + addListener(event: "uncaughtExceptionMonitor", listener: UncaughtExceptionListener): this; + addListener(event: "unhandledRejection", listener: UnhandledRejectionListener): this; + addListener(event: "warning", listener: WarningListener): this; + addListener(event: "message", listener: MessageListener): this; + addListener(event: Signals, listener: SignalsListener): this; + addListener(event: "multipleResolves", listener: MultipleResolveListener): this; + addListener(event: "worker", listener: WorkerListener): this; + emit(event: "beforeExit", code: number): boolean; + emit(event: "disconnect"): boolean; + emit(event: "exit", code: number): boolean; + emit(event: "rejectionHandled", promise: Promise): boolean; + emit(event: "uncaughtException", error: Error): boolean; + emit(event: "uncaughtExceptionMonitor", error: Error): boolean; + emit(event: "unhandledRejection", reason: unknown, promise: Promise): boolean; + emit(event: "warning", warning: Error): boolean; + emit(event: "message", message: unknown, sendHandle: unknown): this; + emit(event: Signals, signal?: Signals): boolean; + emit( + event: "multipleResolves", + type: MultipleResolveType, + promise: Promise, + value: unknown, + ): this; + emit(event: "worker", listener: WorkerListener): this; + on(event: "beforeExit", listener: BeforeExitListener): this; + on(event: "disconnect", listener: DisconnectListener): this; + on(event: "exit", listener: ExitListener): this; + on(event: "rejectionHandled", listener: RejectionHandledListener): this; + on(event: "uncaughtException", listener: UncaughtExceptionListener): this; + on(event: "uncaughtExceptionMonitor", listener: UncaughtExceptionListener): this; + on(event: "unhandledRejection", listener: UnhandledRejectionListener): this; + on(event: "warning", listener: WarningListener): this; + on(event: "message", listener: MessageListener): this; + on(event: Signals, listener: SignalsListener): this; + on(event: "multipleResolves", listener: MultipleResolveListener): this; + on(event: "worker", listener: WorkerListener): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + once(event: "beforeExit", listener: BeforeExitListener): this; + once(event: "disconnect", listener: DisconnectListener): this; + once(event: "exit", listener: ExitListener): this; + once(event: "rejectionHandled", listener: RejectionHandledListener): this; + once(event: "uncaughtException", listener: UncaughtExceptionListener): this; + once(event: "uncaughtExceptionMonitor", listener: UncaughtExceptionListener): this; + once(event: "unhandledRejection", listener: UnhandledRejectionListener): this; + once(event: "warning", listener: WarningListener): this; + once(event: "message", listener: MessageListener): this; + once(event: Signals, listener: SignalsListener): this; + once(event: "multipleResolves", listener: MultipleResolveListener): this; + once(event: "worker", listener: WorkerListener): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + prependListener(event: "beforeExit", listener: BeforeExitListener): this; + prependListener(event: "disconnect", listener: DisconnectListener): this; + prependListener(event: "exit", listener: ExitListener): this; + prependListener(event: "rejectionHandled", listener: RejectionHandledListener): this; + prependListener(event: "uncaughtException", listener: UncaughtExceptionListener): this; + prependListener(event: "uncaughtExceptionMonitor", listener: UncaughtExceptionListener): this; + prependListener(event: "unhandledRejection", listener: UnhandledRejectionListener): this; + prependListener(event: "warning", listener: WarningListener): this; + prependListener(event: "message", listener: MessageListener): this; + prependListener(event: Signals, listener: SignalsListener): this; + prependListener(event: "multipleResolves", listener: MultipleResolveListener): this; + prependListener(event: "worker", listener: WorkerListener): this; + prependOnceListener(event: "beforeExit", listener: BeforeExitListener): this; + prependOnceListener(event: "disconnect", listener: DisconnectListener): this; + prependOnceListener(event: "exit", listener: ExitListener): this; + prependOnceListener(event: "rejectionHandled", listener: RejectionHandledListener): this; + prependOnceListener(event: "uncaughtException", listener: UncaughtExceptionListener): this; + prependOnceListener(event: "uncaughtExceptionMonitor", listener: UncaughtExceptionListener): this; + prependOnceListener(event: "unhandledRejection", listener: UnhandledRejectionListener): this; + prependOnceListener(event: "warning", listener: WarningListener): this; + prependOnceListener(event: "message", listener: MessageListener): this; + prependOnceListener(event: Signals, listener: SignalsListener): this; + prependOnceListener(event: "multipleResolves", listener: MultipleResolveListener): this; + prependOnceListener(event: "worker", listener: WorkerListener): this; + listeners(event: "beforeExit"): BeforeExitListener[]; + listeners(event: "disconnect"): DisconnectListener[]; + listeners(event: "exit"): ExitListener[]; + listeners(event: "rejectionHandled"): RejectionHandledListener[]; + listeners(event: "uncaughtException"): UncaughtExceptionListener[]; + listeners(event: "uncaughtExceptionMonitor"): UncaughtExceptionListener[]; + listeners(event: "unhandledRejection"): UnhandledRejectionListener[]; + listeners(event: "warning"): WarningListener[]; + listeners(event: "message"): MessageListener[]; + listeners(event: Signals): SignalsListener[]; + listeners(event: "multipleResolves"): MultipleResolveListener[]; + listeners(event: "worker"): WorkerListener[]; + } + } + } + export = process; +} +declare module "node:process" { + import process = require("process"); + export = process; +} diff --git a/node_modules/@types/node/punycode.d.ts b/node_modules/@types/node/punycode.d.ts new file mode 100644 index 0000000..137441d --- /dev/null +++ b/node_modules/@types/node/punycode.d.ts @@ -0,0 +1,117 @@ +/** + * **The version of the punycode module bundled in Node.js is being deprecated. **In a future major version of Node.js this module will be removed. Users + * currently depending on the `punycode` module should switch to using the + * userland-provided [Punycode.js](https://github.com/bestiejs/punycode.js) module instead. For punycode-based URL + * encoding, see `url.domainToASCII` or, more generally, the `WHATWG URL API`. + * + * The `punycode` module is a bundled version of the [Punycode.js](https://github.com/bestiejs/punycode.js) module. It + * can be accessed using: + * + * ```js + * const punycode = require('punycode'); + * ``` + * + * [Punycode](https://tools.ietf.org/html/rfc3492) is a character encoding scheme defined by RFC 3492 that is + * primarily intended for use in Internationalized Domain Names. Because host + * names in URLs are limited to ASCII characters only, Domain Names that contain + * non-ASCII characters must be converted into ASCII using the Punycode scheme. + * For instance, the Japanese character that translates into the English word, `'example'` is `'例'`. The Internationalized Domain Name, `'例.com'` (equivalent + * to `'example.com'`) is represented by Punycode as the ASCII string `'xn--fsq.com'`. + * + * The `punycode` module provides a simple implementation of the Punycode standard. + * + * The `punycode` module is a third-party dependency used by Node.js and + * made available to developers as a convenience. Fixes or other modifications to + * the module must be directed to the [Punycode.js](https://github.com/bestiejs/punycode.js) project. + * @deprecated Since v7.0.0 - Deprecated + * @see [source](https://github.com/nodejs/node/blob/v20.13.1/lib/punycode.js) + */ +declare module "punycode" { + /** + * The `punycode.decode()` method converts a [Punycode](https://tools.ietf.org/html/rfc3492) string of ASCII-only + * characters to the equivalent string of Unicode codepoints. + * + * ```js + * punycode.decode('maana-pta'); // 'mañana' + * punycode.decode('--dqo34k'); // '☃-⌘' + * ``` + * @since v0.5.1 + */ + function decode(string: string): string; + /** + * The `punycode.encode()` method converts a string of Unicode codepoints to a [Punycode](https://tools.ietf.org/html/rfc3492) string of ASCII-only characters. + * + * ```js + * punycode.encode('mañana'); // 'maana-pta' + * punycode.encode('☃-⌘'); // '--dqo34k' + * ``` + * @since v0.5.1 + */ + function encode(string: string): string; + /** + * The `punycode.toUnicode()` method converts a string representing a domain name + * containing [Punycode](https://tools.ietf.org/html/rfc3492) encoded characters into Unicode. Only the [Punycode](https://tools.ietf.org/html/rfc3492) encoded parts of the domain name are be + * converted. + * + * ```js + * // decode domain names + * punycode.toUnicode('xn--maana-pta.com'); // 'mañana.com' + * punycode.toUnicode('xn----dqo34k.com'); // '☃-⌘.com' + * punycode.toUnicode('example.com'); // 'example.com' + * ``` + * @since v0.6.1 + */ + function toUnicode(domain: string): string; + /** + * The `punycode.toASCII()` method converts a Unicode string representing an + * Internationalized Domain Name to [Punycode](https://tools.ietf.org/html/rfc3492). Only the non-ASCII parts of the + * domain name will be converted. Calling `punycode.toASCII()` on a string that + * already only contains ASCII characters will have no effect. + * + * ```js + * // encode domain names + * punycode.toASCII('mañana.com'); // 'xn--maana-pta.com' + * punycode.toASCII('☃-⌘.com'); // 'xn----dqo34k.com' + * punycode.toASCII('example.com'); // 'example.com' + * ``` + * @since v0.6.1 + */ + function toASCII(domain: string): string; + /** + * @deprecated since v7.0.0 + * The version of the punycode module bundled in Node.js is being deprecated. + * In a future major version of Node.js this module will be removed. + * Users currently depending on the punycode module should switch to using + * the userland-provided Punycode.js module instead. + */ + const ucs2: ucs2; + interface ucs2 { + /** + * @deprecated since v7.0.0 + * The version of the punycode module bundled in Node.js is being deprecated. + * In a future major version of Node.js this module will be removed. + * Users currently depending on the punycode module should switch to using + * the userland-provided Punycode.js module instead. + */ + decode(string: string): number[]; + /** + * @deprecated since v7.0.0 + * The version of the punycode module bundled in Node.js is being deprecated. + * In a future major version of Node.js this module will be removed. + * Users currently depending on the punycode module should switch to using + * the userland-provided Punycode.js module instead. + */ + encode(codePoints: readonly number[]): string; + } + /** + * @deprecated since v7.0.0 + * The version of the punycode module bundled in Node.js is being deprecated. + * In a future major version of Node.js this module will be removed. + * Users currently depending on the punycode module should switch to using + * the userland-provided Punycode.js module instead. + */ + const version: string; +} +declare module "node:punycode" { + export * from "punycode"; +} diff --git a/node_modules/@types/node/querystring.d.ts b/node_modules/@types/node/querystring.d.ts new file mode 100644 index 0000000..bd494a6 --- /dev/null +++ b/node_modules/@types/node/querystring.d.ts @@ -0,0 +1,153 @@ +/** + * The `node:querystring` module provides utilities for parsing and formatting URL + * query strings. It can be accessed using: + * + * ```js + * const querystring = require('node:querystring'); + * ``` + * + * `querystring` is more performant than `URLSearchParams` but is not a + * standardized API. Use `URLSearchParams` when performance is not critical or + * when compatibility with browser code is desirable. + * @see [source](https://github.com/nodejs/node/blob/v20.13.1/lib/querystring.js) + */ +declare module "querystring" { + interface StringifyOptions { + /** + * The function to use when converting URL-unsafe characters to percent-encoding in the query string. + * @default `querystring.escape()` + */ + encodeURIComponent?: ((str: string) => string) | undefined; + } + interface ParseOptions { + /** + * Specifies the maximum number of keys to parse. Specify `0` to remove key counting limitations. + * @default 1000 + */ + maxKeys?: number | undefined; + /** + * The function to use when decoding percent-encoded characters in the query string. + * @default `querystring.unescape()` + */ + decodeURIComponent?: ((str: string) => string) | undefined; + } + interface ParsedUrlQuery extends NodeJS.Dict {} + interface ParsedUrlQueryInput extends + NodeJS.Dict< + | string + | number + | boolean + | readonly string[] + | readonly number[] + | readonly boolean[] + | null + > + {} + /** + * The `querystring.stringify()` method produces a URL query string from a + * given `obj` by iterating through the object's "own properties". + * + * It serializes the following types of values passed in `obj`: [string](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | + * [number](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) | + * [bigint](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt) | + * [boolean](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) | + * [string\[\]](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#String_type) | + * [number\[\]](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Number_type) | + * [bigint\[\]](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/BigInt) | + * [boolean\[\]](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Boolean_type) The numeric values must be finite. Any other input values will be coerced to + * empty strings. + * + * ```js + * querystring.stringify({ foo: 'bar', baz: ['qux', 'quux'], corge: '' }); + * // Returns 'foo=bar&baz=qux&baz=quux&corge=' + * + * querystring.stringify({ foo: 'bar', baz: 'qux' }, ';', ':'); + * // Returns 'foo:bar;baz:qux' + * ``` + * + * By default, characters requiring percent-encoding within the query string will + * be encoded as UTF-8\. If an alternative encoding is required, then an alternative `encodeURIComponent` option will need to be specified: + * + * ```js + * // Assuming gbkEncodeURIComponent function already exists, + * + * querystring.stringify({ w: '中文', foo: 'bar' }, null, null, + * { encodeURIComponent: gbkEncodeURIComponent }); + * ``` + * @since v0.1.25 + * @param obj The object to serialize into a URL query string + * @param [sep='&'] The substring used to delimit key and value pairs in the query string. + * @param [eq='='] . The substring used to delimit keys and values in the query string. + */ + function stringify(obj?: ParsedUrlQueryInput, sep?: string, eq?: string, options?: StringifyOptions): string; + /** + * The `querystring.parse()` method parses a URL query string (`str`) into a + * collection of key and value pairs. + * + * For example, the query string `'foo=bar&abc=xyz&abc=123'` is parsed into: + * + * ```json + * { + * "foo": "bar", + * "abc": ["xyz", "123"] + * } + * ``` + * + * The object returned by the `querystring.parse()` method _does not_ prototypically inherit from the JavaScript `Object`. This means that typical `Object` methods such as `obj.toString()`, + * `obj.hasOwnProperty()`, and others + * are not defined and _will not work_. + * + * By default, percent-encoded characters within the query string will be assumed + * to use UTF-8 encoding. If an alternative character encoding is used, then an + * alternative `decodeURIComponent` option will need to be specified: + * + * ```js + * // Assuming gbkDecodeURIComponent function already exists... + * + * querystring.parse('w=%D6%D0%CE%C4&foo=bar', null, null, + * { decodeURIComponent: gbkDecodeURIComponent }); + * ``` + * @since v0.1.25 + * @param str The URL query string to parse + * @param [sep='&'] The substring used to delimit key and value pairs in the query string. + * @param [eq='='] The substring used to delimit keys and values in the query string. + */ + function parse(str: string, sep?: string, eq?: string, options?: ParseOptions): ParsedUrlQuery; + /** + * The querystring.encode() function is an alias for querystring.stringify(). + */ + const encode: typeof stringify; + /** + * The querystring.decode() function is an alias for querystring.parse(). + */ + const decode: typeof parse; + /** + * The `querystring.escape()` method performs URL percent-encoding on the given `str` in a manner that is optimized for the specific requirements of URL + * query strings. + * + * The `querystring.escape()` method is used by `querystring.stringify()` and is + * generally not expected to be used directly. It is exported primarily to allow + * application code to provide a replacement percent-encoding implementation if + * necessary by assigning `querystring.escape` to an alternative function. + * @since v0.1.25 + */ + function escape(str: string): string; + /** + * The `querystring.unescape()` method performs decoding of URL percent-encoded + * characters on the given `str`. + * + * The `querystring.unescape()` method is used by `querystring.parse()` and is + * generally not expected to be used directly. It is exported primarily to allow + * application code to provide a replacement decoding implementation if + * necessary by assigning `querystring.unescape` to an alternative function. + * + * By default, the `querystring.unescape()` method will attempt to use the + * JavaScript built-in `decodeURIComponent()` method to decode. If that fails, + * a safer equivalent that does not throw on malformed URLs will be used. + * @since v0.1.25 + */ + function unescape(str: string): string; +} +declare module "node:querystring" { + export * from "querystring"; +} diff --git a/node_modules/@types/node/readline.d.ts b/node_modules/@types/node/readline.d.ts new file mode 100644 index 0000000..06e1705 --- /dev/null +++ b/node_modules/@types/node/readline.d.ts @@ -0,0 +1,540 @@ +/** + * The `node:readline` module provides an interface for reading data from a [Readable](https://nodejs.org/docs/latest-v20.x/api/stream.html#readable-streams) stream + * (such as [`process.stdin`](https://nodejs.org/docs/latest-v20.x/api/process.html#processstdin)) one line at a time. + * + * To use the promise-based APIs: + * + * ```js + * import * as readline from 'node:readline/promises'; + * ``` + * + * To use the callback and sync APIs: + * + * ```js + * import * as readline from 'node:readline'; + * ``` + * + * The following simple example illustrates the basic use of the `node:readline` module. + * + * ```js + * import * as readline from 'node:readline/promises'; + * import { stdin as input, stdout as output } from 'node:process'; + * + * const rl = readline.createInterface({ input, output }); + * + * const answer = await rl.question('What do you think of Node.js? '); + * + * console.log(`Thank you for your valuable feedback: ${answer}`); + * + * rl.close(); + * ``` + * + * Once this code is invoked, the Node.js application will not terminate until the `readline.Interface` is closed because the interface waits for data to be + * received on the `input` stream. + * @see [source](https://github.com/nodejs/node/blob/v20.13.1/lib/readline.js) + */ +declare module "readline" { + import { Abortable, EventEmitter } from "node:events"; + import * as promises from "node:readline/promises"; + export { promises }; + export interface Key { + sequence?: string | undefined; + name?: string | undefined; + ctrl?: boolean | undefined; + meta?: boolean | undefined; + shift?: boolean | undefined; + } + /** + * Instances of the `readline.Interface` class are constructed using the `readline.createInterface()` method. Every instance is associated with a + * single `input` [Readable](https://nodejs.org/docs/latest-v20.x/api/stream.html#readable-streams) stream and a single `output` [Writable](https://nodejs.org/docs/latest-v20.x/api/stream.html#writable-streams) stream. + * The `output` stream is used to print prompts for user input that arrives on, + * and is read from, the `input` stream. + * @since v0.1.104 + */ + export class Interface extends EventEmitter { + readonly terminal: boolean; + /** + * The current input data being processed by node. + * + * This can be used when collecting input from a TTY stream to retrieve the + * current value that has been processed thus far, prior to the `line` event + * being emitted. Once the `line` event has been emitted, this property will + * be an empty string. + * + * Be aware that modifying the value during the instance runtime may have + * unintended consequences if `rl.cursor` is not also controlled. + * + * **If not using a TTY stream for input, use the `'line'` event.** + * + * One possible use case would be as follows: + * + * ```js + * const values = ['lorem ipsum', 'dolor sit amet']; + * const rl = readline.createInterface(process.stdin); + * const showResults = debounce(() => { + * console.log( + * '\n', + * values.filter((val) => val.startsWith(rl.line)).join(' '), + * ); + * }, 300); + * process.stdin.on('keypress', (c, k) => { + * showResults(); + * }); + * ``` + * @since v0.1.98 + */ + readonly line: string; + /** + * The cursor position relative to `rl.line`. + * + * This will track where the current cursor lands in the input string, when + * reading input from a TTY stream. The position of cursor determines the + * portion of the input string that will be modified as input is processed, + * as well as the column where the terminal caret will be rendered. + * @since v0.1.98 + */ + readonly cursor: number; + /** + * NOTE: According to the documentation: + * + * > Instances of the `readline.Interface` class are constructed using the + * > `readline.createInterface()` method. + * + * @see https://nodejs.org/dist/latest-v20.x/docs/api/readline.html#class-interfaceconstructor + */ + protected constructor( + input: NodeJS.ReadableStream, + output?: NodeJS.WritableStream, + completer?: Completer | AsyncCompleter, + terminal?: boolean, + ); + /** + * NOTE: According to the documentation: + * + * > Instances of the `readline.Interface` class are constructed using the + * > `readline.createInterface()` method. + * + * @see https://nodejs.org/dist/latest-v20.x/docs/api/readline.html#class-interfaceconstructor + */ + protected constructor(options: ReadLineOptions); + /** + * The `rl.getPrompt()` method returns the current prompt used by `rl.prompt()`. + * @since v15.3.0, v14.17.0 + * @return the current prompt string + */ + getPrompt(): string; + /** + * The `rl.setPrompt()` method sets the prompt that will be written to `output` whenever `rl.prompt()` is called. + * @since v0.1.98 + */ + setPrompt(prompt: string): void; + /** + * The `rl.prompt()` method writes the `Interface` instances configured`prompt` to a new line in `output` in order to provide a user with a new + * location at which to provide input. + * + * When called, `rl.prompt()` will resume the `input` stream if it has been + * paused. + * + * If the `Interface` was created with `output` set to `null` or `undefined` the prompt is not written. + * @since v0.1.98 + * @param preserveCursor If `true`, prevents the cursor placement from being reset to `0`. + */ + prompt(preserveCursor?: boolean): void; + /** + * The `rl.question()` method displays the `query` by writing it to the `output`, + * waits for user input to be provided on `input`, then invokes the `callback` function passing the provided input as the first argument. + * + * When called, `rl.question()` will resume the `input` stream if it has been + * paused. + * + * If the `Interface` was created with `output` set to `null` or `undefined` the `query` is not written. + * + * The `callback` function passed to `rl.question()` does not follow the typical + * pattern of accepting an `Error` object or `null` as the first argument. + * The `callback` is called with the provided answer as the only argument. + * + * An error will be thrown if calling `rl.question()` after `rl.close()`. + * + * Example usage: + * + * ```js + * rl.question('What is your favorite food? ', (answer) => { + * console.log(`Oh, so your favorite food is ${answer}`); + * }); + * ``` + * + * Using an `AbortController` to cancel a question. + * + * ```js + * const ac = new AbortController(); + * const signal = ac.signal; + * + * rl.question('What is your favorite food? ', { signal }, (answer) => { + * console.log(`Oh, so your favorite food is ${answer}`); + * }); + * + * signal.addEventListener('abort', () => { + * console.log('The food question timed out'); + * }, { once: true }); + * + * setTimeout(() => ac.abort(), 10000); + * ``` + * @since v0.3.3 + * @param query A statement or query to write to `output`, prepended to the prompt. + * @param callback A callback function that is invoked with the user's input in response to the `query`. + */ + question(query: string, callback: (answer: string) => void): void; + question(query: string, options: Abortable, callback: (answer: string) => void): void; + /** + * The `rl.pause()` method pauses the `input` stream, allowing it to be resumed + * later if necessary. + * + * Calling `rl.pause()` does not immediately pause other events (including `'line'`) from being emitted by the `Interface` instance. + * @since v0.3.4 + */ + pause(): this; + /** + * The `rl.resume()` method resumes the `input` stream if it has been paused. + * @since v0.3.4 + */ + resume(): this; + /** + * The `rl.close()` method closes the `Interface` instance and + * relinquishes control over the `input` and `output` streams. When called, + * the `'close'` event will be emitted. + * + * Calling `rl.close()` does not immediately stop other events (including `'line'`) + * from being emitted by the `Interface` instance. + * @since v0.1.98 + */ + close(): void; + /** + * The `rl.write()` method will write either `data` or a key sequence identified + * by `key` to the `output`. The `key` argument is supported only if `output` is + * a `TTY` text terminal. See `TTY keybindings` for a list of key + * combinations. + * + * If `key` is specified, `data` is ignored. + * + * When called, `rl.write()` will resume the `input` stream if it has been + * paused. + * + * If the `Interface` was created with `output` set to `null` or `undefined` the `data` and `key` are not written. + * + * ```js + * rl.write('Delete this!'); + * // Simulate Ctrl+U to delete the line written previously + * rl.write(null, { ctrl: true, name: 'u' }); + * ``` + * + * The `rl.write()` method will write the data to the `readline` `Interface`'s `input` _as if it were provided by the user_. + * @since v0.1.98 + */ + write(data: string | Buffer, key?: Key): void; + write(data: undefined | null | string | Buffer, key: Key): void; + /** + * Returns the real position of the cursor in relation to the input + * prompt + string. Long input (wrapping) strings, as well as multiple + * line prompts are included in the calculations. + * @since v13.5.0, v12.16.0 + */ + getCursorPos(): CursorPos; + /** + * events.EventEmitter + * 1. close + * 2. line + * 3. pause + * 4. resume + * 5. SIGCONT + * 6. SIGINT + * 7. SIGTSTP + * 8. history + */ + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "close", listener: () => void): this; + addListener(event: "line", listener: (input: string) => void): this; + addListener(event: "pause", listener: () => void): this; + addListener(event: "resume", listener: () => void): this; + addListener(event: "SIGCONT", listener: () => void): this; + addListener(event: "SIGINT", listener: () => void): this; + addListener(event: "SIGTSTP", listener: () => void): this; + addListener(event: "history", listener: (history: string[]) => void): this; + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: "close"): boolean; + emit(event: "line", input: string): boolean; + emit(event: "pause"): boolean; + emit(event: "resume"): boolean; + emit(event: "SIGCONT"): boolean; + emit(event: "SIGINT"): boolean; + emit(event: "SIGTSTP"): boolean; + emit(event: "history", history: string[]): boolean; + on(event: string, listener: (...args: any[]) => void): this; + on(event: "close", listener: () => void): this; + on(event: "line", listener: (input: string) => void): this; + on(event: "pause", listener: () => void): this; + on(event: "resume", listener: () => void): this; + on(event: "SIGCONT", listener: () => void): this; + on(event: "SIGINT", listener: () => void): this; + on(event: "SIGTSTP", listener: () => void): this; + on(event: "history", listener: (history: string[]) => void): this; + once(event: string, listener: (...args: any[]) => void): this; + once(event: "close", listener: () => void): this; + once(event: "line", listener: (input: string) => void): this; + once(event: "pause", listener: () => void): this; + once(event: "resume", listener: () => void): this; + once(event: "SIGCONT", listener: () => void): this; + once(event: "SIGINT", listener: () => void): this; + once(event: "SIGTSTP", listener: () => void): this; + once(event: "history", listener: (history: string[]) => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "close", listener: () => void): this; + prependListener(event: "line", listener: (input: string) => void): this; + prependListener(event: "pause", listener: () => void): this; + prependListener(event: "resume", listener: () => void): this; + prependListener(event: "SIGCONT", listener: () => void): this; + prependListener(event: "SIGINT", listener: () => void): this; + prependListener(event: "SIGTSTP", listener: () => void): this; + prependListener(event: "history", listener: (history: string[]) => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "line", listener: (input: string) => void): this; + prependOnceListener(event: "pause", listener: () => void): this; + prependOnceListener(event: "resume", listener: () => void): this; + prependOnceListener(event: "SIGCONT", listener: () => void): this; + prependOnceListener(event: "SIGINT", listener: () => void): this; + prependOnceListener(event: "SIGTSTP", listener: () => void): this; + prependOnceListener(event: "history", listener: (history: string[]) => void): this; + [Symbol.asyncIterator](): AsyncIterableIterator; + } + export type ReadLine = Interface; // type forwarded for backwards compatibility + export type Completer = (line: string) => CompleterResult; + export type AsyncCompleter = ( + line: string, + callback: (err?: null | Error, result?: CompleterResult) => void, + ) => void; + export type CompleterResult = [string[], string]; + export interface ReadLineOptions { + input: NodeJS.ReadableStream; + output?: NodeJS.WritableStream | undefined; + completer?: Completer | AsyncCompleter | undefined; + terminal?: boolean | undefined; + /** + * Initial list of history lines. This option makes sense + * only if `terminal` is set to `true` by the user or by an internal `output` + * check, otherwise the history caching mechanism is not initialized at all. + * @default [] + */ + history?: string[] | undefined; + historySize?: number | undefined; + prompt?: string | undefined; + crlfDelay?: number | undefined; + /** + * If `true`, when a new input line added + * to the history list duplicates an older one, this removes the older line + * from the list. + * @default false + */ + removeHistoryDuplicates?: boolean | undefined; + escapeCodeTimeout?: number | undefined; + tabSize?: number | undefined; + } + /** + * The `readline.createInterface()` method creates a new `readline.Interface` instance. + * + * ```js + * const readline = require('node:readline'); + * const rl = readline.createInterface({ + * input: process.stdin, + * output: process.stdout, + * }); + * ``` + * + * Once the `readline.Interface` instance is created, the most common case is to + * listen for the `'line'` event: + * + * ```js + * rl.on('line', (line) => { + * console.log(`Received: ${line}`); + * }); + * ``` + * + * If `terminal` is `true` for this instance then the `output` stream will get + * the best compatibility if it defines an `output.columns` property and emits + * a `'resize'` event on the `output` if or when the columns ever change + * (`process.stdout` does this automatically when it is a TTY). + * + * When creating a `readline.Interface` using `stdin` as input, the program + * will not terminate until it receives an [EOF character](https://en.wikipedia.org/wiki/End-of-file#EOF_character). To exit without + * waiting for user input, call `process.stdin.unref()`. + * @since v0.1.98 + */ + export function createInterface( + input: NodeJS.ReadableStream, + output?: NodeJS.WritableStream, + completer?: Completer | AsyncCompleter, + terminal?: boolean, + ): Interface; + export function createInterface(options: ReadLineOptions): Interface; + /** + * The `readline.emitKeypressEvents()` method causes the given `Readable` stream to begin emitting `'keypress'` events corresponding to received input. + * + * Optionally, `interface` specifies a `readline.Interface` instance for which + * autocompletion is disabled when copy-pasted input is detected. + * + * If the `stream` is a `TTY`, then it must be in raw mode. + * + * This is automatically called by any readline instance on its `input` if the `input` is a terminal. Closing the `readline` instance does not stop + * the `input` from emitting `'keypress'` events. + * + * ```js + * readline.emitKeypressEvents(process.stdin); + * if (process.stdin.isTTY) + * process.stdin.setRawMode(true); + * ``` + * + * ## Example: Tiny CLI + * + * The following example illustrates the use of `readline.Interface` class to + * implement a small command-line interface: + * + * ```js + * const readline = require('node:readline'); + * const rl = readline.createInterface({ + * input: process.stdin, + * output: process.stdout, + * prompt: 'OHAI> ', + * }); + * + * rl.prompt(); + * + * rl.on('line', (line) => { + * switch (line.trim()) { + * case 'hello': + * console.log('world!'); + * break; + * default: + * console.log(`Say what? I might have heard '${line.trim()}'`); + * break; + * } + * rl.prompt(); + * }).on('close', () => { + * console.log('Have a great day!'); + * process.exit(0); + * }); + * ``` + * + * ## Example: Read file stream line-by-Line + * + * A common use case for `readline` is to consume an input file one line at a + * time. The easiest way to do so is leveraging the `fs.ReadStream` API as + * well as a `for await...of` loop: + * + * ```js + * const fs = require('node:fs'); + * const readline = require('node:readline'); + * + * async function processLineByLine() { + * const fileStream = fs.createReadStream('input.txt'); + * + * const rl = readline.createInterface({ + * input: fileStream, + * crlfDelay: Infinity, + * }); + * // Note: we use the crlfDelay option to recognize all instances of CR LF + * // ('\r\n') in input.txt as a single line break. + * + * for await (const line of rl) { + * // Each line in input.txt will be successively available here as `line`. + * console.log(`Line from file: ${line}`); + * } + * } + * + * processLineByLine(); + * ``` + * + * Alternatively, one could use the `'line'` event: + * + * ```js + * const fs = require('node:fs'); + * const readline = require('node:readline'); + * + * const rl = readline.createInterface({ + * input: fs.createReadStream('sample.txt'), + * crlfDelay: Infinity, + * }); + * + * rl.on('line', (line) => { + * console.log(`Line from file: ${line}`); + * }); + * ``` + * + * Currently, `for await...of` loop can be a bit slower. If `async` / `await` flow and speed are both essential, a mixed approach can be applied: + * + * ```js + * const { once } = require('node:events'); + * const { createReadStream } = require('node:fs'); + * const { createInterface } = require('node:readline'); + * + * (async function processLineByLine() { + * try { + * const rl = createInterface({ + * input: createReadStream('big-file.txt'), + * crlfDelay: Infinity, + * }); + * + * rl.on('line', (line) => { + * // Process the line. + * }); + * + * await once(rl, 'close'); + * + * console.log('File processed.'); + * } catch (err) { + * console.error(err); + * } + * })(); + * ``` + * @since v0.7.7 + */ + export function emitKeypressEvents(stream: NodeJS.ReadableStream, readlineInterface?: Interface): void; + export type Direction = -1 | 0 | 1; + export interface CursorPos { + rows: number; + cols: number; + } + /** + * The `readline.clearLine()` method clears current line of given [TTY](https://nodejs.org/docs/latest-v20.x/api/tty.html) stream + * in a specified direction identified by `dir`. + * @since v0.7.7 + * @param callback Invoked once the operation completes. + * @return `false` if `stream` wishes for the calling code to wait for the `'drain'` event to be emitted before continuing to write additional data; otherwise `true`. + */ + export function clearLine(stream: NodeJS.WritableStream, dir: Direction, callback?: () => void): boolean; + /** + * The `readline.clearScreenDown()` method clears the given [TTY](https://nodejs.org/docs/latest-v20.x/api/tty.html) stream from + * the current position of the cursor down. + * @since v0.7.7 + * @param callback Invoked once the operation completes. + * @return `false` if `stream` wishes for the calling code to wait for the `'drain'` event to be emitted before continuing to write additional data; otherwise `true`. + */ + export function clearScreenDown(stream: NodeJS.WritableStream, callback?: () => void): boolean; + /** + * The `readline.cursorTo()` method moves cursor to the specified position in a + * given [TTY](https://nodejs.org/docs/latest-v20.x/api/tty.html) `stream`. + * @since v0.7.7 + * @param callback Invoked once the operation completes. + * @return `false` if `stream` wishes for the calling code to wait for the `'drain'` event to be emitted before continuing to write additional data; otherwise `true`. + */ + export function cursorTo(stream: NodeJS.WritableStream, x: number, y?: number, callback?: () => void): boolean; + /** + * The `readline.moveCursor()` method moves the cursor _relative_ to its current + * position in a given [TTY](https://nodejs.org/docs/latest-v20.x/api/tty.html) `stream`. + * @since v0.7.7 + * @param callback Invoked once the operation completes. + * @return `false` if `stream` wishes for the calling code to wait for the `'drain'` event to be emitted before continuing to write additional data; otherwise `true`. + */ + export function moveCursor(stream: NodeJS.WritableStream, dx: number, dy: number, callback?: () => void): boolean; +} +declare module "node:readline" { + export * from "readline"; +} diff --git a/node_modules/@types/node/readline/promises.d.ts b/node_modules/@types/node/readline/promises.d.ts new file mode 100644 index 0000000..f2826bb --- /dev/null +++ b/node_modules/@types/node/readline/promises.d.ts @@ -0,0 +1,150 @@ +/** + * @since v17.0.0 + * @experimental + */ +declare module "readline/promises" { + import { AsyncCompleter, Completer, Direction, Interface as _Interface, ReadLineOptions } from "node:readline"; + import { Abortable } from "node:events"; + /** + * Instances of the `readlinePromises.Interface` class are constructed using the `readlinePromises.createInterface()` method. Every instance is associated with a + * single `input` `Readable` stream and a single `output` `Writable` stream. + * The `output` stream is used to print prompts for user input that arrives on, + * and is read from, the `input` stream. + * @since v17.0.0 + */ + class Interface extends _Interface { + /** + * The `rl.question()` method displays the `query` by writing it to the `output`, + * waits for user input to be provided on `input`, then invokes the `callback` function passing the provided input as the first argument. + * + * When called, `rl.question()` will resume the `input` stream if it has been + * paused. + * + * If the `Interface` was created with `output` set to `null` or `undefined` the `query` is not written. + * + * If the question is called after `rl.close()`, it returns a rejected promise. + * + * Example usage: + * + * ```js + * const answer = await rl.question('What is your favorite food? '); + * console.log(`Oh, so your favorite food is ${answer}`); + * ``` + * + * Using an `AbortSignal` to cancel a question. + * + * ```js + * const signal = AbortSignal.timeout(10_000); + * + * signal.addEventListener('abort', () => { + * console.log('The food question timed out'); + * }, { once: true }); + * + * const answer = await rl.question('What is your favorite food? ', { signal }); + * console.log(`Oh, so your favorite food is ${answer}`); + * ``` + * @since v17.0.0 + * @param query A statement or query to write to `output`, prepended to the prompt. + * @return A promise that is fulfilled with the user's input in response to the `query`. + */ + question(query: string): Promise; + question(query: string, options: Abortable): Promise; + } + /** + * @since v17.0.0 + */ + class Readline { + /** + * @param stream A TTY stream. + */ + constructor( + stream: NodeJS.WritableStream, + options?: { + autoCommit?: boolean; + }, + ); + /** + * The `rl.clearLine()` method adds to the internal list of pending action an + * action that clears current line of the associated `stream` in a specified + * direction identified by `dir`. + * Call `rl.commit()` to see the effect of this method, unless `autoCommit: true` was passed to the constructor. + * @since v17.0.0 + * @return this + */ + clearLine(dir: Direction): this; + /** + * The `rl.clearScreenDown()` method adds to the internal list of pending action an + * action that clears the associated stream from the current position of the + * cursor down. + * Call `rl.commit()` to see the effect of this method, unless `autoCommit: true` was passed to the constructor. + * @since v17.0.0 + * @return this + */ + clearScreenDown(): this; + /** + * The `rl.commit()` method sends all the pending actions to the associated `stream` and clears the internal list of pending actions. + * @since v17.0.0 + */ + commit(): Promise; + /** + * The `rl.cursorTo()` method adds to the internal list of pending action an action + * that moves cursor to the specified position in the associated `stream`. + * Call `rl.commit()` to see the effect of this method, unless `autoCommit: true` was passed to the constructor. + * @since v17.0.0 + * @return this + */ + cursorTo(x: number, y?: number): this; + /** + * The `rl.moveCursor()` method adds to the internal list of pending action an + * action that moves the cursor _relative_ to its current position in the + * associated `stream`. + * Call `rl.commit()` to see the effect of this method, unless `autoCommit: true` was passed to the constructor. + * @since v17.0.0 + * @return this + */ + moveCursor(dx: number, dy: number): this; + /** + * The `rl.rollback` methods clears the internal list of pending actions without + * sending it to the associated `stream`. + * @since v17.0.0 + * @return this + */ + rollback(): this; + } + /** + * The `readlinePromises.createInterface()` method creates a new `readlinePromises.Interface` instance. + * + * ```js + * const readlinePromises = require('node:readline/promises'); + * const rl = readlinePromises.createInterface({ + * input: process.stdin, + * output: process.stdout, + * }); + * ``` + * + * Once the `readlinePromises.Interface` instance is created, the most common case + * is to listen for the `'line'` event: + * + * ```js + * rl.on('line', (line) => { + * console.log(`Received: ${line}`); + * }); + * ``` + * + * If `terminal` is `true` for this instance then the `output` stream will get + * the best compatibility if it defines an `output.columns` property and emits + * a `'resize'` event on the `output` if or when the columns ever change + * (`process.stdout` does this automatically when it is a TTY). + * @since v17.0.0 + */ + function createInterface( + input: NodeJS.ReadableStream, + output?: NodeJS.WritableStream, + completer?: Completer | AsyncCompleter, + terminal?: boolean, + ): Interface; + function createInterface(options: ReadLineOptions): Interface; +} +declare module "node:readline/promises" { + export * from "readline/promises"; +} diff --git a/node_modules/@types/node/repl.d.ts b/node_modules/@types/node/repl.d.ts new file mode 100644 index 0000000..f55ef66 --- /dev/null +++ b/node_modules/@types/node/repl.d.ts @@ -0,0 +1,430 @@ +/** + * The `node:repl` module provides a Read-Eval-Print-Loop (REPL) implementation + * that is available both as a standalone program or includible in other + * applications. It can be accessed using: + * + * ```js + * const repl = require('node:repl'); + * ``` + * @see [source](https://github.com/nodejs/node/blob/v20.13.1/lib/repl.js) + */ +declare module "repl" { + import { AsyncCompleter, Completer, Interface } from "node:readline"; + import { Context } from "node:vm"; + import { InspectOptions } from "node:util"; + interface ReplOptions { + /** + * The input prompt to display. + * @default "> " + */ + prompt?: string | undefined; + /** + * The `Readable` stream from which REPL input will be read. + * @default process.stdin + */ + input?: NodeJS.ReadableStream | undefined; + /** + * The `Writable` stream to which REPL output will be written. + * @default process.stdout + */ + output?: NodeJS.WritableStream | undefined; + /** + * If `true`, specifies that the output should be treated as a TTY terminal, and have + * ANSI/VT100 escape codes written to it. + * Default: checking the value of the `isTTY` property on the output stream upon + * instantiation. + */ + terminal?: boolean | undefined; + /** + * The function to be used when evaluating each given line of input. + * Default: an async wrapper for the JavaScript `eval()` function. An `eval` function can + * error with `repl.Recoverable` to indicate the input was incomplete and prompt for + * additional lines. + * + * @see https://nodejs.org/dist/latest-v20.x/docs/api/repl.html#repl_default_evaluation + * @see https://nodejs.org/dist/latest-v20.x/docs/api/repl.html#repl_custom_evaluation_functions + */ + eval?: REPLEval | undefined; + /** + * Defines if the repl prints output previews or not. + * @default `true` Always `false` in case `terminal` is falsy. + */ + preview?: boolean | undefined; + /** + * If `true`, specifies that the default `writer` function should include ANSI color + * styling to REPL output. If a custom `writer` function is provided then this has no + * effect. + * @default the REPL instance's `terminal` value + */ + useColors?: boolean | undefined; + /** + * If `true`, specifies that the default evaluation function will use the JavaScript + * `global` as the context as opposed to creating a new separate context for the REPL + * instance. The node CLI REPL sets this value to `true`. + * @default false + */ + useGlobal?: boolean | undefined; + /** + * If `true`, specifies that the default writer will not output the return value of a + * command if it evaluates to `undefined`. + * @default false + */ + ignoreUndefined?: boolean | undefined; + /** + * The function to invoke to format the output of each command before writing to `output`. + * @default a wrapper for `util.inspect` + * + * @see https://nodejs.org/dist/latest-v20.x/docs/api/repl.html#repl_customizing_repl_output + */ + writer?: REPLWriter | undefined; + /** + * An optional function used for custom Tab auto completion. + * + * @see https://nodejs.org/dist/latest-v20.x/docs/api/readline.html#readline_use_of_the_completer_function + */ + completer?: Completer | AsyncCompleter | undefined; + /** + * A flag that specifies whether the default evaluator executes all JavaScript commands in + * strict mode or default (sloppy) mode. + * Accepted values are: + * - `repl.REPL_MODE_SLOPPY` - evaluates expressions in sloppy mode. + * - `repl.REPL_MODE_STRICT` - evaluates expressions in strict mode. This is equivalent to + * prefacing every repl statement with `'use strict'`. + */ + replMode?: typeof REPL_MODE_SLOPPY | typeof REPL_MODE_STRICT | undefined; + /** + * Stop evaluating the current piece of code when `SIGINT` is received, i.e. `Ctrl+C` is + * pressed. This cannot be used together with a custom `eval` function. + * @default false + */ + breakEvalOnSigint?: boolean | undefined; + } + type REPLEval = ( + this: REPLServer, + evalCmd: string, + context: Context, + file: string, + cb: (err: Error | null, result: any) => void, + ) => void; + type REPLWriter = (this: REPLServer, obj: any) => string; + /** + * This is the default "writer" value, if none is passed in the REPL options, + * and it can be overridden by custom print functions. + */ + const writer: REPLWriter & { + options: InspectOptions; + }; + type REPLCommandAction = (this: REPLServer, text: string) => void; + interface REPLCommand { + /** + * Help text to be displayed when `.help` is entered. + */ + help?: string | undefined; + /** + * The function to execute, optionally accepting a single string argument. + */ + action: REPLCommandAction; + } + /** + * Instances of `repl.REPLServer` are created using the {@link start} method + * or directly using the JavaScript `new` keyword. + * + * ```js + * const repl = require('node:repl'); + * + * const options = { useColors: true }; + * + * const firstInstance = repl.start(options); + * const secondInstance = new repl.REPLServer(options); + * ``` + * @since v0.1.91 + */ + class REPLServer extends Interface { + /** + * The `vm.Context` provided to the `eval` function to be used for JavaScript + * evaluation. + */ + readonly context: Context; + /** + * @deprecated since v14.3.0 - Use `input` instead. + */ + readonly inputStream: NodeJS.ReadableStream; + /** + * @deprecated since v14.3.0 - Use `output` instead. + */ + readonly outputStream: NodeJS.WritableStream; + /** + * The `Readable` stream from which REPL input will be read. + */ + readonly input: NodeJS.ReadableStream; + /** + * The `Writable` stream to which REPL output will be written. + */ + readonly output: NodeJS.WritableStream; + /** + * The commands registered via `replServer.defineCommand()`. + */ + readonly commands: NodeJS.ReadOnlyDict; + /** + * A value indicating whether the REPL is currently in "editor mode". + * + * @see https://nodejs.org/dist/latest-v20.x/docs/api/repl.html#repl_commands_and_special_keys + */ + readonly editorMode: boolean; + /** + * A value indicating whether the `_` variable has been assigned. + * + * @see https://nodejs.org/dist/latest-v20.x/docs/api/repl.html#repl_assignment_of_the_underscore_variable + */ + readonly underscoreAssigned: boolean; + /** + * The last evaluation result from the REPL (assigned to the `_` variable inside of the REPL). + * + * @see https://nodejs.org/dist/latest-v20.x/docs/api/repl.html#repl_assignment_of_the_underscore_variable + */ + readonly last: any; + /** + * A value indicating whether the `_error` variable has been assigned. + * + * @since v9.8.0 + * @see https://nodejs.org/dist/latest-v20.x/docs/api/repl.html#repl_assignment_of_the_underscore_variable + */ + readonly underscoreErrAssigned: boolean; + /** + * The last error raised inside the REPL (assigned to the `_error` variable inside of the REPL). + * + * @since v9.8.0 + * @see https://nodejs.org/dist/latest-v20.x/docs/api/repl.html#repl_assignment_of_the_underscore_variable + */ + readonly lastError: any; + /** + * Specified in the REPL options, this is the function to be used when evaluating each + * given line of input. If not specified in the REPL options, this is an async wrapper + * for the JavaScript `eval()` function. + */ + readonly eval: REPLEval; + /** + * Specified in the REPL options, this is a value indicating whether the default + * `writer` function should include ANSI color styling to REPL output. + */ + readonly useColors: boolean; + /** + * Specified in the REPL options, this is a value indicating whether the default `eval` + * function will use the JavaScript `global` as the context as opposed to creating a new + * separate context for the REPL instance. + */ + readonly useGlobal: boolean; + /** + * Specified in the REPL options, this is a value indicating whether the default `writer` + * function should output the result of a command if it evaluates to `undefined`. + */ + readonly ignoreUndefined: boolean; + /** + * Specified in the REPL options, this is the function to invoke to format the output of + * each command before writing to `outputStream`. If not specified in the REPL options, + * this will be a wrapper for `util.inspect`. + */ + readonly writer: REPLWriter; + /** + * Specified in the REPL options, this is the function to use for custom Tab auto-completion. + */ + readonly completer: Completer | AsyncCompleter; + /** + * Specified in the REPL options, this is a flag that specifies whether the default `eval` + * function should execute all JavaScript commands in strict mode or default (sloppy) mode. + * Possible values are: + * - `repl.REPL_MODE_SLOPPY` - evaluates expressions in sloppy mode. + * - `repl.REPL_MODE_STRICT` - evaluates expressions in strict mode. This is equivalent to + * prefacing every repl statement with `'use strict'`. + */ + readonly replMode: typeof REPL_MODE_SLOPPY | typeof REPL_MODE_STRICT; + /** + * NOTE: According to the documentation: + * + * > Instances of `repl.REPLServer` are created using the `repl.start()` method and + * > _should not_ be created directly using the JavaScript `new` keyword. + * + * `REPLServer` cannot be subclassed due to implementation specifics in NodeJS. + * + * @see https://nodejs.org/dist/latest-v20.x/docs/api/repl.html#repl_class_replserver + */ + private constructor(); + /** + * The `replServer.defineCommand()` method is used to add new `.`\-prefixed commands + * to the REPL instance. Such commands are invoked by typing a `.` followed by the `keyword`. The `cmd` is either a `Function` or an `Object` with the following + * properties: + * + * The following example shows two new commands added to the REPL instance: + * + * ```js + * const repl = require('node:repl'); + * + * const replServer = repl.start({ prompt: '> ' }); + * replServer.defineCommand('sayhello', { + * help: 'Say hello', + * action(name) { + * this.clearBufferedCommand(); + * console.log(`Hello, ${name}!`); + * this.displayPrompt(); + * }, + * }); + * replServer.defineCommand('saybye', function saybye() { + * console.log('Goodbye!'); + * this.close(); + * }); + * ``` + * + * The new commands can then be used from within the REPL instance: + * + * ```console + * > .sayhello Node.js User + * Hello, Node.js User! + * > .saybye + * Goodbye! + * ``` + * @since v0.3.0 + * @param keyword The command keyword (_without_ a leading `.` character). + * @param cmd The function to invoke when the command is processed. + */ + defineCommand(keyword: string, cmd: REPLCommandAction | REPLCommand): void; + /** + * The `replServer.displayPrompt()` method readies the REPL instance for input + * from the user, printing the configured `prompt` to a new line in the `output` and resuming the `input` to accept new input. + * + * When multi-line input is being entered, an ellipsis is printed rather than the + * 'prompt'. + * + * When `preserveCursor` is `true`, the cursor placement will not be reset to `0`. + * + * The `replServer.displayPrompt` method is primarily intended to be called from + * within the action function for commands registered using the `replServer.defineCommand()` method. + * @since v0.1.91 + */ + displayPrompt(preserveCursor?: boolean): void; + /** + * The `replServer.clearBufferedCommand()` method clears any command that has been + * buffered but not yet executed. This method is primarily intended to be + * called from within the action function for commands registered using the `replServer.defineCommand()` method. + * @since v9.0.0 + */ + clearBufferedCommand(): void; + /** + * Initializes a history log file for the REPL instance. When executing the + * Node.js binary and using the command-line REPL, a history file is initialized + * by default. However, this is not the case when creating a REPL + * programmatically. Use this method to initialize a history log file when working + * with REPL instances programmatically. + * @since v11.10.0 + * @param historyPath the path to the history file + * @param callback called when history writes are ready or upon error + */ + setupHistory(path: string, callback: (err: Error | null, repl: this) => void): void; + /** + * events.EventEmitter + * 1. close - inherited from `readline.Interface` + * 2. line - inherited from `readline.Interface` + * 3. pause - inherited from `readline.Interface` + * 4. resume - inherited from `readline.Interface` + * 5. SIGCONT - inherited from `readline.Interface` + * 6. SIGINT - inherited from `readline.Interface` + * 7. SIGTSTP - inherited from `readline.Interface` + * 8. exit + * 9. reset + */ + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "close", listener: () => void): this; + addListener(event: "line", listener: (input: string) => void): this; + addListener(event: "pause", listener: () => void): this; + addListener(event: "resume", listener: () => void): this; + addListener(event: "SIGCONT", listener: () => void): this; + addListener(event: "SIGINT", listener: () => void): this; + addListener(event: "SIGTSTP", listener: () => void): this; + addListener(event: "exit", listener: () => void): this; + addListener(event: "reset", listener: (context: Context) => void): this; + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: "close"): boolean; + emit(event: "line", input: string): boolean; + emit(event: "pause"): boolean; + emit(event: "resume"): boolean; + emit(event: "SIGCONT"): boolean; + emit(event: "SIGINT"): boolean; + emit(event: "SIGTSTP"): boolean; + emit(event: "exit"): boolean; + emit(event: "reset", context: Context): boolean; + on(event: string, listener: (...args: any[]) => void): this; + on(event: "close", listener: () => void): this; + on(event: "line", listener: (input: string) => void): this; + on(event: "pause", listener: () => void): this; + on(event: "resume", listener: () => void): this; + on(event: "SIGCONT", listener: () => void): this; + on(event: "SIGINT", listener: () => void): this; + on(event: "SIGTSTP", listener: () => void): this; + on(event: "exit", listener: () => void): this; + on(event: "reset", listener: (context: Context) => void): this; + once(event: string, listener: (...args: any[]) => void): this; + once(event: "close", listener: () => void): this; + once(event: "line", listener: (input: string) => void): this; + once(event: "pause", listener: () => void): this; + once(event: "resume", listener: () => void): this; + once(event: "SIGCONT", listener: () => void): this; + once(event: "SIGINT", listener: () => void): this; + once(event: "SIGTSTP", listener: () => void): this; + once(event: "exit", listener: () => void): this; + once(event: "reset", listener: (context: Context) => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "close", listener: () => void): this; + prependListener(event: "line", listener: (input: string) => void): this; + prependListener(event: "pause", listener: () => void): this; + prependListener(event: "resume", listener: () => void): this; + prependListener(event: "SIGCONT", listener: () => void): this; + prependListener(event: "SIGINT", listener: () => void): this; + prependListener(event: "SIGTSTP", listener: () => void): this; + prependListener(event: "exit", listener: () => void): this; + prependListener(event: "reset", listener: (context: Context) => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "line", listener: (input: string) => void): this; + prependOnceListener(event: "pause", listener: () => void): this; + prependOnceListener(event: "resume", listener: () => void): this; + prependOnceListener(event: "SIGCONT", listener: () => void): this; + prependOnceListener(event: "SIGINT", listener: () => void): this; + prependOnceListener(event: "SIGTSTP", listener: () => void): this; + prependOnceListener(event: "exit", listener: () => void): this; + prependOnceListener(event: "reset", listener: (context: Context) => void): this; + } + /** + * A flag passed in the REPL options. Evaluates expressions in sloppy mode. + */ + const REPL_MODE_SLOPPY: unique symbol; + /** + * A flag passed in the REPL options. Evaluates expressions in strict mode. + * This is equivalent to prefacing every repl statement with `'use strict'`. + */ + const REPL_MODE_STRICT: unique symbol; + /** + * The `repl.start()` method creates and starts a {@link REPLServer} instance. + * + * If `options` is a string, then it specifies the input prompt: + * + * ```js + * const repl = require('node:repl'); + * + * // a Unix style prompt + * repl.start('$ '); + * ``` + * @since v0.1.91 + */ + function start(options?: string | ReplOptions): REPLServer; + /** + * Indicates a recoverable error that a `REPLServer` can use to support multi-line input. + * + * @see https://nodejs.org/dist/latest-v20.x/docs/api/repl.html#repl_recoverable_errors + */ + class Recoverable extends SyntaxError { + err: Error; + constructor(err: Error); + } +} +declare module "node:repl" { + export * from "repl"; +} diff --git a/node_modules/@types/node/sea.d.ts b/node_modules/@types/node/sea.d.ts new file mode 100644 index 0000000..6f1d1ea --- /dev/null +++ b/node_modules/@types/node/sea.d.ts @@ -0,0 +1,153 @@ +/** + * This feature allows the distribution of a Node.js application conveniently to a + * system that does not have Node.js installed. + * + * Node.js supports the creation of [single executable applications](https://github.com/nodejs/single-executable) by allowing + * the injection of a blob prepared by Node.js, which can contain a bundled script, + * into the `node` binary. During start up, the program checks if anything has been + * injected. If the blob is found, it executes the script in the blob. Otherwise + * Node.js operates as it normally does. + * + * The single executable application feature currently only supports running a + * single embedded script using the `CommonJS` module system. + * + * Users can create a single executable application from their bundled script + * with the `node` binary itself and any tool which can inject resources into the + * binary. + * + * Here are the steps for creating a single executable application using one such + * tool, [postject](https://github.com/nodejs/postject): + * + * 1. Create a JavaScript file: + * ```bash + * echo 'console.log(`Hello, ${process.argv[2]}!`);' > hello.js + * ``` + * 2. Create a configuration file building a blob that can be injected into the + * single executable application (see `Generating single executable preparation blobs` for details): + * ```bash + * echo '{ "main": "hello.js", "output": "sea-prep.blob" }' > sea-config.json + * ``` + * 3. Generate the blob to be injected: + * ```bash + * node --experimental-sea-config sea-config.json + * ``` + * 4. Create a copy of the `node` executable and name it according to your needs: + * * On systems other than Windows: + * ```bash + * cp $(command -v node) hello + * ``` + * * On Windows: + * ```text + * node -e "require('fs').copyFileSync(process.execPath, 'hello.exe')" + * ``` + * The `.exe` extension is necessary. + * 5. Remove the signature of the binary (macOS and Windows only): + * * On macOS: + * ```bash + * codesign --remove-signature hello + * ``` + * * On Windows (optional): + * [signtool](https://learn.microsoft.com/en-us/windows/win32/seccrypto/signtool) can be used from the installed [Windows SDK](https://developer.microsoft.com/en-us/windows/downloads/windows-sdk/). + * If this step is + * skipped, ignore any signature-related warning from postject. + * ```powershell + * signtool remove /s hello.exe + * ``` + * 6. Inject the blob into the copied binary by running `postject` with + * the following options: + * * `hello` / `hello.exe` \- The name of the copy of the `node` executable + * created in step 4. + * * `NODE_SEA_BLOB` \- The name of the resource / note / section in the binary + * where the contents of the blob will be stored. + * * `sea-prep.blob` \- The name of the blob created in step 1. + * * `--sentinel-fuse NODE_SEA_FUSE_fce680ab2cc467b6e072b8b5df1996b2` \- The [fuse](https://www.electronjs.org/docs/latest/tutorial/fuses) used by the Node.js project to detect if a file has been + * injected. + * * `--macho-segment-name NODE_SEA` (only needed on macOS) - The name of the + * segment in the binary where the contents of the blob will be + * stored. + * To summarize, here is the required command for each platform: + * * On Linux: + * ```bash + * npx postject hello NODE_SEA_BLOB sea-prep.blob \ + * --sentinel-fuse NODE_SEA_FUSE_fce680ab2cc467b6e072b8b5df1996b2 + * ``` + * * On Windows - PowerShell: + * ```powershell + * npx postject hello.exe NODE_SEA_BLOB sea-prep.blob ` + * --sentinel-fuse NODE_SEA_FUSE_fce680ab2cc467b6e072b8b5df1996b2 + * ``` + * * On Windows - Command Prompt: + * ```text + * npx postject hello.exe NODE_SEA_BLOB sea-prep.blob ^ + * --sentinel-fuse NODE_SEA_FUSE_fce680ab2cc467b6e072b8b5df1996b2 + * ``` + * * On macOS: + * ```bash + * npx postject hello NODE_SEA_BLOB sea-prep.blob \ + * --sentinel-fuse NODE_SEA_FUSE_fce680ab2cc467b6e072b8b5df1996b2 \ + * --macho-segment-name NODE_SEA + * ``` + * 7. Sign the binary (macOS and Windows only): + * * On macOS: + * ```bash + * codesign --sign - hello + * ``` + * * On Windows (optional): + * A certificate needs to be present for this to work. However, the unsigned + * binary would still be runnable. + * ```powershell + * signtool sign /fd SHA256 hello.exe + * ``` + * 8. Run the binary: + * * On systems other than Windows + * ```console + * $ ./hello world + * Hello, world! + * ``` + * * On Windows + * ```console + * $ .\hello.exe world + * Hello, world! + * ``` + * @since v19.7.0, v18.16.0 + * @experimental + * @see [source](https://github.com/nodejs/node/blob/v20.12.0/src/node_sea.cc) + */ +declare module "node:sea" { + type AssetKey = string; + /** + * @since v20.12.0 + * @return Whether this script is running inside a single-executable application. + */ + function isSea(): boolean; + /** + * This method can be used to retrieve the assets configured to be bundled into the + * single-executable application at build time. + * An error is thrown when no matching asset can be found. + * @since v20.12.0 + */ + function getAsset(key: AssetKey): ArrayBuffer; + function getAsset(key: AssetKey, encoding: string): string; + /** + * Similar to `sea.getAsset()`, but returns the result in a [`Blob`](https://developer.mozilla.org/en-US/docs/Web/API/Blob). + * An error is thrown when no matching asset can be found. + * @since v20.12.0 + */ + function getAssetAsBlob(key: AssetKey, options?: { + type: string; + }): Blob; + /** + * This method can be used to retrieve the assets configured to be bundled into the + * single-executable application at build time. + * An error is thrown when no matching asset can be found. + * + * Unlike `sea.getRawAsset()` or `sea.getAssetAsBlob()`, this method does not + * return a copy. Instead, it returns the raw asset bundled inside the executable. + * + * For now, users should avoid writing to the returned array buffer. If the + * injected section is not marked as writable or not aligned properly, + * writes to the returned array buffer is likely to result in a crash. + * @since v20.12.0 + */ + function getRawAsset(key: AssetKey): string | ArrayBuffer; +} diff --git a/node_modules/@types/node/stream.d.ts b/node_modules/@types/node/stream.d.ts new file mode 100644 index 0000000..fbcd37d --- /dev/null +++ b/node_modules/@types/node/stream.d.ts @@ -0,0 +1,1707 @@ +/** + * A stream is an abstract interface for working with streaming data in Node.js. + * The `node:stream` module provides an API for implementing the stream interface. + * + * There are many stream objects provided by Node.js. For instance, a [request to an HTTP server](https://nodejs.org/docs/latest-v20.x/api/http.html#class-httpincomingmessage) + * and [`process.stdout`](https://nodejs.org/docs/latest-v20.x/api/process.html#processstdout) are both stream instances. + * + * Streams can be readable, writable, or both. All streams are instances of [`EventEmitter`](https://nodejs.org/docs/latest-v20.x/api/events.html#class-eventemitter). + * + * To access the `node:stream` module: + * + * ```js + * const stream = require('node:stream'); + * ``` + * + * The `node:stream` module is useful for creating new types of stream instances. + * It is usually not necessary to use the `node:stream` module to consume streams. + * @see [source](https://github.com/nodejs/node/blob/v20.13.1/lib/stream.js) + */ +declare module "stream" { + import { Abortable, EventEmitter } from "node:events"; + import { Blob as NodeBlob } from "node:buffer"; + import * as streamPromises from "node:stream/promises"; + import * as streamConsumers from "node:stream/consumers"; + import * as streamWeb from "node:stream/web"; + + type ComposeFnParam = (source: any) => void; + + class internal extends EventEmitter { + pipe( + destination: T, + options?: { + end?: boolean | undefined; + }, + ): T; + compose( + stream: T | ComposeFnParam | Iterable | AsyncIterable, + options?: { signal: AbortSignal }, + ): T; + } + import Stream = internal.Stream; + import Readable = internal.Readable; + import ReadableOptions = internal.ReadableOptions; + interface ArrayOptions { + /** + * The maximum concurrent invocations of `fn` to call on the stream at once. + * @default 1 + */ + concurrency?: number; + /** Allows destroying the stream if the signal is aborted. */ + signal?: AbortSignal; + } + class ReadableBase extends Stream implements NodeJS.ReadableStream { + /** + * A utility method for creating Readable Streams out of iterators. + * @since v12.3.0, v10.17.0 + * @param iterable Object implementing the `Symbol.asyncIterator` or `Symbol.iterator` iterable protocol. Emits an 'error' event if a null value is passed. + * @param options Options provided to `new stream.Readable([options])`. By default, `Readable.from()` will set `options.objectMode` to `true`, unless this is explicitly opted out by setting `options.objectMode` to `false`. + */ + static from(iterable: Iterable | AsyncIterable, options?: ReadableOptions): Readable; + /** + * Returns whether the stream has been read from or cancelled. + * @since v16.8.0 + */ + static isDisturbed(stream: Readable | NodeJS.ReadableStream): boolean; + /** + * Returns whether the stream was destroyed or errored before emitting `'end'`. + * @since v16.8.0 + * @experimental + */ + readonly readableAborted: boolean; + /** + * Is `true` if it is safe to call {@link read}, which means + * the stream has not been destroyed or emitted `'error'` or `'end'`. + * @since v11.4.0 + */ + readable: boolean; + /** + * Returns whether `'data'` has been emitted. + * @since v16.7.0, v14.18.0 + * @experimental + */ + readonly readableDidRead: boolean; + /** + * Getter for the property `encoding` of a given `Readable` stream. The `encoding` property can be set using the {@link setEncoding} method. + * @since v12.7.0 + */ + readonly readableEncoding: BufferEncoding | null; + /** + * Becomes `true` when [`'end'`](https://nodejs.org/docs/latest-v20.x/api/stream.html#event-end) event is emitted. + * @since v12.9.0 + */ + readonly readableEnded: boolean; + /** + * This property reflects the current state of a `Readable` stream as described + * in the [Three states](https://nodejs.org/docs/latest-v20.x/api/stream.html#three-states) section. + * @since v9.4.0 + */ + readonly readableFlowing: boolean | null; + /** + * Returns the value of `highWaterMark` passed when creating this `Readable`. + * @since v9.3.0 + */ + readonly readableHighWaterMark: number; + /** + * This property contains the number of bytes (or objects) in the queue + * ready to be read. The value provides introspection data regarding + * the status of the `highWaterMark`. + * @since v9.4.0 + */ + readonly readableLength: number; + /** + * Getter for the property `objectMode` of a given `Readable` stream. + * @since v12.3.0 + */ + readonly readableObjectMode: boolean; + /** + * Is `true` after `readable.destroy()` has been called. + * @since v8.0.0 + */ + destroyed: boolean; + /** + * Is `true` after `'close'` has been emitted. + * @since v18.0.0 + */ + readonly closed: boolean; + /** + * Returns error if the stream has been destroyed with an error. + * @since v18.0.0 + */ + readonly errored: Error | null; + constructor(opts?: ReadableOptions); + _construct?(callback: (error?: Error | null) => void): void; + _read(size: number): void; + /** + * The `readable.read()` method reads data out of the internal buffer and + * returns it. If no data is available to be read, `null` is returned. By default, + * the data is returned as a `Buffer` object unless an encoding has been + * specified using the `readable.setEncoding()` method or the stream is operating + * in object mode. + * + * The optional `size` argument specifies a specific number of bytes to read. If + * `size` bytes are not available to be read, `null` will be returned _unless_ the + * stream has ended, in which case all of the data remaining in the internal buffer + * will be returned. + * + * If the `size` argument is not specified, all of the data contained in the + * internal buffer will be returned. + * + * The `size` argument must be less than or equal to 1 GiB. + * + * The `readable.read()` method should only be called on `Readable` streams + * operating in paused mode. In flowing mode, `readable.read()` is called + * automatically until the internal buffer is fully drained. + * + * ```js + * const readable = getReadableStreamSomehow(); + * + * // 'readable' may be triggered multiple times as data is buffered in + * readable.on('readable', () => { + * let chunk; + * console.log('Stream is readable (new data received in buffer)'); + * // Use a loop to make sure we read all currently available data + * while (null !== (chunk = readable.read())) { + * console.log(`Read ${chunk.length} bytes of data...`); + * } + * }); + * + * // 'end' will be triggered once when there is no more data available + * readable.on('end', () => { + * console.log('Reached end of stream.'); + * }); + * ``` + * + * Each call to `readable.read()` returns a chunk of data, or `null`. The chunks + * are not concatenated. A `while` loop is necessary to consume all data + * currently in the buffer. When reading a large file `.read()` may return `null`, + * having consumed all buffered content so far, but there is still more data to + * come not yet buffered. In this case a new `'readable'` event will be emitted + * when there is more data in the buffer. Finally the `'end'` event will be + * emitted when there is no more data to come. + * + * Therefore to read a file's whole contents from a `readable`, it is necessary + * to collect chunks across multiple `'readable'` events: + * + * ```js + * const chunks = []; + * + * readable.on('readable', () => { + * let chunk; + * while (null !== (chunk = readable.read())) { + * chunks.push(chunk); + * } + * }); + * + * readable.on('end', () => { + * const content = chunks.join(''); + * }); + * ``` + * + * A `Readable` stream in object mode will always return a single item from + * a call to `readable.read(size)`, regardless of the value of the `size` argument. + * + * If the `readable.read()` method returns a chunk of data, a `'data'` event will + * also be emitted. + * + * Calling {@link read} after the `'end'` event has + * been emitted will return `null`. No runtime error will be raised. + * @since v0.9.4 + * @param size Optional argument to specify how much data to read. + */ + read(size?: number): any; + /** + * The `readable.setEncoding()` method sets the character encoding for + * data read from the `Readable` stream. + * + * By default, no encoding is assigned and stream data will be returned as `Buffer` objects. Setting an encoding causes the stream data + * to be returned as strings of the specified encoding rather than as `Buffer` objects. For instance, calling `readable.setEncoding('utf8')` will cause the + * output data to be interpreted as UTF-8 data, and passed as strings. Calling `readable.setEncoding('hex')` will cause the data to be encoded in hexadecimal + * string format. + * + * The `Readable` stream will properly handle multi-byte characters delivered + * through the stream that would otherwise become improperly decoded if simply + * pulled from the stream as `Buffer` objects. + * + * ```js + * const readable = getReadableStreamSomehow(); + * readable.setEncoding('utf8'); + * readable.on('data', (chunk) => { + * assert.equal(typeof chunk, 'string'); + * console.log('Got %d characters of string data:', chunk.length); + * }); + * ``` + * @since v0.9.4 + * @param encoding The encoding to use. + */ + setEncoding(encoding: BufferEncoding): this; + /** + * The `readable.pause()` method will cause a stream in flowing mode to stop + * emitting `'data'` events, switching out of flowing mode. Any data that + * becomes available will remain in the internal buffer. + * + * ```js + * const readable = getReadableStreamSomehow(); + * readable.on('data', (chunk) => { + * console.log(`Received ${chunk.length} bytes of data.`); + * readable.pause(); + * console.log('There will be no additional data for 1 second.'); + * setTimeout(() => { + * console.log('Now data will start flowing again.'); + * readable.resume(); + * }, 1000); + * }); + * ``` + * + * The `readable.pause()` method has no effect if there is a `'readable'` event listener. + * @since v0.9.4 + */ + pause(): this; + /** + * The `readable.resume()` method causes an explicitly paused `Readable` stream to + * resume emitting `'data'` events, switching the stream into flowing mode. + * + * The `readable.resume()` method can be used to fully consume the data from a + * stream without actually processing any of that data: + * + * ```js + * getReadableStreamSomehow() + * .resume() + * .on('end', () => { + * console.log('Reached the end, but did not read anything.'); + * }); + * ``` + * + * The `readable.resume()` method has no effect if there is a `'readable'` event listener. + * @since v0.9.4 + */ + resume(): this; + /** + * The `readable.isPaused()` method returns the current operating state of the `Readable`. + * This is used primarily by the mechanism that underlies the `readable.pipe()` method. + * In most typical cases, there will be no reason to use this method directly. + * + * ```js + * const readable = new stream.Readable(); + * + * readable.isPaused(); // === false + * readable.pause(); + * readable.isPaused(); // === true + * readable.resume(); + * readable.isPaused(); // === false + * ``` + * @since v0.11.14 + */ + isPaused(): boolean; + /** + * The `readable.unpipe()` method detaches a `Writable` stream previously attached + * using the {@link pipe} method. + * + * If the `destination` is not specified, then _all_ pipes are detached. + * + * If the `destination` is specified, but no pipe is set up for it, then + * the method does nothing. + * + * ```js + * const fs = require('node:fs'); + * const readable = getReadableStreamSomehow(); + * const writable = fs.createWriteStream('file.txt'); + * // All the data from readable goes into 'file.txt', + * // but only for the first second. + * readable.pipe(writable); + * setTimeout(() => { + * console.log('Stop writing to file.txt.'); + * readable.unpipe(writable); + * console.log('Manually close the file stream.'); + * writable.end(); + * }, 1000); + * ``` + * @since v0.9.4 + * @param destination Optional specific stream to unpipe + */ + unpipe(destination?: NodeJS.WritableStream): this; + /** + * Passing `chunk` as `null` signals the end of the stream (EOF) and behaves the + * same as `readable.push(null)`, after which no more data can be written. The EOF + * signal is put at the end of the buffer and any buffered data will still be + * flushed. + * + * The `readable.unshift()` method pushes a chunk of data back into the internal + * buffer. This is useful in certain situations where a stream is being consumed by + * code that needs to "un-consume" some amount of data that it has optimistically + * pulled out of the source, so that the data can be passed on to some other party. + * + * The `stream.unshift(chunk)` method cannot be called after the `'end'` event + * has been emitted or a runtime error will be thrown. + * + * Developers using `stream.unshift()` often should consider switching to + * use of a `Transform` stream instead. See the `API for stream implementers` section for more information. + * + * ```js + * // Pull off a header delimited by \n\n. + * // Use unshift() if we get too much. + * // Call the callback with (error, header, stream). + * const { StringDecoder } = require('node:string_decoder'); + * function parseHeader(stream, callback) { + * stream.on('error', callback); + * stream.on('readable', onReadable); + * const decoder = new StringDecoder('utf8'); + * let header = ''; + * function onReadable() { + * let chunk; + * while (null !== (chunk = stream.read())) { + * const str = decoder.write(chunk); + * if (str.includes('\n\n')) { + * // Found the header boundary. + * const split = str.split(/\n\n/); + * header += split.shift(); + * const remaining = split.join('\n\n'); + * const buf = Buffer.from(remaining, 'utf8'); + * stream.removeListener('error', callback); + * // Remove the 'readable' listener before unshifting. + * stream.removeListener('readable', onReadable); + * if (buf.length) + * stream.unshift(buf); + * // Now the body of the message can be read from the stream. + * callback(null, header, stream); + * return; + * } + * // Still reading the header. + * header += str; + * } + * } + * } + * ``` + * + * Unlike {@link push}, `stream.unshift(chunk)` will not + * end the reading process by resetting the internal reading state of the stream. + * This can cause unexpected results if `readable.unshift()` is called during a + * read (i.e. from within a {@link _read} implementation on a + * custom stream). Following the call to `readable.unshift()` with an immediate {@link push} will reset the reading state appropriately, + * however it is best to simply avoid calling `readable.unshift()` while in the + * process of performing a read. + * @since v0.9.11 + * @param chunk Chunk of data to unshift onto the read queue. For streams not operating in object mode, `chunk` must + * be a {string}, {Buffer}, {TypedArray}, {DataView} or `null`. For object mode streams, `chunk` may be any JavaScript value. + * @param encoding Encoding of string chunks. Must be a valid `Buffer` encoding, such as `'utf8'` or `'ascii'`. + */ + unshift(chunk: any, encoding?: BufferEncoding): void; + /** + * Prior to Node.js 0.10, streams did not implement the entire `node:stream` module API as it is currently defined. (See `Compatibility` for more + * information.) + * + * When using an older Node.js library that emits `'data'` events and has a {@link pause} method that is advisory only, the `readable.wrap()` method can be used to create a `Readable` + * stream that uses + * the old stream as its data source. + * + * It will rarely be necessary to use `readable.wrap()` but the method has been + * provided as a convenience for interacting with older Node.js applications and + * libraries. + * + * ```js + * const { OldReader } = require('./old-api-module.js'); + * const { Readable } = require('node:stream'); + * const oreader = new OldReader(); + * const myReader = new Readable().wrap(oreader); + * + * myReader.on('readable', () => { + * myReader.read(); // etc. + * }); + * ``` + * @since v0.9.4 + * @param stream An "old style" readable stream + */ + wrap(stream: NodeJS.ReadableStream): this; + push(chunk: any, encoding?: BufferEncoding): boolean; + /** + * The iterator created by this method gives users the option to cancel the destruction + * of the stream if the `for await...of` loop is exited by `return`, `break`, or `throw`, + * or if the iterator should destroy the stream if the stream emitted an error during iteration. + * @since v16.3.0 + * @param options.destroyOnReturn When set to `false`, calling `return` on the async iterator, + * or exiting a `for await...of` iteration using a `break`, `return`, or `throw` will not destroy the stream. + * **Default: `true`**. + */ + iterator(options?: { destroyOnReturn?: boolean }): AsyncIterableIterator; + /** + * This method allows mapping over the stream. The *fn* function will be called for every chunk in the stream. + * If the *fn* function returns a promise - that promise will be `await`ed before being passed to the result stream. + * @since v17.4.0, v16.14.0 + * @param fn a function to map over every chunk in the stream. Async or not. + * @returns a stream mapped with the function *fn*. + */ + map(fn: (data: any, options?: Pick) => any, options?: ArrayOptions): Readable; + /** + * This method allows filtering the stream. For each chunk in the stream the *fn* function will be called + * and if it returns a truthy value, the chunk will be passed to the result stream. + * If the *fn* function returns a promise - that promise will be `await`ed. + * @since v17.4.0, v16.14.0 + * @param fn a function to filter chunks from the stream. Async or not. + * @returns a stream filtered with the predicate *fn*. + */ + filter( + fn: (data: any, options?: Pick) => boolean | Promise, + options?: ArrayOptions, + ): Readable; + /** + * This method allows iterating a stream. For each chunk in the stream the *fn* function will be called. + * If the *fn* function returns a promise - that promise will be `await`ed. + * + * This method is different from `for await...of` loops in that it can optionally process chunks concurrently. + * In addition, a `forEach` iteration can only be stopped by having passed a `signal` option + * and aborting the related AbortController while `for await...of` can be stopped with `break` or `return`. + * In either case the stream will be destroyed. + * + * This method is different from listening to the `'data'` event in that it uses the `readable` event + * in the underlying machinary and can limit the number of concurrent *fn* calls. + * @since v17.5.0 + * @param fn a function to call on each chunk of the stream. Async or not. + * @returns a promise for when the stream has finished. + */ + forEach( + fn: (data: any, options?: Pick) => void | Promise, + options?: ArrayOptions, + ): Promise; + /** + * This method allows easily obtaining the contents of a stream. + * + * As this method reads the entire stream into memory, it negates the benefits of streams. It's intended + * for interoperability and convenience, not as the primary way to consume streams. + * @since v17.5.0 + * @returns a promise containing an array with the contents of the stream. + */ + toArray(options?: Pick): Promise; + /** + * This method is similar to `Array.prototype.some` and calls *fn* on each chunk in the stream + * until the awaited return value is `true` (or any truthy value). Once an *fn* call on a chunk + * `await`ed return value is truthy, the stream is destroyed and the promise is fulfilled with `true`. + * If none of the *fn* calls on the chunks return a truthy value, the promise is fulfilled with `false`. + * @since v17.5.0 + * @param fn a function to call on each chunk of the stream. Async or not. + * @returns a promise evaluating to `true` if *fn* returned a truthy value for at least one of the chunks. + */ + some( + fn: (data: any, options?: Pick) => boolean | Promise, + options?: ArrayOptions, + ): Promise; + /** + * This method is similar to `Array.prototype.find` and calls *fn* on each chunk in the stream + * to find a chunk with a truthy value for *fn*. Once an *fn* call's awaited return value is truthy, + * the stream is destroyed and the promise is fulfilled with value for which *fn* returned a truthy value. + * If all of the *fn* calls on the chunks return a falsy value, the promise is fulfilled with `undefined`. + * @since v17.5.0 + * @param fn a function to call on each chunk of the stream. Async or not. + * @returns a promise evaluating to the first chunk for which *fn* evaluated with a truthy value, + * or `undefined` if no element was found. + */ + find( + fn: (data: any, options?: Pick) => data is T, + options?: ArrayOptions, + ): Promise; + find( + fn: (data: any, options?: Pick) => boolean | Promise, + options?: ArrayOptions, + ): Promise; + /** + * This method is similar to `Array.prototype.every` and calls *fn* on each chunk in the stream + * to check if all awaited return values are truthy value for *fn*. Once an *fn* call on a chunk + * `await`ed return value is falsy, the stream is destroyed and the promise is fulfilled with `false`. + * If all of the *fn* calls on the chunks return a truthy value, the promise is fulfilled with `true`. + * @since v17.5.0 + * @param fn a function to call on each chunk of the stream. Async or not. + * @returns a promise evaluating to `true` if *fn* returned a truthy value for every one of the chunks. + */ + every( + fn: (data: any, options?: Pick) => boolean | Promise, + options?: ArrayOptions, + ): Promise; + /** + * This method returns a new stream by applying the given callback to each chunk of the stream + * and then flattening the result. + * + * It is possible to return a stream or another iterable or async iterable from *fn* and the result streams + * will be merged (flattened) into the returned stream. + * @since v17.5.0 + * @param fn a function to map over every chunk in the stream. May be async. May be a stream or generator. + * @returns a stream flat-mapped with the function *fn*. + */ + flatMap(fn: (data: any, options?: Pick) => any, options?: ArrayOptions): Readable; + /** + * This method returns a new stream with the first *limit* chunks dropped from the start. + * @since v17.5.0 + * @param limit the number of chunks to drop from the readable. + * @returns a stream with *limit* chunks dropped from the start. + */ + drop(limit: number, options?: Pick): Readable; + /** + * This method returns a new stream with the first *limit* chunks. + * @since v17.5.0 + * @param limit the number of chunks to take from the readable. + * @returns a stream with *limit* chunks taken. + */ + take(limit: number, options?: Pick): Readable; + /** + * This method returns a new stream with chunks of the underlying stream paired with a counter + * in the form `[index, chunk]`. The first index value is `0` and it increases by 1 for each chunk produced. + * @since v17.5.0 + * @returns a stream of indexed pairs. + */ + asIndexedPairs(options?: Pick): Readable; + /** + * This method calls *fn* on each chunk of the stream in order, passing it the result from the calculation + * on the previous element. It returns a promise for the final value of the reduction. + * + * If no *initial* value is supplied the first chunk of the stream is used as the initial value. + * If the stream is empty, the promise is rejected with a `TypeError` with the `ERR_INVALID_ARGS` code property. + * + * The reducer function iterates the stream element-by-element which means that there is no *concurrency* parameter + * or parallelism. To perform a reduce concurrently, you can extract the async function to `readable.map` method. + * @since v17.5.0 + * @param fn a reducer function to call over every chunk in the stream. Async or not. + * @param initial the initial value to use in the reduction. + * @returns a promise for the final value of the reduction. + */ + reduce( + fn: (previous: any, data: any, options?: Pick) => T, + initial?: undefined, + options?: Pick, + ): Promise; + reduce( + fn: (previous: T, data: any, options?: Pick) => T, + initial: T, + options?: Pick, + ): Promise; + _destroy(error: Error | null, callback: (error?: Error | null) => void): void; + /** + * Destroy the stream. Optionally emit an `'error'` event, and emit a `'close'` event (unless `emitClose` is set to `false`). After this call, the readable + * stream will release any internal resources and subsequent calls to `push()` will be ignored. + * + * Once `destroy()` has been called any further calls will be a no-op and no + * further errors except from `_destroy()` may be emitted as `'error'`. + * + * Implementors should not override this method, but instead implement `readable._destroy()`. + * @since v8.0.0 + * @param error Error which will be passed as payload in `'error'` event + */ + destroy(error?: Error): this; + /** + * Event emitter + * The defined events on documents including: + * 1. close + * 2. data + * 3. end + * 4. error + * 5. pause + * 6. readable + * 7. resume + */ + addListener(event: "close", listener: () => void): this; + addListener(event: "data", listener: (chunk: any) => void): this; + addListener(event: "end", listener: () => void): this; + addListener(event: "error", listener: (err: Error) => void): this; + addListener(event: "pause", listener: () => void): this; + addListener(event: "readable", listener: () => void): this; + addListener(event: "resume", listener: () => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + emit(event: "close"): boolean; + emit(event: "data", chunk: any): boolean; + emit(event: "end"): boolean; + emit(event: "error", err: Error): boolean; + emit(event: "pause"): boolean; + emit(event: "readable"): boolean; + emit(event: "resume"): boolean; + emit(event: string | symbol, ...args: any[]): boolean; + on(event: "close", listener: () => void): this; + on(event: "data", listener: (chunk: any) => void): this; + on(event: "end", listener: () => void): this; + on(event: "error", listener: (err: Error) => void): this; + on(event: "pause", listener: () => void): this; + on(event: "readable", listener: () => void): this; + on(event: "resume", listener: () => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + once(event: "close", listener: () => void): this; + once(event: "data", listener: (chunk: any) => void): this; + once(event: "end", listener: () => void): this; + once(event: "error", listener: (err: Error) => void): this; + once(event: "pause", listener: () => void): this; + once(event: "readable", listener: () => void): this; + once(event: "resume", listener: () => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + prependListener(event: "close", listener: () => void): this; + prependListener(event: "data", listener: (chunk: any) => void): this; + prependListener(event: "end", listener: () => void): this; + prependListener(event: "error", listener: (err: Error) => void): this; + prependListener(event: "pause", listener: () => void): this; + prependListener(event: "readable", listener: () => void): this; + prependListener(event: "resume", listener: () => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "data", listener: (chunk: any) => void): this; + prependOnceListener(event: "end", listener: () => void): this; + prependOnceListener(event: "error", listener: (err: Error) => void): this; + prependOnceListener(event: "pause", listener: () => void): this; + prependOnceListener(event: "readable", listener: () => void): this; + prependOnceListener(event: "resume", listener: () => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + removeListener(event: "close", listener: () => void): this; + removeListener(event: "data", listener: (chunk: any) => void): this; + removeListener(event: "end", listener: () => void): this; + removeListener(event: "error", listener: (err: Error) => void): this; + removeListener(event: "pause", listener: () => void): this; + removeListener(event: "readable", listener: () => void): this; + removeListener(event: "resume", listener: () => void): this; + removeListener(event: string | symbol, listener: (...args: any[]) => void): this; + [Symbol.asyncIterator](): AsyncIterableIterator; + /** + * Calls `readable.destroy()` with an `AbortError` and returns a promise that fulfills when the stream is finished. + * @since v20.4.0 + */ + [Symbol.asyncDispose](): Promise; + } + import WritableOptions = internal.WritableOptions; + class WritableBase extends Stream implements NodeJS.WritableStream { + /** + * Is `true` if it is safe to call `writable.write()`, which means + * the stream has not been destroyed, errored, or ended. + * @since v11.4.0 + */ + readonly writable: boolean; + /** + * Is `true` after `writable.end()` has been called. This property + * does not indicate whether the data has been flushed, for this use `writable.writableFinished` instead. + * @since v12.9.0 + */ + readonly writableEnded: boolean; + /** + * Is set to `true` immediately before the `'finish'` event is emitted. + * @since v12.6.0 + */ + readonly writableFinished: boolean; + /** + * Return the value of `highWaterMark` passed when creating this `Writable`. + * @since v9.3.0 + */ + readonly writableHighWaterMark: number; + /** + * This property contains the number of bytes (or objects) in the queue + * ready to be written. The value provides introspection data regarding + * the status of the `highWaterMark`. + * @since v9.4.0 + */ + readonly writableLength: number; + /** + * Getter for the property `objectMode` of a given `Writable` stream. + * @since v12.3.0 + */ + readonly writableObjectMode: boolean; + /** + * Number of times `writable.uncork()` needs to be + * called in order to fully uncork the stream. + * @since v13.2.0, v12.16.0 + */ + readonly writableCorked: number; + /** + * Is `true` after `writable.destroy()` has been called. + * @since v8.0.0 + */ + destroyed: boolean; + /** + * Is `true` after `'close'` has been emitted. + * @since v18.0.0 + */ + readonly closed: boolean; + /** + * Returns error if the stream has been destroyed with an error. + * @since v18.0.0 + */ + readonly errored: Error | null; + /** + * Is `true` if the stream's buffer has been full and stream will emit `'drain'`. + * @since v15.2.0, v14.17.0 + */ + readonly writableNeedDrain: boolean; + constructor(opts?: WritableOptions); + _write(chunk: any, encoding: BufferEncoding, callback: (error?: Error | null) => void): void; + _writev?( + chunks: Array<{ + chunk: any; + encoding: BufferEncoding; + }>, + callback: (error?: Error | null) => void, + ): void; + _construct?(callback: (error?: Error | null) => void): void; + _destroy(error: Error | null, callback: (error?: Error | null) => void): void; + _final(callback: (error?: Error | null) => void): void; + /** + * The `writable.write()` method writes some data to the stream, and calls the + * supplied `callback` once the data has been fully handled. If an error + * occurs, the `callback` will be called with the error as its + * first argument. The `callback` is called asynchronously and before `'error'` is + * emitted. + * + * The return value is `true` if the internal buffer is less than the `highWaterMark` configured when the stream was created after admitting `chunk`. + * If `false` is returned, further attempts to write data to the stream should + * stop until the `'drain'` event is emitted. + * + * While a stream is not draining, calls to `write()` will buffer `chunk`, and + * return false. Once all currently buffered chunks are drained (accepted for + * delivery by the operating system), the `'drain'` event will be emitted. + * Once `write()` returns false, do not write more chunks + * until the `'drain'` event is emitted. While calling `write()` on a stream that + * is not draining is allowed, Node.js will buffer all written chunks until + * maximum memory usage occurs, at which point it will abort unconditionally. + * Even before it aborts, high memory usage will cause poor garbage collector + * performance and high RSS (which is not typically released back to the system, + * even after the memory is no longer required). Since TCP sockets may never + * drain if the remote peer does not read the data, writing a socket that is + * not draining may lead to a remotely exploitable vulnerability. + * + * Writing data while the stream is not draining is particularly + * problematic for a `Transform`, because the `Transform` streams are paused + * by default until they are piped or a `'data'` or `'readable'` event handler + * is added. + * + * If the data to be written can be generated or fetched on demand, it is + * recommended to encapsulate the logic into a `Readable` and use {@link pipe}. However, if calling `write()` is preferred, it is + * possible to respect backpressure and avoid memory issues using the `'drain'` event: + * + * ```js + * function write(data, cb) { + * if (!stream.write(data)) { + * stream.once('drain', cb); + * } else { + * process.nextTick(cb); + * } + * } + * + * // Wait for cb to be called before doing any other write. + * write('hello', () => { + * console.log('Write completed, do more writes now.'); + * }); + * ``` + * + * A `Writable` stream in object mode will always ignore the `encoding` argument. + * @since v0.9.4 + * @param chunk Optional data to write. For streams not operating in object mode, `chunk` must be a {string}, {Buffer}, + * {TypedArray} or {DataView}. For object mode streams, `chunk` may be any JavaScript value other than `null`. + * @param [encoding='utf8'] The encoding, if `chunk` is a string. + * @param callback Callback for when this chunk of data is flushed. + * @return `false` if the stream wishes for the calling code to wait for the `'drain'` event to be emitted before continuing to write additional data; otherwise `true`. + */ + write(chunk: any, callback?: (error: Error | null | undefined) => void): boolean; + write(chunk: any, encoding: BufferEncoding, callback?: (error: Error | null | undefined) => void): boolean; + /** + * The `writable.setDefaultEncoding()` method sets the default `encoding` for a `Writable` stream. + * @since v0.11.15 + * @param encoding The new default encoding + */ + setDefaultEncoding(encoding: BufferEncoding): this; + /** + * Calling the `writable.end()` method signals that no more data will be written + * to the `Writable`. The optional `chunk` and `encoding` arguments allow one + * final additional chunk of data to be written immediately before closing the + * stream. + * + * Calling the {@link write} method after calling {@link end} will raise an error. + * + * ```js + * // Write 'hello, ' and then end with 'world!'. + * const fs = require('node:fs'); + * const file = fs.createWriteStream('example.txt'); + * file.write('hello, '); + * file.end('world!'); + * // Writing more now is not allowed! + * ``` + * @since v0.9.4 + * @param chunk Optional data to write. For streams not operating in object mode, `chunk` must be a {string}, {Buffer}, + * {TypedArray} or {DataView}. For object mode streams, `chunk` may be any JavaScript value other than `null`. + * @param encoding The encoding if `chunk` is a string + * @param callback Callback for when the stream is finished. + */ + end(cb?: () => void): this; + end(chunk: any, cb?: () => void): this; + end(chunk: any, encoding: BufferEncoding, cb?: () => void): this; + /** + * The `writable.cork()` method forces all written data to be buffered in memory. + * The buffered data will be flushed when either the {@link uncork} or {@link end} methods are called. + * + * The primary intent of `writable.cork()` is to accommodate a situation in which + * several small chunks are written to the stream in rapid succession. Instead of + * immediately forwarding them to the underlying destination, `writable.cork()` buffers all the chunks until `writable.uncork()` is called, which will pass them + * all to `writable._writev()`, if present. This prevents a head-of-line blocking + * situation where data is being buffered while waiting for the first small chunk + * to be processed. However, use of `writable.cork()` without implementing `writable._writev()` may have an adverse effect on throughput. + * + * See also: `writable.uncork()`, `writable._writev()`. + * @since v0.11.2 + */ + cork(): void; + /** + * The `writable.uncork()` method flushes all data buffered since {@link cork} was called. + * + * When using `writable.cork()` and `writable.uncork()` to manage the buffering + * of writes to a stream, defer calls to `writable.uncork()` using `process.nextTick()`. Doing so allows batching of all `writable.write()` calls that occur within a given Node.js event + * loop phase. + * + * ```js + * stream.cork(); + * stream.write('some '); + * stream.write('data '); + * process.nextTick(() => stream.uncork()); + * ``` + * + * If the `writable.cork()` method is called multiple times on a stream, the + * same number of calls to `writable.uncork()` must be called to flush the buffered + * data. + * + * ```js + * stream.cork(); + * stream.write('some '); + * stream.cork(); + * stream.write('data '); + * process.nextTick(() => { + * stream.uncork(); + * // The data will not be flushed until uncork() is called a second time. + * stream.uncork(); + * }); + * ``` + * + * See also: `writable.cork()`. + * @since v0.11.2 + */ + uncork(): void; + /** + * Destroy the stream. Optionally emit an `'error'` event, and emit a `'close'` event (unless `emitClose` is set to `false`). After this call, the writable + * stream has ended and subsequent calls to `write()` or `end()` will result in + * an `ERR_STREAM_DESTROYED` error. + * This is a destructive and immediate way to destroy a stream. Previous calls to `write()` may not have drained, and may trigger an `ERR_STREAM_DESTROYED` error. + * Use `end()` instead of destroy if data should flush before close, or wait for + * the `'drain'` event before destroying the stream. + * + * Once `destroy()` has been called any further calls will be a no-op and no + * further errors except from `_destroy()` may be emitted as `'error'`. + * + * Implementors should not override this method, + * but instead implement `writable._destroy()`. + * @since v8.0.0 + * @param error Optional, an error to emit with `'error'` event. + */ + destroy(error?: Error): this; + /** + * Event emitter + * The defined events on documents including: + * 1. close + * 2. drain + * 3. error + * 4. finish + * 5. pipe + * 6. unpipe + */ + addListener(event: "close", listener: () => void): this; + addListener(event: "drain", listener: () => void): this; + addListener(event: "error", listener: (err: Error) => void): this; + addListener(event: "finish", listener: () => void): this; + addListener(event: "pipe", listener: (src: Readable) => void): this; + addListener(event: "unpipe", listener: (src: Readable) => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + emit(event: "close"): boolean; + emit(event: "drain"): boolean; + emit(event: "error", err: Error): boolean; + emit(event: "finish"): boolean; + emit(event: "pipe", src: Readable): boolean; + emit(event: "unpipe", src: Readable): boolean; + emit(event: string | symbol, ...args: any[]): boolean; + on(event: "close", listener: () => void): this; + on(event: "drain", listener: () => void): this; + on(event: "error", listener: (err: Error) => void): this; + on(event: "finish", listener: () => void): this; + on(event: "pipe", listener: (src: Readable) => void): this; + on(event: "unpipe", listener: (src: Readable) => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + once(event: "close", listener: () => void): this; + once(event: "drain", listener: () => void): this; + once(event: "error", listener: (err: Error) => void): this; + once(event: "finish", listener: () => void): this; + once(event: "pipe", listener: (src: Readable) => void): this; + once(event: "unpipe", listener: (src: Readable) => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + prependListener(event: "close", listener: () => void): this; + prependListener(event: "drain", listener: () => void): this; + prependListener(event: "error", listener: (err: Error) => void): this; + prependListener(event: "finish", listener: () => void): this; + prependListener(event: "pipe", listener: (src: Readable) => void): this; + prependListener(event: "unpipe", listener: (src: Readable) => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "drain", listener: () => void): this; + prependOnceListener(event: "error", listener: (err: Error) => void): this; + prependOnceListener(event: "finish", listener: () => void): this; + prependOnceListener(event: "pipe", listener: (src: Readable) => void): this; + prependOnceListener(event: "unpipe", listener: (src: Readable) => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + removeListener(event: "close", listener: () => void): this; + removeListener(event: "drain", listener: () => void): this; + removeListener(event: "error", listener: (err: Error) => void): this; + removeListener(event: "finish", listener: () => void): this; + removeListener(event: "pipe", listener: (src: Readable) => void): this; + removeListener(event: "unpipe", listener: (src: Readable) => void): this; + removeListener(event: string | symbol, listener: (...args: any[]) => void): this; + } + namespace internal { + class Stream extends internal { + constructor(opts?: ReadableOptions); + } + interface StreamOptions extends Abortable { + emitClose?: boolean | undefined; + highWaterMark?: number | undefined; + objectMode?: boolean | undefined; + construct?(this: T, callback: (error?: Error | null) => void): void; + destroy?(this: T, error: Error | null, callback: (error?: Error | null) => void): void; + autoDestroy?: boolean | undefined; + } + interface ReadableOptions extends StreamOptions { + encoding?: BufferEncoding | undefined; + read?(this: Readable, size: number): void; + } + /** + * @since v0.9.4 + */ + class Readable extends ReadableBase { + /** + * A utility method for creating a `Readable` from a web `ReadableStream`. + * @since v17.0.0 + * @experimental + */ + static fromWeb( + readableStream: streamWeb.ReadableStream, + options?: Pick, + ): Readable; + /** + * A utility method for creating a web `ReadableStream` from a `Readable`. + * @since v17.0.0 + * @experimental + */ + static toWeb(streamReadable: Readable): streamWeb.ReadableStream; + } + interface WritableOptions extends StreamOptions { + decodeStrings?: boolean | undefined; + defaultEncoding?: BufferEncoding | undefined; + write?( + this: Writable, + chunk: any, + encoding: BufferEncoding, + callback: (error?: Error | null) => void, + ): void; + writev?( + this: Writable, + chunks: Array<{ + chunk: any; + encoding: BufferEncoding; + }>, + callback: (error?: Error | null) => void, + ): void; + final?(this: Writable, callback: (error?: Error | null) => void): void; + } + /** + * @since v0.9.4 + */ + class Writable extends WritableBase { + /** + * A utility method for creating a `Writable` from a web `WritableStream`. + * @since v17.0.0 + * @experimental + */ + static fromWeb( + writableStream: streamWeb.WritableStream, + options?: Pick, + ): Writable; + /** + * A utility method for creating a web `WritableStream` from a `Writable`. + * @since v17.0.0 + * @experimental + */ + static toWeb(streamWritable: Writable): streamWeb.WritableStream; + } + interface DuplexOptions extends ReadableOptions, WritableOptions { + allowHalfOpen?: boolean | undefined; + readableObjectMode?: boolean | undefined; + writableObjectMode?: boolean | undefined; + readableHighWaterMark?: number | undefined; + writableHighWaterMark?: number | undefined; + writableCorked?: number | undefined; + construct?(this: Duplex, callback: (error?: Error | null) => void): void; + read?(this: Duplex, size: number): void; + write?(this: Duplex, chunk: any, encoding: BufferEncoding, callback: (error?: Error | null) => void): void; + writev?( + this: Duplex, + chunks: Array<{ + chunk: any; + encoding: BufferEncoding; + }>, + callback: (error?: Error | null) => void, + ): void; + final?(this: Duplex, callback: (error?: Error | null) => void): void; + destroy?(this: Duplex, error: Error | null, callback: (error?: Error | null) => void): void; + } + /** + * Duplex streams are streams that implement both the `Readable` and `Writable` interfaces. + * + * Examples of `Duplex` streams include: + * + * * `TCP sockets` + * * `zlib streams` + * * `crypto streams` + * @since v0.9.4 + */ + class Duplex extends ReadableBase implements WritableBase { + readonly writable: boolean; + readonly writableEnded: boolean; + readonly writableFinished: boolean; + readonly writableHighWaterMark: number; + readonly writableLength: number; + readonly writableObjectMode: boolean; + readonly writableCorked: number; + readonly writableNeedDrain: boolean; + readonly closed: boolean; + readonly errored: Error | null; + /** + * If `false` then the stream will automatically end the writable side when the + * readable side ends. Set initially by the `allowHalfOpen` constructor option, + * which defaults to `true`. + * + * This can be changed manually to change the half-open behavior of an existing + * `Duplex` stream instance, but must be changed before the `'end'` event is emitted. + * @since v0.9.4 + */ + allowHalfOpen: boolean; + constructor(opts?: DuplexOptions); + /** + * A utility method for creating duplex streams. + * + * - `Stream` converts writable stream into writable `Duplex` and readable stream + * to `Duplex`. + * - `Blob` converts into readable `Duplex`. + * - `string` converts into readable `Duplex`. + * - `ArrayBuffer` converts into readable `Duplex`. + * - `AsyncIterable` converts into a readable `Duplex`. Cannot yield `null`. + * - `AsyncGeneratorFunction` converts into a readable/writable transform + * `Duplex`. Must take a source `AsyncIterable` as first parameter. Cannot yield + * `null`. + * - `AsyncFunction` converts into a writable `Duplex`. Must return + * either `null` or `undefined` + * - `Object ({ writable, readable })` converts `readable` and + * `writable` into `Stream` and then combines them into `Duplex` where the + * `Duplex` will write to the `writable` and read from the `readable`. + * - `Promise` converts into readable `Duplex`. Value `null` is ignored. + * + * @since v16.8.0 + */ + static from( + src: + | Stream + | NodeBlob + | ArrayBuffer + | string + | Iterable + | AsyncIterable + | AsyncGeneratorFunction + | Promise + | Object, + ): Duplex; + _write(chunk: any, encoding: BufferEncoding, callback: (error?: Error | null) => void): void; + _writev?( + chunks: Array<{ + chunk: any; + encoding: BufferEncoding; + }>, + callback: (error?: Error | null) => void, + ): void; + _destroy(error: Error | null, callback: (error?: Error | null) => void): void; + _final(callback: (error?: Error | null) => void): void; + write(chunk: any, encoding?: BufferEncoding, cb?: (error: Error | null | undefined) => void): boolean; + write(chunk: any, cb?: (error: Error | null | undefined) => void): boolean; + setDefaultEncoding(encoding: BufferEncoding): this; + end(cb?: () => void): this; + end(chunk: any, cb?: () => void): this; + end(chunk: any, encoding?: BufferEncoding, cb?: () => void): this; + cork(): void; + uncork(): void; + /** + * A utility method for creating a web `ReadableStream` and `WritableStream` from a `Duplex`. + * @since v17.0.0 + * @experimental + */ + static toWeb(streamDuplex: Duplex): { + readable: streamWeb.ReadableStream; + writable: streamWeb.WritableStream; + }; + /** + * A utility method for creating a `Duplex` from a web `ReadableStream` and `WritableStream`. + * @since v17.0.0 + * @experimental + */ + static fromWeb( + duplexStream: { + readable: streamWeb.ReadableStream; + writable: streamWeb.WritableStream; + }, + options?: Pick< + DuplexOptions, + "allowHalfOpen" | "decodeStrings" | "encoding" | "highWaterMark" | "objectMode" | "signal" + >, + ): Duplex; + /** + * Event emitter + * The defined events on documents including: + * 1. close + * 2. data + * 3. drain + * 4. end + * 5. error + * 6. finish + * 7. pause + * 8. pipe + * 9. readable + * 10. resume + * 11. unpipe + */ + addListener(event: "close", listener: () => void): this; + addListener(event: "data", listener: (chunk: any) => void): this; + addListener(event: "drain", listener: () => void): this; + addListener(event: "end", listener: () => void): this; + addListener(event: "error", listener: (err: Error) => void): this; + addListener(event: "finish", listener: () => void): this; + addListener(event: "pause", listener: () => void): this; + addListener(event: "pipe", listener: (src: Readable) => void): this; + addListener(event: "readable", listener: () => void): this; + addListener(event: "resume", listener: () => void): this; + addListener(event: "unpipe", listener: (src: Readable) => void): this; + addListener(event: string | symbol, listener: (...args: any[]) => void): this; + emit(event: "close"): boolean; + emit(event: "data", chunk: any): boolean; + emit(event: "drain"): boolean; + emit(event: "end"): boolean; + emit(event: "error", err: Error): boolean; + emit(event: "finish"): boolean; + emit(event: "pause"): boolean; + emit(event: "pipe", src: Readable): boolean; + emit(event: "readable"): boolean; + emit(event: "resume"): boolean; + emit(event: "unpipe", src: Readable): boolean; + emit(event: string | symbol, ...args: any[]): boolean; + on(event: "close", listener: () => void): this; + on(event: "data", listener: (chunk: any) => void): this; + on(event: "drain", listener: () => void): this; + on(event: "end", listener: () => void): this; + on(event: "error", listener: (err: Error) => void): this; + on(event: "finish", listener: () => void): this; + on(event: "pause", listener: () => void): this; + on(event: "pipe", listener: (src: Readable) => void): this; + on(event: "readable", listener: () => void): this; + on(event: "resume", listener: () => void): this; + on(event: "unpipe", listener: (src: Readable) => void): this; + on(event: string | symbol, listener: (...args: any[]) => void): this; + once(event: "close", listener: () => void): this; + once(event: "data", listener: (chunk: any) => void): this; + once(event: "drain", listener: () => void): this; + once(event: "end", listener: () => void): this; + once(event: "error", listener: (err: Error) => void): this; + once(event: "finish", listener: () => void): this; + once(event: "pause", listener: () => void): this; + once(event: "pipe", listener: (src: Readable) => void): this; + once(event: "readable", listener: () => void): this; + once(event: "resume", listener: () => void): this; + once(event: "unpipe", listener: (src: Readable) => void): this; + once(event: string | symbol, listener: (...args: any[]) => void): this; + prependListener(event: "close", listener: () => void): this; + prependListener(event: "data", listener: (chunk: any) => void): this; + prependListener(event: "drain", listener: () => void): this; + prependListener(event: "end", listener: () => void): this; + prependListener(event: "error", listener: (err: Error) => void): this; + prependListener(event: "finish", listener: () => void): this; + prependListener(event: "pause", listener: () => void): this; + prependListener(event: "pipe", listener: (src: Readable) => void): this; + prependListener(event: "readable", listener: () => void): this; + prependListener(event: "resume", listener: () => void): this; + prependListener(event: "unpipe", listener: (src: Readable) => void): this; + prependListener(event: string | symbol, listener: (...args: any[]) => void): this; + prependOnceListener(event: "close", listener: () => void): this; + prependOnceListener(event: "data", listener: (chunk: any) => void): this; + prependOnceListener(event: "drain", listener: () => void): this; + prependOnceListener(event: "end", listener: () => void): this; + prependOnceListener(event: "error", listener: (err: Error) => void): this; + prependOnceListener(event: "finish", listener: () => void): this; + prependOnceListener(event: "pause", listener: () => void): this; + prependOnceListener(event: "pipe", listener: (src: Readable) => void): this; + prependOnceListener(event: "readable", listener: () => void): this; + prependOnceListener(event: "resume", listener: () => void): this; + prependOnceListener(event: "unpipe", listener: (src: Readable) => void): this; + prependOnceListener(event: string | symbol, listener: (...args: any[]) => void): this; + removeListener(event: "close", listener: () => void): this; + removeListener(event: "data", listener: (chunk: any) => void): this; + removeListener(event: "drain", listener: () => void): this; + removeListener(event: "end", listener: () => void): this; + removeListener(event: "error", listener: (err: Error) => void): this; + removeListener(event: "finish", listener: () => void): this; + removeListener(event: "pause", listener: () => void): this; + removeListener(event: "pipe", listener: (src: Readable) => void): this; + removeListener(event: "readable", listener: () => void): this; + removeListener(event: "resume", listener: () => void): this; + removeListener(event: "unpipe", listener: (src: Readable) => void): this; + removeListener(event: string | symbol, listener: (...args: any[]) => void): this; + } + type TransformCallback = (error?: Error | null, data?: any) => void; + interface TransformOptions extends DuplexOptions { + construct?(this: Transform, callback: (error?: Error | null) => void): void; + read?(this: Transform, size: number): void; + write?( + this: Transform, + chunk: any, + encoding: BufferEncoding, + callback: (error?: Error | null) => void, + ): void; + writev?( + this: Transform, + chunks: Array<{ + chunk: any; + encoding: BufferEncoding; + }>, + callback: (error?: Error | null) => void, + ): void; + final?(this: Transform, callback: (error?: Error | null) => void): void; + destroy?(this: Transform, error: Error | null, callback: (error?: Error | null) => void): void; + transform?(this: Transform, chunk: any, encoding: BufferEncoding, callback: TransformCallback): void; + flush?(this: Transform, callback: TransformCallback): void; + } + /** + * Transform streams are `Duplex` streams where the output is in some way + * related to the input. Like all `Duplex` streams, `Transform` streams + * implement both the `Readable` and `Writable` interfaces. + * + * Examples of `Transform` streams include: + * + * * `zlib streams` + * * `crypto streams` + * @since v0.9.4 + */ + class Transform extends Duplex { + constructor(opts?: TransformOptions); + _transform(chunk: any, encoding: BufferEncoding, callback: TransformCallback): void; + _flush(callback: TransformCallback): void; + } + /** + * The `stream.PassThrough` class is a trivial implementation of a `Transform` stream that simply passes the input bytes across to the output. Its purpose is + * primarily for examples and testing, but there are some use cases where `stream.PassThrough` is useful as a building block for novel sorts of streams. + */ + class PassThrough extends Transform {} + /** + * A stream to attach a signal to. + * + * Attaches an AbortSignal to a readable or writeable stream. This lets code + * control stream destruction using an `AbortController`. + * + * Calling `abort` on the `AbortController` corresponding to the passed `AbortSignal` will behave the same way as calling `.destroy(new AbortError())` on the + * stream, and `controller.error(new AbortError())` for webstreams. + * + * ```js + * const fs = require('node:fs'); + * + * const controller = new AbortController(); + * const read = addAbortSignal( + * controller.signal, + * fs.createReadStream(('object.json')), + * ); + * // Later, abort the operation closing the stream + * controller.abort(); + * ``` + * + * Or using an `AbortSignal` with a readable stream as an async iterable: + * + * ```js + * const controller = new AbortController(); + * setTimeout(() => controller.abort(), 10_000); // set a timeout + * const stream = addAbortSignal( + * controller.signal, + * fs.createReadStream(('object.json')), + * ); + * (async () => { + * try { + * for await (const chunk of stream) { + * await process(chunk); + * } + * } catch (e) { + * if (e.name === 'AbortError') { + * // The operation was cancelled + * } else { + * throw e; + * } + * } + * })(); + * ``` + * + * Or using an `AbortSignal` with a ReadableStream: + * + * ```js + * const controller = new AbortController(); + * const rs = new ReadableStream({ + * start(controller) { + * controller.enqueue('hello'); + * controller.enqueue('world'); + * controller.close(); + * }, + * }); + * + * addAbortSignal(controller.signal, rs); + * + * finished(rs, (err) => { + * if (err) { + * if (err.name === 'AbortError') { + * // The operation was cancelled + * } + * } + * }); + * + * const reader = rs.getReader(); + * + * reader.read().then(({ value, done }) => { + * console.log(value); // hello + * console.log(done); // false + * controller.abort(); + * }); + * ``` + * @since v15.4.0 + * @param signal A signal representing possible cancellation + * @param stream A stream to attach a signal to. + */ + function addAbortSignal(signal: AbortSignal, stream: T): T; + /** + * Returns the default highWaterMark used by streams. + * Defaults to `16384` (16 KiB), or `16` for `objectMode`. + * @since v19.9.0 + */ + function getDefaultHighWaterMark(objectMode: boolean): number; + /** + * Sets the default highWaterMark used by streams. + * @since v19.9.0 + * @param value highWaterMark value + */ + function setDefaultHighWaterMark(objectMode: boolean, value: number): void; + interface FinishedOptions extends Abortable { + error?: boolean | undefined; + readable?: boolean | undefined; + writable?: boolean | undefined; + } + /** + * A readable and/or writable stream/webstream. + * + * A function to get notified when a stream is no longer readable, writable + * or has experienced an error or a premature close event. + * + * ```js + * const { finished } = require('node:stream'); + * const fs = require('node:fs'); + * + * const rs = fs.createReadStream('archive.tar'); + * + * finished(rs, (err) => { + * if (err) { + * console.error('Stream failed.', err); + * } else { + * console.log('Stream is done reading.'); + * } + * }); + * + * rs.resume(); // Drain the stream. + * ``` + * + * Especially useful in error handling scenarios where a stream is destroyed + * prematurely (like an aborted HTTP request), and will not emit `'end'` or `'finish'`. + * + * The `finished` API provides [`promise version`](https://nodejs.org/docs/latest-v20.x/api/stream.html#streamfinishedstream-options). + * + * `stream.finished()` leaves dangling event listeners (in particular `'error'`, `'end'`, `'finish'` and `'close'`) after `callback` has been + * invoked. The reason for this is so that unexpected `'error'` events (due to + * incorrect stream implementations) do not cause unexpected crashes. + * If this is unwanted behavior then the returned cleanup function needs to be + * invoked in the callback: + * + * ```js + * const cleanup = finished(rs, (err) => { + * cleanup(); + * // ... + * }); + * ``` + * @since v10.0.0 + * @param stream A readable and/or writable stream. + * @param callback A callback function that takes an optional error argument. + * @returns A cleanup function which removes all registered listeners. + */ + function finished( + stream: NodeJS.ReadableStream | NodeJS.WritableStream | NodeJS.ReadWriteStream, + options: FinishedOptions, + callback: (err?: NodeJS.ErrnoException | null) => void, + ): () => void; + function finished( + stream: NodeJS.ReadableStream | NodeJS.WritableStream | NodeJS.ReadWriteStream, + callback: (err?: NodeJS.ErrnoException | null) => void, + ): () => void; + namespace finished { + function __promisify__( + stream: NodeJS.ReadableStream | NodeJS.WritableStream | NodeJS.ReadWriteStream, + options?: FinishedOptions, + ): Promise; + } + type PipelineSourceFunction = () => Iterable | AsyncIterable; + type PipelineSource = Iterable | AsyncIterable | NodeJS.ReadableStream | PipelineSourceFunction; + type PipelineTransform, U> = + | NodeJS.ReadWriteStream + | (( + source: S extends (...args: any[]) => Iterable | AsyncIterable ? AsyncIterable + : S, + ) => AsyncIterable); + type PipelineTransformSource = PipelineSource | PipelineTransform; + type PipelineDestinationIterableFunction = (source: AsyncIterable) => AsyncIterable; + type PipelineDestinationPromiseFunction = (source: AsyncIterable) => Promise

; + type PipelineDestination, P> = S extends + PipelineTransformSource ? + | NodeJS.WritableStream + | PipelineDestinationIterableFunction + | PipelineDestinationPromiseFunction + : never; + type PipelineCallback> = S extends + PipelineDestinationPromiseFunction ? (err: NodeJS.ErrnoException | null, value: P) => void + : (err: NodeJS.ErrnoException | null) => void; + type PipelinePromise> = S extends + PipelineDestinationPromiseFunction ? Promise

: Promise; + interface PipelineOptions { + signal?: AbortSignal | undefined; + end?: boolean | undefined; + } + /** + * A module method to pipe between streams and generators forwarding errors and + * properly cleaning up and provide a callback when the pipeline is complete. + * + * ```js + * const { pipeline } = require('node:stream'); + * const fs = require('node:fs'); + * const zlib = require('node:zlib'); + * + * // Use the pipeline API to easily pipe a series of streams + * // together and get notified when the pipeline is fully done. + * + * // A pipeline to gzip a potentially huge tar file efficiently: + * + * pipeline( + * fs.createReadStream('archive.tar'), + * zlib.createGzip(), + * fs.createWriteStream('archive.tar.gz'), + * (err) => { + * if (err) { + * console.error('Pipeline failed.', err); + * } else { + * console.log('Pipeline succeeded.'); + * } + * }, + * ); + * ``` + * + * The `pipeline` API provides a [`promise version`](https://nodejs.org/docs/latest-v20.x/api/stream.html#streampipelinesource-transforms-destination-options). + * + * `stream.pipeline()` will call `stream.destroy(err)` on all streams except: + * + * * `Readable` streams which have emitted `'end'` or `'close'`. + * * `Writable` streams which have emitted `'finish'` or `'close'`. + * + * `stream.pipeline()` leaves dangling event listeners on the streams + * after the `callback` has been invoked. In the case of reuse of streams after + * failure, this can cause event listener leaks and swallowed errors. If the last + * stream is readable, dangling event listeners will be removed so that the last + * stream can be consumed later. + * + * `stream.pipeline()` closes all the streams when an error is raised. + * The `IncomingRequest` usage with `pipeline` could lead to an unexpected behavior + * once it would destroy the socket without sending the expected response. + * See the example below: + * + * ```js + * const fs = require('node:fs'); + * const http = require('node:http'); + * const { pipeline } = require('node:stream'); + * + * const server = http.createServer((req, res) => { + * const fileStream = fs.createReadStream('./fileNotExist.txt'); + * pipeline(fileStream, res, (err) => { + * if (err) { + * console.log(err); // No such file + * // this message can't be sent once `pipeline` already destroyed the socket + * return res.end('error!!!'); + * } + * }); + * }); + * ``` + * @since v10.0.0 + * @param callback Called when the pipeline is fully done. + */ + function pipeline, B extends PipelineDestination>( + source: A, + destination: B, + callback: PipelineCallback, + ): B extends NodeJS.WritableStream ? B : NodeJS.WritableStream; + function pipeline< + A extends PipelineSource, + T1 extends PipelineTransform, + B extends PipelineDestination, + >( + source: A, + transform1: T1, + destination: B, + callback: PipelineCallback, + ): B extends NodeJS.WritableStream ? B : NodeJS.WritableStream; + function pipeline< + A extends PipelineSource, + T1 extends PipelineTransform, + T2 extends PipelineTransform, + B extends PipelineDestination, + >( + source: A, + transform1: T1, + transform2: T2, + destination: B, + callback: PipelineCallback, + ): B extends NodeJS.WritableStream ? B : NodeJS.WritableStream; + function pipeline< + A extends PipelineSource, + T1 extends PipelineTransform, + T2 extends PipelineTransform, + T3 extends PipelineTransform, + B extends PipelineDestination, + >( + source: A, + transform1: T1, + transform2: T2, + transform3: T3, + destination: B, + callback: PipelineCallback, + ): B extends NodeJS.WritableStream ? B : NodeJS.WritableStream; + function pipeline< + A extends PipelineSource, + T1 extends PipelineTransform, + T2 extends PipelineTransform, + T3 extends PipelineTransform, + T4 extends PipelineTransform, + B extends PipelineDestination, + >( + source: A, + transform1: T1, + transform2: T2, + transform3: T3, + transform4: T4, + destination: B, + callback: PipelineCallback, + ): B extends NodeJS.WritableStream ? B : NodeJS.WritableStream; + function pipeline( + streams: ReadonlyArray, + callback: (err: NodeJS.ErrnoException | null) => void, + ): NodeJS.WritableStream; + function pipeline( + stream1: NodeJS.ReadableStream, + stream2: NodeJS.ReadWriteStream | NodeJS.WritableStream, + ...streams: Array< + NodeJS.ReadWriteStream | NodeJS.WritableStream | ((err: NodeJS.ErrnoException | null) => void) + > + ): NodeJS.WritableStream; + namespace pipeline { + function __promisify__, B extends PipelineDestination>( + source: A, + destination: B, + options?: PipelineOptions, + ): PipelinePromise; + function __promisify__< + A extends PipelineSource, + T1 extends PipelineTransform, + B extends PipelineDestination, + >( + source: A, + transform1: T1, + destination: B, + options?: PipelineOptions, + ): PipelinePromise; + function __promisify__< + A extends PipelineSource, + T1 extends PipelineTransform, + T2 extends PipelineTransform, + B extends PipelineDestination, + >( + source: A, + transform1: T1, + transform2: T2, + destination: B, + options?: PipelineOptions, + ): PipelinePromise; + function __promisify__< + A extends PipelineSource, + T1 extends PipelineTransform, + T2 extends PipelineTransform, + T3 extends PipelineTransform, + B extends PipelineDestination, + >( + source: A, + transform1: T1, + transform2: T2, + transform3: T3, + destination: B, + options?: PipelineOptions, + ): PipelinePromise; + function __promisify__< + A extends PipelineSource, + T1 extends PipelineTransform, + T2 extends PipelineTransform, + T3 extends PipelineTransform, + T4 extends PipelineTransform, + B extends PipelineDestination, + >( + source: A, + transform1: T1, + transform2: T2, + transform3: T3, + transform4: T4, + destination: B, + options?: PipelineOptions, + ): PipelinePromise; + function __promisify__( + streams: ReadonlyArray, + options?: PipelineOptions, + ): Promise; + function __promisify__( + stream1: NodeJS.ReadableStream, + stream2: NodeJS.ReadWriteStream | NodeJS.WritableStream, + ...streams: Array + ): Promise; + } + interface Pipe { + close(): void; + hasRef(): boolean; + ref(): void; + unref(): void; + } + /** + * Returns whether the stream has encountered an error. + * @since v17.3.0, v16.14.0 + * @experimental + */ + function isErrored(stream: Readable | Writable | NodeJS.ReadableStream | NodeJS.WritableStream): boolean; + /** + * Returns whether the stream is readable. + * @since v17.4.0, v16.14.0 + * @experimental + */ + function isReadable(stream: Readable | NodeJS.ReadableStream): boolean; + const promises: typeof streamPromises; + const consumers: typeof streamConsumers; + } + export = internal; +} +declare module "node:stream" { + import stream = require("stream"); + export = stream; +} diff --git a/node_modules/@types/node/stream/consumers.d.ts b/node_modules/@types/node/stream/consumers.d.ts new file mode 100644 index 0000000..5ad9cba --- /dev/null +++ b/node_modules/@types/node/stream/consumers.d.ts @@ -0,0 +1,12 @@ +declare module "stream/consumers" { + import { Blob as NodeBlob } from "node:buffer"; + import { Readable } from "node:stream"; + function buffer(stream: NodeJS.ReadableStream | Readable | AsyncIterable): Promise; + function text(stream: NodeJS.ReadableStream | Readable | AsyncIterable): Promise; + function arrayBuffer(stream: NodeJS.ReadableStream | Readable | AsyncIterable): Promise; + function blob(stream: NodeJS.ReadableStream | Readable | AsyncIterable): Promise; + function json(stream: NodeJS.ReadableStream | Readable | AsyncIterable): Promise; +} +declare module "node:stream/consumers" { + export * from "stream/consumers"; +} diff --git a/node_modules/@types/node/stream/promises.d.ts b/node_modules/@types/node/stream/promises.d.ts new file mode 100644 index 0000000..6eac5b7 --- /dev/null +++ b/node_modules/@types/node/stream/promises.d.ts @@ -0,0 +1,83 @@ +declare module "stream/promises" { + import { + FinishedOptions, + PipelineDestination, + PipelineOptions, + PipelinePromise, + PipelineSource, + PipelineTransform, + } from "node:stream"; + function finished( + stream: NodeJS.ReadableStream | NodeJS.WritableStream | NodeJS.ReadWriteStream, + options?: FinishedOptions, + ): Promise; + function pipeline, B extends PipelineDestination>( + source: A, + destination: B, + options?: PipelineOptions, + ): PipelinePromise; + function pipeline< + A extends PipelineSource, + T1 extends PipelineTransform, + B extends PipelineDestination, + >( + source: A, + transform1: T1, + destination: B, + options?: PipelineOptions, + ): PipelinePromise; + function pipeline< + A extends PipelineSource, + T1 extends PipelineTransform, + T2 extends PipelineTransform, + B extends PipelineDestination, + >( + source: A, + transform1: T1, + transform2: T2, + destination: B, + options?: PipelineOptions, + ): PipelinePromise; + function pipeline< + A extends PipelineSource, + T1 extends PipelineTransform, + T2 extends PipelineTransform, + T3 extends PipelineTransform, + B extends PipelineDestination, + >( + source: A, + transform1: T1, + transform2: T2, + transform3: T3, + destination: B, + options?: PipelineOptions, + ): PipelinePromise; + function pipeline< + A extends PipelineSource, + T1 extends PipelineTransform, + T2 extends PipelineTransform, + T3 extends PipelineTransform, + T4 extends PipelineTransform, + B extends PipelineDestination, + >( + source: A, + transform1: T1, + transform2: T2, + transform3: T3, + transform4: T4, + destination: B, + options?: PipelineOptions, + ): PipelinePromise; + function pipeline( + streams: ReadonlyArray, + options?: PipelineOptions, + ): Promise; + function pipeline( + stream1: NodeJS.ReadableStream, + stream2: NodeJS.ReadWriteStream | NodeJS.WritableStream, + ...streams: Array + ): Promise; +} +declare module "node:stream/promises" { + export * from "stream/promises"; +} diff --git a/node_modules/@types/node/stream/web.d.ts b/node_modules/@types/node/stream/web.d.ts new file mode 100644 index 0000000..8dd0ded --- /dev/null +++ b/node_modules/@types/node/stream/web.d.ts @@ -0,0 +1,367 @@ +declare module "stream/web" { + // stub module, pending copy&paste from .d.ts or manual impl + // copy from lib.dom.d.ts + interface ReadableWritablePair { + readable: ReadableStream; + /** + * Provides a convenient, chainable way of piping this readable stream + * through a transform stream (or any other { writable, readable } + * pair). It simply pipes the stream into the writable side of the + * supplied pair, and returns the readable side for further use. + * + * Piping a stream will lock it for the duration of the pipe, preventing + * any other consumer from acquiring a reader. + */ + writable: WritableStream; + } + interface StreamPipeOptions { + preventAbort?: boolean; + preventCancel?: boolean; + /** + * Pipes this readable stream to a given writable stream destination. + * The way in which the piping process behaves under various error + * conditions can be customized with a number of passed options. It + * returns a promise that fulfills when the piping process completes + * successfully, or rejects if any errors were encountered. + * + * Piping a stream will lock it for the duration of the pipe, preventing + * any other consumer from acquiring a reader. + * + * Errors and closures of the source and destination streams propagate + * as follows: + * + * An error in this source readable stream will abort destination, + * unless preventAbort is truthy. The returned promise will be rejected + * with the source's error, or with any error that occurs during + * aborting the destination. + * + * An error in destination will cancel this source readable stream, + * unless preventCancel is truthy. The returned promise will be rejected + * with the destination's error, or with any error that occurs during + * canceling the source. + * + * When this source readable stream closes, destination will be closed, + * unless preventClose is truthy. The returned promise will be fulfilled + * once this process completes, unless an error is encountered while + * closing the destination, in which case it will be rejected with that + * error. + * + * If destination starts out closed or closing, this source readable + * stream will be canceled, unless preventCancel is true. The returned + * promise will be rejected with an error indicating piping to a closed + * stream failed, or with any error that occurs during canceling the + * source. + * + * The signal option can be set to an AbortSignal to allow aborting an + * ongoing pipe operation via the corresponding AbortController. In this + * case, this source readable stream will be canceled, and destination + * aborted, unless the respective options preventCancel or preventAbort + * are set. + */ + preventClose?: boolean; + signal?: AbortSignal; + } + interface ReadableStreamGenericReader { + readonly closed: Promise; + cancel(reason?: any): Promise; + } + interface ReadableStreamDefaultReadValueResult { + done: false; + value: T; + } + interface ReadableStreamDefaultReadDoneResult { + done: true; + value?: undefined; + } + type ReadableStreamController = ReadableStreamDefaultController; + type ReadableStreamDefaultReadResult = + | ReadableStreamDefaultReadValueResult + | ReadableStreamDefaultReadDoneResult; + interface ReadableStreamReadValueResult { + done: false; + value: T; + } + interface ReadableStreamReadDoneResult { + done: true; + value?: T; + } + type ReadableStreamReadResult = ReadableStreamReadValueResult | ReadableStreamReadDoneResult; + interface ReadableByteStreamControllerCallback { + (controller: ReadableByteStreamController): void | PromiseLike; + } + interface UnderlyingSinkAbortCallback { + (reason?: any): void | PromiseLike; + } + interface UnderlyingSinkCloseCallback { + (): void | PromiseLike; + } + interface UnderlyingSinkStartCallback { + (controller: WritableStreamDefaultController): any; + } + interface UnderlyingSinkWriteCallback { + (chunk: W, controller: WritableStreamDefaultController): void | PromiseLike; + } + interface UnderlyingSourceCancelCallback { + (reason?: any): void | PromiseLike; + } + interface UnderlyingSourcePullCallback { + (controller: ReadableStreamController): void | PromiseLike; + } + interface UnderlyingSourceStartCallback { + (controller: ReadableStreamController): any; + } + interface TransformerFlushCallback { + (controller: TransformStreamDefaultController): void | PromiseLike; + } + interface TransformerStartCallback { + (controller: TransformStreamDefaultController): any; + } + interface TransformerTransformCallback { + (chunk: I, controller: TransformStreamDefaultController): void | PromiseLike; + } + interface UnderlyingByteSource { + autoAllocateChunkSize?: number; + cancel?: ReadableStreamErrorCallback; + pull?: ReadableByteStreamControllerCallback; + start?: ReadableByteStreamControllerCallback; + type: "bytes"; + } + interface UnderlyingSource { + cancel?: UnderlyingSourceCancelCallback; + pull?: UnderlyingSourcePullCallback; + start?: UnderlyingSourceStartCallback; + type?: undefined; + } + interface UnderlyingSink { + abort?: UnderlyingSinkAbortCallback; + close?: UnderlyingSinkCloseCallback; + start?: UnderlyingSinkStartCallback; + type?: undefined; + write?: UnderlyingSinkWriteCallback; + } + interface ReadableStreamErrorCallback { + (reason: any): void | PromiseLike; + } + /** This Streams API interface represents a readable stream of byte data. */ + interface ReadableStream { + readonly locked: boolean; + cancel(reason?: any): Promise; + getReader(): ReadableStreamDefaultReader; + getReader(options: { mode: "byob" }): ReadableStreamBYOBReader; + pipeThrough(transform: ReadableWritablePair, options?: StreamPipeOptions): ReadableStream; + pipeTo(destination: WritableStream, options?: StreamPipeOptions): Promise; + tee(): [ReadableStream, ReadableStream]; + values(options?: { preventCancel?: boolean }): AsyncIterableIterator; + [Symbol.asyncIterator](): AsyncIterableIterator; + } + const ReadableStream: { + prototype: ReadableStream; + from(iterable: Iterable | AsyncIterable): ReadableStream; + new(underlyingSource: UnderlyingByteSource, strategy?: QueuingStrategy): ReadableStream; + new(underlyingSource?: UnderlyingSource, strategy?: QueuingStrategy): ReadableStream; + }; + interface ReadableStreamDefaultReader extends ReadableStreamGenericReader { + read(): Promise>; + releaseLock(): void; + } + interface ReadableStreamBYOBReader extends ReadableStreamGenericReader { + read(view: T): Promise>; + releaseLock(): void; + } + const ReadableStreamDefaultReader: { + prototype: ReadableStreamDefaultReader; + new(stream: ReadableStream): ReadableStreamDefaultReader; + }; + const ReadableStreamBYOBReader: any; + const ReadableStreamBYOBRequest: any; + interface ReadableByteStreamController { + readonly byobRequest: undefined; + readonly desiredSize: number | null; + close(): void; + enqueue(chunk: ArrayBufferView): void; + error(error?: any): void; + } + const ReadableByteStreamController: { + prototype: ReadableByteStreamController; + new(): ReadableByteStreamController; + }; + interface ReadableStreamDefaultController { + readonly desiredSize: number | null; + close(): void; + enqueue(chunk?: R): void; + error(e?: any): void; + } + const ReadableStreamDefaultController: { + prototype: ReadableStreamDefaultController; + new(): ReadableStreamDefaultController; + }; + interface Transformer { + flush?: TransformerFlushCallback; + readableType?: undefined; + start?: TransformerStartCallback; + transform?: TransformerTransformCallback; + writableType?: undefined; + } + interface TransformStream { + readonly readable: ReadableStream; + readonly writable: WritableStream; + } + const TransformStream: { + prototype: TransformStream; + new( + transformer?: Transformer, + writableStrategy?: QueuingStrategy, + readableStrategy?: QueuingStrategy, + ): TransformStream; + }; + interface TransformStreamDefaultController { + readonly desiredSize: number | null; + enqueue(chunk?: O): void; + error(reason?: any): void; + terminate(): void; + } + const TransformStreamDefaultController: { + prototype: TransformStreamDefaultController; + new(): TransformStreamDefaultController; + }; + /** + * This Streams API interface provides a standard abstraction for writing + * streaming data to a destination, known as a sink. This object comes with + * built-in back pressure and queuing. + */ + interface WritableStream { + readonly locked: boolean; + abort(reason?: any): Promise; + close(): Promise; + getWriter(): WritableStreamDefaultWriter; + } + const WritableStream: { + prototype: WritableStream; + new(underlyingSink?: UnderlyingSink, strategy?: QueuingStrategy): WritableStream; + }; + /** + * This Streams API interface is the object returned by + * WritableStream.getWriter() and once created locks the < writer to the + * WritableStream ensuring that no other streams can write to the underlying + * sink. + */ + interface WritableStreamDefaultWriter { + readonly closed: Promise; + readonly desiredSize: number | null; + readonly ready: Promise; + abort(reason?: any): Promise; + close(): Promise; + releaseLock(): void; + write(chunk?: W): Promise; + } + const WritableStreamDefaultWriter: { + prototype: WritableStreamDefaultWriter; + new(stream: WritableStream): WritableStreamDefaultWriter; + }; + /** + * This Streams API interface represents a controller allowing control of a + * WritableStream's state. When constructing a WritableStream, the + * underlying sink is given a corresponding WritableStreamDefaultController + * instance to manipulate. + */ + interface WritableStreamDefaultController { + error(e?: any): void; + } + const WritableStreamDefaultController: { + prototype: WritableStreamDefaultController; + new(): WritableStreamDefaultController; + }; + interface QueuingStrategy { + highWaterMark?: number; + size?: QueuingStrategySize; + } + interface QueuingStrategySize { + (chunk?: T): number; + } + interface QueuingStrategyInit { + /** + * Creates a new ByteLengthQueuingStrategy with the provided high water + * mark. + * + * Note that the provided high water mark will not be validated ahead of + * time. Instead, if it is negative, NaN, or not a number, the resulting + * ByteLengthQueuingStrategy will cause the corresponding stream + * constructor to throw. + */ + highWaterMark: number; + } + /** + * This Streams API interface provides a built-in byte length queuing + * strategy that can be used when constructing streams. + */ + interface ByteLengthQueuingStrategy extends QueuingStrategy { + readonly highWaterMark: number; + readonly size: QueuingStrategySize; + } + const ByteLengthQueuingStrategy: { + prototype: ByteLengthQueuingStrategy; + new(init: QueuingStrategyInit): ByteLengthQueuingStrategy; + }; + /** + * This Streams API interface provides a built-in byte length queuing + * strategy that can be used when constructing streams. + */ + interface CountQueuingStrategy extends QueuingStrategy { + readonly highWaterMark: number; + readonly size: QueuingStrategySize; + } + const CountQueuingStrategy: { + prototype: CountQueuingStrategy; + new(init: QueuingStrategyInit): CountQueuingStrategy; + }; + interface TextEncoderStream { + /** Returns "utf-8". */ + readonly encoding: "utf-8"; + readonly readable: ReadableStream; + readonly writable: WritableStream; + readonly [Symbol.toStringTag]: string; + } + const TextEncoderStream: { + prototype: TextEncoderStream; + new(): TextEncoderStream; + }; + interface TextDecoderOptions { + fatal?: boolean; + ignoreBOM?: boolean; + } + type BufferSource = ArrayBufferView | ArrayBuffer; + interface TextDecoderStream { + /** Returns encoding's name, lower cased. */ + readonly encoding: string; + /** Returns `true` if error mode is "fatal", and `false` otherwise. */ + readonly fatal: boolean; + /** Returns `true` if ignore BOM flag is set, and `false` otherwise. */ + readonly ignoreBOM: boolean; + readonly readable: ReadableStream; + readonly writable: WritableStream; + readonly [Symbol.toStringTag]: string; + } + const TextDecoderStream: { + prototype: TextDecoderStream; + new(encoding?: string, options?: TextDecoderOptions): TextDecoderStream; + }; + interface CompressionStream { + readonly readable: ReadableStream; + readonly writable: WritableStream; + } + const CompressionStream: { + prototype: CompressionStream; + new(format: "deflate" | "deflate-raw" | "gzip"): CompressionStream; + }; + interface DecompressionStream { + readonly readable: ReadableStream; + readonly writable: WritableStream; + } + const DecompressionStream: { + prototype: DecompressionStream; + new(format: "deflate" | "deflate-raw" | "gzip"): DecompressionStream; + }; +} +declare module "node:stream/web" { + export * from "stream/web"; +} diff --git a/node_modules/@types/node/string_decoder.d.ts b/node_modules/@types/node/string_decoder.d.ts new file mode 100644 index 0000000..9c9d827 --- /dev/null +++ b/node_modules/@types/node/string_decoder.d.ts @@ -0,0 +1,67 @@ +/** + * The `node:string_decoder` module provides an API for decoding `Buffer` objects + * into strings in a manner that preserves encoded multi-byte UTF-8 and UTF-16 + * characters. It can be accessed using: + * + * ```js + * const { StringDecoder } = require('node:string_decoder'); + * ``` + * + * The following example shows the basic use of the `StringDecoder` class. + * + * ```js + * const { StringDecoder } = require('node:string_decoder'); + * const decoder = new StringDecoder('utf8'); + * + * const cent = Buffer.from([0xC2, 0xA2]); + * console.log(decoder.write(cent)); // Prints: ¢ + * + * const euro = Buffer.from([0xE2, 0x82, 0xAC]); + * console.log(decoder.write(euro)); // Prints: € + * ``` + * + * When a `Buffer` instance is written to the `StringDecoder` instance, an + * internal buffer is used to ensure that the decoded string does not contain + * any incomplete multibyte characters. These are held in the buffer until the + * next call to `stringDecoder.write()` or until `stringDecoder.end()` is called. + * + * In the following example, the three UTF-8 encoded bytes of the European Euro + * symbol (`€`) are written over three separate operations: + * + * ```js + * const { StringDecoder } = require('node:string_decoder'); + * const decoder = new StringDecoder('utf8'); + * + * decoder.write(Buffer.from([0xE2])); + * decoder.write(Buffer.from([0x82])); + * console.log(decoder.end(Buffer.from([0xAC]))); // Prints: € + * ``` + * @see [source](https://github.com/nodejs/node/blob/v20.13.1/lib/string_decoder.js) + */ +declare module "string_decoder" { + class StringDecoder { + constructor(encoding?: BufferEncoding); + /** + * Returns a decoded string, ensuring that any incomplete multibyte characters at + * the end of the `Buffer`, or `TypedArray`, or `DataView` are omitted from the + * returned string and stored in an internal buffer for the next call to `stringDecoder.write()` or `stringDecoder.end()`. + * @since v0.1.99 + * @param buffer The bytes to decode. + */ + write(buffer: string | Buffer | NodeJS.ArrayBufferView): string; + /** + * Returns any remaining input stored in the internal buffer as a string. Bytes + * representing incomplete UTF-8 and UTF-16 characters will be replaced with + * substitution characters appropriate for the character encoding. + * + * If the `buffer` argument is provided, one final call to `stringDecoder.write()` is performed before returning the remaining input. + * After `end()` is called, the `stringDecoder` object can be reused for new input. + * @since v0.9.3 + * @param buffer The bytes to decode. + */ + end(buffer?: string | Buffer | NodeJS.ArrayBufferView): string; + } +} +declare module "node:string_decoder" { + export * from "string_decoder"; +} diff --git a/node_modules/@types/node/test.d.ts b/node_modules/@types/node/test.d.ts new file mode 100644 index 0000000..fef7e4e --- /dev/null +++ b/node_modules/@types/node/test.d.ts @@ -0,0 +1,1718 @@ +/** + * The `node:test` module facilitates the creation of JavaScript tests. + * To access it: + * + * ```js + * import test from 'node:test'; + * ``` + * + * This module is only available under the `node:` scheme. The following will not + * work: + * + * ```js + * import test from 'test'; + * ``` + * + * Tests created via the `test` module consist of a single function that is + * processed in one of three ways: + * + * 1. A synchronous function that is considered failing if it throws an exception, + * and is considered passing otherwise. + * 2. A function that returns a `Promise` that is considered failing if the `Promise` rejects, and is considered passing if the `Promise` fulfills. + * 3. A function that receives a callback function. If the callback receives any + * truthy value as its first argument, the test is considered failing. If a + * falsy value is passed as the first argument to the callback, the test is + * considered passing. If the test function receives a callback function and + * also returns a `Promise`, the test will fail. + * + * The following example illustrates how tests are written using the `test` module. + * + * ```js + * test('synchronous passing test', (t) => { + * // This test passes because it does not throw an exception. + * assert.strictEqual(1, 1); + * }); + * + * test('synchronous failing test', (t) => { + * // This test fails because it throws an exception. + * assert.strictEqual(1, 2); + * }); + * + * test('asynchronous passing test', async (t) => { + * // This test passes because the Promise returned by the async + * // function is settled and not rejected. + * assert.strictEqual(1, 1); + * }); + * + * test('asynchronous failing test', async (t) => { + * // This test fails because the Promise returned by the async + * // function is rejected. + * assert.strictEqual(1, 2); + * }); + * + * test('failing test using Promises', (t) => { + * // Promises can be used directly as well. + * return new Promise((resolve, reject) => { + * setImmediate(() => { + * reject(new Error('this will cause the test to fail')); + * }); + * }); + * }); + * + * test('callback passing test', (t, done) => { + * // done() is the callback function. When the setImmediate() runs, it invokes + * // done() with no arguments. + * setImmediate(done); + * }); + * + * test('callback failing test', (t, done) => { + * // When the setImmediate() runs, done() is invoked with an Error object and + * // the test fails. + * setImmediate(() => { + * done(new Error('callback failure')); + * }); + * }); + * ``` + * + * If any tests fail, the process exit code is set to `1`. + * @since v18.0.0, v16.17.0 + * @see [source](https://github.com/nodejs/node/blob/v20.13.1/lib/test.js) + */ +declare module "node:test" { + import { Readable } from "node:stream"; + import { AsyncResource } from "node:async_hooks"; + /** + * **Note:** `shard` is used to horizontally parallelize test running across + * machines or processes, ideal for large-scale executions across varied + * environments. It's incompatible with `watch` mode, tailored for rapid + * code iteration by automatically rerunning tests on file changes. + * + * ```js + * import { tap } from 'node:test/reporters'; + * import { run } from 'node:test'; + * import process from 'node:process'; + * import path from 'node:path'; + * + * run({ files: [path.resolve('./tests/test.js')] }) + * .compose(tap) + * .pipe(process.stdout); + * ``` + * @since v18.9.0, v16.19.0 + * @param options Configuration options for running tests. The following properties are supported: + */ + function run(options?: RunOptions): TestsStream; + /** + * The `test()` function is the value imported from the `test` module. Each + * invocation of this function results in reporting the test to the `TestsStream`. + * + * The `TestContext` object passed to the `fn` argument can be used to perform + * actions related to the current test. Examples include skipping the test, adding + * additional diagnostic information, or creating subtests. + * + * `test()` returns a `Promise` that fulfills once the test completes. + * if `test()` is called within a suite, it fulfills immediately. + * The return value can usually be discarded for top level tests. + * However, the return value from subtests should be used to prevent the parent + * test from finishing first and cancelling the subtest + * as shown in the following example. + * + * ```js + * test('top level test', async (t) => { + * // The setTimeout() in the following subtest would cause it to outlive its + * // parent test if 'await' is removed on the next line. Once the parent test + * // completes, it will cancel any outstanding subtests. + * await t.test('longer running subtest', async (t) => { + * return new Promise((resolve, reject) => { + * setTimeout(resolve, 1000); + * }); + * }); + * }); + * ``` + * + * The `timeout` option can be used to fail the test if it takes longer than `timeout` milliseconds to complete. However, it is not a reliable mechanism for + * canceling tests because a running test might block the application thread and + * thus prevent the scheduled cancellation. + * @since v18.0.0, v16.17.0 + * @param [name='The name'] The name of the test, which is displayed when reporting test results. + * @param options Configuration options for the test. The following properties are supported: + * @param [fn='A no-op function'] The function under test. The first argument to this function is a {@link TestContext} object. If the test uses callbacks, the + * callback function is passed as the second argument. + * @return Fulfilled with `undefined` once the test completes, or immediately if the test runs within a suite. + */ + function test(name?: string, fn?: TestFn): Promise; + function test(name?: string, options?: TestOptions, fn?: TestFn): Promise; + function test(options?: TestOptions, fn?: TestFn): Promise; + function test(fn?: TestFn): Promise; + namespace test { + export { after, afterEach, before, beforeEach, describe, it, mock, only, run, skip, test, todo }; + } + /** + * The `suite()` function is imported from the `node:test` module. + * @param name The name of the suite, which is displayed when reporting test results. **Default:** The `name` property of `fn`, or `''` if `fn` does not have a name. + * @param options Optional configuration options for the suite. This supports the same options as `test([name][, options][, fn])`. + * @param [fn='A no-op function'] The suite function declaring nested tests and suites. The first argument to this function is a `{@link SuiteContext}` object. + * @return Immediately fulfilled with `undefined`. + * @since v20.13.0 + */ + function suite(name?: string, options?: TestOptions, fn?: SuiteFn): Promise; + function suite(name?: string, fn?: SuiteFn): Promise; + function suite(options?: TestOptions, fn?: SuiteFn): Promise; + function suite(fn?: SuiteFn): Promise; + namespace suite { + /** + * Shorthand for skipping a suite. This is the same as [`suite([name], { skip: true }[, fn])`](https://nodejs.org/docs/latest-v20.x/api/test.html#suitename-options-fn). + * @since v20.13.0 + */ + function skip(name?: string, options?: TestOptions, fn?: SuiteFn): Promise; + function skip(name?: string, fn?: SuiteFn): Promise; + function skip(options?: TestOptions, fn?: SuiteFn): Promise; + function skip(fn?: SuiteFn): Promise; + /** + * Shorthand for marking a suite as `TODO`. This is the same as [`suite([name], { todo: true }[, fn])`](https://nodejs.org/docs/latest-v20.x/api/test.html#suitename-options-fn). + * @since v20.13.0 + */ + function todo(name?: string, options?: TestOptions, fn?: SuiteFn): Promise; + function todo(name?: string, fn?: SuiteFn): Promise; + function todo(options?: TestOptions, fn?: SuiteFn): Promise; + function todo(fn?: SuiteFn): Promise; + /** + * Shorthand for marking a suite as `only`. This is the same as [`suite([name], { only: true }[, fn])`](https://nodejs.org/docs/latest-v20.x/api/test.html#suitename-options-fn). + * @since v20.13.0 + */ + function only(name?: string, options?: TestOptions, fn?: SuiteFn): Promise; + function only(name?: string, fn?: SuiteFn): Promise; + function only(options?: TestOptions, fn?: SuiteFn): Promise; + function only(fn?: SuiteFn): Promise; + } + /** + * Alias for `{@link suite}`. + * + * The `describe()` function is imported from the `node:test` module. + */ + function describe(name?: string, options?: TestOptions, fn?: SuiteFn): Promise; + function describe(name?: string, fn?: SuiteFn): Promise; + function describe(options?: TestOptions, fn?: SuiteFn): Promise; + function describe(fn?: SuiteFn): Promise; + namespace describe { + /** + * Shorthand for skipping a suite. This is the same as [`describe([name], { skip: true }[, fn])`](https://nodejs.org/docs/latest-v20.x/api/test.html#describename-options-fn). + * @since v18.15.0 + */ + function skip(name?: string, options?: TestOptions, fn?: SuiteFn): Promise; + function skip(name?: string, fn?: SuiteFn): Promise; + function skip(options?: TestOptions, fn?: SuiteFn): Promise; + function skip(fn?: SuiteFn): Promise; + /** + * Shorthand for marking a suite as `TODO`. This is the same as [`describe([name], { todo: true }[, fn])`](https://nodejs.org/docs/latest-v20.x/api/test.html#describename-options-fn). + * @since v18.15.0 + */ + function todo(name?: string, options?: TestOptions, fn?: SuiteFn): Promise; + function todo(name?: string, fn?: SuiteFn): Promise; + function todo(options?: TestOptions, fn?: SuiteFn): Promise; + function todo(fn?: SuiteFn): Promise; + /** + * Shorthand for marking a suite as `only`. This is the same as [`describe([name], { only: true }[, fn])`](https://nodejs.org/docs/latest-v20.x/api/test.html#describename-options-fn). + * @since v18.15.0 + */ + function only(name?: string, options?: TestOptions, fn?: SuiteFn): Promise; + function only(name?: string, fn?: SuiteFn): Promise; + function only(options?: TestOptions, fn?: SuiteFn): Promise; + function only(fn?: SuiteFn): Promise; + } + /** + * Alias for `test()`. + * + * The `it()` function is imported from the `node:test` module. + * @since v18.6.0, v16.17.0 + */ + function it(name?: string, options?: TestOptions, fn?: TestFn): Promise; + function it(name?: string, fn?: TestFn): Promise; + function it(options?: TestOptions, fn?: TestFn): Promise; + function it(fn?: TestFn): Promise; + namespace it { + /** + * Shorthand for skipping a test, same as `it([name], { skip: true }[, fn])`. + */ + function skip(name?: string, options?: TestOptions, fn?: TestFn): Promise; + function skip(name?: string, fn?: TestFn): Promise; + function skip(options?: TestOptions, fn?: TestFn): Promise; + function skip(fn?: TestFn): Promise; + /** + * Shorthand for marking a test as `TODO`, same as `it([name], { todo: true }[, fn])`. + */ + function todo(name?: string, options?: TestOptions, fn?: TestFn): Promise; + function todo(name?: string, fn?: TestFn): Promise; + function todo(options?: TestOptions, fn?: TestFn): Promise; + function todo(fn?: TestFn): Promise; + /** + * Shorthand for marking a test as `only`, same as `it([name], { only: true }[, fn])`. + * @since v18.15.0 + */ + function only(name?: string, options?: TestOptions, fn?: TestFn): Promise; + function only(name?: string, fn?: TestFn): Promise; + function only(options?: TestOptions, fn?: TestFn): Promise; + function only(fn?: TestFn): Promise; + } + /** + * Shorthand for skipping a test, same as `test([name], { skip: true }[, fn])`. + * @since v20.2.0 + */ + function skip(name?: string, options?: TestOptions, fn?: TestFn): Promise; + function skip(name?: string, fn?: TestFn): Promise; + function skip(options?: TestOptions, fn?: TestFn): Promise; + function skip(fn?: TestFn): Promise; + /** + * Shorthand for marking a test as `TODO`, same as `test([name], { todo: true }[, fn])`. + * @since v20.2.0 + */ + function todo(name?: string, options?: TestOptions, fn?: TestFn): Promise; + function todo(name?: string, fn?: TestFn): Promise; + function todo(options?: TestOptions, fn?: TestFn): Promise; + function todo(fn?: TestFn): Promise; + /** + * Shorthand for marking a test as `only`, same as `test([name], { only: true }[, fn])`. + * @since v20.2.0 + */ + function only(name?: string, options?: TestOptions, fn?: TestFn): Promise; + function only(name?: string, fn?: TestFn): Promise; + function only(options?: TestOptions, fn?: TestFn): Promise; + function only(fn?: TestFn): Promise; + /** + * The type of a function under test. The first argument to this function is a + * {@link TestContext} object. If the test uses callbacks, the callback function is passed as + * the second argument. + */ + type TestFn = (t: TestContext, done: (result?: any) => void) => void | Promise; + /** + * The type of a function under Suite. + */ + type SuiteFn = (s: SuiteContext) => void | Promise; + interface TestShard { + /** + * A positive integer between 1 and `` that specifies the index of the shard to run. + */ + index: number; + /** + * A positive integer that specifies the total number of shards to split the test files to. + */ + total: number; + } + interface RunOptions { + /** + * If a number is provided, then that many test processes would run in parallel, where each process corresponds to one test file. + * If `true`, it would run `os.availableParallelism() - 1` test files in parallel. If `false`, it would only run one test file at a time. + * @default false + */ + concurrency?: number | boolean | undefined; + /** + * An array containing the list of files to run. **Default** matching files from + * [test runner execution model](https://nodejs.org/docs/latest-v20.x/api/test.html#test-runner-execution-model). + */ + files?: readonly string[] | undefined; + /** + * Configures the test runner to exit the process once all known + * tests have finished executing even if the event loop would + * otherwise remain active. + * @default false + */ + forceExit?: boolean | undefined; + /** + * Sets inspector port of test child process. + * If a nullish value is provided, each process gets its own port, + * incremented from the primary's `process.debugPort`. + * @default undefined + */ + inspectPort?: number | (() => number) | undefined; + /** + * If truthy, the test context will only run tests that have the `only` option set + */ + only?: boolean; + /** + * A function that accepts the `TestsStream` instance and can be used to setup listeners before any tests are run. + * @default undefined + */ + setup?: (root: Test) => void | Promise; + /** + * Allows aborting an in-progress test execution. + */ + signal?: AbortSignal | undefined; + /** + * A String, RegExp or a RegExp Array, that can be used to only run tests whose + * name matches the provided pattern. Test name patterns are interpreted as JavaScript + * regular expressions. For each test that is executed, any corresponding test hooks, + * such as `beforeEach()`, are also run. + * @default undefined + */ + testNamePatterns?: string | RegExp | string[] | RegExp[]; + /** + * A number of milliseconds the test execution will fail after. + * If unspecified, subtests inherit this value from their parent. + * @default Infinity + */ + timeout?: number | undefined; + /** + * Whether to run in watch mode or not. + * @default false + */ + watch?: boolean | undefined; + /** + * Running tests in a specific shard. + * @default undefined + */ + shard?: TestShard | undefined; + } + class Test extends AsyncResource { + concurrency: number; + nesting: number; + only: boolean; + reporter: TestsStream; + runOnlySubtests: boolean; + testNumber: number; + timeout: number | null; + } + /** + * A successful call to `run()` method will return a new `TestsStream` object, streaming a series of events representing the execution of the tests. `TestsStream` will emit events, in the + * order of the tests definition + * + * Some of the events are guaranteed to be emitted in the same order as the tests are defined, while others are emitted in the order that the tests execute. + * @since v18.9.0, v16.19.0 + */ + class TestsStream extends Readable implements NodeJS.ReadableStream { + addListener(event: "test:coverage", listener: (data: TestCoverage) => void): this; + addListener(event: "test:complete", listener: (data: TestComplete) => void): this; + addListener(event: "test:dequeue", listener: (data: TestDequeue) => void): this; + addListener(event: "test:diagnostic", listener: (data: DiagnosticData) => void): this; + addListener(event: "test:enqueue", listener: (data: TestEnqueue) => void): this; + addListener(event: "test:fail", listener: (data: TestFail) => void): this; + addListener(event: "test:pass", listener: (data: TestPass) => void): this; + addListener(event: "test:plan", listener: (data: TestPlan) => void): this; + addListener(event: "test:start", listener: (data: TestStart) => void): this; + addListener(event: "test:stderr", listener: (data: TestStderr) => void): this; + addListener(event: "test:stdout", listener: (data: TestStdout) => void): this; + addListener(event: string, listener: (...args: any[]) => void): this; + emit(event: "test:coverage", data: TestCoverage): boolean; + emit(event: "test:complete", data: TestComplete): boolean; + emit(event: "test:dequeue", data: TestDequeue): boolean; + emit(event: "test:diagnostic", data: DiagnosticData): boolean; + emit(event: "test:enqueue", data: TestEnqueue): boolean; + emit(event: "test:fail", data: TestFail): boolean; + emit(event: "test:pass", data: TestPass): boolean; + emit(event: "test:plan", data: TestPlan): boolean; + emit(event: "test:start", data: TestStart): boolean; + emit(event: "test:stderr", data: TestStderr): boolean; + emit(event: "test:stdout", data: TestStdout): boolean; + emit(event: string | symbol, ...args: any[]): boolean; + on(event: "test:coverage", listener: (data: TestCoverage) => void): this; + on(event: "test:complete", listener: (data: TestComplete) => void): this; + on(event: "test:dequeue", listener: (data: TestDequeue) => void): this; + on(event: "test:diagnostic", listener: (data: DiagnosticData) => void): this; + on(event: "test:enqueue", listener: (data: TestEnqueue) => void): this; + on(event: "test:fail", listener: (data: TestFail) => void): this; + on(event: "test:pass", listener: (data: TestPass) => void): this; + on(event: "test:plan", listener: (data: TestPlan) => void): this; + on(event: "test:start", listener: (data: TestStart) => void): this; + on(event: "test:stderr", listener: (data: TestStderr) => void): this; + on(event: "test:stdout", listener: (data: TestStdout) => void): this; + on(event: string, listener: (...args: any[]) => void): this; + once(event: "test:coverage", listener: (data: TestCoverage) => void): this; + once(event: "test:complete", listener: (data: TestComplete) => void): this; + once(event: "test:dequeue", listener: (data: TestDequeue) => void): this; + once(event: "test:diagnostic", listener: (data: DiagnosticData) => void): this; + once(event: "test:enqueue", listener: (data: TestEnqueue) => void): this; + once(event: "test:fail", listener: (data: TestFail) => void): this; + once(event: "test:pass", listener: (data: TestPass) => void): this; + once(event: "test:plan", listener: (data: TestPlan) => void): this; + once(event: "test:start", listener: (data: TestStart) => void): this; + once(event: "test:stderr", listener: (data: TestStderr) => void): this; + once(event: "test:stdout", listener: (data: TestStdout) => void): this; + once(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "test:coverage", listener: (data: TestCoverage) => void): this; + prependListener(event: "test:complete", listener: (data: TestComplete) => void): this; + prependListener(event: "test:dequeue", listener: (data: TestDequeue) => void): this; + prependListener(event: "test:diagnostic", listener: (data: DiagnosticData) => void): this; + prependListener(event: "test:enqueue", listener: (data: TestEnqueue) => void): this; + prependListener(event: "test:fail", listener: (data: TestFail) => void): this; + prependListener(event: "test:pass", listener: (data: TestPass) => void): this; + prependListener(event: "test:plan", listener: (data: TestPlan) => void): this; + prependListener(event: "test:start", listener: (data: TestStart) => void): this; + prependListener(event: "test:stderr", listener: (data: TestStderr) => void): this; + prependListener(event: "test:stdout", listener: (data: TestStdout) => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "test:coverage", listener: (data: TestCoverage) => void): this; + prependOnceListener(event: "test:complete", listener: (data: TestComplete) => void): this; + prependOnceListener(event: "test:dequeue", listener: (data: TestDequeue) => void): this; + prependOnceListener(event: "test:diagnostic", listener: (data: DiagnosticData) => void): this; + prependOnceListener(event: "test:enqueue", listener: (data: TestEnqueue) => void): this; + prependOnceListener(event: "test:fail", listener: (data: TestFail) => void): this; + prependOnceListener(event: "test:pass", listener: (data: TestPass) => void): this; + prependOnceListener(event: "test:plan", listener: (data: TestPlan) => void): this; + prependOnceListener(event: "test:start", listener: (data: TestStart) => void): this; + prependOnceListener(event: "test:stderr", listener: (data: TestStderr) => void): this; + prependOnceListener(event: "test:stdout", listener: (data: TestStdout) => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + } + /** + * An instance of `TestContext` is passed to each test function in order to + * interact with the test runner. However, the `TestContext` constructor is not + * exposed as part of the API. + * @since v18.0.0, v16.17.0 + */ + class TestContext { + /** + * This function is used to create a hook running before subtest of the current test. + * @param fn The hook function. If the hook uses callbacks, the callback function is passed as + * the second argument. **Default:** A no-op function. + * @param options Configuration options for the hook. + * @since v20.1.0 + */ + before: typeof before; + /** + * This function is used to create a hook running before each subtest of the current test. + * @param fn The hook function. If the hook uses callbacks, the callback function is passed as + * the second argument. **Default:** A no-op function. + * @param options Configuration options for the hook. + * @since v18.8.0 + */ + beforeEach: typeof beforeEach; + /** + * This function is used to create a hook that runs after the current test finishes. + * @param [fn='A no-op function'] The hook function. If the hook uses callbacks, the callback function is passed as + * the second argument. Default: A no-op function. + * @param options Configuration options for the hook. + * @since v18.13.0 + */ + after: typeof after; + /** + * This function is used to create a hook running after each subtest of the current test. + * @param fn The hook function. If the hook uses callbacks, the callback function is passed as + * the second argument. **Default:** A no-op function. + * @param options Configuration options for the hook. + * @since v18.8.0 + */ + afterEach: typeof afterEach; + /** + * This function is used to write diagnostics to the output. Any diagnostic + * information is included at the end of the test's results. This function does + * not return a value. + * + * ```js + * test('top level test', (t) => { + * t.diagnostic('A diagnostic message'); + * }); + * ``` + * @since v18.0.0, v16.17.0 + * @param message Message to be reported. + */ + diagnostic(message: string): void; + /** + * The name of the test. + * @since v18.8.0, v16.18.0 + */ + readonly name: string; + /** + * If `shouldRunOnlyTests` is truthy, the test context will only run tests that + * have the `only` option set. Otherwise, all tests are run. If Node.js was not + * started with the `--test-only` command-line option, this function is a + * no-op. + * + * ```js + * test('top level test', (t) => { + * // The test context can be set to run subtests with the 'only' option. + * t.runOnly(true); + * return Promise.all([ + * t.test('this subtest is now skipped'), + * t.test('this subtest is run', { only: true }), + * ]); + * }); + * ``` + * @since v18.0.0, v16.17.0 + * @param shouldRunOnlyTests Whether or not to run `only` tests. + */ + runOnly(shouldRunOnlyTests: boolean): void; + /** + * ```js + * test('top level test', async (t) => { + * await fetch('some/uri', { signal: t.signal }); + * }); + * ``` + * @since v18.7.0, v16.17.0 + */ + readonly signal: AbortSignal; + /** + * This function causes the test's output to indicate the test as skipped. If `message` is provided, it is included in the output. Calling `skip()` does + * not terminate execution of the test function. This function does not return a + * value. + * + * ```js + * test('top level test', (t) => { + * // Make sure to return here as well if the test contains additional logic. + * t.skip('this is skipped'); + * }); + * ``` + * @since v18.0.0, v16.17.0 + * @param message Optional skip message. + */ + skip(message?: string): void; + /** + * This function adds a `TODO` directive to the test's output. If `message` is + * provided, it is included in the output. Calling `todo()` does not terminate + * execution of the test function. This function does not return a value. + * + * ```js + * test('top level test', (t) => { + * // This test is marked as `TODO` + * t.todo('this is a todo'); + * }); + * ``` + * @since v18.0.0, v16.17.0 + * @param message Optional `TODO` message. + */ + todo(message?: string): void; + /** + * This function is used to create subtests under the current test. This function behaves in + * the same fashion as the top level {@link test} function. + * @since v18.0.0 + * @param name The name of the test, which is displayed when reporting test results. + * Default: The `name` property of fn, or `''` if `fn` does not have a name. + * @param options Configuration options for the test + * @param fn The function under test. This first argument to this function is a + * {@link TestContext} object. If the test uses callbacks, the callback function is + * passed as the second argument. **Default:** A no-op function. + * @returns A {@link Promise} resolved with `undefined` once the test completes. + */ + test: typeof test; + /** + * Each test provides its own MockTracker instance. + */ + readonly mock: MockTracker; + } + + /** + * An instance of `SuiteContext` is passed to each suite function in order to + * interact with the test runner. However, the `SuiteContext` constructor is not + * exposed as part of the API. + * @since v18.7.0, v16.17.0 + */ + class SuiteContext { + /** + * The name of the suite. + * @since v18.8.0, v16.18.0 + */ + readonly name: string; + /** + * Can be used to abort test subtasks when the test has been aborted. + * @since v18.7.0, v16.17.0 + */ + readonly signal: AbortSignal; + } + interface TestOptions { + /** + * If a number is provided, then that many tests would run in parallel. + * If truthy, it would run (number of cpu cores - 1) tests in parallel. + * For subtests, it will be `Infinity` tests in parallel. + * If falsy, it would only run one test at a time. + * If unspecified, subtests inherit this value from their parent. + * @default false + */ + concurrency?: number | boolean | undefined; + /** + * If truthy, and the test context is configured to run `only` tests, then this test will be + * run. Otherwise, the test is skipped. + * @default false + */ + only?: boolean | undefined; + /** + * Allows aborting an in-progress test. + * @since v18.8.0 + */ + signal?: AbortSignal | undefined; + /** + * If truthy, the test is skipped. If a string is provided, that string is displayed in the + * test results as the reason for skipping the test. + * @default false + */ + skip?: boolean | string | undefined; + /** + * A number of milliseconds the test will fail after. If unspecified, subtests inherit this + * value from their parent. + * @default Infinity + * @since v18.7.0 + */ + timeout?: number | undefined; + /** + * If truthy, the test marked as `TODO`. If a string is provided, that string is displayed in + * the test results as the reason why the test is `TODO`. + * @default false + */ + todo?: boolean | string | undefined; + } + /** + * This function creates a hook that runs before executing a suite. + * + * ```js + * describe('tests', async () => { + * before(() => console.log('about to run some test')); + * it('is a subtest', () => { + * assert.ok('some relevant assertion here'); + * }); + * }); + * ``` + * @since v18.8.0, v16.18.0 + * @param [fn='A no-op function'] The hook function. If the hook uses callbacks, the callback function is passed as the second argument. + * @param options Configuration options for the hook. The following properties are supported: + */ + function before(fn?: HookFn, options?: HookOptions): void; + /** + * This function creates a hook that runs after executing a suite. + * + * ```js + * describe('tests', async () => { + * after(() => console.log('finished running tests')); + * it('is a subtest', () => { + * assert.ok('some relevant assertion here'); + * }); + * }); + * ``` + * @since v18.8.0, v16.18.0 + * @param [fn='A no-op function'] The hook function. If the hook uses callbacks, the callback function is passed as the second argument. + * @param options Configuration options for the hook. The following properties are supported: + */ + function after(fn?: HookFn, options?: HookOptions): void; + /** + * This function creates a hook that runs before each test in the current suite. + * + * ```js + * describe('tests', async () => { + * beforeEach(() => console.log('about to run a test')); + * it('is a subtest', () => { + * assert.ok('some relevant assertion here'); + * }); + * }); + * ``` + * @since v18.8.0, v16.18.0 + * @param [fn='A no-op function'] The hook function. If the hook uses callbacks, the callback function is passed as the second argument. + * @param options Configuration options for the hook. The following properties are supported: + */ + function beforeEach(fn?: HookFn, options?: HookOptions): void; + /** + * This function creates a hook that runs after each test in the current suite. + * The `afterEach()` hook is run even if the test fails. + * + * ```js + * describe('tests', async () => { + * afterEach(() => console.log('finished running a test')); + * it('is a subtest', () => { + * assert.ok('some relevant assertion here'); + * }); + * }); + * ``` + * @since v18.8.0, v16.18.0 + * @param [fn='A no-op function'] The hook function. If the hook uses callbacks, the callback function is passed as the second argument. + * @param options Configuration options for the hook. The following properties are supported: + */ + function afterEach(fn?: HookFn, options?: HookOptions): void; + /** + * The hook function. If the hook uses callbacks, the callback function is passed as the + * second argument. + */ + type HookFn = (s: SuiteContext, done: (result?: any) => void) => any; + /** + * Configuration options for hooks. + * @since v18.8.0 + */ + interface HookOptions { + /** + * Allows aborting an in-progress hook. + */ + signal?: AbortSignal | undefined; + /** + * A number of milliseconds the hook will fail after. If unspecified, subtests inherit this + * value from their parent. + * @default Infinity + */ + timeout?: number | undefined; + } + interface MockFunctionOptions { + /** + * The number of times that the mock will use the behavior of `implementation`. + * Once the mock function has been called `times` times, + * it will automatically restore the behavior of `original`. + * This value must be an integer greater than zero. + * @default Infinity + */ + times?: number | undefined; + } + interface MockMethodOptions extends MockFunctionOptions { + /** + * If `true`, `object[methodName]` is treated as a getter. + * This option cannot be used with the `setter` option. + */ + getter?: boolean | undefined; + /** + * If `true`, `object[methodName]` is treated as a setter. + * This option cannot be used with the `getter` option. + */ + setter?: boolean | undefined; + } + type Mock = F & { + mock: MockFunctionContext; + }; + type NoOpFunction = (...args: any[]) => undefined; + type FunctionPropertyNames = { + [K in keyof T]: T[K] extends Function ? K : never; + }[keyof T]; + /** + * The `MockTracker` class is used to manage mocking functionality. The test runner + * module provides a top level `mock` export which is a `MockTracker` instance. + * Each test also provides its own `MockTracker` instance via the test context's `mock` property. + * @since v19.1.0, v18.13.0 + */ + class MockTracker { + /** + * This function is used to create a mock function. + * + * The following example creates a mock function that increments a counter by one + * on each invocation. The `times` option is used to modify the mock behavior such + * that the first two invocations add two to the counter instead of one. + * + * ```js + * test('mocks a counting function', (t) => { + * let cnt = 0; + * + * function addOne() { + * cnt++; + * return cnt; + * } + * + * function addTwo() { + * cnt += 2; + * return cnt; + * } + * + * const fn = t.mock.fn(addOne, addTwo, { times: 2 }); + * + * assert.strictEqual(fn(), 2); + * assert.strictEqual(fn(), 4); + * assert.strictEqual(fn(), 5); + * assert.strictEqual(fn(), 6); + * }); + * ``` + * @since v19.1.0, v18.13.0 + * @param [original='A no-op function'] An optional function to create a mock on. + * @param implementation An optional function used as the mock implementation for `original`. This is useful for creating mocks that exhibit one behavior for a specified number of calls and + * then restore the behavior of `original`. + * @param options Optional configuration options for the mock function. The following properties are supported: + * @return The mocked function. The mocked function contains a special `mock` property, which is an instance of {@link MockFunctionContext}, and can be used for inspecting and changing the + * behavior of the mocked function. + */ + fn(original?: F, options?: MockFunctionOptions): Mock; + fn( + original?: F, + implementation?: Implementation, + options?: MockFunctionOptions, + ): Mock; + /** + * This function is used to create a mock on an existing object method. The + * following example demonstrates how a mock is created on an existing object + * method. + * + * ```js + * test('spies on an object method', (t) => { + * const number = { + * value: 5, + * subtract(a) { + * return this.value - a; + * }, + * }; + * + * t.mock.method(number, 'subtract'); + * assert.strictEqual(number.subtract.mock.calls.length, 0); + * assert.strictEqual(number.subtract(3), 2); + * assert.strictEqual(number.subtract.mock.calls.length, 1); + * + * const call = number.subtract.mock.calls[0]; + * + * assert.deepStrictEqual(call.arguments, [3]); + * assert.strictEqual(call.result, 2); + * assert.strictEqual(call.error, undefined); + * assert.strictEqual(call.target, undefined); + * assert.strictEqual(call.this, number); + * }); + * ``` + * @since v19.1.0, v18.13.0 + * @param object The object whose method is being mocked. + * @param methodName The identifier of the method on `object` to mock. If `object[methodName]` is not a function, an error is thrown. + * @param implementation An optional function used as the mock implementation for `object[methodName]`. + * @param options Optional configuration options for the mock method. The following properties are supported: + * @return The mocked method. The mocked method contains a special `mock` property, which is an instance of {@link MockFunctionContext}, and can be used for inspecting and changing the + * behavior of the mocked method. + */ + method< + MockedObject extends object, + MethodName extends FunctionPropertyNames, + >( + object: MockedObject, + methodName: MethodName, + options?: MockFunctionOptions, + ): MockedObject[MethodName] extends Function ? Mock + : never; + method< + MockedObject extends object, + MethodName extends FunctionPropertyNames, + Implementation extends Function, + >( + object: MockedObject, + methodName: MethodName, + implementation: Implementation, + options?: MockFunctionOptions, + ): MockedObject[MethodName] extends Function ? Mock + : never; + method( + object: MockedObject, + methodName: keyof MockedObject, + options: MockMethodOptions, + ): Mock; + method( + object: MockedObject, + methodName: keyof MockedObject, + implementation: Function, + options: MockMethodOptions, + ): Mock; + + /** + * This function is syntax sugar for `MockTracker.method` with `options.getter` set to `true`. + * @since v19.3.0, v18.13.0 + */ + getter< + MockedObject extends object, + MethodName extends keyof MockedObject, + >( + object: MockedObject, + methodName: MethodName, + options?: MockFunctionOptions, + ): Mock<() => MockedObject[MethodName]>; + getter< + MockedObject extends object, + MethodName extends keyof MockedObject, + Implementation extends Function, + >( + object: MockedObject, + methodName: MethodName, + implementation?: Implementation, + options?: MockFunctionOptions, + ): Mock<(() => MockedObject[MethodName]) | Implementation>; + /** + * This function is syntax sugar for `MockTracker.method` with `options.setter` set to `true`. + * @since v19.3.0, v18.13.0 + */ + setter< + MockedObject extends object, + MethodName extends keyof MockedObject, + >( + object: MockedObject, + methodName: MethodName, + options?: MockFunctionOptions, + ): Mock<(value: MockedObject[MethodName]) => void>; + setter< + MockedObject extends object, + MethodName extends keyof MockedObject, + Implementation extends Function, + >( + object: MockedObject, + methodName: MethodName, + implementation?: Implementation, + options?: MockFunctionOptions, + ): Mock<((value: MockedObject[MethodName]) => void) | Implementation>; + /** + * This function restores the default behavior of all mocks that were previously + * created by this `MockTracker` and disassociates the mocks from the `MockTracker` instance. Once disassociated, the mocks can still be used, but the `MockTracker` instance can no longer be + * used to reset their behavior or + * otherwise interact with them. + * + * After each test completes, this function is called on the test context's `MockTracker`. If the global `MockTracker` is used extensively, calling this + * function manually is recommended. + * @since v19.1.0, v18.13.0 + */ + reset(): void; + /** + * This function restores the default behavior of all mocks that were previously + * created by this `MockTracker`. Unlike `mock.reset()`, `mock.restoreAll()` does + * not disassociate the mocks from the `MockTracker` instance. + * @since v19.1.0, v18.13.0 + */ + restoreAll(): void; + timers: MockTimers; + } + const mock: MockTracker; + interface MockFunctionCall< + F extends Function, + ReturnType = F extends (...args: any) => infer T ? T + : F extends abstract new(...args: any) => infer T ? T + : unknown, + Args = F extends (...args: infer Y) => any ? Y + : F extends abstract new(...args: infer Y) => any ? Y + : unknown[], + > { + /** + * An array of the arguments passed to the mock function. + */ + arguments: Args; + /** + * If the mocked function threw then this property contains the thrown value. + */ + error: unknown | undefined; + /** + * The value returned by the mocked function. + * + * If the mocked function threw, it will be `undefined`. + */ + result: ReturnType | undefined; + /** + * An `Error` object whose stack can be used to determine the callsite of the mocked function invocation. + */ + stack: Error; + /** + * If the mocked function is a constructor, this field contains the class being constructed. + * Otherwise this will be `undefined`. + */ + target: F extends abstract new(...args: any) => any ? F : undefined; + /** + * The mocked function's `this` value. + */ + this: unknown; + } + /** + * The `MockFunctionContext` class is used to inspect or manipulate the behavior of + * mocks created via the `MockTracker` APIs. + * @since v19.1.0, v18.13.0 + */ + class MockFunctionContext { + /** + * A getter that returns a copy of the internal array used to track calls to the + * mock. Each entry in the array is an object with the following properties. + * @since v19.1.0, v18.13.0 + */ + readonly calls: Array>; + /** + * This function returns the number of times that this mock has been invoked. This + * function is more efficient than checking `ctx.calls.length` because `ctx.calls` is a getter that creates a copy of the internal call tracking array. + * @since v19.1.0, v18.13.0 + * @return The number of times that this mock has been invoked. + */ + callCount(): number; + /** + * This function is used to change the behavior of an existing mock. + * + * The following example creates a mock function using `t.mock.fn()`, calls the + * mock function, and then changes the mock implementation to a different function. + * + * ```js + * test('changes a mock behavior', (t) => { + * let cnt = 0; + * + * function addOne() { + * cnt++; + * return cnt; + * } + * + * function addTwo() { + * cnt += 2; + * return cnt; + * } + * + * const fn = t.mock.fn(addOne); + * + * assert.strictEqual(fn(), 1); + * fn.mock.mockImplementation(addTwo); + * assert.strictEqual(fn(), 3); + * assert.strictEqual(fn(), 5); + * }); + * ``` + * @since v19.1.0, v18.13.0 + * @param implementation The function to be used as the mock's new implementation. + */ + mockImplementation(implementation: Function): void; + /** + * This function is used to change the behavior of an existing mock for a single + * invocation. Once invocation `onCall` has occurred, the mock will revert to + * whatever behavior it would have used had `mockImplementationOnce()` not been + * called. + * + * The following example creates a mock function using `t.mock.fn()`, calls the + * mock function, changes the mock implementation to a different function for the + * next invocation, and then resumes its previous behavior. + * + * ```js + * test('changes a mock behavior once', (t) => { + * let cnt = 0; + * + * function addOne() { + * cnt++; + * return cnt; + * } + * + * function addTwo() { + * cnt += 2; + * return cnt; + * } + * + * const fn = t.mock.fn(addOne); + * + * assert.strictEqual(fn(), 1); + * fn.mock.mockImplementationOnce(addTwo); + * assert.strictEqual(fn(), 3); + * assert.strictEqual(fn(), 4); + * }); + * ``` + * @since v19.1.0, v18.13.0 + * @param implementation The function to be used as the mock's implementation for the invocation number specified by `onCall`. + * @param onCall The invocation number that will use `implementation`. If the specified invocation has already occurred then an exception is thrown. + */ + mockImplementationOnce(implementation: Function, onCall?: number): void; + /** + * Resets the call history of the mock function. + * @since v19.3.0, v18.13.0 + */ + resetCalls(): void; + /** + * Resets the implementation of the mock function to its original behavior. The + * mock can still be used after calling this function. + * @since v19.1.0, v18.13.0 + */ + restore(): void; + } + type Timer = "setInterval" | "setTimeout" | "setImmediate" | "Date"; + + interface MockTimersOptions { + apis: Timer[]; + now?: number | Date; + } + /** + * Mocking timers is a technique commonly used in software testing to simulate and + * control the behavior of timers, such as `setInterval` and `setTimeout`, + * without actually waiting for the specified time intervals. + * + * The MockTimers API also allows for mocking of the `Date` constructor and + * `setImmediate`/`clearImmediate` functions. + * + * The `MockTracker` provides a top-level `timers` export + * which is a `MockTimers` instance. + * @since v20.4.0 + * @experimental + */ + class MockTimers { + /** + * Enables timer mocking for the specified timers. + * + * **Note:** When you enable mocking for a specific timer, its associated + * clear function will also be implicitly mocked. + * + * **Note:** Mocking `Date` will affect the behavior of the mocked timers + * as they use the same internal clock. + * + * Example usage without setting initial time: + * + * ```js + * import { mock } from 'node:test'; + * mock.timers.enable({ apis: ['setInterval', 'Date'], now: 1234 }); + * ``` + * + * The above example enables mocking for the `Date` constructor, `setInterval` timer and + * implicitly mocks the `clearInterval` function. Only the `Date` constructor from `globalThis`, + * `setInterval` and `clearInterval` functions from `node:timers`, `node:timers/promises`, and `globalThis` will be mocked. + * + * Example usage with initial time set + * + * ```js + * import { mock } from 'node:test'; + * mock.timers.enable({ apis: ['Date'], now: 1000 }); + * ``` + * + * Example usage with initial Date object as time set + * + * ```js + * import { mock } from 'node:test'; + * mock.timers.enable({ apis: ['Date'], now: new Date() }); + * ``` + * + * Alternatively, if you call `mock.timers.enable()` without any parameters: + * + * All timers (`'setInterval'`, `'clearInterval'`, `'Date'`, `'setImmediate'`, `'clearImmediate'`, `'setTimeout'`, and `'clearTimeout'`) + * will be mocked. + * + * The `setInterval`, `clearInterval`, `setTimeout`, and `clearTimeout` functions from `node:timers`, `node:timers/promises`, + * and `globalThis` will be mocked. + * The `Date` constructor from `globalThis` will be mocked. + * + * If there is no initial epoch set, the initial date will be based on 0 in the Unix epoch. This is `January 1st, 1970, 00:00:00 UTC`. You can + * set an initial date by passing a now property to the `.enable()` method. This value will be used as the initial date for the mocked Date + * object. It can either be a positive integer, or another Date object. + * @since v20.4.0 + */ + enable(options?: MockTimersOptions): void; + /** + * You can use the `.setTime()` method to manually move the mocked date to another time. This method only accepts a positive integer. + * Note: This method will execute any mocked timers that are in the past from the new time. + * In the below example we are setting a new time for the mocked date. + * ```js + * import assert from 'node:assert'; + * import { test } from 'node:test'; + * test('sets the time of a date object', (context) => { + * // Optionally choose what to mock + * context.mock.timers.enable({ apis: ['Date'], now: 100 }); + * assert.strictEqual(Date.now(), 100); + * // Advance in time will also advance the date + * context.mock.timers.setTime(1000); + * context.mock.timers.tick(200); + * assert.strictEqual(Date.now(), 1200); + * }); + * ``` + */ + setTime(time: number): void; + /** + * This function restores the default behavior of all mocks that were previously + * created by this `MockTimers` instance and disassociates the mocks + * from the `MockTracker` instance. + * + * **Note:** After each test completes, this function is called on + * the test context's `MockTracker`. + * + * ```js + * import { mock } from 'node:test'; + * mock.timers.reset(); + * ``` + * @since v20.4.0 + */ + reset(): void; + /** + * Advances time for all mocked timers. + * + * **Note:** This diverges from how `setTimeout` in Node.js behaves and accepts + * only positive numbers. In Node.js, `setTimeout` with negative numbers is + * only supported for web compatibility reasons. + * + * The following example mocks a `setTimeout` function and + * by using `.tick` advances in + * time triggering all pending timers. + * + * ```js + * import assert from 'node:assert'; + * import { test } from 'node:test'; + * + * test('mocks setTimeout to be executed synchronously without having to actually wait for it', (context) => { + * const fn = context.mock.fn(); + * + * context.mock.timers.enable({ apis: ['setTimeout'] }); + * + * setTimeout(fn, 9999); + * + * assert.strictEqual(fn.mock.callCount(), 0); + * + * // Advance in time + * context.mock.timers.tick(9999); + * + * assert.strictEqual(fn.mock.callCount(), 1); + * }); + * ``` + * + * Alternativelly, the `.tick` function can be called many times + * + * ```js + * import assert from 'node:assert'; + * import { test } from 'node:test'; + * + * test('mocks setTimeout to be executed synchronously without having to actually wait for it', (context) => { + * const fn = context.mock.fn(); + * context.mock.timers.enable({ apis: ['setTimeout'] }); + * const nineSecs = 9000; + * setTimeout(fn, nineSecs); + * + * const twoSeconds = 3000; + * context.mock.timers.tick(twoSeconds); + * context.mock.timers.tick(twoSeconds); + * context.mock.timers.tick(twoSeconds); + * + * assert.strictEqual(fn.mock.callCount(), 1); + * }); + * ``` + * + * Advancing time using `.tick` will also advance the time for any `Date` object + * created after the mock was enabled (if `Date` was also set to be mocked). + * + * ```js + * import assert from 'node:assert'; + * import { test } from 'node:test'; + * + * test('mocks setTimeout to be executed synchronously without having to actually wait for it', (context) => { + * const fn = context.mock.fn(); + * + * context.mock.timers.enable({ apis: ['setTimeout', 'Date'] }); + * setTimeout(fn, 9999); + * + * assert.strictEqual(fn.mock.callCount(), 0); + * assert.strictEqual(Date.now(), 0); + * + * // Advance in time + * context.mock.timers.tick(9999); + * assert.strictEqual(fn.mock.callCount(), 1); + * assert.strictEqual(Date.now(), 9999); + * }); + * ``` + * @since v20.4.0 + */ + tick(milliseconds: number): void; + /** + * Triggers all pending mocked timers immediately. If the `Date` object is also + * mocked, it will also advance the `Date` object to the furthest timer's time. + * + * The example below triggers all pending timers immediately, + * causing them to execute without any delay. + * + * ```js + * import assert from 'node:assert'; + * import { test } from 'node:test'; + * + * test('runAll functions following the given order', (context) => { + * context.mock.timers.enable({ apis: ['setTimeout', 'Date'] }); + * const results = []; + * setTimeout(() => results.push(1), 9999); + * + * // Notice that if both timers have the same timeout, + * // the order of execution is guaranteed + * setTimeout(() => results.push(3), 8888); + * setTimeout(() => results.push(2), 8888); + * + * assert.deepStrictEqual(results, []); + * + * context.mock.timers.runAll(); + * assert.deepStrictEqual(results, [3, 2, 1]); + * // The Date object is also advanced to the furthest timer's time + * assert.strictEqual(Date.now(), 9999); + * }); + * ``` + * + * **Note:** The `runAll()` function is specifically designed for + * triggering timers in the context of timer mocking. + * It does not have any effect on real-time system + * clocks or actual timers outside of the mocking environment. + * @since v20.4.0 + */ + runAll(): void; + /** + * Calls {@link MockTimers.reset()}. + */ + [Symbol.dispose](): void; + } + export { + after, + afterEach, + before, + beforeEach, + describe, + it, + Mock, + mock, + only, + run, + skip, + SuiteContext, + test, + test as default, + TestContext, + todo, + }; +} + +interface TestLocationInfo { + /** + * The column number where the test is defined, or + * `undefined` if the test was run through the REPL. + */ + column?: number; + /** + * The path of the test file, `undefined` if test was run through the REPL. + */ + file?: string; + /** + * The line number where the test is defined, or `undefined` if the test was run through the REPL. + */ + line?: number; +} +interface DiagnosticData extends TestLocationInfo { + /** + * The diagnostic message. + */ + message: string; + /** + * The nesting level of the test. + */ + nesting: number; +} +interface TestCoverage { + /** + * An object containing the coverage report. + */ + summary: { + /** + * An array of coverage reports for individual files. Each report is an object with the following schema: + */ + files: Array<{ + /** + * The absolute path of the file. + */ + path: string; + /** + * The total number of lines. + */ + totalLineCount: number; + /** + * The total number of branches. + */ + totalBranchCount: number; + /** + * The total number of functions. + */ + totalFunctionCount: number; + /** + * The number of covered lines. + */ + coveredLineCount: number; + /** + * The number of covered branches. + */ + coveredBranchCount: number; + /** + * The number of covered functions. + */ + coveredFunctionCount: number; + /** + * The percentage of lines covered. + */ + coveredLinePercent: number; + /** + * The percentage of branches covered. + */ + coveredBranchPercent: number; + /** + * The percentage of functions covered. + */ + coveredFunctionPercent: number; + /** + * An array of functions representing function coverage. + */ + functions: Array<{ + /** + * The name of the function. + */ + name: string; + /** + * The line number where the function is defined. + */ + line: number; + /** + * The number of times the function was called. + */ + count: number; + }>; + /** + * An array of lines representing line numbers and the number of times they were covered. + */ + lines: Array<{ + /** + * The line number. + */ + line: number; + /** + * The number of times the line was covered. + */ + count: number; + }>; + }>; + /** + * An object containing a summary of coverage for all files. + */ + totals: { + /** + * The total number of lines. + */ + totalLineCount: number; + /** + * The total number of branches. + */ + totalBranchCount: number; + /** + * The total number of functions. + */ + totalFunctionCount: number; + /** + * The number of covered lines. + */ + coveredLineCount: number; + /** + * The number of covered branches. + */ + coveredBranchCount: number; + /** + * The number of covered functions. + */ + coveredFunctionCount: number; + /** + * The percentage of lines covered. + */ + coveredLinePercent: number; + /** + * The percentage of branches covered. + */ + coveredBranchPercent: number; + /** + * The percentage of functions covered. + */ + coveredFunctionPercent: number; + }; + /** + * The working directory when code coverage began. This + * is useful for displaying relative path names in case + * the tests changed the working directory of the Node.js process. + */ + workingDirectory: string; + }; + /** + * The nesting level of the test. + */ + nesting: number; +} +interface TestComplete extends TestLocationInfo { + /** + * Additional execution metadata. + */ + details: { + /** + * Whether the test passed or not. + */ + passed: boolean; + /** + * The duration of the test in milliseconds. + */ + duration_ms: number; + /** + * An error wrapping the error thrown by the test if it did not pass. + */ + error: Error; + /** + * The type of the test, used to denote whether this is a suite. + */ + type?: "suite"; + }; + /** + * The test name. + */ + name: string; + /** + * The nesting level of the test. + */ + nesting: number; + /** + * The ordinal number of the test. + */ + testNumber: number; + /** + * Present if `context.todo` is called. + */ + todo?: string | boolean; + /** + * Present if `context.skip` is called. + */ + skip?: string | boolean; +} +interface TestDequeue extends TestLocationInfo { + /** + * The test name. + */ + name: string; + /** + * The nesting level of the test. + */ + nesting: number; +} +interface TestEnqueue extends TestLocationInfo { + /** + * The test name. + */ + name: string; + /** + * The nesting level of the test. + */ + nesting: number; +} +interface TestFail extends TestLocationInfo { + /** + * Additional execution metadata. + */ + details: { + /** + * The duration of the test in milliseconds. + */ + duration_ms: number; + /** + * An error wrapping the error thrown by the test if it did not pass. + */ + error: Error; + /** + * The type of the test, used to denote whether this is a suite. + * @since v20.0.0, v19.9.0, v18.17.0 + */ + type?: "suite"; + }; + /** + * The test name. + */ + name: string; + /** + * The nesting level of the test. + */ + nesting: number; + /** + * The ordinal number of the test. + */ + testNumber: number; + /** + * Present if `context.todo` is called. + */ + todo?: string | boolean; + /** + * Present if `context.skip` is called. + */ + skip?: string | boolean; +} +interface TestPass extends TestLocationInfo { + /** + * Additional execution metadata. + */ + details: { + /** + * The duration of the test in milliseconds. + */ + duration_ms: number; + /** + * The type of the test, used to denote whether this is a suite. + * @since 20.0.0, 19.9.0, 18.17.0 + */ + type?: "suite"; + }; + /** + * The test name. + */ + name: string; + /** + * The nesting level of the test. + */ + nesting: number; + /** + * The ordinal number of the test. + */ + testNumber: number; + /** + * Present if `context.todo` is called. + */ + todo?: string | boolean; + /** + * Present if `context.skip` is called. + */ + skip?: string | boolean; +} +interface TestPlan extends TestLocationInfo { + /** + * The nesting level of the test. + */ + nesting: number; + /** + * The number of subtests that have ran. + */ + count: number; +} +interface TestStart extends TestLocationInfo { + /** + * The test name. + */ + name: string; + /** + * The nesting level of the test. + */ + nesting: number; +} +interface TestStderr extends TestLocationInfo { + /** + * The message written to `stderr`. + */ + message: string; +} +interface TestStdout extends TestLocationInfo { + /** + * The message written to `stdout`. + */ + message: string; +} + +/** + * The `node:test/reporters` module exposes the builtin-reporters for `node:test`. + * To access it: + * + * ```js + * import test from 'node:test/reporters'; + * ``` + * + * This module is only available under the `node:` scheme. The following will not + * work: + * + * ```js + * import test from 'test/reporters'; + * ``` + * @since v19.9.0 + * @see [source](https://github.com/nodejs/node/blob/v20.13.1/lib/test/reporters.js) + */ +declare module "node:test/reporters" { + import { Transform, TransformOptions } from "node:stream"; + + type TestEvent = + | { type: "test:coverage"; data: TestCoverage } + | { type: "test:complete"; data: TestComplete } + | { type: "test:dequeue"; data: TestDequeue } + | { type: "test:diagnostic"; data: DiagnosticData } + | { type: "test:enqueue"; data: TestEnqueue } + | { type: "test:fail"; data: TestFail } + | { type: "test:pass"; data: TestPass } + | { type: "test:plan"; data: TestPlan } + | { type: "test:start"; data: TestStart } + | { type: "test:stderr"; data: TestStderr } + | { type: "test:stdout"; data: TestStdout } + | { type: "test:watch:drained" }; + type TestEventGenerator = AsyncGenerator; + + /** + * The `dot` reporter outputs the test results in a compact format, + * where each passing test is represented by a `.`, + * and each failing test is represented by a `X`. + */ + function dot(source: TestEventGenerator): AsyncGenerator<"\n" | "." | "X", void>; + /** + * The `tap` reporter outputs the test results in the [TAP](https://testanything.org/) format. + */ + function tap(source: TestEventGenerator): AsyncGenerator; + /** + * The `spec` reporter outputs the test results in a human-readable format. + */ + class Spec extends Transform { + constructor(); + } + /** + * The `junit` reporter outputs test results in a jUnit XML format. + */ + function junit(source: TestEventGenerator): AsyncGenerator; + /** + * The `lcov` reporter outputs test coverage when used with the [`--experimental-test-coverage`](https://nodejs.org/docs/latest-v20.x/api/cli.html#--experimental-test-coverage) flag. + */ + class Lcov extends Transform { + constructor(opts?: TransformOptions); + } + export { dot, junit, Lcov as lcov, Spec as spec, tap, TestEvent }; +} diff --git a/node_modules/@types/node/timers.d.ts b/node_modules/@types/node/timers.d.ts new file mode 100644 index 0000000..5a73ca9 --- /dev/null +++ b/node_modules/@types/node/timers.d.ts @@ -0,0 +1,240 @@ +/** + * The `timer` module exposes a global API for scheduling functions to + * be called at some future period of time. Because the timer functions are + * globals, there is no need to call `require('node:timers')` to use the API. + * + * The timer functions within Node.js implement a similar API as the timers API + * provided by Web Browsers but use a different internal implementation that is + * built around the Node.js [Event Loop](https://nodejs.org/en/docs/guides/event-loop-timers-and-nexttick/#setimmediate-vs-settimeout). + * @see [source](https://github.com/nodejs/node/blob/v20.13.1/lib/timers.js) + */ +declare module "timers" { + import { Abortable } from "node:events"; + import { + setImmediate as setImmediatePromise, + setInterval as setIntervalPromise, + setTimeout as setTimeoutPromise, + } from "node:timers/promises"; + interface TimerOptions extends Abortable { + /** + * Set to `false` to indicate that the scheduled `Timeout` + * should not require the Node.js event loop to remain active. + * @default true + */ + ref?: boolean | undefined; + } + let setTimeout: typeof global.setTimeout; + let clearTimeout: typeof global.clearTimeout; + let setInterval: typeof global.setInterval; + let clearInterval: typeof global.clearInterval; + let setImmediate: typeof global.setImmediate; + let clearImmediate: typeof global.clearImmediate; + global { + namespace NodeJS { + // compatibility with older typings + interface Timer extends RefCounted { + hasRef(): boolean; + refresh(): this; + [Symbol.toPrimitive](): number; + } + /** + * This object is created internally and is returned from `setImmediate()`. It + * can be passed to `clearImmediate()` in order to cancel the scheduled + * actions. + * + * By default, when an immediate is scheduled, the Node.js event loop will continue + * running as long as the immediate is active. The `Immediate` object returned by `setImmediate()` exports both `immediate.ref()` and `immediate.unref()` functions that can be used to + * control this default behavior. + */ + class Immediate implements RefCounted { + /** + * When called, requests that the Node.js event loop _not_ exit so long as the `Immediate` is active. Calling `immediate.ref()` multiple times will have no + * effect. + * + * By default, all `Immediate` objects are "ref'ed", making it normally unnecessary + * to call `immediate.ref()` unless `immediate.unref()` had been called previously. + * @since v9.7.0 + * @return a reference to `immediate` + */ + ref(): this; + /** + * When called, the active `Immediate` object will not require the Node.js event + * loop to remain active. If there is no other activity keeping the event loop + * running, the process may exit before the `Immediate` object's callback is + * invoked. Calling `immediate.unref()` multiple times will have no effect. + * @since v9.7.0 + * @return a reference to `immediate` + */ + unref(): this; + /** + * If true, the `Immediate` object will keep the Node.js event loop active. + * @since v11.0.0 + */ + hasRef(): boolean; + _onImmediate: Function; // to distinguish it from the Timeout class + /** + * Cancels the immediate. This is similar to calling `clearImmediate()`. + * @since v20.5.0 + */ + [Symbol.dispose](): void; + } + /** + * This object is created internally and is returned from `setTimeout()` and `setInterval()`. It can be passed to either `clearTimeout()` or `clearInterval()` in order to cancel the + * scheduled actions. + * + * By default, when a timer is scheduled using either `setTimeout()` or `setInterval()`, the Node.js event loop will continue running as long as the + * timer is active. Each of the `Timeout` objects returned by these functions + * export both `timeout.ref()` and `timeout.unref()` functions that can be used to + * control this default behavior. + */ + class Timeout implements Timer { + /** + * When called, requests that the Node.js event loop _not_ exit so long as the`Timeout` is active. Calling `timeout.ref()` multiple times will have no effect. + * + * By default, all `Timeout` objects are "ref'ed", making it normally unnecessary + * to call `timeout.ref()` unless `timeout.unref()` had been called previously. + * @since v0.9.1 + * @return a reference to `timeout` + */ + ref(): this; + /** + * When called, the active `Timeout` object will not require the Node.js event loop + * to remain active. If there is no other activity keeping the event loop running, + * the process may exit before the `Timeout` object's callback is invoked. Calling `timeout.unref()` multiple times will have no effect. + * @since v0.9.1 + * @return a reference to `timeout` + */ + unref(): this; + /** + * If true, the `Timeout` object will keep the Node.js event loop active. + * @since v11.0.0 + */ + hasRef(): boolean; + /** + * Sets the timer's start time to the current time, and reschedules the timer to + * call its callback at the previously specified duration adjusted to the current + * time. This is useful for refreshing a timer without allocating a new + * JavaScript object. + * + * Using this on a timer that has already called its callback will reactivate the + * timer. + * @since v10.2.0 + * @return a reference to `timeout` + */ + refresh(): this; + [Symbol.toPrimitive](): number; + /** + * Cancels the timeout. + * @since v20.5.0 + */ + [Symbol.dispose](): void; + } + } + /** + * Schedules execution of a one-time `callback` after `delay` milliseconds. + * + * The `callback` will likely not be invoked in precisely `delay` milliseconds. + * Node.js makes no guarantees about the exact timing of when callbacks will fire, + * nor of their ordering. The callback will be called as close as possible to the + * time specified. + * + * When `delay` is larger than `2147483647` or less than `1`, the `delay` will be set to `1`. Non-integer delays are truncated to an integer. + * + * If `callback` is not a function, a `TypeError` will be thrown. + * + * This method has a custom variant for promises that is available using `timersPromises.setTimeout()`. + * @since v0.0.1 + * @param callback The function to call when the timer elapses. + * @param [delay=1] The number of milliseconds to wait before calling the `callback`. + * @param args Optional arguments to pass when the `callback` is called. + * @return for use with {@link clearTimeout} + */ + function setTimeout( + callback: (...args: TArgs) => void, + ms?: number, + ...args: TArgs + ): NodeJS.Timeout; + // util.promisify no rest args compability + // eslint-disable-next-line @typescript-eslint/no-invalid-void-type + function setTimeout(callback: (args: void) => void, ms?: number): NodeJS.Timeout; + namespace setTimeout { + const __promisify__: typeof setTimeoutPromise; + } + /** + * Cancels a `Timeout` object created by `setTimeout()`. + * @since v0.0.1 + * @param timeout A `Timeout` object as returned by {@link setTimeout} or the `primitive` of the `Timeout` object as a string or a number. + */ + function clearTimeout(timeoutId: NodeJS.Timeout | string | number | undefined): void; + /** + * Schedules repeated execution of `callback` every `delay` milliseconds. + * + * When `delay` is larger than `2147483647` or less than `1`, the `delay` will be + * set to `1`. Non-integer delays are truncated to an integer. + * + * If `callback` is not a function, a `TypeError` will be thrown. + * + * This method has a custom variant for promises that is available using `timersPromises.setInterval()`. + * @since v0.0.1 + * @param callback The function to call when the timer elapses. + * @param [delay=1] The number of milliseconds to wait before calling the `callback`. + * @param args Optional arguments to pass when the `callback` is called. + * @return for use with {@link clearInterval} + */ + function setInterval( + callback: (...args: TArgs) => void, + ms?: number, + ...args: TArgs + ): NodeJS.Timeout; + // util.promisify no rest args compability + // eslint-disable-next-line @typescript-eslint/no-invalid-void-type + function setInterval(callback: (args: void) => void, ms?: number): NodeJS.Timeout; + namespace setInterval { + const __promisify__: typeof setIntervalPromise; + } + /** + * Cancels a `Timeout` object created by `setInterval()`. + * @since v0.0.1 + * @param timeout A `Timeout` object as returned by {@link setInterval} or the `primitive` of the `Timeout` object as a string or a number. + */ + function clearInterval(intervalId: NodeJS.Timeout | string | number | undefined): void; + /** + * Schedules the "immediate" execution of the `callback` after I/O events' + * callbacks. + * + * When multiple calls to `setImmediate()` are made, the `callback` functions are + * queued for execution in the order in which they are created. The entire callback + * queue is processed every event loop iteration. If an immediate timer is queued + * from inside an executing callback, that timer will not be triggered until the + * next event loop iteration. + * + * If `callback` is not a function, a `TypeError` will be thrown. + * + * This method has a custom variant for promises that is available using `timersPromises.setImmediate()`. + * @since v0.9.1 + * @param callback The function to call at the end of this turn of the Node.js `Event Loop` + * @param args Optional arguments to pass when the `callback` is called. + * @return for use with {@link clearImmediate} + */ + function setImmediate( + callback: (...args: TArgs) => void, + ...args: TArgs + ): NodeJS.Immediate; + // util.promisify no rest args compability + // eslint-disable-next-line @typescript-eslint/no-invalid-void-type + function setImmediate(callback: (args: void) => void): NodeJS.Immediate; + namespace setImmediate { + const __promisify__: typeof setImmediatePromise; + } + /** + * Cancels an `Immediate` object created by `setImmediate()`. + * @since v0.9.1 + * @param immediate An `Immediate` object as returned by {@link setImmediate}. + */ + function clearImmediate(immediateId: NodeJS.Immediate | undefined): void; + function queueMicrotask(callback: () => void): void; + } +} +declare module "node:timers" { + export * from "timers"; +} diff --git a/node_modules/@types/node/timers/promises.d.ts b/node_modules/@types/node/timers/promises.d.ts new file mode 100644 index 0000000..50cee98 --- /dev/null +++ b/node_modules/@types/node/timers/promises.d.ts @@ -0,0 +1,97 @@ +/** + * The `timers/promises` API provides an alternative set of timer functions + * that return `Promise` objects. The API is accessible via `require('node:timers/promises')`. + * + * ```js + * import { + * setTimeout, + * setImmediate, + * setInterval, + * } from 'timers/promises'; + * ``` + * @since v15.0.0 + */ +declare module "timers/promises" { + import { TimerOptions } from "node:timers"; + /** + * ```js + * import { + * setTimeout, + * } from 'timers/promises'; + * + * const res = await setTimeout(100, 'result'); + * + * console.log(res); // Prints 'result' + * ``` + * @since v15.0.0 + * @param [delay=1] The number of milliseconds to wait before fulfilling the promise. + * @param value A value with which the promise is fulfilled. + */ + function setTimeout(delay?: number, value?: T, options?: TimerOptions): Promise; + /** + * ```js + * import { + * setImmediate, + * } from 'timers/promises'; + * + * const res = await setImmediate('result'); + * + * console.log(res); // Prints 'result' + * ``` + * @since v15.0.0 + * @param value A value with which the promise is fulfilled. + */ + function setImmediate(value?: T, options?: TimerOptions): Promise; + /** + * Returns an async iterator that generates values in an interval of `delay` ms. + * If `ref` is `true`, you need to call `next()` of async iterator explicitly + * or implicitly to keep the event loop alive. + * + * ```js + * import { + * setInterval, + * } from 'timers/promises'; + * + * const interval = 100; + * for await (const startTime of setInterval(interval, Date.now())) { + * const now = Date.now(); + * console.log(now); + * if ((now - startTime) > 1000) + * break; + * } + * console.log(Date.now()); + * ``` + * @since v15.9.0 + */ + function setInterval(delay?: number, value?: T, options?: TimerOptions): AsyncIterable; + interface Scheduler { + /** + * An experimental API defined by the [Scheduling APIs](https://github.com/WICG/scheduling-apis) draft specification being developed as a standard Web Platform API. + * + * Calling `timersPromises.scheduler.wait(delay, options)` is roughly equivalent to calling `timersPromises.setTimeout(delay, undefined, options)` except that the `ref` + * option is not supported. + * + * ```js + * import { scheduler } from 'node:timers/promises'; + * + * await scheduler.wait(1000); // Wait one second before continuing + * ``` + * @since v16.14.0 + * @experimental + * @param [delay=1] The number of milliseconds to wait before fulfilling the promise. + */ + wait: (delay?: number, options?: Pick) => Promise; + /** + * An experimental API defined by the [Scheduling APIs](https://nodejs.org/docs/latest-v20.x/api/async_hooks.html#promise-execution-tracking) draft specification + * being developed as a standard Web Platform API. + * Calling `timersPromises.scheduler.yield()` is equivalent to calling `timersPromises.setImmediate()` with no arguments. + * @since v16.14.0 + * @experimental + */ + yield: () => Promise; + } + const scheduler: Scheduler; +} +declare module "node:timers/promises" { + export * from "timers/promises"; +} diff --git a/node_modules/@types/node/tls.d.ts b/node_modules/@types/node/tls.d.ts new file mode 100644 index 0000000..707549b --- /dev/null +++ b/node_modules/@types/node/tls.d.ts @@ -0,0 +1,1217 @@ +/** + * The `node:tls` module provides an implementation of the Transport Layer Security + * (TLS) and Secure Socket Layer (SSL) protocols that is built on top of OpenSSL. + * The module can be accessed using: + * + * ```js + * const tls = require('node:tls'); + * ``` + * @see [source](https://github.com/nodejs/node/blob/v20.13.1/lib/tls.js) + */ +declare module "tls" { + import { X509Certificate } from "node:crypto"; + import * as net from "node:net"; + import * as stream from "stream"; + const CLIENT_RENEG_LIMIT: number; + const CLIENT_RENEG_WINDOW: number; + interface Certificate { + /** + * Country code. + */ + C: string; + /** + * Street. + */ + ST: string; + /** + * Locality. + */ + L: string; + /** + * Organization. + */ + O: string; + /** + * Organizational unit. + */ + OU: string; + /** + * Common name. + */ + CN: string; + } + interface PeerCertificate { + /** + * `true` if a Certificate Authority (CA), `false` otherwise. + * @since v18.13.0 + */ + ca: boolean; + /** + * The DER encoded X.509 certificate data. + */ + raw: Buffer; + /** + * The certificate subject. + */ + subject: Certificate; + /** + * The certificate issuer, described in the same terms as the `subject`. + */ + issuer: Certificate; + /** + * The date-time the certificate is valid from. + */ + valid_from: string; + /** + * The date-time the certificate is valid to. + */ + valid_to: string; + /** + * The certificate serial number, as a hex string. + */ + serialNumber: string; + /** + * The SHA-1 digest of the DER encoded certificate. + * It is returned as a `:` separated hexadecimal string. + */ + fingerprint: string; + /** + * The SHA-256 digest of the DER encoded certificate. + * It is returned as a `:` separated hexadecimal string. + */ + fingerprint256: string; + /** + * The SHA-512 digest of the DER encoded certificate. + * It is returned as a `:` separated hexadecimal string. + */ + fingerprint512: string; + /** + * The extended key usage, a set of OIDs. + */ + ext_key_usage?: string[]; + /** + * A string containing concatenated names for the subject, + * an alternative to the `subject` names. + */ + subjectaltname?: string; + /** + * An array describing the AuthorityInfoAccess, used with OCSP. + */ + infoAccess?: NodeJS.Dict; + /** + * For RSA keys: The RSA bit size. + * + * For EC keys: The key size in bits. + */ + bits?: number; + /** + * The RSA exponent, as a string in hexadecimal number notation. + */ + exponent?: string; + /** + * The RSA modulus, as a hexadecimal string. + */ + modulus?: string; + /** + * The public key. + */ + pubkey?: Buffer; + /** + * The ASN.1 name of the OID of the elliptic curve. + * Well-known curves are identified by an OID. + * While it is unusual, it is possible that the curve + * is identified by its mathematical properties, + * in which case it will not have an OID. + */ + asn1Curve?: string; + /** + * The NIST name for the elliptic curve, if it has one + * (not all well-known curves have been assigned names by NIST). + */ + nistCurve?: string; + } + interface DetailedPeerCertificate extends PeerCertificate { + /** + * The issuer certificate object. + * For self-signed certificates, this may be a circular reference. + */ + issuerCertificate: DetailedPeerCertificate; + } + interface CipherNameAndProtocol { + /** + * The cipher name. + */ + name: string; + /** + * SSL/TLS protocol version. + */ + version: string; + /** + * IETF name for the cipher suite. + */ + standardName: string; + } + interface EphemeralKeyInfo { + /** + * The supported types are 'DH' and 'ECDH'. + */ + type: string; + /** + * The name property is available only when type is 'ECDH'. + */ + name?: string | undefined; + /** + * The size of parameter of an ephemeral key exchange. + */ + size: number; + } + interface KeyObject { + /** + * Private keys in PEM format. + */ + pem: string | Buffer; + /** + * Optional passphrase. + */ + passphrase?: string | undefined; + } + interface PxfObject { + /** + * PFX or PKCS12 encoded private key and certificate chain. + */ + buf: string | Buffer; + /** + * Optional passphrase. + */ + passphrase?: string | undefined; + } + interface TLSSocketOptions extends SecureContextOptions, CommonConnectionOptions { + /** + * If true the TLS socket will be instantiated in server-mode. + * Defaults to false. + */ + isServer?: boolean | undefined; + /** + * An optional net.Server instance. + */ + server?: net.Server | undefined; + /** + * An optional Buffer instance containing a TLS session. + */ + session?: Buffer | undefined; + /** + * If true, specifies that the OCSP status request extension will be + * added to the client hello and an 'OCSPResponse' event will be + * emitted on the socket before establishing a secure communication + */ + requestOCSP?: boolean | undefined; + } + /** + * Performs transparent encryption of written data and all required TLS + * negotiation. + * + * Instances of `tls.TLSSocket` implement the duplex `Stream` interface. + * + * Methods that return TLS connection metadata (e.g.{@link TLSSocket.getPeerCertificate}) will only return data while the + * connection is open. + * @since v0.11.4 + */ + class TLSSocket extends net.Socket { + /** + * Construct a new tls.TLSSocket object from an existing TCP socket. + */ + constructor(socket: net.Socket | stream.Duplex, options?: TLSSocketOptions); + /** + * This property is `true` if the peer certificate was signed by one of the CAs + * specified when creating the `tls.TLSSocket` instance, otherwise `false`. + * @since v0.11.4 + */ + authorized: boolean; + /** + * Returns the reason why the peer's certificate was not been verified. This + * property is set only when `tlsSocket.authorized === false`. + * @since v0.11.4 + */ + authorizationError: Error; + /** + * Always returns `true`. This may be used to distinguish TLS sockets from regular`net.Socket` instances. + * @since v0.11.4 + */ + encrypted: true; + /** + * String containing the selected ALPN protocol. + * Before a handshake has completed, this value is always null. + * When a handshake is completed but not ALPN protocol was selected, tlsSocket.alpnProtocol equals false. + */ + alpnProtocol: string | false | null; + /** + * Returns an object representing the local certificate. The returned object has + * some properties corresponding to the fields of the certificate. + * + * See {@link TLSSocket.getPeerCertificate} for an example of the certificate + * structure. + * + * If there is no local certificate, an empty object will be returned. If the + * socket has been destroyed, `null` will be returned. + * @since v11.2.0 + */ + getCertificate(): PeerCertificate | object | null; + /** + * Returns an object containing information on the negotiated cipher suite. + * + * For example, a TLSv1.2 protocol with AES256-SHA cipher: + * + * ```json + * { + * "name": "AES256-SHA", + * "standardName": "TLS_RSA_WITH_AES_256_CBC_SHA", + * "version": "SSLv3" + * } + * ``` + * + * See [SSL\_CIPHER\_get\_name](https://www.openssl.org/docs/man1.1.1/man3/SSL_CIPHER_get_name.html) for more information. + * @since v0.11.4 + */ + getCipher(): CipherNameAndProtocol; + /** + * Returns an object representing the type, name, and size of parameter of + * an ephemeral key exchange in `perfect forward secrecy` on a client + * connection. It returns an empty object when the key exchange is not + * ephemeral. As this is only supported on a client socket; `null` is returned + * if called on a server socket. The supported types are `'DH'` and `'ECDH'`. The `name` property is available only when type is `'ECDH'`. + * + * For example: `{ type: 'ECDH', name: 'prime256v1', size: 256 }`. + * @since v5.0.0 + */ + getEphemeralKeyInfo(): EphemeralKeyInfo | object | null; + /** + * As the `Finished` messages are message digests of the complete handshake + * (with a total of 192 bits for TLS 1.0 and more for SSL 3.0), they can + * be used for external authentication procedures when the authentication + * provided by SSL/TLS is not desired or is not enough. + * + * Corresponds to the `SSL_get_finished` routine in OpenSSL and may be used + * to implement the `tls-unique` channel binding from [RFC 5929](https://tools.ietf.org/html/rfc5929). + * @since v9.9.0 + * @return The latest `Finished` message that has been sent to the socket as part of a SSL/TLS handshake, or `undefined` if no `Finished` message has been sent yet. + */ + getFinished(): Buffer | undefined; + /** + * Returns an object representing the peer's certificate. If the peer does not + * provide a certificate, an empty object will be returned. If the socket has been + * destroyed, `null` will be returned. + * + * If the full certificate chain was requested, each certificate will include an`issuerCertificate` property containing an object representing its issuer's + * certificate. + * @since v0.11.4 + * @param detailed Include the full certificate chain if `true`, otherwise include just the peer's certificate. + * @return A certificate object. + */ + getPeerCertificate(detailed: true): DetailedPeerCertificate; + getPeerCertificate(detailed?: false): PeerCertificate; + getPeerCertificate(detailed?: boolean): PeerCertificate | DetailedPeerCertificate; + /** + * As the `Finished` messages are message digests of the complete handshake + * (with a total of 192 bits for TLS 1.0 and more for SSL 3.0), they can + * be used for external authentication procedures when the authentication + * provided by SSL/TLS is not desired or is not enough. + * + * Corresponds to the `SSL_get_peer_finished` routine in OpenSSL and may be used + * to implement the `tls-unique` channel binding from [RFC 5929](https://tools.ietf.org/html/rfc5929). + * @since v9.9.0 + * @return The latest `Finished` message that is expected or has actually been received from the socket as part of a SSL/TLS handshake, or `undefined` if there is no `Finished` message so + * far. + */ + getPeerFinished(): Buffer | undefined; + /** + * Returns a string containing the negotiated SSL/TLS protocol version of the + * current connection. The value `'unknown'` will be returned for connected + * sockets that have not completed the handshaking process. The value `null` will + * be returned for server sockets or disconnected client sockets. + * + * Protocol versions are: + * + * * `'SSLv3'` + * * `'TLSv1'` + * * `'TLSv1.1'` + * * `'TLSv1.2'` + * * `'TLSv1.3'` + * + * See the OpenSSL [`SSL_get_version`](https://www.openssl.org/docs/man1.1.1/man3/SSL_get_version.html) documentation for more information. + * @since v5.7.0 + */ + getProtocol(): string | null; + /** + * Returns the TLS session data or `undefined` if no session was + * negotiated. On the client, the data can be provided to the `session` option of {@link connect} to resume the connection. On the server, it may be useful + * for debugging. + * + * See `Session Resumption` for more information. + * + * Note: `getSession()` works only for TLSv1.2 and below. For TLSv1.3, applications + * must use the `'session'` event (it also works for TLSv1.2 and below). + * @since v0.11.4 + */ + getSession(): Buffer | undefined; + /** + * See [SSL\_get\_shared\_sigalgs](https://www.openssl.org/docs/man1.1.1/man3/SSL_get_shared_sigalgs.html) for more information. + * @since v12.11.0 + * @return List of signature algorithms shared between the server and the client in the order of decreasing preference. + */ + getSharedSigalgs(): string[]; + /** + * For a client, returns the TLS session ticket if one is available, or`undefined`. For a server, always returns `undefined`. + * + * It may be useful for debugging. + * + * See `Session Resumption` for more information. + * @since v0.11.4 + */ + getTLSTicket(): Buffer | undefined; + /** + * See `Session Resumption` for more information. + * @since v0.5.6 + * @return `true` if the session was reused, `false` otherwise. + */ + isSessionReused(): boolean; + /** + * The `tlsSocket.renegotiate()` method initiates a TLS renegotiation process. + * Upon completion, the `callback` function will be passed a single argument + * that is either an `Error` (if the request failed) or `null`. + * + * This method can be used to request a peer's certificate after the secure + * connection has been established. + * + * When running as the server, the socket will be destroyed with an error after `handshakeTimeout` timeout. + * + * For TLSv1.3, renegotiation cannot be initiated, it is not supported by the + * protocol. + * @since v0.11.8 + * @param callback If `renegotiate()` returned `true`, callback is attached once to the `'secure'` event. If `renegotiate()` returned `false`, `callback` will be called in the next tick with + * an error, unless the `tlsSocket` has been destroyed, in which case `callback` will not be called at all. + * @return `true` if renegotiation was initiated, `false` otherwise. + */ + renegotiate( + options: { + rejectUnauthorized?: boolean | undefined; + requestCert?: boolean | undefined; + }, + callback: (err: Error | null) => void, + ): undefined | boolean; + /** + * The `tlsSocket.setMaxSendFragment()` method sets the maximum TLS fragment size. + * Returns `true` if setting the limit succeeded; `false` otherwise. + * + * Smaller fragment sizes decrease the buffering latency on the client: larger + * fragments are buffered by the TLS layer until the entire fragment is received + * and its integrity is verified; large fragments can span multiple roundtrips + * and their processing can be delayed due to packet loss or reordering. However, + * smaller fragments add extra TLS framing bytes and CPU overhead, which may + * decrease overall server throughput. + * @since v0.11.11 + * @param [size=16384] The maximum TLS fragment size. The maximum value is `16384`. + */ + setMaxSendFragment(size: number): boolean; + /** + * Disables TLS renegotiation for this `TLSSocket` instance. Once called, attempts + * to renegotiate will trigger an `'error'` event on the `TLSSocket`. + * @since v8.4.0 + */ + disableRenegotiation(): void; + /** + * When enabled, TLS packet trace information is written to `stderr`. This can be + * used to debug TLS connection problems. + * + * The format of the output is identical to the output of`openssl s_client -trace` or `openssl s_server -trace`. While it is produced by + * OpenSSL's `SSL_trace()` function, the format is undocumented, can change + * without notice, and should not be relied on. + * @since v12.2.0 + */ + enableTrace(): void; + /** + * Returns the peer certificate as an `X509Certificate` object. + * + * If there is no peer certificate, or the socket has been destroyed,`undefined` will be returned. + * @since v15.9.0 + */ + getPeerX509Certificate(): X509Certificate | undefined; + /** + * Returns the local certificate as an `X509Certificate` object. + * + * If there is no local certificate, or the socket has been destroyed,`undefined` will be returned. + * @since v15.9.0 + */ + getX509Certificate(): X509Certificate | undefined; + /** + * Keying material is used for validations to prevent different kind of attacks in + * network protocols, for example in the specifications of IEEE 802.1X. + * + * Example + * + * ```js + * const keyingMaterial = tlsSocket.exportKeyingMaterial( + * 128, + * 'client finished'); + * + * /* + * Example return value of keyingMaterial: + * + * + * ``` + * + * See the OpenSSL [`SSL_export_keying_material`](https://www.openssl.org/docs/man1.1.1/man3/SSL_export_keying_material.html) documentation for more + * information. + * @since v13.10.0, v12.17.0 + * @param length number of bytes to retrieve from keying material + * @param label an application specific label, typically this will be a value from the [IANA Exporter Label + * Registry](https://www.iana.org/assignments/tls-parameters/tls-parameters.xhtml#exporter-labels). + * @param context Optionally provide a context. + * @return requested bytes of the keying material + */ + exportKeyingMaterial(length: number, label: string, context: Buffer): Buffer; + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "OCSPResponse", listener: (response: Buffer) => void): this; + addListener(event: "secureConnect", listener: () => void): this; + addListener(event: "session", listener: (session: Buffer) => void): this; + addListener(event: "keylog", listener: (line: Buffer) => void): this; + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: "OCSPResponse", response: Buffer): boolean; + emit(event: "secureConnect"): boolean; + emit(event: "session", session: Buffer): boolean; + emit(event: "keylog", line: Buffer): boolean; + on(event: string, listener: (...args: any[]) => void): this; + on(event: "OCSPResponse", listener: (response: Buffer) => void): this; + on(event: "secureConnect", listener: () => void): this; + on(event: "session", listener: (session: Buffer) => void): this; + on(event: "keylog", listener: (line: Buffer) => void): this; + once(event: string, listener: (...args: any[]) => void): this; + once(event: "OCSPResponse", listener: (response: Buffer) => void): this; + once(event: "secureConnect", listener: () => void): this; + once(event: "session", listener: (session: Buffer) => void): this; + once(event: "keylog", listener: (line: Buffer) => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "OCSPResponse", listener: (response: Buffer) => void): this; + prependListener(event: "secureConnect", listener: () => void): this; + prependListener(event: "session", listener: (session: Buffer) => void): this; + prependListener(event: "keylog", listener: (line: Buffer) => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "OCSPResponse", listener: (response: Buffer) => void): this; + prependOnceListener(event: "secureConnect", listener: () => void): this; + prependOnceListener(event: "session", listener: (session: Buffer) => void): this; + prependOnceListener(event: "keylog", listener: (line: Buffer) => void): this; + } + interface CommonConnectionOptions { + /** + * An optional TLS context object from tls.createSecureContext() + */ + secureContext?: SecureContext | undefined; + /** + * When enabled, TLS packet trace information is written to `stderr`. This can be + * used to debug TLS connection problems. + * @default false + */ + enableTrace?: boolean | undefined; + /** + * If true the server will request a certificate from clients that + * connect and attempt to verify that certificate. Defaults to + * false. + */ + requestCert?: boolean | undefined; + /** + * An array of strings or a Buffer naming possible ALPN protocols. + * (Protocols should be ordered by their priority.) + */ + ALPNProtocols?: string[] | Uint8Array[] | Uint8Array | undefined; + /** + * SNICallback(servername, cb) A function that will be + * called if the client supports SNI TLS extension. Two arguments + * will be passed when called: servername and cb. SNICallback should + * invoke cb(null, ctx), where ctx is a SecureContext instance. + * (tls.createSecureContext(...) can be used to get a proper + * SecureContext.) If SNICallback wasn't provided the default callback + * with high-level API will be used (see below). + */ + SNICallback?: ((servername: string, cb: (err: Error | null, ctx?: SecureContext) => void) => void) | undefined; + /** + * If true the server will reject any connection which is not + * authorized with the list of supplied CAs. This option only has an + * effect if requestCert is true. + * @default true + */ + rejectUnauthorized?: boolean | undefined; + } + interface TlsOptions extends SecureContextOptions, CommonConnectionOptions, net.ServerOpts { + /** + * Abort the connection if the SSL/TLS handshake does not finish in the + * specified number of milliseconds. A 'tlsClientError' is emitted on + * the tls.Server object whenever a handshake times out. Default: + * 120000 (120 seconds). + */ + handshakeTimeout?: number | undefined; + /** + * The number of seconds after which a TLS session created by the + * server will no longer be resumable. See Session Resumption for more + * information. Default: 300. + */ + sessionTimeout?: number | undefined; + /** + * 48-bytes of cryptographically strong pseudo-random data. + */ + ticketKeys?: Buffer | undefined; + /** + * @param socket + * @param identity identity parameter sent from the client. + * @return pre-shared key that must either be + * a buffer or `null` to stop the negotiation process. Returned PSK must be + * compatible with the selected cipher's digest. + * + * When negotiating TLS-PSK (pre-shared keys), this function is called + * with the identity provided by the client. + * If the return value is `null` the negotiation process will stop and an + * "unknown_psk_identity" alert message will be sent to the other party. + * If the server wishes to hide the fact that the PSK identity was not known, + * the callback must provide some random data as `psk` to make the connection + * fail with "decrypt_error" before negotiation is finished. + * PSK ciphers are disabled by default, and using TLS-PSK thus + * requires explicitly specifying a cipher suite with the `ciphers` option. + * More information can be found in the RFC 4279. + */ + pskCallback?(socket: TLSSocket, identity: string): DataView | NodeJS.TypedArray | null; + /** + * hint to send to a client to help + * with selecting the identity during TLS-PSK negotiation. Will be ignored + * in TLS 1.3. Upon failing to set pskIdentityHint `tlsClientError` will be + * emitted with `ERR_TLS_PSK_SET_IDENTIY_HINT_FAILED` code. + */ + pskIdentityHint?: string | undefined; + } + interface PSKCallbackNegotation { + psk: DataView | NodeJS.TypedArray; + identity: string; + } + interface ConnectionOptions extends SecureContextOptions, CommonConnectionOptions { + host?: string | undefined; + port?: number | undefined; + path?: string | undefined; // Creates unix socket connection to path. If this option is specified, `host` and `port` are ignored. + socket?: stream.Duplex | undefined; // Establish secure connection on a given socket rather than creating a new socket + checkServerIdentity?: typeof checkServerIdentity | undefined; + servername?: string | undefined; // SNI TLS Extension + session?: Buffer | undefined; + minDHSize?: number | undefined; + lookup?: net.LookupFunction | undefined; + timeout?: number | undefined; + /** + * When negotiating TLS-PSK (pre-shared keys), this function is called + * with optional identity `hint` provided by the server or `null` + * in case of TLS 1.3 where `hint` was removed. + * It will be necessary to provide a custom `tls.checkServerIdentity()` + * for the connection as the default one will try to check hostname/IP + * of the server against the certificate but that's not applicable for PSK + * because there won't be a certificate present. + * More information can be found in the RFC 4279. + * + * @param hint message sent from the server to help client + * decide which identity to use during negotiation. + * Always `null` if TLS 1.3 is used. + * @returns Return `null` to stop the negotiation process. `psk` must be + * compatible with the selected cipher's digest. + * `identity` must use UTF-8 encoding. + */ + pskCallback?(hint: string | null): PSKCallbackNegotation | null; + } + /** + * Accepts encrypted connections using TLS or SSL. + * @since v0.3.2 + */ + class Server extends net.Server { + constructor(secureConnectionListener?: (socket: TLSSocket) => void); + constructor(options: TlsOptions, secureConnectionListener?: (socket: TLSSocket) => void); + /** + * The `server.addContext()` method adds a secure context that will be used if + * the client request's SNI name matches the supplied `hostname` (or wildcard). + * + * When there are multiple matching contexts, the most recently added one is + * used. + * @since v0.5.3 + * @param hostname A SNI host name or wildcard (e.g. `'*'`) + * @param context An object containing any of the possible properties from the {@link createSecureContext} `options` arguments (e.g. `key`, `cert`, `ca`, etc), or a TLS context object created + * with {@link createSecureContext} itself. + */ + addContext(hostname: string, context: SecureContextOptions): void; + /** + * Returns the session ticket keys. + * + * See `Session Resumption` for more information. + * @since v3.0.0 + * @return A 48-byte buffer containing the session ticket keys. + */ + getTicketKeys(): Buffer; + /** + * The `server.setSecureContext()` method replaces the secure context of an + * existing server. Existing connections to the server are not interrupted. + * @since v11.0.0 + * @param options An object containing any of the possible properties from the {@link createSecureContext} `options` arguments (e.g. `key`, `cert`, `ca`, etc). + */ + setSecureContext(options: SecureContextOptions): void; + /** + * Sets the session ticket keys. + * + * Changes to the ticket keys are effective only for future server connections. + * Existing or currently pending server connections will use the previous keys. + * + * See `Session Resumption` for more information. + * @since v3.0.0 + * @param keys A 48-byte buffer containing the session ticket keys. + */ + setTicketKeys(keys: Buffer): void; + /** + * events.EventEmitter + * 1. tlsClientError + * 2. newSession + * 3. OCSPRequest + * 4. resumeSession + * 5. secureConnection + * 6. keylog + */ + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "tlsClientError", listener: (err: Error, tlsSocket: TLSSocket) => void): this; + addListener( + event: "newSession", + listener: (sessionId: Buffer, sessionData: Buffer, callback: () => void) => void, + ): this; + addListener( + event: "OCSPRequest", + listener: ( + certificate: Buffer, + issuer: Buffer, + callback: (err: Error | null, resp: Buffer) => void, + ) => void, + ): this; + addListener( + event: "resumeSession", + listener: (sessionId: Buffer, callback: (err: Error | null, sessionData: Buffer | null) => void) => void, + ): this; + addListener(event: "secureConnection", listener: (tlsSocket: TLSSocket) => void): this; + addListener(event: "keylog", listener: (line: Buffer, tlsSocket: TLSSocket) => void): this; + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: "tlsClientError", err: Error, tlsSocket: TLSSocket): boolean; + emit(event: "newSession", sessionId: Buffer, sessionData: Buffer, callback: () => void): boolean; + emit( + event: "OCSPRequest", + certificate: Buffer, + issuer: Buffer, + callback: (err: Error | null, resp: Buffer) => void, + ): boolean; + emit( + event: "resumeSession", + sessionId: Buffer, + callback: (err: Error | null, sessionData: Buffer | null) => void, + ): boolean; + emit(event: "secureConnection", tlsSocket: TLSSocket): boolean; + emit(event: "keylog", line: Buffer, tlsSocket: TLSSocket): boolean; + on(event: string, listener: (...args: any[]) => void): this; + on(event: "tlsClientError", listener: (err: Error, tlsSocket: TLSSocket) => void): this; + on(event: "newSession", listener: (sessionId: Buffer, sessionData: Buffer, callback: () => void) => void): this; + on( + event: "OCSPRequest", + listener: ( + certificate: Buffer, + issuer: Buffer, + callback: (err: Error | null, resp: Buffer) => void, + ) => void, + ): this; + on( + event: "resumeSession", + listener: (sessionId: Buffer, callback: (err: Error | null, sessionData: Buffer | null) => void) => void, + ): this; + on(event: "secureConnection", listener: (tlsSocket: TLSSocket) => void): this; + on(event: "keylog", listener: (line: Buffer, tlsSocket: TLSSocket) => void): this; + once(event: string, listener: (...args: any[]) => void): this; + once(event: "tlsClientError", listener: (err: Error, tlsSocket: TLSSocket) => void): this; + once( + event: "newSession", + listener: (sessionId: Buffer, sessionData: Buffer, callback: () => void) => void, + ): this; + once( + event: "OCSPRequest", + listener: ( + certificate: Buffer, + issuer: Buffer, + callback: (err: Error | null, resp: Buffer) => void, + ) => void, + ): this; + once( + event: "resumeSession", + listener: (sessionId: Buffer, callback: (err: Error | null, sessionData: Buffer | null) => void) => void, + ): this; + once(event: "secureConnection", listener: (tlsSocket: TLSSocket) => void): this; + once(event: "keylog", listener: (line: Buffer, tlsSocket: TLSSocket) => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "tlsClientError", listener: (err: Error, tlsSocket: TLSSocket) => void): this; + prependListener( + event: "newSession", + listener: (sessionId: Buffer, sessionData: Buffer, callback: () => void) => void, + ): this; + prependListener( + event: "OCSPRequest", + listener: ( + certificate: Buffer, + issuer: Buffer, + callback: (err: Error | null, resp: Buffer) => void, + ) => void, + ): this; + prependListener( + event: "resumeSession", + listener: (sessionId: Buffer, callback: (err: Error | null, sessionData: Buffer | null) => void) => void, + ): this; + prependListener(event: "secureConnection", listener: (tlsSocket: TLSSocket) => void): this; + prependListener(event: "keylog", listener: (line: Buffer, tlsSocket: TLSSocket) => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "tlsClientError", listener: (err: Error, tlsSocket: TLSSocket) => void): this; + prependOnceListener( + event: "newSession", + listener: (sessionId: Buffer, sessionData: Buffer, callback: () => void) => void, + ): this; + prependOnceListener( + event: "OCSPRequest", + listener: ( + certificate: Buffer, + issuer: Buffer, + callback: (err: Error | null, resp: Buffer) => void, + ) => void, + ): this; + prependOnceListener( + event: "resumeSession", + listener: (sessionId: Buffer, callback: (err: Error | null, sessionData: Buffer | null) => void) => void, + ): this; + prependOnceListener(event: "secureConnection", listener: (tlsSocket: TLSSocket) => void): this; + prependOnceListener(event: "keylog", listener: (line: Buffer, tlsSocket: TLSSocket) => void): this; + } + /** + * @deprecated since v0.11.3 Use `tls.TLSSocket` instead. + */ + interface SecurePair { + encrypted: TLSSocket; + cleartext: TLSSocket; + } + type SecureVersion = "TLSv1.3" | "TLSv1.2" | "TLSv1.1" | "TLSv1"; + interface SecureContextOptions { + /** + * If set, this will be called when a client opens a connection using the ALPN extension. + * One argument will be passed to the callback: an object containing `servername` and `protocols` fields, + * respectively containing the server name from the SNI extension (if any) and an array of + * ALPN protocol name strings. The callback must return either one of the strings listed in `protocols`, + * which will be returned to the client as the selected ALPN protocol, or `undefined`, + * to reject the connection with a fatal alert. If a string is returned that does not match one of + * the client's ALPN protocols, an error will be thrown. + * This option cannot be used with the `ALPNProtocols` option, and setting both options will throw an error. + */ + ALPNCallback?: ((arg: { servername: string; protocols: string[] }) => string | undefined) | undefined; + /** + * Optionally override the trusted CA certificates. Default is to trust + * the well-known CAs curated by Mozilla. Mozilla's CAs are completely + * replaced when CAs are explicitly specified using this option. + */ + ca?: string | Buffer | Array | undefined; + /** + * Cert chains in PEM format. One cert chain should be provided per + * private key. Each cert chain should consist of the PEM formatted + * certificate for a provided private key, followed by the PEM + * formatted intermediate certificates (if any), in order, and not + * including the root CA (the root CA must be pre-known to the peer, + * see ca). When providing multiple cert chains, they do not have to + * be in the same order as their private keys in key. If the + * intermediate certificates are not provided, the peer will not be + * able to validate the certificate, and the handshake will fail. + */ + cert?: string | Buffer | Array | undefined; + /** + * Colon-separated list of supported signature algorithms. The list + * can contain digest algorithms (SHA256, MD5 etc.), public key + * algorithms (RSA-PSS, ECDSA etc.), combination of both (e.g + * 'RSA+SHA384') or TLS v1.3 scheme names (e.g. rsa_pss_pss_sha512). + */ + sigalgs?: string | undefined; + /** + * Cipher suite specification, replacing the default. For more + * information, see modifying the default cipher suite. Permitted + * ciphers can be obtained via tls.getCiphers(). Cipher names must be + * uppercased in order for OpenSSL to accept them. + */ + ciphers?: string | undefined; + /** + * Name of an OpenSSL engine which can provide the client certificate. + */ + clientCertEngine?: string | undefined; + /** + * PEM formatted CRLs (Certificate Revocation Lists). + */ + crl?: string | Buffer | Array | undefined; + /** + * `'auto'` or custom Diffie-Hellman parameters, required for non-ECDHE perfect forward secrecy. + * If omitted or invalid, the parameters are silently discarded and DHE ciphers will not be available. + * ECDHE-based perfect forward secrecy will still be available. + */ + dhparam?: string | Buffer | undefined; + /** + * A string describing a named curve or a colon separated list of curve + * NIDs or names, for example P-521:P-384:P-256, to use for ECDH key + * agreement. Set to auto to select the curve automatically. Use + * crypto.getCurves() to obtain a list of available curve names. On + * recent releases, openssl ecparam -list_curves will also display the + * name and description of each available elliptic curve. Default: + * tls.DEFAULT_ECDH_CURVE. + */ + ecdhCurve?: string | undefined; + /** + * Attempt to use the server's cipher suite preferences instead of the + * client's. When true, causes SSL_OP_CIPHER_SERVER_PREFERENCE to be + * set in secureOptions + */ + honorCipherOrder?: boolean | undefined; + /** + * Private keys in PEM format. PEM allows the option of private keys + * being encrypted. Encrypted keys will be decrypted with + * options.passphrase. Multiple keys using different algorithms can be + * provided either as an array of unencrypted key strings or buffers, + * or an array of objects in the form {pem: [, + * passphrase: ]}. The object form can only occur in an array. + * object.passphrase is optional. Encrypted keys will be decrypted with + * object.passphrase if provided, or options.passphrase if it is not. + */ + key?: string | Buffer | Array | undefined; + /** + * Name of an OpenSSL engine to get private key from. Should be used + * together with privateKeyIdentifier. + */ + privateKeyEngine?: string | undefined; + /** + * Identifier of a private key managed by an OpenSSL engine. Should be + * used together with privateKeyEngine. Should not be set together with + * key, because both options define a private key in different ways. + */ + privateKeyIdentifier?: string | undefined; + /** + * Optionally set the maximum TLS version to allow. One + * of `'TLSv1.3'`, `'TLSv1.2'`, `'TLSv1.1'`, or `'TLSv1'`. Cannot be specified along with the + * `secureProtocol` option, use one or the other. + * **Default:** `'TLSv1.3'`, unless changed using CLI options. Using + * `--tls-max-v1.2` sets the default to `'TLSv1.2'`. Using `--tls-max-v1.3` sets the default to + * `'TLSv1.3'`. If multiple of the options are provided, the highest maximum is used. + */ + maxVersion?: SecureVersion | undefined; + /** + * Optionally set the minimum TLS version to allow. One + * of `'TLSv1.3'`, `'TLSv1.2'`, `'TLSv1.1'`, or `'TLSv1'`. Cannot be specified along with the + * `secureProtocol` option, use one or the other. It is not recommended to use + * less than TLSv1.2, but it may be required for interoperability. + * **Default:** `'TLSv1.2'`, unless changed using CLI options. Using + * `--tls-v1.0` sets the default to `'TLSv1'`. Using `--tls-v1.1` sets the default to + * `'TLSv1.1'`. Using `--tls-min-v1.3` sets the default to + * 'TLSv1.3'. If multiple of the options are provided, the lowest minimum is used. + */ + minVersion?: SecureVersion | undefined; + /** + * Shared passphrase used for a single private key and/or a PFX. + */ + passphrase?: string | undefined; + /** + * PFX or PKCS12 encoded private key and certificate chain. pfx is an + * alternative to providing key and cert individually. PFX is usually + * encrypted, if it is, passphrase will be used to decrypt it. Multiple + * PFX can be provided either as an array of unencrypted PFX buffers, + * or an array of objects in the form {buf: [, + * passphrase: ]}. The object form can only occur in an array. + * object.passphrase is optional. Encrypted PFX will be decrypted with + * object.passphrase if provided, or options.passphrase if it is not. + */ + pfx?: string | Buffer | Array | undefined; + /** + * Optionally affect the OpenSSL protocol behavior, which is not + * usually necessary. This should be used carefully if at all! Value is + * a numeric bitmask of the SSL_OP_* options from OpenSSL Options + */ + secureOptions?: number | undefined; // Value is a numeric bitmask of the `SSL_OP_*` options + /** + * Legacy mechanism to select the TLS protocol version to use, it does + * not support independent control of the minimum and maximum version, + * and does not support limiting the protocol to TLSv1.3. Use + * minVersion and maxVersion instead. The possible values are listed as + * SSL_METHODS, use the function names as strings. For example, use + * 'TLSv1_1_method' to force TLS version 1.1, or 'TLS_method' to allow + * any TLS protocol version up to TLSv1.3. It is not recommended to use + * TLS versions less than 1.2, but it may be required for + * interoperability. Default: none, see minVersion. + */ + secureProtocol?: string | undefined; + /** + * Opaque identifier used by servers to ensure session state is not + * shared between applications. Unused by clients. + */ + sessionIdContext?: string | undefined; + /** + * 48-bytes of cryptographically strong pseudo-random data. + * See Session Resumption for more information. + */ + ticketKeys?: Buffer | undefined; + /** + * The number of seconds after which a TLS session created by the + * server will no longer be resumable. See Session Resumption for more + * information. Default: 300. + */ + sessionTimeout?: number | undefined; + } + interface SecureContext { + context: any; + } + /** + * Verifies the certificate `cert` is issued to `hostname`. + * + * Returns [Error](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error) object, populating it with `reason`, `host`, and `cert` on + * failure. On success, returns [undefined](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Undefined_type). + * + * This function is intended to be used in combination with the`checkServerIdentity` option that can be passed to {@link connect} and as + * such operates on a `certificate object`. For other purposes, consider using `x509.checkHost()` instead. + * + * This function can be overwritten by providing an alternative function as the `options.checkServerIdentity` option that is passed to `tls.connect()`. The + * overwriting function can call `tls.checkServerIdentity()` of course, to augment + * the checks done with additional verification. + * + * This function is only called if the certificate passed all other checks, such as + * being issued by trusted CA (`options.ca`). + * + * Earlier versions of Node.js incorrectly accepted certificates for a given`hostname` if a matching `uniformResourceIdentifier` subject alternative name + * was present (see [CVE-2021-44531](https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2021-44531)). Applications that wish to accept`uniformResourceIdentifier` subject alternative names can use + * a custom `options.checkServerIdentity` function that implements the desired behavior. + * @since v0.8.4 + * @param hostname The host name or IP address to verify the certificate against. + * @param cert A `certificate object` representing the peer's certificate. + */ + function checkServerIdentity(hostname: string, cert: PeerCertificate): Error | undefined; + /** + * Creates a new {@link Server}. The `secureConnectionListener`, if provided, is + * automatically set as a listener for the `'secureConnection'` event. + * + * The `ticketKeys` options is automatically shared between `node:cluster` module + * workers. + * + * The following illustrates a simple echo server: + * + * ```js + * const tls = require('node:tls'); + * const fs = require('node:fs'); + * + * const options = { + * key: fs.readFileSync('server-key.pem'), + * cert: fs.readFileSync('server-cert.pem'), + * + * // This is necessary only if using client certificate authentication. + * requestCert: true, + * + * // This is necessary only if the client uses a self-signed certificate. + * ca: [ fs.readFileSync('client-cert.pem') ], + * }; + * + * const server = tls.createServer(options, (socket) => { + * console.log('server connected', + * socket.authorized ? 'authorized' : 'unauthorized'); + * socket.write('welcome!\n'); + * socket.setEncoding('utf8'); + * socket.pipe(socket); + * }); + * server.listen(8000, () => { + * console.log('server bound'); + * }); + * ``` + * + * The server can be tested by connecting to it using the example client from {@link connect}. + * @since v0.3.2 + */ + function createServer(secureConnectionListener?: (socket: TLSSocket) => void): Server; + function createServer(options: TlsOptions, secureConnectionListener?: (socket: TLSSocket) => void): Server; + /** + * The `callback` function, if specified, will be added as a listener for the `'secureConnect'` event. + * + * `tls.connect()` returns a {@link TLSSocket} object. + * + * Unlike the `https` API, `tls.connect()` does not enable the + * SNI (Server Name Indication) extension by default, which may cause some + * servers to return an incorrect certificate or reject the connection + * altogether. To enable SNI, set the `servername` option in addition + * to `host`. + * + * The following illustrates a client for the echo server example from {@link createServer}: + * + * ```js + * // Assumes an echo server that is listening on port 8000. + * const tls = require('node:tls'); + * const fs = require('node:fs'); + * + * const options = { + * // Necessary only if the server requires client certificate authentication. + * key: fs.readFileSync('client-key.pem'), + * cert: fs.readFileSync('client-cert.pem'), + * + * // Necessary only if the server uses a self-signed certificate. + * ca: [ fs.readFileSync('server-cert.pem') ], + * + * // Necessary only if the server's cert isn't for "localhost". + * checkServerIdentity: () => { return null; }, + * }; + * + * const socket = tls.connect(8000, options, () => { + * console.log('client connected', + * socket.authorized ? 'authorized' : 'unauthorized'); + * process.stdin.pipe(socket); + * process.stdin.resume(); + * }); + * socket.setEncoding('utf8'); + * socket.on('data', (data) => { + * console.log(data); + * }); + * socket.on('end', () => { + * console.log('server ends connection'); + * }); + * ``` + * @since v0.11.3 + */ + function connect(options: ConnectionOptions, secureConnectListener?: () => void): TLSSocket; + function connect( + port: number, + host?: string, + options?: ConnectionOptions, + secureConnectListener?: () => void, + ): TLSSocket; + function connect(port: number, options?: ConnectionOptions, secureConnectListener?: () => void): TLSSocket; + /** + * Creates a new secure pair object with two streams, one of which reads and writes + * the encrypted data and the other of which reads and writes the cleartext data. + * Generally, the encrypted stream is piped to/from an incoming encrypted data + * stream and the cleartext one is used as a replacement for the initial encrypted + * stream. + * + * `tls.createSecurePair()` returns a `tls.SecurePair` object with `cleartext` and `encrypted` stream properties. + * + * Using `cleartext` has the same API as {@link TLSSocket}. + * + * The `tls.createSecurePair()` method is now deprecated in favor of`tls.TLSSocket()`. For example, the code: + * + * ```js + * pair = tls.createSecurePair(// ... ); + * pair.encrypted.pipe(socket); + * socket.pipe(pair.encrypted); + * ``` + * + * can be replaced by: + * + * ```js + * secureSocket = tls.TLSSocket(socket, options); + * ``` + * + * where `secureSocket` has the same API as `pair.cleartext`. + * @since v0.3.2 + * @deprecated Since v0.11.3 - Use {@link TLSSocket} instead. + * @param context A secure context object as returned by `tls.createSecureContext()` + * @param isServer `true` to specify that this TLS connection should be opened as a server. + * @param requestCert `true` to specify whether a server should request a certificate from a connecting client. Only applies when `isServer` is `true`. + * @param rejectUnauthorized If not `false` a server automatically reject clients with invalid certificates. Only applies when `isServer` is `true`. + */ + function createSecurePair( + context?: SecureContext, + isServer?: boolean, + requestCert?: boolean, + rejectUnauthorized?: boolean, + ): SecurePair; + /** + * `{@link createServer}` sets the default value of the `honorCipherOrder` option + * to `true`, other APIs that create secure contexts leave it unset. + * + * `{@link createServer}` uses a 128 bit truncated SHA1 hash value generated + * from `process.argv` as the default value of the `sessionIdContext` option, other + * APIs that create secure contexts have no default value. + * + * The `tls.createSecureContext()` method creates a `SecureContext` object. It is + * usable as an argument to several `tls` APIs, such as `server.addContext()`, + * but has no public methods. The {@link Server} constructor and the {@link createServer} method do not support the `secureContext` option. + * + * A key is _required_ for ciphers that use certificates. Either `key` or `pfx` can be used to provide it. + * + * If the `ca` option is not given, then Node.js will default to using [Mozilla's publicly trusted list of + * CAs](https://hg.mozilla.org/mozilla-central/raw-file/tip/security/nss/lib/ckfw/builtins/certdata.txt). + * + * Custom DHE parameters are discouraged in favor of the new `dhparam: 'auto' `option. When set to `'auto'`, well-known DHE parameters of sufficient strength + * will be selected automatically. Otherwise, if necessary, `openssl dhparam` can + * be used to create custom parameters. The key length must be greater than or + * equal to 1024 bits or else an error will be thrown. Although 1024 bits is + * permissible, use 2048 bits or larger for stronger security. + * @since v0.11.13 + */ + function createSecureContext(options?: SecureContextOptions): SecureContext; + /** + * Returns an array with the names of the supported TLS ciphers. The names are + * lower-case for historical reasons, but must be uppercased to be used in + * the `ciphers` option of `{@link createSecureContext}`. + * + * Not all supported ciphers are enabled by default. See + * [Modifying the default TLS cipher suite](https://nodejs.org/docs/latest-v20.x/api/tls.html#modifying-the-default-tls-cipher-suite). + * + * Cipher names that start with `'tls_'` are for TLSv1.3, all the others are for + * TLSv1.2 and below. + * + * ```js + * console.log(tls.getCiphers()); // ['aes128-gcm-sha256', 'aes128-sha', ...] + * ``` + * @since v0.10.2 + */ + function getCiphers(): string[]; + /** + * The default curve name to use for ECDH key agreement in a tls server. + * The default value is `'auto'`. See `{@link createSecureContext()}` for further + * information. + * @since v0.11.13 + */ + let DEFAULT_ECDH_CURVE: string; + /** + * The default value of the `maxVersion` option of `{@link createSecureContext()}`. + * It can be assigned any of the supported TLS protocol versions, + * `'TLSv1.3'`, `'TLSv1.2'`, `'TLSv1.1'`, or `'TLSv1'`. **Default:** `'TLSv1.3'`, unless + * changed using CLI options. Using `--tls-max-v1.2` sets the default to `'TLSv1.2'`. Using + * `--tls-max-v1.3` sets the default to `'TLSv1.3'`. If multiple of the options + * are provided, the highest maximum is used. + * @since v11.4.0 + */ + let DEFAULT_MAX_VERSION: SecureVersion; + /** + * The default value of the `minVersion` option of `{@link createSecureContext()}`. + * It can be assigned any of the supported TLS protocol versions, + * `'TLSv1.3'`, `'TLSv1.2'`, `'TLSv1.1'`, or `'TLSv1'`. **Default:** `'TLSv1.2'`, unless + * changed using CLI options. Using `--tls-min-v1.0` sets the default to + * `'TLSv1'`. Using `--tls-min-v1.1` sets the default to `'TLSv1.1'`. Using + * `--tls-min-v1.3` sets the default to `'TLSv1.3'`. If multiple of the options + * are provided, the lowest minimum is used. + * @since v11.4.0 + */ + let DEFAULT_MIN_VERSION: SecureVersion; + /** + * The default value of the `ciphers` option of `{@link createSecureContext()}`. + * It can be assigned any of the supported OpenSSL ciphers. + * Defaults to the content of `crypto.constants.defaultCoreCipherList`, unless + * changed using CLI options using `--tls-default-ciphers`. + * @since v19.8.0 + */ + let DEFAULT_CIPHERS: string; + /** + * An immutable array of strings representing the root certificates (in PEM format) + * from the bundled Mozilla CA store as supplied by the current Node.js version. + * + * The bundled CA store, as supplied by Node.js, is a snapshot of Mozilla CA store + * that is fixed at release time. It is identical on all supported platforms. + * @since v12.3.0 + */ + const rootCertificates: readonly string[]; +} +declare module "node:tls" { + export * from "tls"; +} diff --git a/node_modules/@types/node/trace_events.d.ts b/node_modules/@types/node/trace_events.d.ts new file mode 100644 index 0000000..b9d498e --- /dev/null +++ b/node_modules/@types/node/trace_events.d.ts @@ -0,0 +1,197 @@ +/** + * The `node:trace_events` module provides a mechanism to centralize tracing information + * generated by V8, Node.js core, and userspace code. + * + * Tracing can be enabled with the `--trace-event-categories` command-line flag + * or by using the `trace_events` module. The `--trace-event-categories` flag + * accepts a list of comma-separated category names. + * + * The available categories are: + * + * * `node`: An empty placeholder. + * * `node.async_hooks`: Enables capture of detailed [`async_hooks`](https://nodejs.org/docs/latest-v20.x/api/async_hooks.html) trace data. + * The [`async_hooks`](https://nodejs.org/docs/latest-v20.x/api/async_hooks.html) events have a unique `asyncId` and a special `triggerId` `triggerAsyncId` property. + * * `node.bootstrap`: Enables capture of Node.js bootstrap milestones. + * * `node.console`: Enables capture of `console.time()` and `console.count()` output. + * * `node.threadpoolwork.sync`: Enables capture of trace data for threadpool synchronous operations, such as `blob`, `zlib`, `crypto` and `node_api`. + * * `node.threadpoolwork.async`: Enables capture of trace data for threadpool asynchronous operations, such as `blob`, `zlib`, `crypto` and `node_api`. + * * `node.dns.native`: Enables capture of trace data for DNS queries. + * * `node.net.native`: Enables capture of trace data for network. + * * `node.environment`: Enables capture of Node.js Environment milestones. + * * `node.fs.sync`: Enables capture of trace data for file system sync methods. + * * `node.fs_dir.sync`: Enables capture of trace data for file system sync directory methods. + * * `node.fs.async`: Enables capture of trace data for file system async methods. + * * `node.fs_dir.async`: Enables capture of trace data for file system async directory methods. + * * `node.perf`: Enables capture of [Performance API](https://nodejs.org/docs/latest-v20.x/api/perf_hooks.html) measurements. + * * `node.perf.usertiming`: Enables capture of only Performance API User Timing + * measures and marks. + * * `node.perf.timerify`: Enables capture of only Performance API timerify + * measurements. + * * `node.promises.rejections`: Enables capture of trace data tracking the number + * of unhandled Promise rejections and handled-after-rejections. + * * `node.vm.script`: Enables capture of trace data for the `node:vm` module's `runInNewContext()`, `runInContext()`, and `runInThisContext()` methods. + * * `v8`: The [V8](https://nodejs.org/docs/latest-v20.x/api/v8.html) events are GC, compiling, and execution related. + * * `node.http`: Enables capture of trace data for http request / response. + * + * By default the `node`, `node.async_hooks`, and `v8` categories are enabled. + * + * ```bash + * node --trace-event-categories v8,node,node.async_hooks server.js + * ``` + * + * Prior versions of Node.js required the use of the `--trace-events-enabled` flag to enable trace events. This requirement has been removed. However, the `--trace-events-enabled` flag _may_ still be + * used and will enable the `node`, `node.async_hooks`, and `v8` trace event categories by default. + * + * ```bash + * node --trace-events-enabled + * + * # is equivalent to + * + * node --trace-event-categories v8,node,node.async_hooks + * ``` + * + * Alternatively, trace events may be enabled using the `node:trace_events` module: + * + * ```js + * const trace_events = require('node:trace_events'); + * const tracing = trace_events.createTracing({ categories: ['node.perf'] }); + * tracing.enable(); // Enable trace event capture for the 'node.perf' category + * + * // do work + * + * tracing.disable(); // Disable trace event capture for the 'node.perf' category + * ``` + * + * Running Node.js with tracing enabled will produce log files that can be opened + * in the [`chrome://tracing`](https://www.chromium.org/developers/how-tos/trace-event-profiling-tool) tab of Chrome. + * + * The logging file is by default called `node_trace.${rotation}.log`, where `${rotation}` is an incrementing log-rotation id. The filepath pattern can + * be specified with `--trace-event-file-pattern` that accepts a template + * string that supports `${rotation}` and `${pid}`: + * + * ```bash + * node --trace-event-categories v8 --trace-event-file-pattern '${pid}-${rotation}.log' server.js + * ``` + * + * To guarantee that the log file is properly generated after signal events like `SIGINT`, `SIGTERM`, or `SIGBREAK`, make sure to have the appropriate handlers + * in your code, such as: + * + * ```js + * process.on('SIGINT', function onSigint() { + * console.info('Received SIGINT.'); + * process.exit(130); // Or applicable exit code depending on OS and signal + * }); + * ``` + * + * The tracing system uses the same time source + * as the one used by `process.hrtime()`. + * However the trace-event timestamps are expressed in microseconds, + * unlike `process.hrtime()` which returns nanoseconds. + * + * The features from this module are not available in [`Worker`](https://nodejs.org/docs/latest-v20.x/api/worker_threads.html#class-worker) threads. + * @experimental + * @see [source](https://github.com/nodejs/node/blob/v20.13.1/lib/trace_events.js) + */ +declare module "trace_events" { + /** + * The `Tracing` object is used to enable or disable tracing for sets of + * categories. Instances are created using the + * `trace_events.createTracing()` method. + * + * When created, the `Tracing` object is disabled. Calling the + * `tracing.enable()` method adds the categories to the set of enabled trace + * event categories. Calling `tracing.disable()` will remove the categories + * from the set of enabled trace event categories. + */ + interface Tracing { + /** + * A comma-separated list of the trace event categories covered by this + * `Tracing` object. + * @since v10.0.0 + */ + readonly categories: string; + /** + * Disables this `Tracing` object. + * + * Only trace event categories _not_ covered by other enabled `Tracing` + * objects and _not_ specified by the `--trace-event-categories` flag + * will be disabled. + * + * ```js + * const trace_events = require('node:trace_events'); + * const t1 = trace_events.createTracing({ categories: ['node', 'v8'] }); + * const t2 = trace_events.createTracing({ categories: ['node.perf', 'node'] }); + * t1.enable(); + * t2.enable(); + * + * // Prints 'node,node.perf,v8' + * console.log(trace_events.getEnabledCategories()); + * + * t2.disable(); // Will only disable emission of the 'node.perf' category + * + * // Prints 'node,v8' + * console.log(trace_events.getEnabledCategories()); + * ``` + * @since v10.0.0 + */ + disable(): void; + /** + * Enables this `Tracing` object for the set of categories covered by + * the `Tracing` object. + * @since v10.0.0 + */ + enable(): void; + /** + * `true` only if the `Tracing` object has been enabled. + * @since v10.0.0 + */ + readonly enabled: boolean; + } + interface CreateTracingOptions { + /** + * An array of trace category names. Values included in the array are + * coerced to a string when possible. An error will be thrown if the + * value cannot be coerced. + */ + categories: string[]; + } + /** + * Creates and returns a `Tracing` object for the given set of `categories`. + * + * ```js + * const trace_events = require('node:trace_events'); + * const categories = ['node.perf', 'node.async_hooks']; + * const tracing = trace_events.createTracing({ categories }); + * tracing.enable(); + * // do stuff + * tracing.disable(); + * ``` + * @since v10.0.0 + */ + function createTracing(options: CreateTracingOptions): Tracing; + /** + * Returns a comma-separated list of all currently-enabled trace event + * categories. The current set of enabled trace event categories is determined + * by the _union_ of all currently-enabled `Tracing` objects and any categories + * enabled using the `--trace-event-categories` flag. + * + * Given the file `test.js` below, the command `node --trace-event-categories node.perf test.js` will print `'node.async_hooks,node.perf'` to the console. + * + * ```js + * const trace_events = require('node:trace_events'); + * const t1 = trace_events.createTracing({ categories: ['node.async_hooks'] }); + * const t2 = trace_events.createTracing({ categories: ['node.perf'] }); + * const t3 = trace_events.createTracing({ categories: ['v8'] }); + * + * t1.enable(); + * t2.enable(); + * + * console.log(trace_events.getEnabledCategories()); + * ``` + * @since v10.0.0 + */ + function getEnabledCategories(): string | undefined; +} +declare module "node:trace_events" { + export * from "trace_events"; +} diff --git a/node_modules/@types/node/tty.d.ts b/node_modules/@types/node/tty.d.ts new file mode 100644 index 0000000..099aef0 --- /dev/null +++ b/node_modules/@types/node/tty.d.ts @@ -0,0 +1,208 @@ +/** + * The `node:tty` module provides the `tty.ReadStream` and `tty.WriteStream` classes. In most cases, it will not be necessary or possible to use this module + * directly. However, it can be accessed using: + * + * ```js + * const tty = require('node:tty'); + * ``` + * + * When Node.js detects that it is being run with a text terminal ("TTY") + * attached, `process.stdin` will, by default, be initialized as an instance of `tty.ReadStream` and both `process.stdout` and `process.stderr` will, by + * default, be instances of `tty.WriteStream`. The preferred method of determining + * whether Node.js is being run within a TTY context is to check that the value of + * the `process.stdout.isTTY` property is `true`: + * + * ```console + * $ node -p -e "Boolean(process.stdout.isTTY)" + * true + * $ node -p -e "Boolean(process.stdout.isTTY)" | cat + * false + * ``` + * + * In most cases, there should be little to no reason for an application to + * manually create instances of the `tty.ReadStream` and `tty.WriteStream` classes. + * @see [source](https://github.com/nodejs/node/blob/v20.13.1/lib/tty.js) + */ +declare module "tty" { + import * as net from "node:net"; + /** + * The `tty.isatty()` method returns `true` if the given `fd` is associated with + * a TTY and `false` if it is not, including whenever `fd` is not a non-negative + * integer. + * @since v0.5.8 + * @param fd A numeric file descriptor + */ + function isatty(fd: number): boolean; + /** + * Represents the readable side of a TTY. In normal circumstances `process.stdin` will be the only `tty.ReadStream` instance in a Node.js + * process and there should be no reason to create additional instances. + * @since v0.5.8 + */ + class ReadStream extends net.Socket { + constructor(fd: number, options?: net.SocketConstructorOpts); + /** + * A `boolean` that is `true` if the TTY is currently configured to operate as a + * raw device. + * + * This flag is always `false` when a process starts, even if the terminal is + * operating in raw mode. Its value will change with subsequent calls to `setRawMode`. + * @since v0.7.7 + */ + isRaw: boolean; + /** + * Allows configuration of `tty.ReadStream` so that it operates as a raw device. + * + * When in raw mode, input is always available character-by-character, not + * including modifiers. Additionally, all special processing of characters by the + * terminal is disabled, including echoing input + * characters. Ctrl+C will no longer cause a `SIGINT` when + * in this mode. + * @since v0.7.7 + * @param mode If `true`, configures the `tty.ReadStream` to operate as a raw device. If `false`, configures the `tty.ReadStream` to operate in its default mode. The `readStream.isRaw` + * property will be set to the resulting mode. + * @return The read stream instance. + */ + setRawMode(mode: boolean): this; + /** + * A `boolean` that is always `true` for `tty.ReadStream` instances. + * @since v0.5.8 + */ + isTTY: boolean; + } + /** + * -1 - to the left from cursor + * 0 - the entire line + * 1 - to the right from cursor + */ + type Direction = -1 | 0 | 1; + /** + * Represents the writable side of a TTY. In normal circumstances, `process.stdout` and `process.stderr` will be the only`tty.WriteStream` instances created for a Node.js process and there + * should be no reason to create additional instances. + * @since v0.5.8 + */ + class WriteStream extends net.Socket { + constructor(fd: number); + addListener(event: string, listener: (...args: any[]) => void): this; + addListener(event: "resize", listener: () => void): this; + emit(event: string | symbol, ...args: any[]): boolean; + emit(event: "resize"): boolean; + on(event: string, listener: (...args: any[]) => void): this; + on(event: "resize", listener: () => void): this; + once(event: string, listener: (...args: any[]) => void): this; + once(event: "resize", listener: () => void): this; + prependListener(event: string, listener: (...args: any[]) => void): this; + prependListener(event: "resize", listener: () => void): this; + prependOnceListener(event: string, listener: (...args: any[]) => void): this; + prependOnceListener(event: "resize", listener: () => void): this; + /** + * `writeStream.clearLine()` clears the current line of this `WriteStream` in a + * direction identified by `dir`. + * @since v0.7.7 + * @param callback Invoked once the operation completes. + * @return `false` if the stream wishes for the calling code to wait for the `'drain'` event to be emitted before continuing to write additional data; otherwise `true`. + */ + clearLine(dir: Direction, callback?: () => void): boolean; + /** + * `writeStream.clearScreenDown()` clears this `WriteStream` from the current + * cursor down. + * @since v0.7.7 + * @param callback Invoked once the operation completes. + * @return `false` if the stream wishes for the calling code to wait for the `'drain'` event to be emitted before continuing to write additional data; otherwise `true`. + */ + clearScreenDown(callback?: () => void): boolean; + /** + * `writeStream.cursorTo()` moves this `WriteStream`'s cursor to the specified + * position. + * @since v0.7.7 + * @param callback Invoked once the operation completes. + * @return `false` if the stream wishes for the calling code to wait for the `'drain'` event to be emitted before continuing to write additional data; otherwise `true`. + */ + cursorTo(x: number, y?: number, callback?: () => void): boolean; + cursorTo(x: number, callback: () => void): boolean; + /** + * `writeStream.moveCursor()` moves this `WriteStream`'s cursor _relative_ to its + * current position. + * @since v0.7.7 + * @param callback Invoked once the operation completes. + * @return `false` if the stream wishes for the calling code to wait for the `'drain'` event to be emitted before continuing to write additional data; otherwise `true`. + */ + moveCursor(dx: number, dy: number, callback?: () => void): boolean; + /** + * Returns: + * + * * `1` for 2, + * * `4` for 16, + * * `8` for 256, + * * `24` for 16,777,216 colors supported. + * + * Use this to determine what colors the terminal supports. Due to the nature of + * colors in terminals it is possible to either have false positives or false + * negatives. It depends on process information and the environment variables that + * may lie about what terminal is used. + * It is possible to pass in an `env` object to simulate the usage of a specific + * terminal. This can be useful to check how specific environment settings behave. + * + * To enforce a specific color support, use one of the below environment settings. + * + * * 2 colors: `FORCE_COLOR = 0` (Disables colors) + * * 16 colors: `FORCE_COLOR = 1` + * * 256 colors: `FORCE_COLOR = 2` + * * 16,777,216 colors: `FORCE_COLOR = 3` + * + * Disabling color support is also possible by using the `NO_COLOR` and `NODE_DISABLE_COLORS` environment variables. + * @since v9.9.0 + * @param [env=process.env] An object containing the environment variables to check. This enables simulating the usage of a specific terminal. + */ + getColorDepth(env?: object): number; + /** + * Returns `true` if the `writeStream` supports at least as many colors as provided + * in `count`. Minimum support is 2 (black and white). + * + * This has the same false positives and negatives as described in `writeStream.getColorDepth()`. + * + * ```js + * process.stdout.hasColors(); + * // Returns true or false depending on if `stdout` supports at least 16 colors. + * process.stdout.hasColors(256); + * // Returns true or false depending on if `stdout` supports at least 256 colors. + * process.stdout.hasColors({ TMUX: '1' }); + * // Returns true. + * process.stdout.hasColors(2 ** 24, { TMUX: '1' }); + * // Returns false (the environment setting pretends to support 2 ** 8 colors). + * ``` + * @since v11.13.0, v10.16.0 + * @param [count=16] The number of colors that are requested (minimum 2). + * @param [env=process.env] An object containing the environment variables to check. This enables simulating the usage of a specific terminal. + */ + hasColors(count?: number): boolean; + hasColors(env?: object): boolean; + hasColors(count: number, env?: object): boolean; + /** + * `writeStream.getWindowSize()` returns the size of the TTY + * corresponding to this `WriteStream`. The array is of the type `[numColumns, numRows]` where `numColumns` and `numRows` represent the number + * of columns and rows in the corresponding TTY. + * @since v0.7.7 + */ + getWindowSize(): [number, number]; + /** + * A `number` specifying the number of columns the TTY currently has. This property + * is updated whenever the `'resize'` event is emitted. + * @since v0.7.7 + */ + columns: number; + /** + * A `number` specifying the number of rows the TTY currently has. This property + * is updated whenever the `'resize'` event is emitted. + * @since v0.7.7 + */ + rows: number; + /** + * A `boolean` that is always `true`. + * @since v0.5.8 + */ + isTTY: boolean; + } +} +declare module "node:tty" { + export * from "tty"; +} diff --git a/node_modules/@types/node/url.d.ts b/node_modules/@types/node/url.d.ts new file mode 100644 index 0000000..0a53528 --- /dev/null +++ b/node_modules/@types/node/url.d.ts @@ -0,0 +1,952 @@ +/** + * The `node:url` module provides utilities for URL resolution and parsing. It can + * be accessed using: + * + * ```js + * import url from 'node:url'; + * ``` + * @see [source](https://github.com/nodejs/node/blob/v20.13.1/lib/url.js) + */ +declare module "url" { + import { Blob as NodeBlob } from "node:buffer"; + import { ClientRequestArgs } from "node:http"; + import { ParsedUrlQuery, ParsedUrlQueryInput } from "node:querystring"; + // Input to `url.format` + interface UrlObject { + auth?: string | null | undefined; + hash?: string | null | undefined; + host?: string | null | undefined; + hostname?: string | null | undefined; + href?: string | null | undefined; + pathname?: string | null | undefined; + protocol?: string | null | undefined; + search?: string | null | undefined; + slashes?: boolean | null | undefined; + port?: string | number | null | undefined; + query?: string | null | ParsedUrlQueryInput | undefined; + } + // Output of `url.parse` + interface Url { + auth: string | null; + hash: string | null; + host: string | null; + hostname: string | null; + href: string; + path: string | null; + pathname: string | null; + protocol: string | null; + search: string | null; + slashes: boolean | null; + port: string | null; + query: string | null | ParsedUrlQuery; + } + interface UrlWithParsedQuery extends Url { + query: ParsedUrlQuery; + } + interface UrlWithStringQuery extends Url { + query: string | null; + } + interface FileUrlToPathOptions { + /** + * `true` if the `path` should be return as a windows filepath, `false` for posix, and `undefined` for the system default. + * @default undefined + */ + windows?: boolean | undefined; + } + interface PathToFileUrlOptions extends FileUrlToPathOptions {} + /** + * The `url.parse()` method takes a URL string, parses it, and returns a URL + * object. + * + * A `TypeError` is thrown if `urlString` is not a string. + * + * A `URIError` is thrown if the `auth` property is present but cannot be decoded. + * + * `url.parse()` uses a lenient, non-standard algorithm for parsing URL + * strings. It is prone to security issues such as [host name spoofing](https://hackerone.com/reports/678487) and incorrect handling of usernames and passwords. Do not use with untrusted + * input. CVEs are not issued for `url.parse()` vulnerabilities. Use the `WHATWG URL` API instead. + * @since v0.1.25 + * @deprecated Use the WHATWG URL API instead. + * @param urlString The URL string to parse. + * @param [parseQueryString=false] If `true`, the `query` property will always be set to an object returned by the {@link querystring} module's `parse()` method. If `false`, the `query` property + * on the returned URL object will be an unparsed, undecoded string. + * @param [slashesDenoteHost=false] If `true`, the first token after the literal string `//` and preceding the next `/` will be interpreted as the `host`. For instance, given `//foo/bar`, the + * result would be `{host: 'foo', pathname: '/bar'}` rather than `{pathname: '//foo/bar'}`. + */ + function parse(urlString: string): UrlWithStringQuery; + function parse( + urlString: string, + parseQueryString: false | undefined, + slashesDenoteHost?: boolean, + ): UrlWithStringQuery; + function parse(urlString: string, parseQueryString: true, slashesDenoteHost?: boolean): UrlWithParsedQuery; + function parse(urlString: string, parseQueryString: boolean, slashesDenoteHost?: boolean): Url; + /** + * The `url.format()` method returns a formatted URL string derived from `urlObject`. + * + * ```js + * const url = require('node:url'); + * url.format({ + * protocol: 'https', + * hostname: 'example.com', + * pathname: '/some/path', + * query: { + * page: 1, + * format: 'json', + * }, + * }); + * + * // => 'https://example.com/some/path?page=1&format=json' + * ``` + * + * If `urlObject` is not an object or a string, `url.format()` will throw a `TypeError`. + * + * The formatting process operates as follows: + * + * * A new empty string `result` is created. + * * If `urlObject.protocol` is a string, it is appended as-is to `result`. + * * Otherwise, if `urlObject.protocol` is not `undefined` and is not a string, an `Error` is thrown. + * * For all string values of `urlObject.protocol` that _do not end_ with an ASCII + * colon (`:`) character, the literal string `:` will be appended to `result`. + * * If either of the following conditions is true, then the literal string `//` will be appended to `result`: + * * `urlObject.slashes` property is true; + * * `urlObject.protocol` begins with `http`, `https`, `ftp`, `gopher`, or `file`; + * * If the value of the `urlObject.auth` property is truthy, and either `urlObject.host` or `urlObject.hostname` are not `undefined`, the value of `urlObject.auth` will be coerced into a string + * and appended to `result` followed by the literal string `@`. + * * If the `urlObject.host` property is `undefined` then: + * * If the `urlObject.hostname` is a string, it is appended to `result`. + * * Otherwise, if `urlObject.hostname` is not `undefined` and is not a string, + * an `Error` is thrown. + * * If the `urlObject.port` property value is truthy, and `urlObject.hostname` is not `undefined`: + * * The literal string `:` is appended to `result`, and + * * The value of `urlObject.port` is coerced to a string and appended to `result`. + * * Otherwise, if the `urlObject.host` property value is truthy, the value of `urlObject.host` is coerced to a string and appended to `result`. + * * If the `urlObject.pathname` property is a string that is not an empty string: + * * If the `urlObject.pathname` _does not start_ with an ASCII forward slash + * (`/`), then the literal string `'/'` is appended to `result`. + * * The value of `urlObject.pathname` is appended to `result`. + * * Otherwise, if `urlObject.pathname` is not `undefined` and is not a string, an `Error` is thrown. + * * If the `urlObject.search` property is `undefined` and if the `urlObject.query`property is an `Object`, the literal string `?` is appended to `result` followed by the output of calling the + * `querystring` module's `stringify()` method passing the value of `urlObject.query`. + * * Otherwise, if `urlObject.search` is a string: + * * If the value of `urlObject.search` _does not start_ with the ASCII question + * mark (`?`) character, the literal string `?` is appended to `result`. + * * The value of `urlObject.search` is appended to `result`. + * * Otherwise, if `urlObject.search` is not `undefined` and is not a string, an `Error` is thrown. + * * If the `urlObject.hash` property is a string: + * * If the value of `urlObject.hash` _does not start_ with the ASCII hash (`#`) + * character, the literal string `#` is appended to `result`. + * * The value of `urlObject.hash` is appended to `result`. + * * Otherwise, if the `urlObject.hash` property is not `undefined` and is not a + * string, an `Error` is thrown. + * * `result` is returned. + * @since v0.1.25 + * @legacy Use the WHATWG URL API instead. + * @param urlObject A URL object (as returned by `url.parse()` or constructed otherwise). If a string, it is converted to an object by passing it to `url.parse()`. + */ + function format(urlObject: URL, options?: URLFormatOptions): string; + /** + * The `url.format()` method returns a formatted URL string derived from `urlObject`. + * + * ```js + * const url = require('node:url'); + * url.format({ + * protocol: 'https', + * hostname: 'example.com', + * pathname: '/some/path', + * query: { + * page: 1, + * format: 'json', + * }, + * }); + * + * // => 'https://example.com/some/path?page=1&format=json' + * ``` + * + * If `urlObject` is not an object or a string, `url.format()` will throw a `TypeError`. + * + * The formatting process operates as follows: + * + * * A new empty string `result` is created. + * * If `urlObject.protocol` is a string, it is appended as-is to `result`. + * * Otherwise, if `urlObject.protocol` is not `undefined` and is not a string, an `Error` is thrown. + * * For all string values of `urlObject.protocol` that _do not end_ with an ASCII + * colon (`:`) character, the literal string `:` will be appended to `result`. + * * If either of the following conditions is true, then the literal string `//` will be appended to `result`: + * * `urlObject.slashes` property is true; + * * `urlObject.protocol` begins with `http`, `https`, `ftp`, `gopher`, or `file`; + * * If the value of the `urlObject.auth` property is truthy, and either `urlObject.host` or `urlObject.hostname` are not `undefined`, the value of `urlObject.auth` will be coerced into a string + * and appended to `result` followed by the literal string `@`. + * * If the `urlObject.host` property is `undefined` then: + * * If the `urlObject.hostname` is a string, it is appended to `result`. + * * Otherwise, if `urlObject.hostname` is not `undefined` and is not a string, + * an `Error` is thrown. + * * If the `urlObject.port` property value is truthy, and `urlObject.hostname` is not `undefined`: + * * The literal string `:` is appended to `result`, and + * * The value of `urlObject.port` is coerced to a string and appended to `result`. + * * Otherwise, if the `urlObject.host` property value is truthy, the value of `urlObject.host` is coerced to a string and appended to `result`. + * * If the `urlObject.pathname` property is a string that is not an empty string: + * * If the `urlObject.pathname` _does not start_ with an ASCII forward slash + * (`/`), then the literal string `'/'` is appended to `result`. + * * The value of `urlObject.pathname` is appended to `result`. + * * Otherwise, if `urlObject.pathname` is not `undefined` and is not a string, an `Error` is thrown. + * * If the `urlObject.search` property is `undefined` and if the `urlObject.query`property is an `Object`, the literal string `?` is appended to `result` followed by the output of calling the + * `querystring` module's `stringify()` method passing the value of `urlObject.query`. + * * Otherwise, if `urlObject.search` is a string: + * * If the value of `urlObject.search` _does not start_ with the ASCII question + * mark (`?`) character, the literal string `?` is appended to `result`. + * * The value of `urlObject.search` is appended to `result`. + * * Otherwise, if `urlObject.search` is not `undefined` and is not a string, an `Error` is thrown. + * * If the `urlObject.hash` property is a string: + * * If the value of `urlObject.hash` _does not start_ with the ASCII hash (`#`) + * character, the literal string `#` is appended to `result`. + * * The value of `urlObject.hash` is appended to `result`. + * * Otherwise, if the `urlObject.hash` property is not `undefined` and is not a + * string, an `Error` is thrown. + * * `result` is returned. + * @since v0.1.25 + * @legacy Use the WHATWG URL API instead. + * @param urlObject A URL object (as returned by `url.parse()` or constructed otherwise). If a string, it is converted to an object by passing it to `url.parse()`. + */ + function format(urlObject: UrlObject | string): string; + /** + * The `url.resolve()` method resolves a target URL relative to a base URL in a + * manner similar to that of a web browser resolving an anchor tag. + * + * ```js + * const url = require('node:url'); + * url.resolve('/one/two/three', 'four'); // '/one/two/four' + * url.resolve('http://example.com/', '/one'); // 'http://example.com/one' + * url.resolve('http://example.com/one', '/two'); // 'http://example.com/two' + * ``` + * + * To achieve the same result using the WHATWG URL API: + * + * ```js + * function resolve(from, to) { + * const resolvedUrl = new URL(to, new URL(from, 'resolve://')); + * if (resolvedUrl.protocol === 'resolve:') { + * // `from` is a relative URL. + * const { pathname, search, hash } = resolvedUrl; + * return pathname + search + hash; + * } + * return resolvedUrl.toString(); + * } + * + * resolve('/one/two/three', 'four'); // '/one/two/four' + * resolve('http://example.com/', '/one'); // 'http://example.com/one' + * resolve('http://example.com/one', '/two'); // 'http://example.com/two' + * ``` + * @since v0.1.25 + * @legacy Use the WHATWG URL API instead. + * @param from The base URL to use if `to` is a relative URL. + * @param to The target URL to resolve. + */ + function resolve(from: string, to: string): string; + /** + * Returns the [Punycode](https://tools.ietf.org/html/rfc5891#section-4.4) ASCII serialization of the `domain`. If `domain` is an + * invalid domain, the empty string is returned. + * + * It performs the inverse operation to {@link domainToUnicode}. + * + * ```js + * import url from 'node:url'; + * + * console.log(url.domainToASCII('español.com')); + * // Prints xn--espaol-zwa.com + * console.log(url.domainToASCII('中文.com')); + * // Prints xn--fiq228c.com + * console.log(url.domainToASCII('xn--iñvalid.com')); + * // Prints an empty string + * ``` + * @since v7.4.0, v6.13.0 + */ + function domainToASCII(domain: string): string; + /** + * Returns the Unicode serialization of the `domain`. If `domain` is an invalid + * domain, the empty string is returned. + * + * It performs the inverse operation to {@link domainToASCII}. + * + * ```js + * import url from 'node:url'; + * + * console.log(url.domainToUnicode('xn--espaol-zwa.com')); + * // Prints español.com + * console.log(url.domainToUnicode('xn--fiq228c.com')); + * // Prints 中文.com + * console.log(url.domainToUnicode('xn--iñvalid.com')); + * // Prints an empty string + * ``` + * @since v7.4.0, v6.13.0 + */ + function domainToUnicode(domain: string): string; + /** + * This function ensures the correct decodings of percent-encoded characters as + * well as ensuring a cross-platform valid absolute path string. + * + * ```js + * import { fileURLToPath } from 'node:url'; + * + * const __filename = fileURLToPath(import.meta.url); + * + * new URL('file:///C:/path/').pathname; // Incorrect: /C:/path/ + * fileURLToPath('file:///C:/path/'); // Correct: C:\path\ (Windows) + * + * new URL('file://nas/foo.txt').pathname; // Incorrect: /foo.txt + * fileURLToPath('file://nas/foo.txt'); // Correct: \\nas\foo.txt (Windows) + * + * new URL('file:///你好.txt').pathname; // Incorrect: /%E4%BD%A0%E5%A5%BD.txt + * fileURLToPath('file:///你好.txt'); // Correct: /你好.txt (POSIX) + * + * new URL('file:///hello world').pathname; // Incorrect: /hello%20world + * fileURLToPath('file:///hello world'); // Correct: /hello world (POSIX) + * ``` + * @since v10.12.0 + * @param url The file URL string or URL object to convert to a path. + * @return The fully-resolved platform-specific Node.js file path. + */ + function fileURLToPath(url: string | URL, options?: FileUrlToPathOptions): string; + /** + * This function ensures that `path` is resolved absolutely, and that the URL + * control characters are correctly encoded when converting into a File URL. + * + * ```js + * import { pathToFileURL } from 'node:url'; + * + * new URL('/foo#1', 'file:'); // Incorrect: file:///foo#1 + * pathToFileURL('/foo#1'); // Correct: file:///foo%231 (POSIX) + * + * new URL('/some/path%.c', 'file:'); // Incorrect: file:///some/path%.c + * pathToFileURL('/some/path%.c'); // Correct: file:///some/path%25.c (POSIX) + * ``` + * @since v10.12.0 + * @param path The path to convert to a File URL. + * @return The file URL object. + */ + function pathToFileURL(path: string, options?: PathToFileUrlOptions): URL; + /** + * This utility function converts a URL object into an ordinary options object as + * expected by the `http.request()` and `https.request()` APIs. + * + * ```js + * import { urlToHttpOptions } from 'node:url'; + * const myURL = new URL('https://a:b@測試?abc#foo'); + * + * console.log(urlToHttpOptions(myURL)); + * /* + * { + * protocol: 'https:', + * hostname: 'xn--g6w251d', + * hash: '#foo', + * search: '?abc', + * pathname: '/', + * path: '/?abc', + * href: 'https://a:b@xn--g6w251d/?abc#foo', + * auth: 'a:b' + * } + * + * ``` + * @since v15.7.0, v14.18.0 + * @param url The `WHATWG URL` object to convert to an options object. + * @return Options object + */ + function urlToHttpOptions(url: URL): ClientRequestArgs; + interface URLFormatOptions { + /** + * `true` if the serialized URL string should include the username and password, `false` otherwise. + * @default true + */ + auth?: boolean | undefined; + /** + * `true` if the serialized URL string should include the fragment, `false` otherwise. + * @default true + */ + fragment?: boolean | undefined; + /** + * `true` if the serialized URL string should include the search query, `false` otherwise. + * @default true + */ + search?: boolean | undefined; + /** + * `true` if Unicode characters appearing in the host component of the URL string should be encoded directly as opposed to + * being Punycode encoded. + * @default false + */ + unicode?: boolean | undefined; + } + /** + * Browser-compatible `URL` class, implemented by following the WHATWG URL + * Standard. [Examples of parsed URLs](https://url.spec.whatwg.org/#example-url-parsing) may be found in the Standard itself. + * The `URL` class is also available on the global object. + * + * In accordance with browser conventions, all properties of `URL` objects + * are implemented as getters and setters on the class prototype, rather than as + * data properties on the object itself. Thus, unlike `legacy urlObject`s, + * using the `delete` keyword on any properties of `URL` objects (e.g. `delete myURL.protocol`, `delete myURL.pathname`, etc) has no effect but will still + * return `true`. + * @since v7.0.0, v6.13.0 + */ + class URL { + /** + * Creates a `'blob:nodedata:...'` URL string that represents the given `Blob` object and can be used to retrieve the `Blob` later. + * + * ```js + * const { + * Blob, + * resolveObjectURL, + * } = require('node:buffer'); + * + * const blob = new Blob(['hello']); + * const id = URL.createObjectURL(blob); + * + * // later... + * + * const otherBlob = resolveObjectURL(id); + * console.log(otherBlob.size); + * ``` + * + * The data stored by the registered `Blob` will be retained in memory until `URL.revokeObjectURL()` is called to remove it. + * + * `Blob` objects are registered within the current thread. If using Worker + * Threads, `Blob` objects registered within one Worker will not be available + * to other workers or the main thread. + * @since v16.7.0 + * @experimental + */ + static createObjectURL(blob: NodeBlob): string; + /** + * Removes the stored `Blob` identified by the given ID. Attempting to revoke a + * ID that isn't registered will silently fail. + * @since v16.7.0 + * @experimental + * @param id A `'blob:nodedata:...` URL string returned by a prior call to `URL.createObjectURL()`. + */ + static revokeObjectURL(id: string): void; + /** + * Checks if an `input` relative to the `base` can be parsed to a `URL`. + * + * ```js + * const isValid = URL.canParse('/foo', 'https://example.org/'); // true + * + * const isNotValid = URL.canParse('/foo'); // false + * ``` + * @since v19.9.0 + * @param input The absolute or relative input URL to parse. If `input` is relative, then `base` is required. If `input` is absolute, the `base` is ignored. If `input` is not a string, it is + * `converted to a string` first. + * @param base The base URL to resolve against if the `input` is not absolute. If `base` is not a string, it is `converted to a string` first. + */ + static canParse(input: string, base?: string): boolean; + constructor(input: string | { toString: () => string }, base?: string | URL); + /** + * Gets and sets the fragment portion of the URL. + * + * ```js + * const myURL = new URL('https://example.org/foo#bar'); + * console.log(myURL.hash); + * // Prints #bar + * + * myURL.hash = 'baz'; + * console.log(myURL.href); + * // Prints https://example.org/foo#baz + * ``` + * + * Invalid URL characters included in the value assigned to the `hash` property + * are `percent-encoded`. The selection of which characters to + * percent-encode may vary somewhat from what the {@link parse} and {@link format} methods would produce. + */ + hash: string; + /** + * Gets and sets the host portion of the URL. + * + * ```js + * const myURL = new URL('https://example.org:81/foo'); + * console.log(myURL.host); + * // Prints example.org:81 + * + * myURL.host = 'example.com:82'; + * console.log(myURL.href); + * // Prints https://example.com:82/foo + * ``` + * + * Invalid host values assigned to the `host` property are ignored. + */ + host: string; + /** + * Gets and sets the host name portion of the URL. The key difference between`url.host` and `url.hostname` is that `url.hostname` does _not_ include the + * port. + * + * ```js + * const myURL = new URL('https://example.org:81/foo'); + * console.log(myURL.hostname); + * // Prints example.org + * + * // Setting the hostname does not change the port + * myURL.hostname = 'example.com'; + * console.log(myURL.href); + * // Prints https://example.com:81/foo + * + * // Use myURL.host to change the hostname and port + * myURL.host = 'example.org:82'; + * console.log(myURL.href); + * // Prints https://example.org:82/foo + * ``` + * + * Invalid host name values assigned to the `hostname` property are ignored. + */ + hostname: string; + /** + * Gets and sets the serialized URL. + * + * ```js + * const myURL = new URL('https://example.org/foo'); + * console.log(myURL.href); + * // Prints https://example.org/foo + * + * myURL.href = 'https://example.com/bar'; + * console.log(myURL.href); + * // Prints https://example.com/bar + * ``` + * + * Getting the value of the `href` property is equivalent to calling {@link toString}. + * + * Setting the value of this property to a new value is equivalent to creating a + * new `URL` object using `new URL(value)`. Each of the `URL` object's properties will be modified. + * + * If the value assigned to the `href` property is not a valid URL, a `TypeError` will be thrown. + */ + href: string; + /** + * Gets the read-only serialization of the URL's origin. + * + * ```js + * const myURL = new URL('https://example.org/foo/bar?baz'); + * console.log(myURL.origin); + * // Prints https://example.org + * ``` + * + * ```js + * const idnURL = new URL('https://測試'); + * console.log(idnURL.origin); + * // Prints https://xn--g6w251d + * + * console.log(idnURL.hostname); + * // Prints xn--g6w251d + * ``` + */ + readonly origin: string; + /** + * Gets and sets the password portion of the URL. + * + * ```js + * const myURL = new URL('https://abc:xyz@example.com'); + * console.log(myURL.password); + * // Prints xyz + * + * myURL.password = '123'; + * console.log(myURL.href); + * // Prints https://abc:123@example.com/ + * ``` + * + * Invalid URL characters included in the value assigned to the `password` property + * are `percent-encoded`. The selection of which characters to + * percent-encode may vary somewhat from what the {@link parse} and {@link format} methods would produce. + */ + password: string; + /** + * Gets and sets the path portion of the URL. + * + * ```js + * const myURL = new URL('https://example.org/abc/xyz?123'); + * console.log(myURL.pathname); + * // Prints /abc/xyz + * + * myURL.pathname = '/abcdef'; + * console.log(myURL.href); + * // Prints https://example.org/abcdef?123 + * ``` + * + * Invalid URL characters included in the value assigned to the `pathname` property are `percent-encoded`. The selection of which characters + * to percent-encode may vary somewhat from what the {@link parse} and {@link format} methods would produce. + */ + pathname: string; + /** + * Gets and sets the port portion of the URL. + * + * The port value may be a number or a string containing a number in the range `0` to `65535` (inclusive). Setting the value to the default port of the `URL` objects given `protocol` will + * result in the `port` value becoming + * the empty string (`''`). + * + * The port value can be an empty string in which case the port depends on + * the protocol/scheme: + * + * + * + * Upon assigning a value to the port, the value will first be converted to a + * string using `.toString()`. + * + * If that string is invalid but it begins with a number, the leading number is + * assigned to `port`. + * If the number lies outside the range denoted above, it is ignored. + * + * ```js + * const myURL = new URL('https://example.org:8888'); + * console.log(myURL.port); + * // Prints 8888 + * + * // Default ports are automatically transformed to the empty string + * // (HTTPS protocol's default port is 443) + * myURL.port = '443'; + * console.log(myURL.port); + * // Prints the empty string + * console.log(myURL.href); + * // Prints https://example.org/ + * + * myURL.port = 1234; + * console.log(myURL.port); + * // Prints 1234 + * console.log(myURL.href); + * // Prints https://example.org:1234/ + * + * // Completely invalid port strings are ignored + * myURL.port = 'abcd'; + * console.log(myURL.port); + * // Prints 1234 + * + * // Leading numbers are treated as a port number + * myURL.port = '5678abcd'; + * console.log(myURL.port); + * // Prints 5678 + * + * // Non-integers are truncated + * myURL.port = 1234.5678; + * console.log(myURL.port); + * // Prints 1234 + * + * // Out-of-range numbers which are not represented in scientific notation + * // will be ignored. + * myURL.port = 1e10; // 10000000000, will be range-checked as described below + * console.log(myURL.port); + * // Prints 1234 + * ``` + * + * Numbers which contain a decimal point, + * such as floating-point numbers or numbers in scientific notation, + * are not an exception to this rule. + * Leading numbers up to the decimal point will be set as the URL's port, + * assuming they are valid: + * + * ```js + * myURL.port = 4.567e21; + * console.log(myURL.port); + * // Prints 4 (because it is the leading number in the string '4.567e21') + * ``` + */ + port: string; + /** + * Gets and sets the protocol portion of the URL. + * + * ```js + * const myURL = new URL('https://example.org'); + * console.log(myURL.protocol); + * // Prints https: + * + * myURL.protocol = 'ftp'; + * console.log(myURL.href); + * // Prints ftp://example.org/ + * ``` + * + * Invalid URL protocol values assigned to the `protocol` property are ignored. + */ + protocol: string; + /** + * Gets and sets the serialized query portion of the URL. + * + * ```js + * const myURL = new URL('https://example.org/abc?123'); + * console.log(myURL.search); + * // Prints ?123 + * + * myURL.search = 'abc=xyz'; + * console.log(myURL.href); + * // Prints https://example.org/abc?abc=xyz + * ``` + * + * Any invalid URL characters appearing in the value assigned the `search` property will be `percent-encoded`. The selection of which + * characters to percent-encode may vary somewhat from what the {@link parse} and {@link format} methods would produce. + */ + search: string; + /** + * Gets the `URLSearchParams` object representing the query parameters of the + * URL. This property is read-only but the `URLSearchParams` object it provides + * can be used to mutate the URL instance; to replace the entirety of query + * parameters of the URL, use the {@link search} setter. See `URLSearchParams` documentation for details. + * + * Use care when using `.searchParams` to modify the `URL` because, + * per the WHATWG specification, the `URLSearchParams` object uses + * different rules to determine which characters to percent-encode. For + * instance, the `URL` object will not percent encode the ASCII tilde (`~`) + * character, while `URLSearchParams` will always encode it: + * + * ```js + * const myURL = new URL('https://example.org/abc?foo=~bar'); + * + * console.log(myURL.search); // prints ?foo=~bar + * + * // Modify the URL via searchParams... + * myURL.searchParams.sort(); + * + * console.log(myURL.search); // prints ?foo=%7Ebar + * ``` + */ + readonly searchParams: URLSearchParams; + /** + * Gets and sets the username portion of the URL. + * + * ```js + * const myURL = new URL('https://abc:xyz@example.com'); + * console.log(myURL.username); + * // Prints abc + * + * myURL.username = '123'; + * console.log(myURL.href); + * // Prints https://123:xyz@example.com/ + * ``` + * + * Any invalid URL characters appearing in the value assigned the `username` property will be `percent-encoded`. The selection of which + * characters to percent-encode may vary somewhat from what the {@link parse} and {@link format} methods would produce. + */ + username: string; + /** + * The `toString()` method on the `URL` object returns the serialized URL. The + * value returned is equivalent to that of {@link href} and {@link toJSON}. + */ + toString(): string; + /** + * The `toJSON()` method on the `URL` object returns the serialized URL. The + * value returned is equivalent to that of {@link href} and {@link toString}. + * + * This method is automatically called when an `URL` object is serialized + * with [`JSON.stringify()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify). + * + * ```js + * const myURLs = [ + * new URL('https://www.example.com'), + * new URL('https://test.example.org'), + * ]; + * console.log(JSON.stringify(myURLs)); + * // Prints ["https://www.example.com/","https://test.example.org/"] + * ``` + */ + toJSON(): string; + } + /** + * The `URLSearchParams` API provides read and write access to the query of a `URL`. The `URLSearchParams` class can also be used standalone with one of the + * four following constructors. + * The `URLSearchParams` class is also available on the global object. + * + * The WHATWG `URLSearchParams` interface and the `querystring` module have + * similar purpose, but the purpose of the `querystring` module is more + * general, as it allows the customization of delimiter characters (`&` and `=`). + * On the other hand, this API is designed purely for URL query strings. + * + * ```js + * const myURL = new URL('https://example.org/?abc=123'); + * console.log(myURL.searchParams.get('abc')); + * // Prints 123 + * + * myURL.searchParams.append('abc', 'xyz'); + * console.log(myURL.href); + * // Prints https://example.org/?abc=123&abc=xyz + * + * myURL.searchParams.delete('abc'); + * myURL.searchParams.set('a', 'b'); + * console.log(myURL.href); + * // Prints https://example.org/?a=b + * + * const newSearchParams = new URLSearchParams(myURL.searchParams); + * // The above is equivalent to + * // const newSearchParams = new URLSearchParams(myURL.search); + * + * newSearchParams.append('a', 'c'); + * console.log(myURL.href); + * // Prints https://example.org/?a=b + * console.log(newSearchParams.toString()); + * // Prints a=b&a=c + * + * // newSearchParams.toString() is implicitly called + * myURL.search = newSearchParams; + * console.log(myURL.href); + * // Prints https://example.org/?a=b&a=c + * newSearchParams.delete('a'); + * console.log(myURL.href); + * // Prints https://example.org/?a=b&a=c + * ``` + * @since v7.5.0, v6.13.0 + */ + class URLSearchParams implements Iterable<[string, string]> { + constructor( + init?: + | URLSearchParams + | string + | Record + | Iterable<[string, string]> + | ReadonlyArray<[string, string]>, + ); + /** + * Append a new name-value pair to the query string. + */ + append(name: string, value: string): void; + /** + * If `value` is provided, removes all name-value pairs + * where name is `name` and value is `value`. + * + * If `value` is not provided, removes all name-value pairs whose name is `name`. + */ + delete(name: string, value?: string): void; + /** + * Returns an ES6 `Iterator` over each of the name-value pairs in the query. + * Each item of the iterator is a JavaScript `Array`. The first item of the `Array` is the `name`, the second item of the `Array` is the `value`. + * + * Alias for `urlSearchParams[@@iterator]()`. + */ + entries(): IterableIterator<[string, string]>; + /** + * Iterates over each name-value pair in the query and invokes the given function. + * + * ```js + * const myURL = new URL('https://example.org/?a=b&c=d'); + * myURL.searchParams.forEach((value, name, searchParams) => { + * console.log(name, value, myURL.searchParams === searchParams); + * }); + * // Prints: + * // a b true + * // c d true + * ``` + * @param fn Invoked for each name-value pair in the query + * @param thisArg To be used as `this` value for when `fn` is called + */ + forEach( + fn: (this: TThis, value: string, name: string, searchParams: URLSearchParams) => void, + thisArg?: TThis, + ): void; + /** + * Returns the value of the first name-value pair whose name is `name`. If there + * are no such pairs, `null` is returned. + * @return or `null` if there is no name-value pair with the given `name`. + */ + get(name: string): string | null; + /** + * Returns the values of all name-value pairs whose name is `name`. If there are + * no such pairs, an empty array is returned. + */ + getAll(name: string): string[]; + /** + * Checks if the `URLSearchParams` object contains key-value pair(s) based on `name` and an optional `value` argument. + * + * If `value` is provided, returns `true` when name-value pair with + * same `name` and `value` exists. + * + * If `value` is not provided, returns `true` if there is at least one name-value + * pair whose name is `name`. + */ + has(name: string, value?: string): boolean; + /** + * Returns an ES6 `Iterator` over the names of each name-value pair. + * + * ```js + * const params = new URLSearchParams('foo=bar&foo=baz'); + * for (const name of params.keys()) { + * console.log(name); + * } + * // Prints: + * // foo + * // foo + * ``` + */ + keys(): IterableIterator; + /** + * Sets the value in the `URLSearchParams` object associated with `name` to `value`. If there are any pre-existing name-value pairs whose names are `name`, + * set the first such pair's value to `value` and remove all others. If not, + * append the name-value pair to the query string. + * + * ```js + * const params = new URLSearchParams(); + * params.append('foo', 'bar'); + * params.append('foo', 'baz'); + * params.append('abc', 'def'); + * console.log(params.toString()); + * // Prints foo=bar&foo=baz&abc=def + * + * params.set('foo', 'def'); + * params.set('xyz', 'opq'); + * console.log(params.toString()); + * // Prints foo=def&abc=def&xyz=opq + * ``` + */ + set(name: string, value: string): void; + /** + * The total number of parameter entries. + * @since v19.8.0 + */ + readonly size: number; + /** + * Sort all existing name-value pairs in-place by their names. Sorting is done + * with a [stable sorting algorithm](https://en.wikipedia.org/wiki/Sorting_algorithm#Stability), so relative order between name-value pairs + * with the same name is preserved. + * + * This method can be used, in particular, to increase cache hits. + * + * ```js + * const params = new URLSearchParams('query[]=abc&type=search&query[]=123'); + * params.sort(); + * console.log(params.toString()); + * // Prints query%5B%5D=abc&query%5B%5D=123&type=search + * ``` + * @since v7.7.0, v6.13.0 + */ + sort(): void; + /** + * Returns the search parameters serialized as a string, with characters + * percent-encoded where necessary. + */ + toString(): string; + /** + * Returns an ES6 `Iterator` over the values of each name-value pair. + */ + values(): IterableIterator; + [Symbol.iterator](): IterableIterator<[string, string]>; + } + import { URL as _URL, URLSearchParams as _URLSearchParams } from "url"; + global { + interface URLSearchParams extends _URLSearchParams {} + interface URL extends _URL {} + interface Global { + URL: typeof _URL; + URLSearchParams: typeof _URLSearchParams; + } + /** + * `URL` class is a global reference for `require('url').URL` + * https://nodejs.org/api/url.html#the-whatwg-url-api + * @since v10.0.0 + */ + var URL: typeof globalThis extends { + onmessage: any; + URL: infer T; + } ? T + : typeof _URL; + /** + * `URLSearchParams` class is a global reference for `require('url').URLSearchParams` + * https://nodejs.org/api/url.html#class-urlsearchparams + * @since v10.0.0 + */ + var URLSearchParams: typeof globalThis extends { + onmessage: any; + URLSearchParams: infer T; + } ? T + : typeof _URLSearchParams; + } +} +declare module "node:url" { + export * from "url"; +} diff --git a/node_modules/@types/node/util.d.ts b/node_modules/@types/node/util.d.ts new file mode 100644 index 0000000..9847242 --- /dev/null +++ b/node_modules/@types/node/util.d.ts @@ -0,0 +1,2292 @@ +/** + * The `node:util` module supports the needs of Node.js internal APIs. Many of the + * utilities are useful for application and module developers as well. To access + * it: + * + * ```js + * const util = require('node:util'); + * ``` + * @see [source](https://github.com/nodejs/node/blob/v20.13.1/lib/util.js) + */ +declare module "util" { + import * as types from "node:util/types"; + export interface InspectOptions { + /** + * If `true`, object's non-enumerable symbols and properties are included in the formatted result. + * `WeakMap` and `WeakSet` entries are also included as well as user defined prototype properties (excluding method properties). + * @default false + */ + showHidden?: boolean | undefined; + /** + * Specifies the number of times to recurse while formatting object. + * This is useful for inspecting large objects. + * To recurse up to the maximum call stack size pass `Infinity` or `null`. + * @default 2 + */ + depth?: number | null | undefined; + /** + * If `true`, the output is styled with ANSI color codes. Colors are customizable. + */ + colors?: boolean | undefined; + /** + * If `false`, `[util.inspect.custom](depth, opts, inspect)` functions are not invoked. + * @default true + */ + customInspect?: boolean | undefined; + /** + * If `true`, `Proxy` inspection includes the target and handler objects. + * @default false + */ + showProxy?: boolean | undefined; + /** + * Specifies the maximum number of `Array`, `TypedArray`, `WeakMap`, and `WeakSet` elements + * to include when formatting. Set to `null` or `Infinity` to show all elements. + * Set to `0` or negative to show no elements. + * @default 100 + */ + maxArrayLength?: number | null | undefined; + /** + * Specifies the maximum number of characters to + * include when formatting. Set to `null` or `Infinity` to show all elements. + * Set to `0` or negative to show no characters. + * @default 10000 + */ + maxStringLength?: number | null | undefined; + /** + * The length at which input values are split across multiple lines. + * Set to `Infinity` to format the input as a single line + * (in combination with `compact` set to `true` or any number >= `1`). + * @default 80 + */ + breakLength?: number | undefined; + /** + * Setting this to `false` causes each object key + * to be displayed on a new line. It will also add new lines to text that is + * longer than `breakLength`. If set to a number, the most `n` inner elements + * are united on a single line as long as all properties fit into + * `breakLength`. Short array elements are also grouped together. Note that no + * text will be reduced below 16 characters, no matter the `breakLength` size. + * For more information, see the example below. + * @default true + */ + compact?: boolean | number | undefined; + /** + * If set to `true` or a function, all properties of an object, and `Set` and `Map` + * entries are sorted in the resulting string. + * If set to `true` the default sort is used. + * If set to a function, it is used as a compare function. + */ + sorted?: boolean | ((a: string, b: string) => number) | undefined; + /** + * If set to `true`, getters are going to be + * inspected as well. If set to `'get'` only getters without setter are going + * to be inspected. If set to `'set'` only getters having a corresponding + * setter are going to be inspected. This might cause side effects depending on + * the getter function. + * @default false + */ + getters?: "get" | "set" | boolean | undefined; + /** + * If set to `true`, an underscore is used to separate every three digits in all bigints and numbers. + * @default false + */ + numericSeparator?: boolean | undefined; + } + export type Style = + | "special" + | "number" + | "bigint" + | "boolean" + | "undefined" + | "null" + | "string" + | "symbol" + | "date" + | "regexp" + | "module"; + export type CustomInspectFunction = (depth: number, options: InspectOptionsStylized) => any; // TODO: , inspect: inspect + export interface InspectOptionsStylized extends InspectOptions { + stylize(text: string, styleType: Style): string; + } + /** + * The `util.format()` method returns a formatted string using the first argument + * as a `printf`-like format string which can contain zero or more format + * specifiers. Each specifier is replaced with the converted value from the + * corresponding argument. Supported specifiers are: + * + * If a specifier does not have a corresponding argument, it is not replaced: + * + * ```js + * util.format('%s:%s', 'foo'); + * // Returns: 'foo:%s' + * ``` + * + * Values that are not part of the format string are formatted using `util.inspect()` if their type is not `string`. + * + * If there are more arguments passed to the `util.format()` method than the + * number of specifiers, the extra arguments are concatenated to the returned + * string, separated by spaces: + * + * ```js + * util.format('%s:%s', 'foo', 'bar', 'baz'); + * // Returns: 'foo:bar baz' + * ``` + * + * If the first argument does not contain a valid format specifier, `util.format()` returns a string that is the concatenation of all arguments separated by spaces: + * + * ```js + * util.format(1, 2, 3); + * // Returns: '1 2 3' + * ``` + * + * If only one argument is passed to `util.format()`, it is returned as it is + * without any formatting: + * + * ```js + * util.format('%% %s'); + * // Returns: '%% %s' + * ``` + * + * `util.format()` is a synchronous method that is intended as a debugging tool. + * Some input values can have a significant performance overhead that can block the + * event loop. Use this function with care and never in a hot code path. + * @since v0.5.3 + * @param format A `printf`-like format string. + */ + export function format(format?: any, ...param: any[]): string; + /** + * This function is identical to {@link format}, except in that it takes + * an `inspectOptions` argument which specifies options that are passed along to {@link inspect}. + * + * ```js + * util.formatWithOptions({ colors: true }, 'See object %O', { foo: 42 }); + * // Returns 'See object { foo: 42 }', where `42` is colored as a number + * // when printed to a terminal. + * ``` + * @since v10.0.0 + */ + export function formatWithOptions(inspectOptions: InspectOptions, format?: any, ...param: any[]): string; + /** + * Returns the string name for a numeric error code that comes from a Node.js API. + * The mapping between error codes and error names is platform-dependent. + * See `Common System Errors` for the names of common errors. + * + * ```js + * fs.access('file/that/does/not/exist', (err) => { + * const name = util.getSystemErrorName(err.errno); + * console.error(name); // ENOENT + * }); + * ``` + * @since v9.7.0 + */ + export function getSystemErrorName(err: number): string; + /** + * Returns a Map of all system error codes available from the Node.js API. + * The mapping between error codes and error names is platform-dependent. + * See `Common System Errors` for the names of common errors. + * + * ```js + * fs.access('file/that/does/not/exist', (err) => { + * const errorMap = util.getSystemErrorMap(); + * const name = errorMap.get(err.errno); + * console.error(name); // ENOENT + * }); + * ``` + * @since v16.0.0, v14.17.0 + */ + export function getSystemErrorMap(): Map; + /** + * The `util.log()` method prints the given `string` to `stdout` with an included + * timestamp. + * + * ```js + * const util = require('node:util'); + * + * util.log('Timestamped message.'); + * ``` + * @since v0.3.0 + * @deprecated Since v6.0.0 - Use a third party module instead. + */ + export function log(string: string): void; + /** + * Returns the `string` after replacing any surrogate code points + * (or equivalently, any unpaired surrogate code units) with the + * Unicode "replacement character" U+FFFD. + * @since v16.8.0, v14.18.0 + */ + export function toUSVString(string: string): string; + /** + * Creates and returns an `AbortController` instance whose `AbortSignal` is marked + * as transferable and can be used with `structuredClone()` or `postMessage()`. + * @since v18.11.0 + * @experimental + * @returns A transferable AbortController + */ + export function transferableAbortController(): AbortController; + /** + * Marks the given `AbortSignal` as transferable so that it can be used with`structuredClone()` and `postMessage()`. + * + * ```js + * const signal = transferableAbortSignal(AbortSignal.timeout(100)); + * const channel = new MessageChannel(); + * channel.port2.postMessage(signal, [signal]); + * ``` + * @since v18.11.0 + * @experimental + * @param signal The AbortSignal + * @returns The same AbortSignal + */ + export function transferableAbortSignal(signal: AbortSignal): AbortSignal; + /** + * Listens to abort event on the provided `signal` and + * returns a promise that is fulfilled when the `signal` is + * aborted. If the passed `resource` is garbage collected before the `signal` is + * aborted, the returned promise shall remain pending indefinitely. + * + * ```js + * import { aborted } from 'node:util'; + * + * const dependent = obtainSomethingAbortable(); + * + * aborted(dependent.signal, dependent).then(() => { + * // Do something when dependent is aborted. + * }); + * + * dependent.on('event', () => { + * dependent.abort(); + * }); + * ``` + * @since v19.7.0 + * @experimental + * @param resource Any non-null entity, reference to which is held weakly. + */ + export function aborted(signal: AbortSignal, resource: any): Promise; + /** + * The `util.inspect()` method returns a string representation of `object` that is + * intended for debugging. The output of `util.inspect` may change at any time + * and should not be depended upon programmatically. Additional `options` may be + * passed that alter the result. `util.inspect()` will use the constructor's name and/or `@@toStringTag` to make + * an identifiable tag for an inspected value. + * + * ```js + * class Foo { + * get [Symbol.toStringTag]() { + * return 'bar'; + * } + * } + * + * class Bar {} + * + * const baz = Object.create(null, { [Symbol.toStringTag]: { value: 'foo' } }); + * + * util.inspect(new Foo()); // 'Foo [bar] {}' + * util.inspect(new Bar()); // 'Bar {}' + * util.inspect(baz); // '[foo] {}' + * ``` + * + * Circular references point to their anchor by using a reference index: + * + * ```js + * const { inspect } = require('node:util'); + * + * const obj = {}; + * obj.a = [obj]; + * obj.b = {}; + * obj.b.inner = obj.b; + * obj.b.obj = obj; + * + * console.log(inspect(obj)); + * // { + * // a: [ [Circular *1] ], + * // b: { inner: [Circular *2], obj: [Circular *1] } + * // } + * ``` + * + * The following example inspects all properties of the `util` object: + * + * ```js + * const util = require('node:util'); + * + * console.log(util.inspect(util, { showHidden: true, depth: null })); + * ``` + * + * The following example highlights the effect of the `compact` option: + * + * ```js + * const util = require('node:util'); + * + * const o = { + * a: [1, 2, [[ + * 'Lorem ipsum dolor sit amet,\nconsectetur adipiscing elit, sed do ' + + * 'eiusmod \ntempor incididunt ut labore et dolore magna aliqua.', + * 'test', + * 'foo']], 4], + * b: new Map([['za', 1], ['zb', 'test']]), + * }; + * console.log(util.inspect(o, { compact: true, depth: 5, breakLength: 80 })); + * + * // { a: + * // [ 1, + * // 2, + * // [ [ 'Lorem ipsum dolor sit amet,\nconsectetur [...]', // A long line + * // 'test', + * // 'foo' ] ], + * // 4 ], + * // b: Map(2) { 'za' => 1, 'zb' => 'test' } } + * + * // Setting `compact` to false or an integer creates more reader friendly output. + * console.log(util.inspect(o, { compact: false, depth: 5, breakLength: 80 })); + * + * // { + * // a: [ + * // 1, + * // 2, + * // [ + * // [ + * // 'Lorem ipsum dolor sit amet,\n' + + * // 'consectetur adipiscing elit, sed do eiusmod \n' + + * // 'tempor incididunt ut labore et dolore magna aliqua.', + * // 'test', + * // 'foo' + * // ] + * // ], + * // 4 + * // ], + * // b: Map(2) { + * // 'za' => 1, + * // 'zb' => 'test' + * // } + * // } + * + * // Setting `breakLength` to e.g. 150 will print the "Lorem ipsum" text in a + * // single line. + * ``` + * + * The `showHidden` option allows [`WeakMap`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakMap) and + * [`WeakSet`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakSet) entries to be + * inspected. If there are more entries than `maxArrayLength`, there is no + * guarantee which entries are displayed. That means retrieving the same [`WeakSet`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakSet) entries twice may + * result in different output. Furthermore, entries + * with no remaining strong references may be garbage collected at any time. + * + * ```js + * const { inspect } = require('node:util'); + * + * const obj = { a: 1 }; + * const obj2 = { b: 2 }; + * const weakSet = new WeakSet([obj, obj2]); + * + * console.log(inspect(weakSet, { showHidden: true })); + * // WeakSet { { a: 1 }, { b: 2 } } + * ``` + * + * The `sorted` option ensures that an object's property insertion order does not + * impact the result of `util.inspect()`. + * + * ```js + * const { inspect } = require('node:util'); + * const assert = require('node:assert'); + * + * const o1 = { + * b: [2, 3, 1], + * a: '`a` comes before `b`', + * c: new Set([2, 3, 1]), + * }; + * console.log(inspect(o1, { sorted: true })); + * // { a: '`a` comes before `b`', b: [ 2, 3, 1 ], c: Set(3) { 1, 2, 3 } } + * console.log(inspect(o1, { sorted: (a, b) => b.localeCompare(a) })); + * // { c: Set(3) { 3, 2, 1 }, b: [ 2, 3, 1 ], a: '`a` comes before `b`' } + * + * const o2 = { + * c: new Set([2, 1, 3]), + * a: '`a` comes before `b`', + * b: [2, 3, 1], + * }; + * assert.strict.equal( + * inspect(o1, { sorted: true }), + * inspect(o2, { sorted: true }), + * ); + * ``` + * + * The `numericSeparator` option adds an underscore every three digits to all + * numbers. + * + * ```js + * const { inspect } = require('node:util'); + * + * const thousand = 1_000; + * const million = 1_000_000; + * const bigNumber = 123_456_789n; + * const bigDecimal = 1_234.123_45; + * + * console.log(inspect(thousand, { numericSeparator: true })); + * // 1_000 + * console.log(inspect(million, { numericSeparator: true })); + * // 1_000_000 + * console.log(inspect(bigNumber, { numericSeparator: true })); + * // 123_456_789n + * console.log(inspect(bigDecimal, { numericSeparator: true })); + * // 1_234.123_45 + * ``` + * + * `util.inspect()` is a synchronous method intended for debugging. Its maximum + * output length is approximately 128 MiB. Inputs that result in longer output will + * be truncated. + * @since v0.3.0 + * @param object Any JavaScript primitive or `Object`. + * @return The representation of `object`. + */ + export function inspect(object: any, showHidden?: boolean, depth?: number | null, color?: boolean): string; + export function inspect(object: any, options?: InspectOptions): string; + export namespace inspect { + let colors: NodeJS.Dict<[number, number]>; + let styles: { + [K in Style]: string; + }; + let defaultOptions: InspectOptions; + /** + * Allows changing inspect settings from the repl. + */ + let replDefaults: InspectOptions; + /** + * That can be used to declare custom inspect functions. + */ + const custom: unique symbol; + } + /** + * Alias for [`Array.isArray()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/isArray). + * + * Returns `true` if the given `object` is an `Array`. Otherwise, returns `false`. + * + * ```js + * const util = require('node:util'); + * + * util.isArray([]); + * // Returns: true + * util.isArray(new Array()); + * // Returns: true + * util.isArray({}); + * // Returns: false + * ``` + * @since v0.6.0 + * @deprecated Since v4.0.0 - Use `isArray` instead. + */ + export function isArray(object: unknown): object is unknown[]; + /** + * Returns `true` if the given `object` is a `RegExp`. Otherwise, returns `false`. + * + * ```js + * const util = require('node:util'); + * + * util.isRegExp(/some regexp/); + * // Returns: true + * util.isRegExp(new RegExp('another regexp')); + * // Returns: true + * util.isRegExp({}); + * // Returns: false + * ``` + * @since v0.6.0 + * @deprecated Since v4.0.0 - Deprecated + */ + export function isRegExp(object: unknown): object is RegExp; + /** + * Returns `true` if the given `object` is a `Date`. Otherwise, returns `false`. + * + * ```js + * const util = require('node:util'); + * + * util.isDate(new Date()); + * // Returns: true + * util.isDate(Date()); + * // false (without 'new' returns a String) + * util.isDate({}); + * // Returns: false + * ``` + * @since v0.6.0 + * @deprecated Since v4.0.0 - Use {@link types.isDate} instead. + */ + export function isDate(object: unknown): object is Date; + /** + * Returns `true` if the given `object` is an `Error`. Otherwise, returns `false`. + * + * ```js + * const util = require('node:util'); + * + * util.isError(new Error()); + * // Returns: true + * util.isError(new TypeError()); + * // Returns: true + * util.isError({ name: 'Error', message: 'an error occurred' }); + * // Returns: false + * ``` + * + * This method relies on `Object.prototype.toString()` behavior. It is + * possible to obtain an incorrect result when the `object` argument manipulates `@@toStringTag`. + * + * ```js + * const util = require('node:util'); + * const obj = { name: 'Error', message: 'an error occurred' }; + * + * util.isError(obj); + * // Returns: false + * obj[Symbol.toStringTag] = 'Error'; + * util.isError(obj); + * // Returns: true + * ``` + * @since v0.6.0 + * @deprecated Since v4.0.0 - Use {@link types.isNativeError} instead. + */ + export function isError(object: unknown): object is Error; + /** + * Usage of `util.inherits()` is discouraged. Please use the ES6 `class` and `extends` keywords to get language level inheritance support. Also note + * that the two styles are [semantically incompatible](https://github.com/nodejs/node/issues/4179). + * + * Inherit the prototype methods from one [constructor](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/constructor) into another. The + * prototype of `constructor` will be set to a new object created from `superConstructor`. + * + * This mainly adds some input validation on top of`Object.setPrototypeOf(constructor.prototype, superConstructor.prototype)`. + * As an additional convenience, `superConstructor` will be accessible + * through the `constructor.super_` property. + * + * ```js + * const util = require('node:util'); + * const EventEmitter = require('node:events'); + * + * function MyStream() { + * EventEmitter.call(this); + * } + * + * util.inherits(MyStream, EventEmitter); + * + * MyStream.prototype.write = function(data) { + * this.emit('data', data); + * }; + * + * const stream = new MyStream(); + * + * console.log(stream instanceof EventEmitter); // true + * console.log(MyStream.super_ === EventEmitter); // true + * + * stream.on('data', (data) => { + * console.log(`Received data: "${data}"`); + * }); + * stream.write('It works!'); // Received data: "It works!" + * ``` + * + * ES6 example using `class` and `extends`: + * + * ```js + * const EventEmitter = require('node:events'); + * + * class MyStream extends EventEmitter { + * write(data) { + * this.emit('data', data); + * } + * } + * + * const stream = new MyStream(); + * + * stream.on('data', (data) => { + * console.log(`Received data: "${data}"`); + * }); + * stream.write('With ES6'); + * ``` + * @since v0.3.0 + * @legacy Use ES2015 class syntax and `extends` keyword instead. + */ + export function inherits(constructor: unknown, superConstructor: unknown): void; + export type DebugLoggerFunction = (msg: string, ...param: unknown[]) => void; + export interface DebugLogger extends DebugLoggerFunction { + enabled: boolean; + } + /** + * The `util.debuglog()` method is used to create a function that conditionally + * writes debug messages to `stderr` based on the existence of the `NODE_DEBUG`environment variable. If the `section` name appears within the value of that + * environment variable, then the returned function operates similar to `console.error()`. If not, then the returned function is a no-op. + * + * ```js + * const util = require('node:util'); + * const debuglog = util.debuglog('foo'); + * + * debuglog('hello from foo [%d]', 123); + * ``` + * + * If this program is run with `NODE_DEBUG=foo` in the environment, then + * it will output something like: + * + * ```console + * FOO 3245: hello from foo [123] + * ``` + * + * where `3245` is the process id. If it is not run with that + * environment variable set, then it will not print anything. + * + * The `section` supports wildcard also: + * + * ```js + * const util = require('node:util'); + * const debuglog = util.debuglog('foo-bar'); + * + * debuglog('hi there, it\'s foo-bar [%d]', 2333); + * ``` + * + * if it is run with `NODE_DEBUG=foo*` in the environment, then it will output + * something like: + * + * ```console + * FOO-BAR 3257: hi there, it's foo-bar [2333] + * ``` + * + * Multiple comma-separated `section` names may be specified in the `NODE_DEBUG`environment variable: `NODE_DEBUG=fs,net,tls`. + * + * The optional `callback` argument can be used to replace the logging function + * with a different function that doesn't have any initialization or + * unnecessary wrapping. + * + * ```js + * const util = require('node:util'); + * let debuglog = util.debuglog('internals', (debug) => { + * // Replace with a logging function that optimizes out + * // testing if the section is enabled + * debuglog = debug; + * }); + * ``` + * @since v0.11.3 + * @param section A string identifying the portion of the application for which the `debuglog` function is being created. + * @param callback A callback invoked the first time the logging function is called with a function argument that is a more optimized logging function. + * @return The logging function + */ + export function debuglog(section: string, callback?: (fn: DebugLoggerFunction) => void): DebugLogger; + export const debug: typeof debuglog; + /** + * Returns `true` if the given `object` is a `Boolean`. Otherwise, returns `false`. + * + * ```js + * const util = require('node:util'); + * + * util.isBoolean(1); + * // Returns: false + * util.isBoolean(0); + * // Returns: false + * util.isBoolean(false); + * // Returns: true + * ``` + * @since v0.11.5 + * @deprecated Since v4.0.0 - Use `typeof value === 'boolean'` instead. + */ + export function isBoolean(object: unknown): object is boolean; + /** + * Returns `true` if the given `object` is a `Buffer`. Otherwise, returns `false`. + * + * ```js + * const util = require('node:util'); + * + * util.isBuffer({ length: 0 }); + * // Returns: false + * util.isBuffer([]); + * // Returns: false + * util.isBuffer(Buffer.from('hello world')); + * // Returns: true + * ``` + * @since v0.11.5 + * @deprecated Since v4.0.0 - Use `isBuffer` instead. + */ + export function isBuffer(object: unknown): object is Buffer; + /** + * Returns `true` if the given `object` is a `Function`. Otherwise, returns `false`. + * + * ```js + * const util = require('node:util'); + * + * function Foo() {} + * const Bar = () => {}; + * + * util.isFunction({}); + * // Returns: false + * util.isFunction(Foo); + * // Returns: true + * util.isFunction(Bar); + * // Returns: true + * ``` + * @since v0.11.5 + * @deprecated Since v4.0.0 - Use `typeof value === 'function'` instead. + */ + export function isFunction(object: unknown): boolean; + /** + * Returns `true` if the given `object` is strictly `null`. Otherwise, returns`false`. + * + * ```js + * const util = require('node:util'); + * + * util.isNull(0); + * // Returns: false + * util.isNull(undefined); + * // Returns: false + * util.isNull(null); + * // Returns: true + * ``` + * @since v0.11.5 + * @deprecated Since v4.0.0 - Use `value === null` instead. + */ + export function isNull(object: unknown): object is null; + /** + * Returns `true` if the given `object` is `null` or `undefined`. Otherwise, + * returns `false`. + * + * ```js + * const util = require('node:util'); + * + * util.isNullOrUndefined(0); + * // Returns: false + * util.isNullOrUndefined(undefined); + * // Returns: true + * util.isNullOrUndefined(null); + * // Returns: true + * ``` + * @since v0.11.5 + * @deprecated Since v4.0.0 - Use `value === undefined || value === null` instead. + */ + export function isNullOrUndefined(object: unknown): object is null | undefined; + /** + * Returns `true` if the given `object` is a `Number`. Otherwise, returns `false`. + * + * ```js + * const util = require('node:util'); + * + * util.isNumber(false); + * // Returns: false + * util.isNumber(Infinity); + * // Returns: true + * util.isNumber(0); + * // Returns: true + * util.isNumber(NaN); + * // Returns: true + * ``` + * @since v0.11.5 + * @deprecated Since v4.0.0 - Use `typeof value === 'number'` instead. + */ + export function isNumber(object: unknown): object is number; + /** + * Returns `true` if the given `object` is strictly an `Object`**and** not a`Function` (even though functions are objects in JavaScript). + * Otherwise, returns `false`. + * + * ```js + * const util = require('node:util'); + * + * util.isObject(5); + * // Returns: false + * util.isObject(null); + * // Returns: false + * util.isObject({}); + * // Returns: true + * util.isObject(() => {}); + * // Returns: false + * ``` + * @since v0.11.5 + * @deprecated Since v4.0.0 - Use `value !== null && typeof value === 'object'` instead. + */ + export function isObject(object: unknown): boolean; + /** + * Returns `true` if the given `object` is a primitive type. Otherwise, returns`false`. + * + * ```js + * const util = require('node:util'); + * + * util.isPrimitive(5); + * // Returns: true + * util.isPrimitive('foo'); + * // Returns: true + * util.isPrimitive(false); + * // Returns: true + * util.isPrimitive(null); + * // Returns: true + * util.isPrimitive(undefined); + * // Returns: true + * util.isPrimitive({}); + * // Returns: false + * util.isPrimitive(() => {}); + * // Returns: false + * util.isPrimitive(/^$/); + * // Returns: false + * util.isPrimitive(new Date()); + * // Returns: false + * ``` + * @since v0.11.5 + * @deprecated Since v4.0.0 - Use `(typeof value !== 'object' && typeof value !== 'function') || value === null` instead. + */ + export function isPrimitive(object: unknown): boolean; + /** + * Returns `true` if the given `object` is a `string`. Otherwise, returns `false`. + * + * ```js + * const util = require('node:util'); + * + * util.isString(''); + * // Returns: true + * util.isString('foo'); + * // Returns: true + * util.isString(String('foo')); + * // Returns: true + * util.isString(5); + * // Returns: false + * ``` + * @since v0.11.5 + * @deprecated Since v4.0.0 - Use `typeof value === 'string'` instead. + */ + export function isString(object: unknown): object is string; + /** + * Returns `true` if the given `object` is a `Symbol`. Otherwise, returns `false`. + * + * ```js + * const util = require('node:util'); + * + * util.isSymbol(5); + * // Returns: false + * util.isSymbol('foo'); + * // Returns: false + * util.isSymbol(Symbol('foo')); + * // Returns: true + * ``` + * @since v0.11.5 + * @deprecated Since v4.0.0 - Use `typeof value === 'symbol'` instead. + */ + export function isSymbol(object: unknown): object is symbol; + /** + * Returns `true` if the given `object` is `undefined`. Otherwise, returns `false`. + * + * ```js + * const util = require('node:util'); + * + * const foo = undefined; + * util.isUndefined(5); + * // Returns: false + * util.isUndefined(foo); + * // Returns: true + * util.isUndefined(null); + * // Returns: false + * ``` + * @since v0.11.5 + * @deprecated Since v4.0.0 - Use `value === undefined` instead. + */ + export function isUndefined(object: unknown): object is undefined; + /** + * The `util.deprecate()` method wraps `fn` (which may be a function or class) in + * such a way that it is marked as deprecated. + * + * ```js + * const util = require('node:util'); + * + * exports.obsoleteFunction = util.deprecate(() => { + * // Do something here. + * }, 'obsoleteFunction() is deprecated. Use newShinyFunction() instead.'); + * ``` + * + * When called, `util.deprecate()` will return a function that will emit a `DeprecationWarning` using the `'warning'` event. The warning will + * be emitted and printed to `stderr` the first time the returned function is + * called. After the warning is emitted, the wrapped function is called without + * emitting a warning. + * + * If the same optional `code` is supplied in multiple calls to `util.deprecate()`, + * the warning will be emitted only once for that `code`. + * + * ```js + * const util = require('node:util'); + * + * const fn1 = util.deprecate(someFunction, someMessage, 'DEP0001'); + * const fn2 = util.deprecate(someOtherFunction, someOtherMessage, 'DEP0001'); + * fn1(); // Emits a deprecation warning with code DEP0001 + * fn2(); // Does not emit a deprecation warning because it has the same code + * ``` + * + * If either the `--no-deprecation` or `--no-warnings` command-line flags are + * used, or if the `process.noDeprecation` property is set to `true`_prior_ to + * the first deprecation warning, the `util.deprecate()` method does nothing. + * + * If the `--trace-deprecation` or `--trace-warnings` command-line flags are set, + * or the `process.traceDeprecation` property is set to `true`, a warning and a + * stack trace are printed to `stderr` the first time the deprecated function is + * called. + * + * If the `--throw-deprecation` command-line flag is set, or the `process.throwDeprecation` property is set to `true`, then an exception will be + * thrown when the deprecated function is called. + * + * The `--throw-deprecation` command-line flag and `process.throwDeprecation` property take precedence over `--trace-deprecation` and `process.traceDeprecation`. + * @since v0.8.0 + * @param fn The function that is being deprecated. + * @param msg A warning message to display when the deprecated function is invoked. + * @param code A deprecation code. See the `list of deprecated APIs` for a list of codes. + * @return The deprecated function wrapped to emit a warning. + */ + export function deprecate(fn: T, msg: string, code?: string): T; + /** + * Returns `true` if there is deep strict equality between `val1` and `val2`. + * Otherwise, returns `false`. + * + * See `assert.deepStrictEqual()` for more information about deep strict + * equality. + * @since v9.0.0 + */ + export function isDeepStrictEqual(val1: unknown, val2: unknown): boolean; + /** + * Returns `str` with any ANSI escape codes removed. + * + * ```js + * console.log(util.stripVTControlCharacters('\u001B[4mvalue\u001B[0m')); + * // Prints "value" + * ``` + * @since v16.11.0 + */ + export function stripVTControlCharacters(str: string): string; + /** + * Takes an `async` function (or a function that returns a `Promise`) and returns a + * function following the error-first callback style, i.e. taking + * an `(err, value) => ...` callback as the last argument. In the callback, the + * first argument will be the rejection reason (or `null` if the `Promise` resolved), and the second argument will be the resolved value. + * + * ```js + * const util = require('node:util'); + * + * async function fn() { + * return 'hello world'; + * } + * const callbackFunction = util.callbackify(fn); + * + * callbackFunction((err, ret) => { + * if (err) throw err; + * console.log(ret); + * }); + * ``` + * + * Will print: + * + * ```text + * hello world + * ``` + * + * The callback is executed asynchronously, and will have a limited stack trace. + * If the callback throws, the process will emit an `'uncaughtException'` event, and if not handled will exit. + * + * Since `null` has a special meaning as the first argument to a callback, if a + * wrapped function rejects a `Promise` with a falsy value as a reason, the value + * is wrapped in an `Error` with the original value stored in a field named `reason`. + * + * ```js + * function fn() { + * return Promise.reject(null); + * } + * const callbackFunction = util.callbackify(fn); + * + * callbackFunction((err, ret) => { + * // When the Promise was rejected with `null` it is wrapped with an Error and + * // the original value is stored in `reason`. + * err && Object.hasOwn(err, 'reason') && err.reason === null; // true + * }); + * ``` + * @since v8.2.0 + * @param fn An `async` function + * @return a callback style function + */ + export function callbackify(fn: () => Promise): (callback: (err: NodeJS.ErrnoException) => void) => void; + export function callbackify( + fn: () => Promise, + ): (callback: (err: NodeJS.ErrnoException, result: TResult) => void) => void; + export function callbackify( + fn: (arg1: T1) => Promise, + ): (arg1: T1, callback: (err: NodeJS.ErrnoException) => void) => void; + export function callbackify( + fn: (arg1: T1) => Promise, + ): (arg1: T1, callback: (err: NodeJS.ErrnoException, result: TResult) => void) => void; + export function callbackify( + fn: (arg1: T1, arg2: T2) => Promise, + ): (arg1: T1, arg2: T2, callback: (err: NodeJS.ErrnoException) => void) => void; + export function callbackify( + fn: (arg1: T1, arg2: T2) => Promise, + ): (arg1: T1, arg2: T2, callback: (err: NodeJS.ErrnoException | null, result: TResult) => void) => void; + export function callbackify( + fn: (arg1: T1, arg2: T2, arg3: T3) => Promise, + ): (arg1: T1, arg2: T2, arg3: T3, callback: (err: NodeJS.ErrnoException) => void) => void; + export function callbackify( + fn: (arg1: T1, arg2: T2, arg3: T3) => Promise, + ): (arg1: T1, arg2: T2, arg3: T3, callback: (err: NodeJS.ErrnoException | null, result: TResult) => void) => void; + export function callbackify( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => Promise, + ): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, callback: (err: NodeJS.ErrnoException) => void) => void; + export function callbackify( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => Promise, + ): ( + arg1: T1, + arg2: T2, + arg3: T3, + arg4: T4, + callback: (err: NodeJS.ErrnoException | null, result: TResult) => void, + ) => void; + export function callbackify( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5) => Promise, + ): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, callback: (err: NodeJS.ErrnoException) => void) => void; + export function callbackify( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5) => Promise, + ): ( + arg1: T1, + arg2: T2, + arg3: T3, + arg4: T4, + arg5: T5, + callback: (err: NodeJS.ErrnoException | null, result: TResult) => void, + ) => void; + export function callbackify( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, arg6: T6) => Promise, + ): ( + arg1: T1, + arg2: T2, + arg3: T3, + arg4: T4, + arg5: T5, + arg6: T6, + callback: (err: NodeJS.ErrnoException) => void, + ) => void; + export function callbackify( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, arg6: T6) => Promise, + ): ( + arg1: T1, + arg2: T2, + arg3: T3, + arg4: T4, + arg5: T5, + arg6: T6, + callback: (err: NodeJS.ErrnoException | null, result: TResult) => void, + ) => void; + export interface CustomPromisifyLegacy extends Function { + __promisify__: TCustom; + } + export interface CustomPromisifySymbol extends Function { + [promisify.custom]: TCustom; + } + export type CustomPromisify = + | CustomPromisifySymbol + | CustomPromisifyLegacy; + /** + * Takes a function following the common error-first callback style, i.e. taking + * an `(err, value) => ...` callback as the last argument, and returns a version + * that returns promises. + * + * ```js + * const util = require('node:util'); + * const fs = require('node:fs'); + * + * const stat = util.promisify(fs.stat); + * stat('.').then((stats) => { + * // Do something with `stats` + * }).catch((error) => { + * // Handle the error. + * }); + * ``` + * + * Or, equivalently using `async function`s: + * + * ```js + * const util = require('node:util'); + * const fs = require('node:fs'); + * + * const stat = util.promisify(fs.stat); + * + * async function callStat() { + * const stats = await stat('.'); + * console.log(`This directory is owned by ${stats.uid}`); + * } + * + * callStat(); + * ``` + * + * If there is an `original[util.promisify.custom]` property present, `promisify` will return its value, see `Custom promisified functions`. + * + * `promisify()` assumes that `original` is a function taking a callback as its + * final argument in all cases. If `original` is not a function, `promisify()` will throw an error. If `original` is a function but its last argument is not + * an error-first callback, it will still be passed an error-first + * callback as its last argument. + * + * Using `promisify()` on class methods or other methods that use `this` may not + * work as expected unless handled specially: + * + * ```js + * const util = require('node:util'); + * + * class Foo { + * constructor() { + * this.a = 42; + * } + * + * bar(callback) { + * callback(null, this.a); + * } + * } + * + * const foo = new Foo(); + * + * const naiveBar = util.promisify(foo.bar); + * // TypeError: Cannot read property 'a' of undefined + * // naiveBar().then(a => console.log(a)); + * + * naiveBar.call(foo).then((a) => console.log(a)); // '42' + * + * const bindBar = naiveBar.bind(foo); + * bindBar().then((a) => console.log(a)); // '42' + * ``` + * @since v8.0.0 + */ + export function promisify(fn: CustomPromisify): TCustom; + export function promisify( + fn: (callback: (err: any, result: TResult) => void) => void, + ): () => Promise; + export function promisify(fn: (callback: (err?: any) => void) => void): () => Promise; + export function promisify( + fn: (arg1: T1, callback: (err: any, result: TResult) => void) => void, + ): (arg1: T1) => Promise; + export function promisify(fn: (arg1: T1, callback: (err?: any) => void) => void): (arg1: T1) => Promise; + export function promisify( + fn: (arg1: T1, arg2: T2, callback: (err: any, result: TResult) => void) => void, + ): (arg1: T1, arg2: T2) => Promise; + export function promisify( + fn: (arg1: T1, arg2: T2, callback: (err?: any) => void) => void, + ): (arg1: T1, arg2: T2) => Promise; + export function promisify( + fn: (arg1: T1, arg2: T2, arg3: T3, callback: (err: any, result: TResult) => void) => void, + ): (arg1: T1, arg2: T2, arg3: T3) => Promise; + export function promisify( + fn: (arg1: T1, arg2: T2, arg3: T3, callback: (err?: any) => void) => void, + ): (arg1: T1, arg2: T2, arg3: T3) => Promise; + export function promisify( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, callback: (err: any, result: TResult) => void) => void, + ): (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => Promise; + export function promisify( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, callback: (err?: any) => void) => void, + ): (arg1: T1, arg2: T2, arg3: T3, arg4: T4) => Promise; + export function promisify( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, callback: (err: any, result: TResult) => void) => void, + ): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5) => Promise; + export function promisify( + fn: (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5, callback: (err?: any) => void) => void, + ): (arg1: T1, arg2: T2, arg3: T3, arg4: T4, arg5: T5) => Promise; + export function promisify(fn: Function): Function; + export namespace promisify { + /** + * That can be used to declare custom promisified variants of functions. + */ + const custom: unique symbol; + } + /** + * Stability: 1.1 - Active development + * Given an example `.env` file: + * + * ```js + * const { parseEnv } = require('node:util'); + * + * parseEnv('HELLO=world\nHELLO=oh my\n'); + * // Returns: { HELLO: 'oh my' } + * ``` + * @param content The raw contents of a `.env` file. + * @since v20.12.0 + */ + export function parseEnv(content: string): object; + // https://nodejs.org/docs/latest/api/util.html#foreground-colors + type ForegroundColors = + | "black" + | "blackBright" + | "blue" + | "blueBright" + | "cyan" + | "cyanBright" + | "gray" + | "green" + | "greenBright" + | "grey" + | "magenta" + | "magentaBright" + | "red" + | "redBright" + | "white" + | "whiteBright" + | "yellow" + | "yellowBright"; + // https://nodejs.org/docs/latest/api/util.html#background-colors + type BackgroundColors = + | "bgBlack" + | "bgBlackBright" + | "bgBlue" + | "bgBlueBright" + | "bgCyan" + | "bgCyanBright" + | "bgGray" + | "bgGreen" + | "bgGreenBright" + | "bgGrey" + | "bgMagenta" + | "bgMagentaBright" + | "bgRed" + | "bgRedBright" + | "bgWhite" + | "bgWhiteBright" + | "bgYellow" + | "bgYellowBright"; + // https://nodejs.org/docs/latest/api/util.html#modifiers + type Modifiers = + | "blink" + | "bold" + | "dim" + | "doubleunderline" + | "framed" + | "hidden" + | "inverse" + | "italic" + | "overlined" + | "reset" + | "strikethrough" + | "underline"; + /** + * Stability: 1.1 - Active development + * + * This function returns a formatted text considering the `format` passed. + * + * ```js + * const { styleText } = require('node:util'); + * const errorMessage = styleText('red', 'Error! Error!'); + * console.log(errorMessage); + * ``` + * + * `util.inspect.colors` also provides text formats such as `italic`, and `underline` and you can combine both: + * + * ```js + * console.log( + * util.styleText(['underline', 'italic'], 'My italic underlined message'), + * ); + * ``` + * + * When passing an array of formats, the order of the format applied is left to right so the following style + * might overwrite the previous one. + * + * ```js + * console.log( + * util.styleText(['red', 'green'], 'text'), // green + * ); + * ``` + * + * The full list of formats can be found in [modifiers](https://nodejs.org/docs/latest-v20.x/api/util.html#modifiers). + * @param format A text format or an Array of text formats defined in `util.inspect.colors`. + * @param text The text to to be formatted. + * @since v20.12.0 + */ + export function styleText( + format: + | ForegroundColors + | BackgroundColors + | Modifiers + | Array, + text: string, + ): string; + /** + * An implementation of the [WHATWG Encoding Standard](https://encoding.spec.whatwg.org/) `TextDecoder` API. + * + * ```js + * const decoder = new TextDecoder(); + * const u8arr = new Uint8Array([72, 101, 108, 108, 111]); + * console.log(decoder.decode(u8arr)); // Hello + * ``` + * @since v8.3.0 + */ + export class TextDecoder { + /** + * The encoding supported by the `TextDecoder` instance. + */ + readonly encoding: string; + /** + * The value will be `true` if decoding errors result in a `TypeError` being + * thrown. + */ + readonly fatal: boolean; + /** + * The value will be `true` if the decoding result will include the byte order + * mark. + */ + readonly ignoreBOM: boolean; + constructor( + encoding?: string, + options?: { + fatal?: boolean | undefined; + ignoreBOM?: boolean | undefined; + }, + ); + /** + * Decodes the `input` and returns a string. If `options.stream` is `true`, any + * incomplete byte sequences occurring at the end of the `input` are buffered + * internally and emitted after the next call to `textDecoder.decode()`. + * + * If `textDecoder.fatal` is `true`, decoding errors that occur will result in a `TypeError` being thrown. + * @param input An `ArrayBuffer`, `DataView`, or `TypedArray` instance containing the encoded data. + */ + decode( + input?: NodeJS.ArrayBufferView | ArrayBuffer | null, + options?: { + stream?: boolean | undefined; + }, + ): string; + } + export interface EncodeIntoResult { + /** + * The read Unicode code units of input. + */ + read: number; + /** + * The written UTF-8 bytes of output. + */ + written: number; + } + export { types }; + + //// TextEncoder/Decoder + /** + * An implementation of the [WHATWG Encoding Standard](https://encoding.spec.whatwg.org/) `TextEncoder` API. All + * instances of `TextEncoder` only support UTF-8 encoding. + * + * ```js + * const encoder = new TextEncoder(); + * const uint8array = encoder.encode('this is some data'); + * ``` + * + * The `TextEncoder` class is also available on the global object. + * @since v8.3.0 + */ + export class TextEncoder { + /** + * The encoding supported by the `TextEncoder` instance. Always set to `'utf-8'`. + */ + readonly encoding: string; + /** + * UTF-8 encodes the `input` string and returns a `Uint8Array` containing the + * encoded bytes. + * @param [input='an empty string'] The text to encode. + */ + encode(input?: string): Uint8Array; + /** + * UTF-8 encodes the `src` string to the `dest` Uint8Array and returns an object + * containing the read Unicode code units and written UTF-8 bytes. + * + * ```js + * const encoder = new TextEncoder(); + * const src = 'this is some data'; + * const dest = new Uint8Array(10); + * const { read, written } = encoder.encodeInto(src, dest); + * ``` + * @param src The text to encode. + * @param dest The array to hold the encode result. + */ + encodeInto(src: string, dest: Uint8Array): EncodeIntoResult; + } + import { TextDecoder as _TextDecoder, TextEncoder as _TextEncoder } from "util"; + global { + /** + * `TextDecoder` class is a global reference for `require('util').TextDecoder` + * https://nodejs.org/api/globals.html#textdecoder + * @since v11.0.0 + */ + var TextDecoder: typeof globalThis extends { + onmessage: any; + TextDecoder: infer TextDecoder; + } ? TextDecoder + : typeof _TextDecoder; + /** + * `TextEncoder` class is a global reference for `require('util').TextEncoder` + * https://nodejs.org/api/globals.html#textencoder + * @since v11.0.0 + */ + var TextEncoder: typeof globalThis extends { + onmessage: any; + TextEncoder: infer TextEncoder; + } ? TextEncoder + : typeof _TextEncoder; + } + + //// parseArgs + /** + * Provides a higher level API for command-line argument parsing than interacting + * with `process.argv` directly. Takes a specification for the expected arguments + * and returns a structured object with the parsed options and positionals. + * + * ```js + * import { parseArgs } from 'node:util'; + * const args = ['-f', '--bar', 'b']; + * const options = { + * foo: { + * type: 'boolean', + * short: 'f', + * }, + * bar: { + * type: 'string', + * }, + * }; + * const { + * values, + * positionals, + * } = parseArgs({ args, options }); + * console.log(values, positionals); + * // Prints: [Object: null prototype] { foo: true, bar: 'b' } [] + * ``` + * @since v18.3.0, v16.17.0 + * @param config Used to provide arguments for parsing and to configure the parser. `config` supports the following properties: + * @return The parsed command line arguments: + */ + export function parseArgs(config?: T): ParsedResults; + interface ParseArgsOptionConfig { + /** + * Type of argument. + */ + type: "string" | "boolean"; + /** + * Whether this option can be provided multiple times. + * If `true`, all values will be collected in an array. + * If `false`, values for the option are last-wins. + * @default false. + */ + multiple?: boolean | undefined; + /** + * A single character alias for the option. + */ + short?: string | undefined; + /** + * The default option value when it is not set by args. + * It must be of the same type as the the `type` property. + * When `multiple` is `true`, it must be an array. + * @since v18.11.0 + */ + default?: string | boolean | string[] | boolean[] | undefined; + } + interface ParseArgsOptionsConfig { + [longOption: string]: ParseArgsOptionConfig; + } + export interface ParseArgsConfig { + /** + * Array of argument strings. + */ + args?: string[] | undefined; + /** + * Used to describe arguments known to the parser. + */ + options?: ParseArgsOptionsConfig | undefined; + /** + * Should an error be thrown when unknown arguments are encountered, + * or when arguments are passed that do not match the `type` configured in `options`. + * @default true + */ + strict?: boolean | undefined; + /** + * Whether this command accepts positional arguments. + */ + allowPositionals?: boolean | undefined; + /** + * Return the parsed tokens. This is useful for extending the built-in behavior, + * from adding additional checks through to reprocessing the tokens in different ways. + * @default false + */ + tokens?: boolean | undefined; + } + /* + IfDefaultsTrue and IfDefaultsFalse are helpers to handle default values for missing boolean properties. + TypeScript does not have exact types for objects: https://github.com/microsoft/TypeScript/issues/12936 + This means it is impossible to distinguish between "field X is definitely not present" and "field X may or may not be present". + But we expect users to generally provide their config inline or `as const`, which means TS will always know whether a given field is present. + So this helper treats "not definitely present" (i.e., not `extends boolean`) as being "definitely not present", i.e. it should have its default value. + This is technically incorrect but is a much nicer UX for the common case. + The IfDefaultsTrue version is for things which default to true; the IfDefaultsFalse version is for things which default to false. + */ + type IfDefaultsTrue = T extends true ? IfTrue + : T extends false ? IfFalse + : IfTrue; + + // we put the `extends false` condition first here because `undefined` compares like `any` when `strictNullChecks: false` + type IfDefaultsFalse = T extends false ? IfFalse + : T extends true ? IfTrue + : IfFalse; + + type ExtractOptionValue = IfDefaultsTrue< + T["strict"], + O["type"] extends "string" ? string : O["type"] extends "boolean" ? boolean : string | boolean, + string | boolean + >; + + type ParsedValues = + & IfDefaultsTrue + & (T["options"] extends ParseArgsOptionsConfig ? { + -readonly [LongOption in keyof T["options"]]: IfDefaultsFalse< + T["options"][LongOption]["multiple"], + undefined | Array>, + undefined | ExtractOptionValue + >; + } + : {}); + + type ParsedPositionals = IfDefaultsTrue< + T["strict"], + IfDefaultsFalse, + IfDefaultsTrue + >; + + type PreciseTokenForOptions< + K extends string, + O extends ParseArgsOptionConfig, + > = O["type"] extends "string" ? { + kind: "option"; + index: number; + name: K; + rawName: string; + value: string; + inlineValue: boolean; + } + : O["type"] extends "boolean" ? { + kind: "option"; + index: number; + name: K; + rawName: string; + value: undefined; + inlineValue: undefined; + } + : OptionToken & { name: K }; + + type TokenForOptions< + T extends ParseArgsConfig, + K extends keyof T["options"] = keyof T["options"], + > = K extends unknown + ? T["options"] extends ParseArgsOptionsConfig ? PreciseTokenForOptions + : OptionToken + : never; + + type ParsedOptionToken = IfDefaultsTrue, OptionToken>; + + type ParsedPositionalToken = IfDefaultsTrue< + T["strict"], + IfDefaultsFalse, + IfDefaultsTrue + >; + + type ParsedTokens = Array< + ParsedOptionToken | ParsedPositionalToken | { kind: "option-terminator"; index: number } + >; + + type PreciseParsedResults = IfDefaultsFalse< + T["tokens"], + { + values: ParsedValues; + positionals: ParsedPositionals; + tokens: ParsedTokens; + }, + { + values: ParsedValues; + positionals: ParsedPositionals; + } + >; + + type OptionToken = + | { kind: "option"; index: number; name: string; rawName: string; value: string; inlineValue: boolean } + | { + kind: "option"; + index: number; + name: string; + rawName: string; + value: undefined; + inlineValue: undefined; + }; + + type Token = + | OptionToken + | { kind: "positional"; index: number; value: string } + | { kind: "option-terminator"; index: number }; + + // If ParseArgsConfig extends T, then the user passed config constructed elsewhere. + // So we can't rely on the `"not definitely present" implies "definitely not present"` assumption mentioned above. + type ParsedResults = ParseArgsConfig extends T ? { + values: { + [longOption: string]: undefined | string | boolean | Array; + }; + positionals: string[]; + tokens?: Token[]; + } + : PreciseParsedResults; + + /** + * An implementation of [the MIMEType class](https://bmeck.github.io/node-proposal-mime-api/). + * + * In accordance with browser conventions, all properties of `MIMEType` objects + * are implemented as getters and setters on the class prototype, rather than as + * data properties on the object itself. + * + * A MIME string is a structured string containing multiple meaningful + * components. When parsed, a `MIMEType` object is returned containing + * properties for each of these components. + * @since v19.1.0, v18.13.0 + * @experimental + */ + export class MIMEType { + /** + * Creates a new MIMEType object by parsing the input. + * + * A `TypeError` will be thrown if the `input` is not a valid MIME. + * Note that an effort will be made to coerce the given values into strings. + * @param input The input MIME to parse. + */ + constructor(input: string | { toString: () => string }); + + /** + * Gets and sets the type portion of the MIME. + * + * ```js + * import { MIMEType } from 'node:util'; + * + * const myMIME = new MIMEType('text/javascript'); + * console.log(myMIME.type); + * // Prints: text + * myMIME.type = 'application'; + * console.log(myMIME.type); + * // Prints: application + * console.log(String(myMIME)); + * // Prints: application/javascript + * ``` + */ + type: string; + /** + * Gets and sets the subtype portion of the MIME. + * + * ```js + * import { MIMEType } from 'node:util'; + * + * const myMIME = new MIMEType('text/ecmascript'); + * console.log(myMIME.subtype); + * // Prints: ecmascript + * myMIME.subtype = 'javascript'; + * console.log(myMIME.subtype); + * // Prints: javascript + * console.log(String(myMIME)); + * // Prints: text/javascript + * ``` + */ + subtype: string; + /** + * Gets the essence of the MIME. This property is read only. + * Use `mime.type` or `mime.subtype` to alter the MIME. + * + * ```js + * import { MIMEType } from 'node:util'; + * + * const myMIME = new MIMEType('text/javascript;key=value'); + * console.log(myMIME.essence); + * // Prints: text/javascript + * myMIME.type = 'application'; + * console.log(myMIME.essence); + * // Prints: application/javascript + * console.log(String(myMIME)); + * // Prints: application/javascript;key=value + * ``` + */ + readonly essence: string; + /** + * Gets the `MIMEParams` object representing the + * parameters of the MIME. This property is read-only. See `MIMEParams` documentation for details. + */ + readonly params: MIMEParams; + /** + * The `toString()` method on the `MIMEType` object returns the serialized MIME. + * + * Because of the need for standard compliance, this method does not allow users + * to customize the serialization process of the MIME. + */ + toString(): string; + } + /** + * The `MIMEParams` API provides read and write access to the parameters of a `MIMEType`. + * @since v19.1.0, v18.13.0 + */ + export class MIMEParams { + /** + * Remove all name-value pairs whose name is `name`. + */ + delete(name: string): void; + /** + * Returns an iterator over each of the name-value pairs in the parameters. + * Each item of the iterator is a JavaScript `Array`. The first item of the array + * is the `name`, the second item of the array is the `value`. + */ + entries(): IterableIterator<[name: string, value: string]>; + /** + * Returns the value of the first name-value pair whose name is `name`. If there + * are no such pairs, `null` is returned. + * @return or `null` if there is no name-value pair with the given `name`. + */ + get(name: string): string | null; + /** + * Returns `true` if there is at least one name-value pair whose name is `name`. + */ + has(name: string): boolean; + /** + * Returns an iterator over the names of each name-value pair. + * + * ```js + * import { MIMEType } from 'node:util'; + * + * const { params } = new MIMEType('text/plain;foo=0;bar=1'); + * for (const name of params.keys()) { + * console.log(name); + * } + * // Prints: + * // foo + * // bar + * ``` + */ + keys(): IterableIterator; + /** + * Sets the value in the `MIMEParams` object associated with `name` to `value`. If there are any pre-existing name-value pairs whose names are `name`, + * set the first such pair's value to `value`. + * + * ```js + * import { MIMEType } from 'node:util'; + * + * const { params } = new MIMEType('text/plain;foo=0;bar=1'); + * params.set('foo', 'def'); + * params.set('baz', 'xyz'); + * console.log(params.toString()); + * // Prints: foo=def;bar=1;baz=xyz + * ``` + */ + set(name: string, value: string): void; + /** + * Returns an iterator over the values of each name-value pair. + */ + values(): IterableIterator; + /** + * Returns an iterator over each of the name-value pairs in the parameters. + */ + [Symbol.iterator]: typeof MIMEParams.prototype.entries; + } +} +declare module "util/types" { + import { KeyObject, webcrypto } from "node:crypto"; + /** + * Returns `true` if the value is a built-in [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) or + * [`SharedArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer) instance. + * + * See also `util.types.isArrayBuffer()` and `util.types.isSharedArrayBuffer()`. + * + * ```js + * util.types.isAnyArrayBuffer(new ArrayBuffer()); // Returns true + * util.types.isAnyArrayBuffer(new SharedArrayBuffer()); // Returns true + * ``` + * @since v10.0.0 + */ + function isAnyArrayBuffer(object: unknown): object is ArrayBufferLike; + /** + * Returns `true` if the value is an `arguments` object. + * + * ```js + * function foo() { + * util.types.isArgumentsObject(arguments); // Returns true + * } + * ``` + * @since v10.0.0 + */ + function isArgumentsObject(object: unknown): object is IArguments; + /** + * Returns `true` if the value is a built-in [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) instance. + * This does _not_ include [`SharedArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer) instances. Usually, it is + * desirable to test for both; See `util.types.isAnyArrayBuffer()` for that. + * + * ```js + * util.types.isArrayBuffer(new ArrayBuffer()); // Returns true + * util.types.isArrayBuffer(new SharedArrayBuffer()); // Returns false + * ``` + * @since v10.0.0 + */ + function isArrayBuffer(object: unknown): object is ArrayBuffer; + /** + * Returns `true` if the value is an instance of one of the [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) views, such as typed + * array objects or [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView). Equivalent to + * [`ArrayBuffer.isView()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer/isView). + * + * ```js + * util.types.isArrayBufferView(new Int8Array()); // true + * util.types.isArrayBufferView(Buffer.from('hello world')); // true + * util.types.isArrayBufferView(new DataView(new ArrayBuffer(16))); // true + * util.types.isArrayBufferView(new ArrayBuffer()); // false + * ``` + * @since v10.0.0 + */ + function isArrayBufferView(object: unknown): object is NodeJS.ArrayBufferView; + /** + * Returns `true` if the value is an [async function](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/async_function). + * This only reports back what the JavaScript engine is seeing; + * in particular, the return value may not match the original source code if + * a transpilation tool was used. + * + * ```js + * util.types.isAsyncFunction(function foo() {}); // Returns false + * util.types.isAsyncFunction(async function foo() {}); // Returns true + * ``` + * @since v10.0.0 + */ + function isAsyncFunction(object: unknown): boolean; + /** + * Returns `true` if the value is a `BigInt64Array` instance. + * + * ```js + * util.types.isBigInt64Array(new BigInt64Array()); // Returns true + * util.types.isBigInt64Array(new BigUint64Array()); // Returns false + * ``` + * @since v10.0.0 + */ + function isBigInt64Array(value: unknown): value is BigInt64Array; + /** + * Returns `true` if the value is a `BigUint64Array` instance. + * + * ```js + * util.types.isBigUint64Array(new BigInt64Array()); // Returns false + * util.types.isBigUint64Array(new BigUint64Array()); // Returns true + * ``` + * @since v10.0.0 + */ + function isBigUint64Array(value: unknown): value is BigUint64Array; + /** + * Returns `true` if the value is a boolean object, e.g. created + * by `new Boolean()`. + * + * ```js + * util.types.isBooleanObject(false); // Returns false + * util.types.isBooleanObject(true); // Returns false + * util.types.isBooleanObject(new Boolean(false)); // Returns true + * util.types.isBooleanObject(new Boolean(true)); // Returns true + * util.types.isBooleanObject(Boolean(false)); // Returns false + * util.types.isBooleanObject(Boolean(true)); // Returns false + * ``` + * @since v10.0.0 + */ + function isBooleanObject(object: unknown): object is Boolean; + /** + * Returns `true` if the value is any boxed primitive object, e.g. created + * by `new Boolean()`, `new String()` or `Object(Symbol())`. + * + * For example: + * + * ```js + * util.types.isBoxedPrimitive(false); // Returns false + * util.types.isBoxedPrimitive(new Boolean(false)); // Returns true + * util.types.isBoxedPrimitive(Symbol('foo')); // Returns false + * util.types.isBoxedPrimitive(Object(Symbol('foo'))); // Returns true + * util.types.isBoxedPrimitive(Object(BigInt(5))); // Returns true + * ``` + * @since v10.11.0 + */ + function isBoxedPrimitive(object: unknown): object is String | Number | BigInt | Boolean | Symbol; + /** + * Returns `true` if the value is a built-in [`DataView`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/DataView) instance. + * + * ```js + * const ab = new ArrayBuffer(20); + * util.types.isDataView(new DataView(ab)); // Returns true + * util.types.isDataView(new Float64Array()); // Returns false + * ``` + * + * See also [`ArrayBuffer.isView()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer/isView). + * @since v10.0.0 + */ + function isDataView(object: unknown): object is DataView; + /** + * Returns `true` if the value is a built-in [`Date`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date) instance. + * + * ```js + * util.types.isDate(new Date()); // Returns true + * ``` + * @since v10.0.0 + */ + function isDate(object: unknown): object is Date; + /** + * Returns `true` if the value is a native `External` value. + * + * A native `External` value is a special type of object that contains a + * raw C++ pointer (`void*`) for access from native code, and has no other + * properties. Such objects are created either by Node.js internals or native + * addons. In JavaScript, they are [frozen](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/freeze) objects with a`null` prototype. + * + * ```c + * #include + * #include + * napi_value result; + * static napi_value MyNapi(napi_env env, napi_callback_info info) { + * int* raw = (int*) malloc(1024); + * napi_status status = napi_create_external(env, (void*) raw, NULL, NULL, &result); + * if (status != napi_ok) { + * napi_throw_error(env, NULL, "napi_create_external failed"); + * return NULL; + * } + * return result; + * } + * ... + * DECLARE_NAPI_PROPERTY("myNapi", MyNapi) + * ... + * ``` + * + * ```js + * const native = require('napi_addon.node'); + * const data = native.myNapi(); + * util.types.isExternal(data); // returns true + * util.types.isExternal(0); // returns false + * util.types.isExternal(new String('foo')); // returns false + * ``` + * + * For further information on `napi_create_external`, refer to `napi_create_external()`. + * @since v10.0.0 + */ + function isExternal(object: unknown): boolean; + /** + * Returns `true` if the value is a built-in [`Float32Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Float32Array) instance. + * + * ```js + * util.types.isFloat32Array(new ArrayBuffer()); // Returns false + * util.types.isFloat32Array(new Float32Array()); // Returns true + * util.types.isFloat32Array(new Float64Array()); // Returns false + * ``` + * @since v10.0.0 + */ + function isFloat32Array(object: unknown): object is Float32Array; + /** + * Returns `true` if the value is a built-in [`Float64Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Float64Array) instance. + * + * ```js + * util.types.isFloat64Array(new ArrayBuffer()); // Returns false + * util.types.isFloat64Array(new Uint8Array()); // Returns false + * util.types.isFloat64Array(new Float64Array()); // Returns true + * ``` + * @since v10.0.0 + */ + function isFloat64Array(object: unknown): object is Float64Array; + /** + * Returns `true` if the value is a generator function. + * This only reports back what the JavaScript engine is seeing; + * in particular, the return value may not match the original source code if + * a transpilation tool was used. + * + * ```js + * util.types.isGeneratorFunction(function foo() {}); // Returns false + * util.types.isGeneratorFunction(function* foo() {}); // Returns true + * ``` + * @since v10.0.0 + */ + function isGeneratorFunction(object: unknown): object is GeneratorFunction; + /** + * Returns `true` if the value is a generator object as returned from a + * built-in generator function. + * This only reports back what the JavaScript engine is seeing; + * in particular, the return value may not match the original source code if + * a transpilation tool was used. + * + * ```js + * function* foo() {} + * const generator = foo(); + * util.types.isGeneratorObject(generator); // Returns true + * ``` + * @since v10.0.0 + */ + function isGeneratorObject(object: unknown): object is Generator; + /** + * Returns `true` if the value is a built-in [`Int8Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Int8Array) instance. + * + * ```js + * util.types.isInt8Array(new ArrayBuffer()); // Returns false + * util.types.isInt8Array(new Int8Array()); // Returns true + * util.types.isInt8Array(new Float64Array()); // Returns false + * ``` + * @since v10.0.0 + */ + function isInt8Array(object: unknown): object is Int8Array; + /** + * Returns `true` if the value is a built-in [`Int16Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Int16Array) instance. + * + * ```js + * util.types.isInt16Array(new ArrayBuffer()); // Returns false + * util.types.isInt16Array(new Int16Array()); // Returns true + * util.types.isInt16Array(new Float64Array()); // Returns false + * ``` + * @since v10.0.0 + */ + function isInt16Array(object: unknown): object is Int16Array; + /** + * Returns `true` if the value is a built-in [`Int32Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Int32Array) instance. + * + * ```js + * util.types.isInt32Array(new ArrayBuffer()); // Returns false + * util.types.isInt32Array(new Int32Array()); // Returns true + * util.types.isInt32Array(new Float64Array()); // Returns false + * ``` + * @since v10.0.0 + */ + function isInt32Array(object: unknown): object is Int32Array; + /** + * Returns `true` if the value is a built-in [`Map`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map) instance. + * + * ```js + * util.types.isMap(new Map()); // Returns true + * ``` + * @since v10.0.0 + */ + function isMap( + object: T | {}, + ): object is T extends ReadonlyMap ? (unknown extends T ? never : ReadonlyMap) + : Map; + /** + * Returns `true` if the value is an iterator returned for a built-in [`Map`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map) instance. + * + * ```js + * const map = new Map(); + * util.types.isMapIterator(map.keys()); // Returns true + * util.types.isMapIterator(map.values()); // Returns true + * util.types.isMapIterator(map.entries()); // Returns true + * util.types.isMapIterator(map[Symbol.iterator]()); // Returns true + * ``` + * @since v10.0.0 + */ + function isMapIterator(object: unknown): boolean; + /** + * Returns `true` if the value is an instance of a [Module Namespace Object](https://tc39.github.io/ecma262/#sec-module-namespace-exotic-objects). + * + * ```js + * import * as ns from './a.js'; + * + * util.types.isModuleNamespaceObject(ns); // Returns true + * ``` + * @since v10.0.0 + */ + function isModuleNamespaceObject(value: unknown): boolean; + /** + * Returns `true` if the value was returned by the constructor of a [built-in `Error` type](https://tc39.es/ecma262/#sec-error-objects). + * + * ```js + * console.log(util.types.isNativeError(new Error())); // true + * console.log(util.types.isNativeError(new TypeError())); // true + * console.log(util.types.isNativeError(new RangeError())); // true + * ``` + * + * Subclasses of the native error types are also native errors: + * + * ```js + * class MyError extends Error {} + * console.log(util.types.isNativeError(new MyError())); // true + * ``` + * + * A value being `instanceof` a native error class is not equivalent to `isNativeError()` returning `true` for that value. `isNativeError()` returns `true` for errors + * which come from a different [realm](https://tc39.es/ecma262/#realm) while `instanceof Error` returns `false` for these errors: + * + * ```js + * const vm = require('node:vm'); + * const context = vm.createContext({}); + * const myError = vm.runInContext('new Error()', context); + * console.log(util.types.isNativeError(myError)); // true + * console.log(myError instanceof Error); // false + * ``` + * + * Conversely, `isNativeError()` returns `false` for all objects which were not + * returned by the constructor of a native error. That includes values + * which are `instanceof` native errors: + * + * ```js + * const myError = { __proto__: Error.prototype }; + * console.log(util.types.isNativeError(myError)); // false + * console.log(myError instanceof Error); // true + * ``` + * @since v10.0.0 + */ + function isNativeError(object: unknown): object is Error; + /** + * Returns `true` if the value is a number object, e.g. created + * by `new Number()`. + * + * ```js + * util.types.isNumberObject(0); // Returns false + * util.types.isNumberObject(new Number(0)); // Returns true + * ``` + * @since v10.0.0 + */ + function isNumberObject(object: unknown): object is Number; + /** + * Returns `true` if the value is a built-in [`Promise`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise). + * + * ```js + * util.types.isPromise(Promise.resolve(42)); // Returns true + * ``` + * @since v10.0.0 + */ + function isPromise(object: unknown): object is Promise; + /** + * Returns `true` if the value is a [`Proxy`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Proxy) instance. + * + * ```js + * const target = {}; + * const proxy = new Proxy(target, {}); + * util.types.isProxy(target); // Returns false + * util.types.isProxy(proxy); // Returns true + * ``` + * @since v10.0.0 + */ + function isProxy(object: unknown): boolean; + /** + * Returns `true` if the value is a regular expression object. + * + * ```js + * util.types.isRegExp(/abc/); // Returns true + * util.types.isRegExp(new RegExp('abc')); // Returns true + * ``` + * @since v10.0.0 + */ + function isRegExp(object: unknown): object is RegExp; + /** + * Returns `true` if the value is a built-in [`Set`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set) instance. + * + * ```js + * util.types.isSet(new Set()); // Returns true + * ``` + * @since v10.0.0 + */ + function isSet( + object: T | {}, + ): object is T extends ReadonlySet ? (unknown extends T ? never : ReadonlySet) : Set; + /** + * Returns `true` if the value is an iterator returned for a built-in [`Set`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set) instance. + * + * ```js + * const set = new Set(); + * util.types.isSetIterator(set.keys()); // Returns true + * util.types.isSetIterator(set.values()); // Returns true + * util.types.isSetIterator(set.entries()); // Returns true + * util.types.isSetIterator(set[Symbol.iterator]()); // Returns true + * ``` + * @since v10.0.0 + */ + function isSetIterator(object: unknown): boolean; + /** + * Returns `true` if the value is a built-in [`SharedArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/SharedArrayBuffer) instance. + * This does _not_ include [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer) instances. Usually, it is + * desirable to test for both; See `util.types.isAnyArrayBuffer()` for that. + * + * ```js + * util.types.isSharedArrayBuffer(new ArrayBuffer()); // Returns false + * util.types.isSharedArrayBuffer(new SharedArrayBuffer()); // Returns true + * ``` + * @since v10.0.0 + */ + function isSharedArrayBuffer(object: unknown): object is SharedArrayBuffer; + /** + * Returns `true` if the value is a string object, e.g. created + * by `new String()`. + * + * ```js + * util.types.isStringObject('foo'); // Returns false + * util.types.isStringObject(new String('foo')); // Returns true + * ``` + * @since v10.0.0 + */ + function isStringObject(object: unknown): object is String; + /** + * Returns `true` if the value is a symbol object, created + * by calling `Object()` on a `Symbol` primitive. + * + * ```js + * const symbol = Symbol('foo'); + * util.types.isSymbolObject(symbol); // Returns false + * util.types.isSymbolObject(Object(symbol)); // Returns true + * ``` + * @since v10.0.0 + */ + function isSymbolObject(object: unknown): object is Symbol; + /** + * Returns `true` if the value is a built-in [`TypedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray) instance. + * + * ```js + * util.types.isTypedArray(new ArrayBuffer()); // Returns false + * util.types.isTypedArray(new Uint8Array()); // Returns true + * util.types.isTypedArray(new Float64Array()); // Returns true + * ``` + * + * See also [`ArrayBuffer.isView()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer/isView). + * @since v10.0.0 + */ + function isTypedArray(object: unknown): object is NodeJS.TypedArray; + /** + * Returns `true` if the value is a built-in [`Uint8Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8Array) instance. + * + * ```js + * util.types.isUint8Array(new ArrayBuffer()); // Returns false + * util.types.isUint8Array(new Uint8Array()); // Returns true + * util.types.isUint8Array(new Float64Array()); // Returns false + * ``` + * @since v10.0.0 + */ + function isUint8Array(object: unknown): object is Uint8Array; + /** + * Returns `true` if the value is a built-in [`Uint8ClampedArray`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint8ClampedArray) instance. + * + * ```js + * util.types.isUint8ClampedArray(new ArrayBuffer()); // Returns false + * util.types.isUint8ClampedArray(new Uint8ClampedArray()); // Returns true + * util.types.isUint8ClampedArray(new Float64Array()); // Returns false + * ``` + * @since v10.0.0 + */ + function isUint8ClampedArray(object: unknown): object is Uint8ClampedArray; + /** + * Returns `true` if the value is a built-in [`Uint16Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint16Array) instance. + * + * ```js + * util.types.isUint16Array(new ArrayBuffer()); // Returns false + * util.types.isUint16Array(new Uint16Array()); // Returns true + * util.types.isUint16Array(new Float64Array()); // Returns false + * ``` + * @since v10.0.0 + */ + function isUint16Array(object: unknown): object is Uint16Array; + /** + * Returns `true` if the value is a built-in [`Uint32Array`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Uint32Array) instance. + * + * ```js + * util.types.isUint32Array(new ArrayBuffer()); // Returns false + * util.types.isUint32Array(new Uint32Array()); // Returns true + * util.types.isUint32Array(new Float64Array()); // Returns false + * ``` + * @since v10.0.0 + */ + function isUint32Array(object: unknown): object is Uint32Array; + /** + * Returns `true` if the value is a built-in [`WeakMap`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakMap) instance. + * + * ```js + * util.types.isWeakMap(new WeakMap()); // Returns true + * ``` + * @since v10.0.0 + */ + function isWeakMap(object: unknown): object is WeakMap; + /** + * Returns `true` if the value is a built-in [`WeakSet`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/WeakSet) instance. + * + * ```js + * util.types.isWeakSet(new WeakSet()); // Returns true + * ``` + * @since v10.0.0 + */ + function isWeakSet(object: unknown): object is WeakSet; + /** + * Returns `true` if `value` is a `KeyObject`, `false` otherwise. + * @since v16.2.0 + */ + function isKeyObject(object: unknown): object is KeyObject; + /** + * Returns `true` if `value` is a `CryptoKey`, `false` otherwise. + * @since v16.2.0 + */ + function isCryptoKey(object: unknown): object is webcrypto.CryptoKey; +} +declare module "node:util" { + export * from "util"; +} +declare module "node:util/types" { + export * from "util/types"; +} diff --git a/node_modules/@types/node/v8.d.ts b/node_modules/@types/node/v8.d.ts new file mode 100644 index 0000000..c1268ef --- /dev/null +++ b/node_modules/@types/node/v8.d.ts @@ -0,0 +1,808 @@ +/** + * The `node:v8` module exposes APIs that are specific to the version of [V8](https://developers.google.com/v8/) built into the Node.js binary. It can be accessed using: + * + * ```js + * const v8 = require('node:v8'); + * ``` + * @see [source](https://github.com/nodejs/node/blob/v20.13.1/lib/v8.js) + */ +declare module "v8" { + import { Readable } from "node:stream"; + interface HeapSpaceInfo { + space_name: string; + space_size: number; + space_used_size: number; + space_available_size: number; + physical_space_size: number; + } + // ** Signifies if the --zap_code_space option is enabled or not. 1 == enabled, 0 == disabled. */ + type DoesZapCodeSpaceFlag = 0 | 1; + interface HeapInfo { + total_heap_size: number; + total_heap_size_executable: number; + total_physical_size: number; + total_available_size: number; + used_heap_size: number; + heap_size_limit: number; + malloced_memory: number; + peak_malloced_memory: number; + does_zap_garbage: DoesZapCodeSpaceFlag; + number_of_native_contexts: number; + number_of_detached_contexts: number; + total_global_handles_size: number; + used_global_handles_size: number; + external_memory: number; + } + interface HeapCodeStatistics { + code_and_metadata_size: number; + bytecode_and_metadata_size: number; + external_script_source_size: number; + } + interface HeapSnapshotOptions { + /** + * If true, expose internals in the heap snapshot. + * @default false + */ + exposeInternals?: boolean; + /** + * If true, expose numeric values in artificial fields. + * @default false + */ + exposeNumericValues?: boolean; + } + /** + * Returns an integer representing a version tag derived from the V8 version, + * command-line flags, and detected CPU features. This is useful for determining + * whether a `vm.Script` `cachedData` buffer is compatible with this instance + * of V8. + * + * ```js + * console.log(v8.cachedDataVersionTag()); // 3947234607 + * // The value returned by v8.cachedDataVersionTag() is derived from the V8 + * // version, command-line flags, and detected CPU features. Test that the value + * // does indeed update when flags are toggled. + * v8.setFlagsFromString('--allow_natives_syntax'); + * console.log(v8.cachedDataVersionTag()); // 183726201 + * ``` + * @since v8.0.0 + */ + function cachedDataVersionTag(): number; + /** + * Returns an object with the following properties: + * + * `does_zap_garbage` is a 0/1 boolean, which signifies whether the `--zap_code_space` option is enabled or not. This makes V8 overwrite heap + * garbage with a bit pattern. The RSS footprint (resident set size) gets bigger + * because it continuously touches all heap pages and that makes them less likely + * to get swapped out by the operating system. + * + * `number_of_native_contexts` The value of native\_context is the number of the + * top-level contexts currently active. Increase of this number over time indicates + * a memory leak. + * + * `number_of_detached_contexts` The value of detached\_context is the number + * of contexts that were detached and not yet garbage collected. This number + * being non-zero indicates a potential memory leak. + * + * `total_global_handles_size` The value of total\_global\_handles\_size is the + * total memory size of V8 global handles. + * + * `used_global_handles_size` The value of used\_global\_handles\_size is the + * used memory size of V8 global handles. + * + * `external_memory` The value of external\_memory is the memory size of array + * buffers and external strings. + * + * ```js + * { + * total_heap_size: 7326976, + * total_heap_size_executable: 4194304, + * total_physical_size: 7326976, + * total_available_size: 1152656, + * used_heap_size: 3476208, + * heap_size_limit: 1535115264, + * malloced_memory: 16384, + * peak_malloced_memory: 1127496, + * does_zap_garbage: 0, + * number_of_native_contexts: 1, + * number_of_detached_contexts: 0, + * total_global_handles_size: 8192, + * used_global_handles_size: 3296, + * external_memory: 318824 + * } + * ``` + * @since v1.0.0 + */ + function getHeapStatistics(): HeapInfo; + /** + * Returns statistics about the V8 heap spaces, i.e. the segments which make up + * the V8 heap. Neither the ordering of heap spaces, nor the availability of a + * heap space can be guaranteed as the statistics are provided via the + * V8 [`GetHeapSpaceStatistics`](https://v8docs.nodesource.com/node-13.2/d5/dda/classv8_1_1_isolate.html#ac673576f24fdc7a33378f8f57e1d13a4) function and may change from one V8 version to the + * next. + * + * The value returned is an array of objects containing the following properties: + * + * ```json + * [ + * { + * "space_name": "new_space", + * "space_size": 2063872, + * "space_used_size": 951112, + * "space_available_size": 80824, + * "physical_space_size": 2063872 + * }, + * { + * "space_name": "old_space", + * "space_size": 3090560, + * "space_used_size": 2493792, + * "space_available_size": 0, + * "physical_space_size": 3090560 + * }, + * { + * "space_name": "code_space", + * "space_size": 1260160, + * "space_used_size": 644256, + * "space_available_size": 960, + * "physical_space_size": 1260160 + * }, + * { + * "space_name": "map_space", + * "space_size": 1094160, + * "space_used_size": 201608, + * "space_available_size": 0, + * "physical_space_size": 1094160 + * }, + * { + * "space_name": "large_object_space", + * "space_size": 0, + * "space_used_size": 0, + * "space_available_size": 1490980608, + * "physical_space_size": 0 + * } + * ] + * ``` + * @since v6.0.0 + */ + function getHeapSpaceStatistics(): HeapSpaceInfo[]; + /** + * The `v8.setFlagsFromString()` method can be used to programmatically set + * V8 command-line flags. This method should be used with care. Changing settings + * after the VM has started may result in unpredictable behavior, including + * crashes and data loss; or it may simply do nothing. + * + * The V8 options available for a version of Node.js may be determined by running `node --v8-options`. + * + * Usage: + * + * ```js + * // Print GC events to stdout for one minute. + * const v8 = require('node:v8'); + * v8.setFlagsFromString('--trace_gc'); + * setTimeout(() => { v8.setFlagsFromString('--notrace_gc'); }, 60e3); + * ``` + * @since v1.0.0 + */ + function setFlagsFromString(flags: string): void; + /** + * This is similar to the [`queryObjects()` console API](https://developer.chrome.com/docs/devtools/console/utilities#queryObjects-function) + * provided by the Chromium DevTools console. It can be used to search for objects that have the matching constructor on its prototype chain + * in the heap after a full garbage collection, which can be useful for memory leak regression tests. To avoid surprising results, users should + * avoid using this API on constructors whose implementation they don't control, or on constructors that can be invoked by other parties in the + * application. + * + * To avoid accidental leaks, this API does not return raw references to the objects found. By default, it returns the count of the objects + * found. If `options.format` is `'summary'`, it returns an array containing brief string representations for each object. The visibility provided + * in this API is similar to what the heap snapshot provides, while users can save the cost of serialization and parsing and directly filter the + * target objects during the search. + * + * Only objects created in the current execution context are included in the results. + * + * ```js + * import { queryObjects } from 'node:v8'; + * class A { foo = 'bar'; } + * console.log(queryObjects(A)); // 0 + * const a = new A(); + * console.log(queryObjects(A)); // 1 + * // [ "A { foo: 'bar' }" ] + * console.log(queryObjects(A, { format: 'summary' })); + * + * class B extends A { bar = 'qux'; } + * const b = new B(); + * console.log(queryObjects(B)); // 1 + * // [ "B { foo: 'bar', bar: 'qux' }" ] + * console.log(queryObjects(B, { format: 'summary' })); + * + * // Note that, when there are child classes inheriting from a constructor, + * // the constructor also shows up in the prototype chain of the child + * // classes's prototoype, so the child classes's prototoype would also be + * // included in the result. + * console.log(queryObjects(A)); // 3 + * // [ "B { foo: 'bar', bar: 'qux' }", 'A {}', "A { foo: 'bar' }" ] + * console.log(queryObjects(A, { format: 'summary' })); + * ``` + * @param ctor The constructor that can be used to search on the prototype chain in order to filter target objects in the heap. + * @since v20.13.0 + * @experimental + */ + function queryObjects(ctor: Function): number | string[]; + function queryObjects(ctor: Function, options: { format: "count" }): number; + function queryObjects(ctor: Function, options: { format: "summary" }): string[]; + /** + * Generates a snapshot of the current V8 heap and returns a Readable + * Stream that may be used to read the JSON serialized representation. + * This JSON stream format is intended to be used with tools such as + * Chrome DevTools. The JSON schema is undocumented and specific to the + * V8 engine. Therefore, the schema may change from one version of V8 to the next. + * + * Creating a heap snapshot requires memory about twice the size of the heap at + * the time the snapshot is created. This results in the risk of OOM killers + * terminating the process. + * + * Generating a snapshot is a synchronous operation which blocks the event loop + * for a duration depending on the heap size. + * + * ```js + * // Print heap snapshot to the console + * const v8 = require('node:v8'); + * const stream = v8.getHeapSnapshot(); + * stream.pipe(process.stdout); + * ``` + * @since v11.13.0 + * @return A Readable containing the V8 heap snapshot. + */ + function getHeapSnapshot(options?: HeapSnapshotOptions): Readable; + /** + * Generates a snapshot of the current V8 heap and writes it to a JSON + * file. This file is intended to be used with tools such as Chrome + * DevTools. The JSON schema is undocumented and specific to the V8 + * engine, and may change from one version of V8 to the next. + * + * A heap snapshot is specific to a single V8 isolate. When using `worker threads`, a heap snapshot generated from the main thread will + * not contain any information about the workers, and vice versa. + * + * Creating a heap snapshot requires memory about twice the size of the heap at + * the time the snapshot is created. This results in the risk of OOM killers + * terminating the process. + * + * Generating a snapshot is a synchronous operation which blocks the event loop + * for a duration depending on the heap size. + * + * ```js + * const { writeHeapSnapshot } = require('node:v8'); + * const { + * Worker, + * isMainThread, + * parentPort, + * } = require('node:worker_threads'); + * + * if (isMainThread) { + * const worker = new Worker(__filename); + * + * worker.once('message', (filename) => { + * console.log(`worker heapdump: ${filename}`); + * // Now get a heapdump for the main thread. + * console.log(`main thread heapdump: ${writeHeapSnapshot()}`); + * }); + * + * // Tell the worker to create a heapdump. + * worker.postMessage('heapdump'); + * } else { + * parentPort.once('message', (message) => { + * if (message === 'heapdump') { + * // Generate a heapdump for the worker + * // and return the filename to the parent. + * parentPort.postMessage(writeHeapSnapshot()); + * } + * }); + * } + * ``` + * @since v11.13.0 + * @param filename The file path where the V8 heap snapshot is to be saved. If not specified, a file name with the pattern `'Heap-${yyyymmdd}-${hhmmss}-${pid}-${thread_id}.heapsnapshot'` will be + * generated, where `{pid}` will be the PID of the Node.js process, `{thread_id}` will be `0` when `writeHeapSnapshot()` is called from the main Node.js thread or the id of a + * worker thread. + * @return The filename where the snapshot was saved. + */ + function writeHeapSnapshot(filename?: string, options?: HeapSnapshotOptions): string; + /** + * Get statistics about code and its metadata in the heap, see + * V8 [`GetHeapCodeAndMetadataStatistics`](https://v8docs.nodesource.com/node-13.2/d5/dda/classv8_1_1_isolate.html#a6079122af17612ef54ef3348ce170866) API. Returns an object with the + * following properties: + * + * ```js + * { + * code_and_metadata_size: 212208, + * bytecode_and_metadata_size: 161368, + * external_script_source_size: 1410794, + * cpu_profiler_metadata_size: 0, + * } + * ``` + * @since v12.8.0 + */ + function getHeapCodeStatistics(): HeapCodeStatistics; + /** + * @since v8.0.0 + */ + class Serializer { + /** + * Writes out a header, which includes the serialization format version. + */ + writeHeader(): void; + /** + * Serializes a JavaScript value and adds the serialized representation to the + * internal buffer. + * + * This throws an error if `value` cannot be serialized. + */ + writeValue(val: any): boolean; + /** + * Returns the stored internal buffer. This serializer should not be used once + * the buffer is released. Calling this method results in undefined behavior + * if a previous write has failed. + */ + releaseBuffer(): Buffer; + /** + * Marks an `ArrayBuffer` as having its contents transferred out of band. + * Pass the corresponding `ArrayBuffer` in the deserializing context to `deserializer.transferArrayBuffer()`. + * @param id A 32-bit unsigned integer. + * @param arrayBuffer An `ArrayBuffer` instance. + */ + transferArrayBuffer(id: number, arrayBuffer: ArrayBuffer): void; + /** + * Write a raw 32-bit unsigned integer. + * For use inside of a custom `serializer._writeHostObject()`. + */ + writeUint32(value: number): void; + /** + * Write a raw 64-bit unsigned integer, split into high and low 32-bit parts. + * For use inside of a custom `serializer._writeHostObject()`. + */ + writeUint64(hi: number, lo: number): void; + /** + * Write a JS `number` value. + * For use inside of a custom `serializer._writeHostObject()`. + */ + writeDouble(value: number): void; + /** + * Write raw bytes into the serializer's internal buffer. The deserializer + * will require a way to compute the length of the buffer. + * For use inside of a custom `serializer._writeHostObject()`. + */ + writeRawBytes(buffer: NodeJS.TypedArray): void; + } + /** + * A subclass of `Serializer` that serializes `TypedArray`(in particular `Buffer`) and `DataView` objects as host objects, and only + * stores the part of their underlying `ArrayBuffer`s that they are referring to. + * @since v8.0.0 + */ + class DefaultSerializer extends Serializer {} + /** + * @since v8.0.0 + */ + class Deserializer { + constructor(data: NodeJS.TypedArray); + /** + * Reads and validates a header (including the format version). + * May, for example, reject an invalid or unsupported wire format. In that case, + * an `Error` is thrown. + */ + readHeader(): boolean; + /** + * Deserializes a JavaScript value from the buffer and returns it. + */ + readValue(): any; + /** + * Marks an `ArrayBuffer` as having its contents transferred out of band. + * Pass the corresponding `ArrayBuffer` in the serializing context to `serializer.transferArrayBuffer()` (or return the `id` from `serializer._getSharedArrayBufferId()` in the case of + * `SharedArrayBuffer`s). + * @param id A 32-bit unsigned integer. + * @param arrayBuffer An `ArrayBuffer` instance. + */ + transferArrayBuffer(id: number, arrayBuffer: ArrayBuffer): void; + /** + * Reads the underlying wire format version. Likely mostly to be useful to + * legacy code reading old wire format versions. May not be called before `.readHeader()`. + */ + getWireFormatVersion(): number; + /** + * Read a raw 32-bit unsigned integer and return it. + * For use inside of a custom `deserializer._readHostObject()`. + */ + readUint32(): number; + /** + * Read a raw 64-bit unsigned integer and return it as an array `[hi, lo]` with two 32-bit unsigned integer entries. + * For use inside of a custom `deserializer._readHostObject()`. + */ + readUint64(): [number, number]; + /** + * Read a JS `number` value. + * For use inside of a custom `deserializer._readHostObject()`. + */ + readDouble(): number; + /** + * Read raw bytes from the deserializer's internal buffer. The `length` parameter + * must correspond to the length of the buffer that was passed to `serializer.writeRawBytes()`. + * For use inside of a custom `deserializer._readHostObject()`. + */ + readRawBytes(length: number): Buffer; + } + /** + * A subclass of `Deserializer` corresponding to the format written by `DefaultSerializer`. + * @since v8.0.0 + */ + class DefaultDeserializer extends Deserializer {} + /** + * Uses a `DefaultSerializer` to serialize `value` into a buffer. + * + * `ERR_BUFFER_TOO_LARGE` will be thrown when trying to + * serialize a huge object which requires buffer + * larger than `buffer.constants.MAX_LENGTH`. + * @since v8.0.0 + */ + function serialize(value: any): Buffer; + /** + * Uses a `DefaultDeserializer` with default options to read a JS value + * from a buffer. + * @since v8.0.0 + * @param buffer A buffer returned by {@link serialize}. + */ + function deserialize(buffer: NodeJS.TypedArray): any; + /** + * The `v8.takeCoverage()` method allows the user to write the coverage started by `NODE_V8_COVERAGE` to disk on demand. This method can be invoked multiple + * times during the lifetime of the process. Each time the execution counter will + * be reset and a new coverage report will be written to the directory specified + * by `NODE_V8_COVERAGE`. + * + * When the process is about to exit, one last coverage will still be written to + * disk unless {@link stopCoverage} is invoked before the process exits. + * @since v15.1.0, v14.18.0, v12.22.0 + */ + function takeCoverage(): void; + /** + * The `v8.stopCoverage()` method allows the user to stop the coverage collection + * started by `NODE_V8_COVERAGE`, so that V8 can release the execution count + * records and optimize code. This can be used in conjunction with {@link takeCoverage} if the user wants to collect the coverage on demand. + * @since v15.1.0, v14.18.0, v12.22.0 + */ + function stopCoverage(): void; + /** + * The API is a no-op if `--heapsnapshot-near-heap-limit` is already set from the command line or the API is called more than once. + * `limit` must be a positive integer. See [`--heapsnapshot-near-heap-limit`](https://nodejs.org/docs/latest-v20.x/api/cli.html#--heapsnapshot-near-heap-limitmax_count) for more information. + * @experimental + * @since v18.10.0, v16.18.0 + */ + function setHeapSnapshotNearHeapLimit(limit: number): void; + /** + * This API collects GC data in current thread. + * @since v19.6.0, v18.15.0 + */ + class GCProfiler { + /** + * Start collecting GC data. + * @since v19.6.0, v18.15.0 + */ + start(): void; + /** + * Stop collecting GC data and return an object. The content of object + * is as follows. + * + * ```json + * { + * "version": 1, + * "startTime": 1674059033862, + * "statistics": [ + * { + * "gcType": "Scavenge", + * "beforeGC": { + * "heapStatistics": { + * "totalHeapSize": 5005312, + * "totalHeapSizeExecutable": 524288, + * "totalPhysicalSize": 5226496, + * "totalAvailableSize": 4341325216, + * "totalGlobalHandlesSize": 8192, + * "usedGlobalHandlesSize": 2112, + * "usedHeapSize": 4883840, + * "heapSizeLimit": 4345298944, + * "mallocedMemory": 254128, + * "externalMemory": 225138, + * "peakMallocedMemory": 181760 + * }, + * "heapSpaceStatistics": [ + * { + * "spaceName": "read_only_space", + * "spaceSize": 0, + * "spaceUsedSize": 0, + * "spaceAvailableSize": 0, + * "physicalSpaceSize": 0 + * } + * ] + * }, + * "cost": 1574.14, + * "afterGC": { + * "heapStatistics": { + * "totalHeapSize": 6053888, + * "totalHeapSizeExecutable": 524288, + * "totalPhysicalSize": 5500928, + * "totalAvailableSize": 4341101384, + * "totalGlobalHandlesSize": 8192, + * "usedGlobalHandlesSize": 2112, + * "usedHeapSize": 4059096, + * "heapSizeLimit": 4345298944, + * "mallocedMemory": 254128, + * "externalMemory": 225138, + * "peakMallocedMemory": 181760 + * }, + * "heapSpaceStatistics": [ + * { + * "spaceName": "read_only_space", + * "spaceSize": 0, + * "spaceUsedSize": 0, + * "spaceAvailableSize": 0, + * "physicalSpaceSize": 0 + * } + * ] + * } + * } + * ], + * "endTime": 1674059036865 + * } + * ``` + * + * Here's an example. + * + * ```js + * const { GCProfiler } = require('v8'); + * const profiler = new GCProfiler(); + * profiler.start(); + * setTimeout(() => { + * console.log(profiler.stop()); + * }, 1000); + * ``` + * @since v19.6.0, v18.15.0 + */ + stop(): GCProfilerResult; + } + interface GCProfilerResult { + version: number; + startTime: number; + endTime: number; + statistics: Array<{ + gcType: string; + cost: number; + beforeGC: { + heapStatistics: HeapStatistics; + heapSpaceStatistics: HeapSpaceStatistics[]; + }; + afterGC: { + heapStatistics: HeapStatistics; + heapSpaceStatistics: HeapSpaceStatistics[]; + }; + }>; + } + interface HeapStatistics { + totalHeapSize: number; + totalHeapSizeExecutable: number; + totalPhysicalSize: number; + totalAvailableSize: number; + totalGlobalHandlesSize: number; + usedGlobalHandlesSize: number; + usedHeapSize: number; + heapSizeLimit: number; + mallocedMemory: number; + externalMemory: number; + peakMallocedMemory: number; + } + interface HeapSpaceStatistics { + spaceName: string; + spaceSize: number; + spaceUsedSize: number; + spaceAvailableSize: number; + physicalSpaceSize: number; + } + /** + * Called when a promise is constructed. This does not mean that corresponding before/after events will occur, only that the possibility exists. This will + * happen if a promise is created without ever getting a continuation. + * @since v17.1.0, v16.14.0 + * @param promise The promise being created. + * @param parent The promise continued from, if applicable. + */ + interface Init { + (promise: Promise, parent: Promise): void; + } + /** + * Called before a promise continuation executes. This can be in the form of `then()`, `catch()`, or `finally()` handlers or an await resuming. + * + * The before callback will be called 0 to N times. The before callback will typically be called 0 times if no continuation was ever made for the promise. + * The before callback may be called many times in the case where many continuations have been made from the same promise. + * @since v17.1.0, v16.14.0 + */ + interface Before { + (promise: Promise): void; + } + /** + * Called immediately after a promise continuation executes. This may be after a `then()`, `catch()`, or `finally()` handler or before an await after another await. + * @since v17.1.0, v16.14.0 + */ + interface After { + (promise: Promise): void; + } + /** + * Called when the promise receives a resolution or rejection value. This may occur synchronously in the case of {@link Promise.resolve()} or + * {@link Promise.reject()}. + * @since v17.1.0, v16.14.0 + */ + interface Settled { + (promise: Promise): void; + } + /** + * Key events in the lifetime of a promise have been categorized into four areas: creation of a promise, before/after a continuation handler is called or + * around an await, and when the promise resolves or rejects. + * + * Because promises are asynchronous resources whose lifecycle is tracked via the promise hooks mechanism, the `init()`, `before()`, `after()`, and + * `settled()` callbacks must not be async functions as they create more promises which would produce an infinite loop. + * @since v17.1.0, v16.14.0 + */ + interface HookCallbacks { + init?: Init; + before?: Before; + after?: After; + settled?: Settled; + } + interface PromiseHooks { + /** + * The `init` hook must be a plain function. Providing an async function will throw as it would produce an infinite microtask loop. + * @since v17.1.0, v16.14.0 + * @param init The {@link Init | `init` callback} to call when a promise is created. + * @return Call to stop the hook. + */ + onInit: (init: Init) => Function; + /** + * The `settled` hook must be a plain function. Providing an async function will throw as it would produce an infinite microtask loop. + * @since v17.1.0, v16.14.0 + * @param settled The {@link Settled | `settled` callback} to call when a promise is created. + * @return Call to stop the hook. + */ + onSettled: (settled: Settled) => Function; + /** + * The `before` hook must be a plain function. Providing an async function will throw as it would produce an infinite microtask loop. + * @since v17.1.0, v16.14.0 + * @param before The {@link Before | `before` callback} to call before a promise continuation executes. + * @return Call to stop the hook. + */ + onBefore: (before: Before) => Function; + /** + * The `after` hook must be a plain function. Providing an async function will throw as it would produce an infinite microtask loop. + * @since v17.1.0, v16.14.0 + * @param after The {@link After | `after` callback} to call after a promise continuation executes. + * @return Call to stop the hook. + */ + onAfter: (after: After) => Function; + /** + * Registers functions to be called for different lifetime events of each promise. + * The callbacks `init()`/`before()`/`after()`/`settled()` are called for the respective events during a promise's lifetime. + * All callbacks are optional. For example, if only promise creation needs to be tracked, then only the init callback needs to be passed. + * The hook callbacks must be plain functions. Providing async functions will throw as it would produce an infinite microtask loop. + * @since v17.1.0, v16.14.0 + * @param callbacks The {@link HookCallbacks | Hook Callbacks} to register + * @return Used for disabling hooks + */ + createHook: (callbacks: HookCallbacks) => Function; + } + /** + * The `promiseHooks` interface can be used to track promise lifecycle events. + * @since v17.1.0, v16.14.0 + */ + const promiseHooks: PromiseHooks; + type StartupSnapshotCallbackFn = (args: any) => any; + interface StartupSnapshot { + /** + * Add a callback that will be called when the Node.js instance is about to get serialized into a snapshot and exit. + * This can be used to release resources that should not or cannot be serialized or to convert user data into a form more suitable for serialization. + * @since v18.6.0, v16.17.0 + */ + addSerializeCallback(callback: StartupSnapshotCallbackFn, data?: any): void; + /** + * Add a callback that will be called when the Node.js instance is deserialized from a snapshot. + * The `callback` and the `data` (if provided) will be serialized into the snapshot, they can be used to re-initialize the state of the application or + * to re-acquire resources that the application needs when the application is restarted from the snapshot. + * @since v18.6.0, v16.17.0 + */ + addDeserializeCallback(callback: StartupSnapshotCallbackFn, data?: any): void; + /** + * This sets the entry point of the Node.js application when it is deserialized from a snapshot. This can be called only once in the snapshot building script. + * If called, the deserialized application no longer needs an additional entry point script to start up and will simply invoke the callback along with the deserialized + * data (if provided), otherwise an entry point script still needs to be provided to the deserialized application. + * @since v18.6.0, v16.17.0 + */ + setDeserializeMainFunction(callback: StartupSnapshotCallbackFn, data?: any): void; + /** + * Returns true if the Node.js instance is run to build a snapshot. + * @since v18.6.0, v16.17.0 + */ + isBuildingSnapshot(): boolean; + } + /** + * The `v8.startupSnapshot` interface can be used to add serialization and deserialization hooks for custom startup snapshots. + * + * ```bash + * $ node --snapshot-blob snapshot.blob --build-snapshot entry.js + * # This launches a process with the snapshot + * $ node --snapshot-blob snapshot.blob + * ``` + * + * In the example above, `entry.js` can use methods from the `v8.startupSnapshot` interface to specify how to save information for custom objects + * in the snapshot during serialization and how the information can be used to synchronize these objects during deserialization of the snapshot. + * For example, if the `entry.js` contains the following script: + * + * ```js + * 'use strict'; + * + * const fs = require('node:fs'); + * const zlib = require('node:zlib'); + * const path = require('node:path'); + * const assert = require('node:assert'); + * + * const v8 = require('node:v8'); + * + * class BookShelf { + * storage = new Map(); + * + * // Reading a series of files from directory and store them into storage. + * constructor(directory, books) { + * for (const book of books) { + * this.storage.set(book, fs.readFileSync(path.join(directory, book))); + * } + * } + * + * static compressAll(shelf) { + * for (const [ book, content ] of shelf.storage) { + * shelf.storage.set(book, zlib.gzipSync(content)); + * } + * } + * + * static decompressAll(shelf) { + * for (const [ book, content ] of shelf.storage) { + * shelf.storage.set(book, zlib.gunzipSync(content)); + * } + * } + * } + * + * // __dirname here is where the snapshot script is placed + * // during snapshot building time. + * const shelf = new BookShelf(__dirname, [ + * 'book1.en_US.txt', + * 'book1.es_ES.txt', + * 'book2.zh_CN.txt', + * ]); + * + * assert(v8.startupSnapshot.isBuildingSnapshot()); + * // On snapshot serialization, compress the books to reduce size. + * v8.startupSnapshot.addSerializeCallback(BookShelf.compressAll, shelf); + * // On snapshot deserialization, decompress the books. + * v8.startupSnapshot.addDeserializeCallback(BookShelf.decompressAll, shelf); + * v8.startupSnapshot.setDeserializeMainFunction((shelf) => { + * // process.env and process.argv are refreshed during snapshot + * // deserialization. + * const lang = process.env.BOOK_LANG || 'en_US'; + * const book = process.argv[1]; + * const name = `${book}.${lang}.txt`; + * console.log(shelf.storage.get(name)); + * }, shelf); + * ``` + * + * The resulted binary will get print the data deserialized from the snapshot during start up, using the refreshed `process.env` and `process.argv` of the launched process: + * + * ```bash + * $ BOOK_LANG=es_ES node --snapshot-blob snapshot.blob book1 + * # Prints content of book1.es_ES.txt deserialized from the snapshot. + * ``` + * + * Currently the application deserialized from a user-land snapshot cannot be snapshotted again, so these APIs are only available to applications that are not deserialized from a user-land snapshot. + * + * @experimental + * @since v18.6.0, v16.17.0 + */ + const startupSnapshot: StartupSnapshot; +} +declare module "node:v8" { + export * from "v8"; +} diff --git a/node_modules/@types/node/vm.d.ts b/node_modules/@types/node/vm.d.ts new file mode 100644 index 0000000..1bdae9a --- /dev/null +++ b/node_modules/@types/node/vm.d.ts @@ -0,0 +1,924 @@ +/** + * The `node:vm` module enables compiling and running code within V8 Virtual + * Machine contexts. + * + * **The `node:vm` module is not a security** + * **mechanism. Do not use it to run untrusted code.** + * + * JavaScript code can be compiled and run immediately or + * compiled, saved, and run later. + * + * A common use case is to run the code in a different V8 Context. This means + * invoked code has a different global object than the invoking code. + * + * One can provide the context by `contextifying` an + * object. The invoked code treats any property in the context like a + * global variable. Any changes to global variables caused by the invoked + * code are reflected in the context object. + * + * ```js + * const vm = require('node:vm'); + * + * const x = 1; + * + * const context = { x: 2 }; + * vm.createContext(context); // Contextify the object. + * + * const code = 'x += 40; var y = 17;'; + * // `x` and `y` are global variables in the context. + * // Initially, x has the value 2 because that is the value of context.x. + * vm.runInContext(code, context); + * + * console.log(context.x); // 42 + * console.log(context.y); // 17 + * + * console.log(x); // 1; y is not defined. + * ``` + * @see [source](https://github.com/nodejs/node/blob/v20.13.1/lib/vm.js) + */ +declare module "vm" { + import { ImportAttributes } from "node:module"; + interface Context extends NodeJS.Dict {} + interface BaseOptions { + /** + * Specifies the filename used in stack traces produced by this script. + * @default '' + */ + filename?: string | undefined; + /** + * Specifies the line number offset that is displayed in stack traces produced by this script. + * @default 0 + */ + lineOffset?: number | undefined; + /** + * Specifies the column number offset that is displayed in stack traces produced by this script. + * @default 0 + */ + columnOffset?: number | undefined; + } + interface ScriptOptions extends BaseOptions { + /** + * V8's code cache data for the supplied source. + */ + cachedData?: Buffer | NodeJS.ArrayBufferView | undefined; + /** @deprecated in favor of `script.createCachedData()` */ + produceCachedData?: boolean | undefined; + /** + * Used to specify how the modules should be loaded during the evaluation of this script when `import()` is called. This option is + * part of the experimental modules API. We do not recommend using it in a production environment. For detailed information, see + * [Support of dynamic `import()` in compilation APIs](https://nodejs.org/docs/latest-v20.x/api/vm.html#support-of-dynamic-import-in-compilation-apis). + */ + importModuleDynamically?: + | ((specifier: string, script: Script, importAttributes: ImportAttributes) => Module) + | typeof constants.USE_MAIN_CONTEXT_DEFAULT_LOADER + | undefined; + } + interface RunningScriptOptions extends BaseOptions { + /** + * When `true`, if an `Error` occurs while compiling the `code`, the line of code causing the error is attached to the stack trace. + * @default true + */ + displayErrors?: boolean | undefined; + /** + * Specifies the number of milliseconds to execute code before terminating execution. + * If execution is terminated, an `Error` will be thrown. This value must be a strictly positive integer. + */ + timeout?: number | undefined; + /** + * If `true`, the execution will be terminated when `SIGINT` (Ctrl+C) is received. + * Existing handlers for the event that have been attached via `process.on('SIGINT')` will be disabled during script execution, but will continue to work after that. + * If execution is terminated, an `Error` will be thrown. + * @default false + */ + breakOnSigint?: boolean | undefined; + } + interface RunningScriptInNewContextOptions extends RunningScriptOptions { + /** + * Human-readable name of the newly created context. + */ + contextName?: CreateContextOptions["name"]; + /** + * Origin corresponding to the newly created context for display purposes. The origin should be formatted like a URL, + * but with only the scheme, host, and port (if necessary), like the value of the `url.origin` property of a `URL` object. + * Most notably, this string should omit the trailing slash, as that denotes a path. + */ + contextOrigin?: CreateContextOptions["origin"]; + contextCodeGeneration?: CreateContextOptions["codeGeneration"]; + /** + * If set to `afterEvaluate`, microtasks will be run immediately after the script has run. + */ + microtaskMode?: CreateContextOptions["microtaskMode"]; + } + interface RunningCodeOptions extends RunningScriptOptions { + cachedData?: ScriptOptions["cachedData"]; + importModuleDynamically?: ScriptOptions["importModuleDynamically"]; + } + interface RunningCodeInNewContextOptions extends RunningScriptInNewContextOptions { + cachedData?: ScriptOptions["cachedData"]; + importModuleDynamically?: ScriptOptions["importModuleDynamically"]; + } + interface CompileFunctionOptions extends BaseOptions { + /** + * Provides an optional data with V8's code cache data for the supplied source. + */ + cachedData?: Buffer | undefined; + /** + * Specifies whether to produce new cache data. + * @default false + */ + produceCachedData?: boolean | undefined; + /** + * The sandbox/context in which the said function should be compiled in. + */ + parsingContext?: Context | undefined; + /** + * An array containing a collection of context extensions (objects wrapping the current scope) to be applied while compiling + */ + contextExtensions?: Object[] | undefined; + } + interface CreateContextOptions { + /** + * Human-readable name of the newly created context. + * @default 'VM Context i' Where i is an ascending numerical index of the created context. + */ + name?: string | undefined; + /** + * Corresponds to the newly created context for display purposes. + * The origin should be formatted like a `URL`, but with only the scheme, host, and port (if necessary), + * like the value of the `url.origin` property of a URL object. + * Most notably, this string should omit the trailing slash, as that denotes a path. + * @default '' + */ + origin?: string | undefined; + codeGeneration?: + | { + /** + * If set to false any calls to eval or function constructors (Function, GeneratorFunction, etc) + * will throw an EvalError. + * @default true + */ + strings?: boolean | undefined; + /** + * If set to false any attempt to compile a WebAssembly module will throw a WebAssembly.CompileError. + * @default true + */ + wasm?: boolean | undefined; + } + | undefined; + /** + * If set to `afterEvaluate`, microtasks will be run immediately after the script has run. + */ + microtaskMode?: "afterEvaluate" | undefined; + } + type MeasureMemoryMode = "summary" | "detailed"; + interface MeasureMemoryOptions { + /** + * @default 'summary' + */ + mode?: MeasureMemoryMode | undefined; + /** + * @default 'default' + */ + execution?: "default" | "eager" | undefined; + } + interface MemoryMeasurement { + total: { + jsMemoryEstimate: number; + jsMemoryRange: [number, number]; + }; + } + /** + * Instances of the `vm.Script` class contain precompiled scripts that can be + * executed in specific contexts. + * @since v0.3.1 + */ + class Script { + constructor(code: string, options?: ScriptOptions | string); + /** + * Runs the compiled code contained by the `vm.Script` object within the given `contextifiedObject` and returns the result. Running code does not have access + * to local scope. + * + * The following example compiles code that increments a global variable, sets + * the value of another global variable, then execute the code multiple times. + * The globals are contained in the `context` object. + * + * ```js + * const vm = require('node:vm'); + * + * const context = { + * animal: 'cat', + * count: 2, + * }; + * + * const script = new vm.Script('count += 1; name = "kitty";'); + * + * vm.createContext(context); + * for (let i = 0; i < 10; ++i) { + * script.runInContext(context); + * } + * + * console.log(context); + * // Prints: { animal: 'cat', count: 12, name: 'kitty' } + * ``` + * + * Using the `timeout` or `breakOnSigint` options will result in new event loops + * and corresponding threads being started, which have a non-zero performance + * overhead. + * @since v0.3.1 + * @param contextifiedObject A `contextified` object as returned by the `vm.createContext()` method. + * @return the result of the very last statement executed in the script. + */ + runInContext(contextifiedObject: Context, options?: RunningScriptOptions): any; + /** + * First contextifies the given `contextObject`, runs the compiled code contained + * by the `vm.Script` object within the created context, and returns the result. + * Running code does not have access to local scope. + * + * The following example compiles code that sets a global variable, then executes + * the code multiple times in different contexts. The globals are set on and + * contained within each individual `context`. + * + * ```js + * const vm = require('node:vm'); + * + * const script = new vm.Script('globalVar = "set"'); + * + * const contexts = [{}, {}, {}]; + * contexts.forEach((context) => { + * script.runInNewContext(context); + * }); + * + * console.log(contexts); + * // Prints: [{ globalVar: 'set' }, { globalVar: 'set' }, { globalVar: 'set' }] + * ``` + * @since v0.3.1 + * @param contextObject An object that will be `contextified`. If `undefined`, a new object will be created. + * @return the result of the very last statement executed in the script. + */ + runInNewContext(contextObject?: Context, options?: RunningScriptInNewContextOptions): any; + /** + * Runs the compiled code contained by the `vm.Script` within the context of the + * current `global` object. Running code does not have access to local scope, but _does_ have access to the current `global` object. + * + * The following example compiles code that increments a `global` variable then + * executes that code multiple times: + * + * ```js + * const vm = require('node:vm'); + * + * global.globalVar = 0; + * + * const script = new vm.Script('globalVar += 1', { filename: 'myfile.vm' }); + * + * for (let i = 0; i < 1000; ++i) { + * script.runInThisContext(); + * } + * + * console.log(globalVar); + * + * // 1000 + * ``` + * @since v0.3.1 + * @return the result of the very last statement executed in the script. + */ + runInThisContext(options?: RunningScriptOptions): any; + /** + * Creates a code cache that can be used with the `Script` constructor's `cachedData` option. Returns a `Buffer`. This method may be called at any + * time and any number of times. + * + * The code cache of the `Script` doesn't contain any JavaScript observable + * states. The code cache is safe to be saved along side the script source and + * used to construct new `Script` instances multiple times. + * + * Functions in the `Script` source can be marked as lazily compiled and they are + * not compiled at construction of the `Script`. These functions are going to be + * compiled when they are invoked the first time. The code cache serializes the + * metadata that V8 currently knows about the `Script` that it can use to speed up + * future compilations. + * + * ```js + * const script = new vm.Script(` + * function add(a, b) { + * return a + b; + * } + * + * const x = add(1, 2); + * `); + * + * const cacheWithoutAdd = script.createCachedData(); + * // In `cacheWithoutAdd` the function `add()` is marked for full compilation + * // upon invocation. + * + * script.runInThisContext(); + * + * const cacheWithAdd = script.createCachedData(); + * // `cacheWithAdd` contains fully compiled function `add()`. + * ``` + * @since v10.6.0 + */ + createCachedData(): Buffer; + /** @deprecated in favor of `script.createCachedData()` */ + cachedDataProduced?: boolean | undefined; + /** + * When `cachedData` is supplied to create the `vm.Script`, this value will be set + * to either `true` or `false` depending on acceptance of the data by V8. + * Otherwise the value is `undefined`. + * @since v5.7.0 + */ + cachedDataRejected?: boolean | undefined; + cachedData?: Buffer | undefined; + /** + * When the script is compiled from a source that contains a source map magic + * comment, this property will be set to the URL of the source map. + * + * ```js + * import vm from 'node:vm'; + * + * const script = new vm.Script(` + * function myFunc() {} + * //# sourceMappingURL=sourcemap.json + * `); + * + * console.log(script.sourceMapURL); + * // Prints: sourcemap.json + * ``` + * @since v19.1.0, v18.13.0 + */ + sourceMapURL?: string | undefined; + } + /** + * If given a `contextObject`, the `vm.createContext()` method will + * [prepare that object](https://nodejs.org/docs/latest-v20.x/api/vm.html#what-does-it-mean-to-contextify-an-object) + * and return a reference to it so that it can be used in `{@link runInContext}` or + * [`script.runInContext()`](https://nodejs.org/docs/latest-v20.x/api/vm.html#scriptrunincontextcontextifiedobject-options). Inside such + * scripts, the `contextObject` will be the global object, retaining all of its + * existing properties but also having the built-in objects and functions any + * standard [global object](https://es5.github.io/#x15.1) has. Outside of scripts run by the vm module, global + * variables will remain unchanged. + * + * ```js + * const vm = require('node:vm'); + * + * global.globalVar = 3; + * + * const context = { globalVar: 1 }; + * vm.createContext(context); + * + * vm.runInContext('globalVar *= 2;', context); + * + * console.log(context); + * // Prints: { globalVar: 2 } + * + * console.log(global.globalVar); + * // Prints: 3 + * ``` + * + * If `contextObject` is omitted (or passed explicitly as `undefined`), a new, + * empty `contextified` object will be returned. + * + * The `vm.createContext()` method is primarily useful for creating a single + * context that can be used to run multiple scripts. For instance, if emulating a + * web browser, the method can be used to create a single context representing a + * window's global object, then run all ` +``` + +Production: + +``` + +``` + +**Remember** to replace the version tag with the exact [release](https://github.com/protobufjs/protobuf.js/tags) your project depends upon. + +The library supports CommonJS and AMD loaders and also exports globally as `protobuf`. + +### Distributions + +Where bundle size is a factor, there are additional stripped-down versions of the [full library][dist-full] (~19kb gzipped) available that exclude certain functionality: + +* When working with JSON descriptors (i.e. generated by [pbjs](cli/README.md#pbjs-for-javascript)) and/or reflection only, see the [light library][dist-light] (~16kb gzipped) that excludes the parser. CommonJS entry point is: + + ```js + var protobuf = require("protobufjs/light"); + ``` + +* When working with statically generated code only, see the [minimal library][dist-minimal] (~6.5kb gzipped) that also excludes reflection. CommonJS entry point is: + + ```js + var protobuf = require("protobufjs/minimal"); + ``` + +| Distribution | Location +|------------|----------------------------------- +| Full | +| Light | +| Minimal | + +Usage +----- + +Because JavaScript is a dynamically typed language, protobuf.js introduces the concept of a **valid message** in order to provide the best possible [performance](#performance) (and, as a side product, proper typings): + +### Valid message + +> A valid message is an object (1) not missing any required fields and (2) exclusively composed of JS types understood by the wire format writer. + +There are two possible types of valid messages and the encoder is able to work with both of these for convenience: + +* **Message instances** (explicit instances of message classes with default values on their prototype) always (have to) satisfy the requirements of a valid message by design and +* **Plain JavaScript objects** that just so happen to be composed in a way satisfying the requirements of a valid message as well. + +In a nutshell, the wire format writer understands the following types: + +| Field type | Expected JS type (create, encode) | Conversion (fromObject) +|------------|-----------------------------------|------------------------ +| s-/u-/int32
s-/fixed32 | `number` (32 bit integer) | value | 0 if signed
`value >>> 0` if unsigned +| s-/u-/int64
s-/fixed64 | `Long`-like (optimal)
`number` (53 bit integer) | `Long.fromValue(value)` with long.js
`parseInt(value, 10)` otherwise +| float
double | `number` | `Number(value)` +| bool | `boolean` | `Boolean(value)` +| string | `string` | `String(value)` +| bytes | `Uint8Array` (optimal)
`Buffer` (optimal under node)
`Array.` (8 bit integers) | `base64.decode(value)` if a `string`
`Object` with non-zero `.length` is assumed to be buffer-like +| enum | `number` (32 bit integer) | Looks up the numeric id if a `string` +| message | Valid message | `Message.fromObject(value)` + +* Explicit `undefined` and `null` are considered as not set if the field is optional. +* Repeated fields are `Array.`. +* Map fields are `Object.` with the key being the string representation of the respective value or an 8 characters long binary hash string for `Long`-likes. +* Types marked as *optimal* provide the best performance because no conversion step (i.e. number to low and high bits or base64 string to buffer) is required. + +### Toolset + +With that in mind and again for performance reasons, each message class provides a distinct set of methods with each method doing just one thing. This avoids unnecessary assertions / redundant operations where performance is a concern but also forces a user to perform verification (of plain JavaScript objects that *might* just so happen to be a valid message) explicitly where necessary - for example when dealing with user input. + +**Note** that `Message` below refers to any message class. + +* **Message.verify**(message: `Object`): `null|string`
+ verifies that a **plain JavaScript object** satisfies the requirements of a valid message and thus can be encoded without issues. Instead of throwing, it returns the error message as a string, if any. + + ```js + var payload = "invalid (not an object)"; + var err = AwesomeMessage.verify(payload); + if (err) + throw Error(err); + ``` + +* **Message.encode**(message: `Message|Object` [, writer: `Writer`]): `Writer`
+ encodes a **message instance** or valid **plain JavaScript object**. This method does not implicitly verify the message and it's up to the user to make sure that the payload is a valid message. + + ```js + var buffer = AwesomeMessage.encode(message).finish(); + ``` + +* **Message.encodeDelimited**(message: `Message|Object` [, writer: `Writer`]): `Writer`
+ works like `Message.encode` but additionally prepends the length of the message as a varint. + +* **Message.decode**(reader: `Reader|Uint8Array`): `Message`
+ decodes a buffer to a **message instance**. If required fields are missing, it throws a `util.ProtocolError` with an `instance` property set to the so far decoded message. If the wire format is invalid, it throws an `Error`. + + ```js + try { + var decodedMessage = AwesomeMessage.decode(buffer); + } catch (e) { + if (e instanceof protobuf.util.ProtocolError) { + // e.instance holds the so far decoded message with missing required fields + } else { + // wire format is invalid + } + } + ``` + +* **Message.decodeDelimited**(reader: `Reader|Uint8Array`): `Message`
+ works like `Message.decode` but additionally reads the length of the message prepended as a varint. + +* **Message.create**(properties: `Object`): `Message`
+ creates a new **message instance** from a set of properties that satisfy the requirements of a valid message. Where applicable, it is recommended to prefer `Message.create` over `Message.fromObject` because it doesn't perform possibly redundant conversion. + + ```js + var message = AwesomeMessage.create({ awesomeField: "AwesomeString" }); + ``` + +* **Message.fromObject**(object: `Object`): `Message`
+ converts any non-valid **plain JavaScript object** to a **message instance** using the conversion steps outlined within the table above. + + ```js + var message = AwesomeMessage.fromObject({ awesomeField: 42 }); + // converts awesomeField to a string + ``` + +* **Message.toObject**(message: `Message` [, options: `ConversionOptions`]): `Object`
+ converts a **message instance** to an arbitrary **plain JavaScript object** for interoperability with other libraries or storage. The resulting plain JavaScript object *might* still satisfy the requirements of a valid message depending on the actual conversion options specified, but most of the time it does not. + + ```js + var object = AwesomeMessage.toObject(message, { + enums: String, // enums as string names + longs: String, // longs as strings (requires long.js) + bytes: String, // bytes as base64 encoded strings + defaults: true, // includes default values + arrays: true, // populates empty arrays (repeated fields) even if defaults=false + objects: true, // populates empty objects (map fields) even if defaults=false + oneofs: true // includes virtual oneof fields set to the present field's name + }); + ``` + +For reference, the following diagram aims to display relationships between the different methods and the concept of a valid message: + +

Toolset Diagram

+ +> In other words: `verify` indicates that calling `create` or `encode` directly on the plain object will [result in a valid message respectively] succeed. `fromObject`, on the other hand, does conversion from a broader range of plain objects to create valid messages. ([ref](https://github.com/dcodeIO/protobuf.js/issues/748#issuecomment-291925749)) + +Examples +-------- + +### Using .proto files + +It is possible to load existing .proto files using the full library, which parses and compiles the definitions to ready to use (reflection-based) message classes: + +```protobuf +// awesome.proto +package awesomepackage; +syntax = "proto3"; + +message AwesomeMessage { + string awesome_field = 1; // becomes awesomeField +} +``` + +```js +protobuf.load("awesome.proto", function(err, root) { + if (err) + throw err; + + // Obtain a message type + var AwesomeMessage = root.lookupType("awesomepackage.AwesomeMessage"); + + // Exemplary payload + var payload = { awesomeField: "AwesomeString" }; + + // Verify the payload if necessary (i.e. when possibly incomplete or invalid) + var errMsg = AwesomeMessage.verify(payload); + if (errMsg) + throw Error(errMsg); + + // Create a new message + var message = AwesomeMessage.create(payload); // or use .fromObject if conversion is necessary + + // Encode a message to an Uint8Array (browser) or Buffer (node) + var buffer = AwesomeMessage.encode(message).finish(); + // ... do something with buffer + + // Decode an Uint8Array (browser) or Buffer (node) to a message + var message = AwesomeMessage.decode(buffer); + // ... do something with message + + // If the application uses length-delimited buffers, there is also encodeDelimited and decodeDelimited. + + // Maybe convert the message back to a plain object + var object = AwesomeMessage.toObject(message, { + longs: String, + enums: String, + bytes: String, + // see ConversionOptions + }); +}); +``` + +Additionally, promise syntax can be used by omitting the callback, if preferred: + +```js +protobuf.load("awesome.proto") + .then(function(root) { + ... + }); +``` + +### Using JSON descriptors + +The library utilizes JSON descriptors that are equivalent to a .proto definition. For example, the following is identical to the .proto definition seen above: + +```json +// awesome.json +{ + "nested": { + "awesomepackage": { + "nested": { + "AwesomeMessage": { + "fields": { + "awesomeField": { + "type": "string", + "id": 1 + } + } + } + } + } + } +} +``` + +JSON descriptors closely resemble the internal reflection structure: + +| Type (T) | Extends | Type-specific properties +|--------------------|--------------------|------------------------- +| *ReflectionObject* | | options +| *Namespace* | *ReflectionObject* | nested +| Root | *Namespace* | **nested** +| Type | *Namespace* | **fields** +| Enum | *ReflectionObject* | **values** +| Field | *ReflectionObject* | rule, **type**, **id** +| MapField | Field | **keyType** +| OneOf | *ReflectionObject* | **oneof** (array of field names) +| Service | *Namespace* | **methods** +| Method | *ReflectionObject* | type, **requestType**, **responseType**, requestStream, responseStream + +* **Bold properties** are required. *Italic types* are abstract. +* `T.fromJSON(name, json)` creates the respective reflection object from a JSON descriptor +* `T#toJSON()` creates a JSON descriptor from the respective reflection object (its name is used as the key within the parent) + +Exclusively using JSON descriptors instead of .proto files enables the use of just the light library (the parser isn't required in this case). + +A JSON descriptor can either be loaded the usual way: + +```js +protobuf.load("awesome.json", function(err, root) { + if (err) throw err; + + // Continue at "Obtain a message type" above +}); +``` + +Or it can be loaded inline: + +```js +var jsonDescriptor = require("./awesome.json"); // exemplary for node + +var root = protobuf.Root.fromJSON(jsonDescriptor); + +// Continue at "Obtain a message type" above +``` + +### Using reflection only + +Both the full and the light library include full reflection support. One could, for example, define the .proto definitions seen in the examples above using just reflection: + +```js +... +var Root = protobuf.Root, + Type = protobuf.Type, + Field = protobuf.Field; + +var AwesomeMessage = new Type("AwesomeMessage").add(new Field("awesomeField", 1, "string")); + +var root = new Root().define("awesomepackage").add(AwesomeMessage); + +// Continue at "Create a new message" above +... +``` + +Detailed information on the reflection structure is available within the [API documentation](#additional-documentation). + +### Using custom classes + +Message classes can also be extended with custom functionality and it is also possible to register a custom constructor with a reflected message type: + +```js +... + +// Define a custom constructor +function AwesomeMessage(properties) { + // custom initialization code + ... +} + +// Register the custom constructor with its reflected type (*) +root.lookupType("awesomepackage.AwesomeMessage").ctor = AwesomeMessage; + +// Define custom functionality +AwesomeMessage.customStaticMethod = function() { ... }; +AwesomeMessage.prototype.customInstanceMethod = function() { ... }; + +// Continue at "Create a new message" above +``` + +(*) Besides referencing its reflected type through `AwesomeMessage.$type` and `AwesomeMesage#$type`, the respective custom class is automatically populated with: + +* `AwesomeMessage.create` +* `AwesomeMessage.encode` and `AwesomeMessage.encodeDelimited` +* `AwesomeMessage.decode` and `AwesomeMessage.decodeDelimited` +* `AwesomeMessage.verify` +* `AwesomeMessage.fromObject`, `AwesomeMessage.toObject` and `AwesomeMessage#toJSON` + +Afterwards, decoded messages of this type are `instanceof AwesomeMessage`. + +Alternatively, it is also possible to reuse and extend the internal constructor if custom initialization code is not required: + +```js +... + +// Reuse the internal constructor +var AwesomeMessage = root.lookupType("awesomepackage.AwesomeMessage").ctor; + +// Define custom functionality +AwesomeMessage.customStaticMethod = function() { ... }; +AwesomeMessage.prototype.customInstanceMethod = function() { ... }; + +// Continue at "Create a new message" above +``` + +### Using services + +The library also supports consuming services but it doesn't make any assumptions about the actual transport channel. Instead, a user must provide a suitable RPC implementation, which is an asynchronous function that takes the reflected service method, the binary request and a node-style callback as its parameters: + +```js +function rpcImpl(method, requestData, callback) { + // perform the request using an HTTP request or a WebSocket for example + var responseData = ...; + // and call the callback with the binary response afterwards: + callback(null, responseData); +} +``` + +Below is a working example with a typescript implementation using grpc npm package. +```ts +const grpc = require('grpc') + +const Client = grpc.makeGenericClientConstructor({}) +const client = new Client( + grpcServerUrl, + grpc.credentials.createInsecure() +) + +const rpcImpl = function(method, requestData, callback) { + client.makeUnaryRequest( + method.name, + arg => arg, + arg => arg, + requestData, + callback + ) +} +``` + +Example: + +```protobuf +// greeter.proto +syntax = "proto3"; + +service Greeter { + rpc SayHello (HelloRequest) returns (HelloReply) {} +} + +message HelloRequest { + string name = 1; +} + +message HelloReply { + string message = 1; +} +``` + +```js +... +var Greeter = root.lookup("Greeter"); +var greeter = Greeter.create(/* see above */ rpcImpl, /* request delimited? */ false, /* response delimited? */ false); + +greeter.sayHello({ name: 'you' }, function(err, response) { + console.log('Greeting:', response.message); +}); +``` + +Services also support promises: + +```js +greeter.sayHello({ name: 'you' }) + .then(function(response) { + console.log('Greeting:', response.message); + }); +``` + +There is also an [example for streaming RPC](https://github.com/dcodeIO/protobuf.js/blob/master/examples/streaming-rpc.js). + +Note that the service API is meant for clients. Implementing a server-side endpoint pretty much always requires transport channel (i.e. http, websocket, etc.) specific code with the only common denominator being that it decodes and encodes messages. + +### Usage with TypeScript + +The library ships with its own [type definitions](https://github.com/dcodeIO/protobuf.js/blob/master/index.d.ts) and modern editors like [Visual Studio Code](https://code.visualstudio.com/) will automatically detect and use them for code completion. + +The npm package depends on [@types/node](https://www.npmjs.com/package/@types/node) because of `Buffer` and [@types/long](https://www.npmjs.com/package/@types/long) because of `Long`. If you are not building for node and/or not using long.js, it should be safe to exclude them manually. + +#### Using the JS API + +The API shown above works pretty much the same with TypeScript. However, because everything is typed, accessing fields on instances of dynamically generated message classes requires either using bracket-notation (i.e. `message["awesomeField"]`) or explicit casts. Alternatively, it is possible to use a [typings file generated for its static counterpart](#pbts-for-typescript). + +```ts +import { load } from "protobufjs"; // respectively "./node_modules/protobufjs" + +load("awesome.proto", function(err, root) { + if (err) + throw err; + + // example code + const AwesomeMessage = root.lookupType("awesomepackage.AwesomeMessage"); + + let message = AwesomeMessage.create({ awesomeField: "hello" }); + console.log(`message = ${JSON.stringify(message)}`); + + let buffer = AwesomeMessage.encode(message).finish(); + console.log(`buffer = ${Array.prototype.toString.call(buffer)}`); + + let decoded = AwesomeMessage.decode(buffer); + console.log(`decoded = ${JSON.stringify(decoded)}`); +}); +``` + +#### Using generated static code + +If you generated static code to `bundle.js` using the CLI and its type definitions to `bundle.d.ts`, then you can just do: + +```ts +import { AwesomeMessage } from "./bundle.js"; + +// example code +let message = AwesomeMessage.create({ awesomeField: "hello" }); +let buffer = AwesomeMessage.encode(message).finish(); +let decoded = AwesomeMessage.decode(buffer); +``` + +#### Using decorators + +The library also includes an early implementation of [decorators](https://www.typescriptlang.org/docs/handbook/decorators.html). + +**Note** that decorators are an experimental feature in TypeScript and that declaration order is important depending on the JS target. For example, `@Field.d(2, AwesomeArrayMessage)` requires that `AwesomeArrayMessage` has been defined earlier when targeting `ES5`. + +```ts +import { Message, Type, Field, OneOf } from "protobufjs/light"; // respectively "./node_modules/protobufjs/light.js" + +export class AwesomeSubMessage extends Message { + + @Field.d(1, "string") + public awesomeString: string; + +} + +export enum AwesomeEnum { + ONE = 1, + TWO = 2 +} + +@Type.d("SuperAwesomeMessage") +export class AwesomeMessage extends Message { + + @Field.d(1, "string", "optional", "awesome default string") + public awesomeField: string; + + @Field.d(2, AwesomeSubMessage) + public awesomeSubMessage: AwesomeSubMessage; + + @Field.d(3, AwesomeEnum, "optional", AwesomeEnum.ONE) + public awesomeEnum: AwesomeEnum; + + @OneOf.d("awesomeSubMessage", "awesomeEnum") + public which: string; + +} + +// example code +let message = new AwesomeMessage({ awesomeField: "hello" }); +let buffer = AwesomeMessage.encode(message).finish(); +let decoded = AwesomeMessage.decode(buffer); +``` + +Supported decorators are: + +* **Type.d(typeName?: `string`)**   *(optional)*
+ annotates a class as a protobuf message type. If `typeName` is not specified, the constructor's runtime function name is used for the reflected type. + +* **Field.d<T>(fieldId: `number`, fieldType: `string | Constructor`, fieldRule?: `"optional" | "required" | "repeated"`, defaultValue?: `T`)**
+ annotates a property as a protobuf field with the specified id and protobuf type. + +* **MapField.d<T extends { [key: string]: any }>(fieldId: `number`, fieldKeyType: `string`, fieldValueType. `string | Constructor<{}>`)**
+ annotates a property as a protobuf map field with the specified id, protobuf key and value type. + +* **OneOf.d<T extends string>(...fieldNames: `string[]`)**
+ annotates a property as a protobuf oneof covering the specified fields. + +Other notes: + +* Decorated types reside in `protobuf.roots["decorated"]` using a flat structure, so no duplicate names. +* Enums are copied to a reflected enum with a generic name on decorator evaluation because referenced enum objects have no runtime name the decorator could use. +* Default values must be specified as arguments to the decorator instead of using a property initializer for proper prototype behavior. +* Property names on decorated classes must not be renamed on compile time (i.e. by a minifier) because decorators just receive the original field name as a string. + +**ProTip!** Not as pretty, but you can [use decorators in plain JavaScript](https://github.com/dcodeIO/protobuf.js/blob/master/examples/js-decorators.js) as well. + +Additional documentation +------------------------ + +#### Protocol Buffers +* [Google's Developer Guide](https://developers.google.com/protocol-buffers/docs/overview) + +#### protobuf.js +* [API Documentation](https://protobufjs.github.io/protobuf.js) +* [CHANGELOG](https://github.com/dcodeIO/protobuf.js/blob/master/CHANGELOG.md) +* [Frequently asked questions](https://github.com/dcodeIO/protobuf.js/wiki) on our wiki + +#### Community +* [Questions and answers](http://stackoverflow.com/search?tab=newest&q=protobuf.js) on StackOverflow + +Performance +----------- +The package includes a benchmark that compares protobuf.js performance to native JSON (as far as this is possible) and [Google's JS implementation](https://github.com/google/protobuf/tree/master/js). On an i7-2600K running node 6.9.1 it yields: + +``` +benchmarking encoding performance ... + +protobuf.js (reflect) x 541,707 ops/sec ±1.13% (87 runs sampled) +protobuf.js (static) x 548,134 ops/sec ±1.38% (89 runs sampled) +JSON (string) x 318,076 ops/sec ±0.63% (93 runs sampled) +JSON (buffer) x 179,165 ops/sec ±2.26% (91 runs sampled) +google-protobuf x 74,406 ops/sec ±0.85% (86 runs sampled) + + protobuf.js (static) was fastest + protobuf.js (reflect) was 0.9% ops/sec slower (factor 1.0) + JSON (string) was 41.5% ops/sec slower (factor 1.7) + JSON (buffer) was 67.6% ops/sec slower (factor 3.1) + google-protobuf was 86.4% ops/sec slower (factor 7.3) + +benchmarking decoding performance ... + +protobuf.js (reflect) x 1,383,981 ops/sec ±0.88% (93 runs sampled) +protobuf.js (static) x 1,378,925 ops/sec ±0.81% (93 runs sampled) +JSON (string) x 302,444 ops/sec ±0.81% (93 runs sampled) +JSON (buffer) x 264,882 ops/sec ±0.81% (93 runs sampled) +google-protobuf x 179,180 ops/sec ±0.64% (94 runs sampled) + + protobuf.js (reflect) was fastest + protobuf.js (static) was 0.3% ops/sec slower (factor 1.0) + JSON (string) was 78.1% ops/sec slower (factor 4.6) + JSON (buffer) was 80.8% ops/sec slower (factor 5.2) + google-protobuf was 87.0% ops/sec slower (factor 7.7) + +benchmarking combined performance ... + +protobuf.js (reflect) x 275,900 ops/sec ±0.78% (90 runs sampled) +protobuf.js (static) x 290,096 ops/sec ±0.96% (90 runs sampled) +JSON (string) x 129,381 ops/sec ±0.77% (90 runs sampled) +JSON (buffer) x 91,051 ops/sec ±0.94% (90 runs sampled) +google-protobuf x 42,050 ops/sec ±0.85% (91 runs sampled) + + protobuf.js (static) was fastest + protobuf.js (reflect) was 4.7% ops/sec slower (factor 1.0) + JSON (string) was 55.3% ops/sec slower (factor 2.2) + JSON (buffer) was 68.6% ops/sec slower (factor 3.2) + google-protobuf was 85.5% ops/sec slower (factor 6.9) +``` + +These results are achieved by + +* generating type-specific encoders, decoders, verifiers and converters at runtime +* configuring the reader/writer interface according to the environment +* using node-specific functionality where beneficial and, of course +* avoiding unnecessary operations through splitting up [the toolset](#toolset). + +You can also run [the benchmark](https://github.com/dcodeIO/protobuf.js/blob/master/bench/index.js) ... + +``` +$> npm run bench +``` + +and [the profiler](https://github.com/dcodeIO/protobuf.js/blob/master/bench/prof.js) yourself (the latter requires a recent version of node): + +``` +$> npm run prof [iterations=10000000] +``` + +Note that as of this writing, the benchmark suite performs significantly slower on node 7.2.0 compared to 6.9.1 because moths. + +Compatibility +------------- + +* Works in all modern and not-so-modern browsers except IE8. +* Because the internals of this package do not rely on `google/protobuf/descriptor.proto`, options are parsed and presented literally. +* If typed arrays are not supported by the environment, plain arrays will be used instead. +* Support for pre-ES5 environments (except IE8) can be achieved by [using a polyfill](https://github.com/dcodeIO/protobuf.js/blob/master/scripts/polyfill.js). +* Support for [Content Security Policy](https://w3c.github.io/webappsec-csp/)-restricted environments (like Chrome extensions without [unsafe-eval](https://developer.chrome.com/extensions/contentSecurityPolicy#relaxing-eval)) can be achieved by generating and using static code instead. +* If a proper way to work with 64 bit values (uint64, int64 etc.) is required, just install [long.js](https://github.com/dcodeIO/long.js) alongside this library. All 64 bit numbers will then be returned as a `Long` instance instead of a possibly unsafe JavaScript number ([see](https://github.com/dcodeIO/long.js)). +* For descriptor.proto interoperability, see [ext/descriptor](https://github.com/dcodeIO/protobuf.js/tree/master/ext/descriptor) + +Building +-------- + +To build the library or its components yourself, clone it from GitHub and install the development dependencies: + +``` +$> git clone https://github.com/dcodeIO/protobuf.js.git +$> cd protobuf.js +$> npm install +``` + +Building the respective development and production versions with their respective source maps to `dist/`: + +``` +$> npm run build +``` + +Building the documentation to `docs/`: + +``` +$> npm run docs +``` + +Building the TypeScript definition to `index.d.ts`: + +``` +$> npm run types +``` + +### Browserify integration + +By default, protobuf.js integrates into any browserify build-process without requiring any optional modules. Hence: + +* If int64 support is required, explicitly require the `long` module somewhere in your project as it will be excluded otherwise. This assumes that a global `require` function is present that protobuf.js can call to obtain the long module. + + If there is no global `require` function present after bundling, it's also possible to assign the long module programmatically: + + ```js + var Long = ...; + + protobuf.util.Long = Long; + protobuf.configure(); + ``` + +* If you have any special requirements, there is [the bundler](https://github.com/dcodeIO/protobuf.js/blob/master/scripts/bundle.js) for reference. + +**License:** [BSD 3-Clause License](https://opensource.org/licenses/BSD-3-Clause) diff --git a/node_modules/protobufjs/dist/light/protobuf.js b/node_modules/protobufjs/dist/light/protobuf.js new file mode 100644 index 0000000..47e586a --- /dev/null +++ b/node_modules/protobufjs/dist/light/protobuf.js @@ -0,0 +1,7381 @@ +/*! + * protobuf.js v7.3.0 (c) 2016, daniel wirtz + * compiled fri, 10 may 2024 03:38:34 utc + * licensed under the bsd-3-clause license + * see: https://github.com/dcodeio/protobuf.js for details + */ +(function(undefined){"use strict";(function prelude(modules, cache, entries) { + + // This is the prelude used to bundle protobuf.js for the browser. Wraps up the CommonJS + // sources through a conflict-free require shim and is again wrapped within an iife that + // provides a minification-friendly `undefined` var plus a global "use strict" directive + // so that minification can remove the directives of each module. + + function $require(name) { + var $module = cache[name]; + if (!$module) + modules[name][0].call($module = cache[name] = { exports: {} }, $require, $module, $module.exports); + return $module.exports; + } + + var protobuf = $require(entries[0]); + + // Expose globally + protobuf.util.global.protobuf = protobuf; + + // Be nice to AMD + if (typeof define === "function" && define.amd) + define(["long"], function(Long) { + if (Long && Long.isLong) { + protobuf.util.Long = Long; + protobuf.configure(); + } + return protobuf; + }); + + // Be nice to CommonJS + if (typeof module === "object" && module && module.exports) + module.exports = protobuf; + +})/* end of prelude */({1:[function(require,module,exports){ +"use strict"; +module.exports = asPromise; + +/** + * Callback as used by {@link util.asPromise}. + * @typedef asPromiseCallback + * @type {function} + * @param {Error|null} error Error, if any + * @param {...*} params Additional arguments + * @returns {undefined} + */ + +/** + * Returns a promise from a node-style callback function. + * @memberof util + * @param {asPromiseCallback} fn Function to call + * @param {*} ctx Function context + * @param {...*} params Function arguments + * @returns {Promise<*>} Promisified function + */ +function asPromise(fn, ctx/*, varargs */) { + var params = new Array(arguments.length - 1), + offset = 0, + index = 2, + pending = true; + while (index < arguments.length) + params[offset++] = arguments[index++]; + return new Promise(function executor(resolve, reject) { + params[offset] = function callback(err/*, varargs */) { + if (pending) { + pending = false; + if (err) + reject(err); + else { + var params = new Array(arguments.length - 1), + offset = 0; + while (offset < params.length) + params[offset++] = arguments[offset]; + resolve.apply(null, params); + } + } + }; + try { + fn.apply(ctx || null, params); + } catch (err) { + if (pending) { + pending = false; + reject(err); + } + } + }); +} + +},{}],2:[function(require,module,exports){ +"use strict"; + +/** + * A minimal base64 implementation for number arrays. + * @memberof util + * @namespace + */ +var base64 = exports; + +/** + * Calculates the byte length of a base64 encoded string. + * @param {string} string Base64 encoded string + * @returns {number} Byte length + */ +base64.length = function length(string) { + var p = string.length; + if (!p) + return 0; + var n = 0; + while (--p % 4 > 1 && string.charAt(p) === "=") + ++n; + return Math.ceil(string.length * 3) / 4 - n; +}; + +// Base64 encoding table +var b64 = new Array(64); + +// Base64 decoding table +var s64 = new Array(123); + +// 65..90, 97..122, 48..57, 43, 47 +for (var i = 0; i < 64;) + s64[b64[i] = i < 26 ? i + 65 : i < 52 ? i + 71 : i < 62 ? i - 4 : i - 59 | 43] = i++; + +/** + * Encodes a buffer to a base64 encoded string. + * @param {Uint8Array} buffer Source buffer + * @param {number} start Source start + * @param {number} end Source end + * @returns {string} Base64 encoded string + */ +base64.encode = function encode(buffer, start, end) { + var parts = null, + chunk = []; + var i = 0, // output index + j = 0, // goto index + t; // temporary + while (start < end) { + var b = buffer[start++]; + switch (j) { + case 0: + chunk[i++] = b64[b >> 2]; + t = (b & 3) << 4; + j = 1; + break; + case 1: + chunk[i++] = b64[t | b >> 4]; + t = (b & 15) << 2; + j = 2; + break; + case 2: + chunk[i++] = b64[t | b >> 6]; + chunk[i++] = b64[b & 63]; + j = 0; + break; + } + if (i > 8191) { + (parts || (parts = [])).push(String.fromCharCode.apply(String, chunk)); + i = 0; + } + } + if (j) { + chunk[i++] = b64[t]; + chunk[i++] = 61; + if (j === 1) + chunk[i++] = 61; + } + if (parts) { + if (i) + parts.push(String.fromCharCode.apply(String, chunk.slice(0, i))); + return parts.join(""); + } + return String.fromCharCode.apply(String, chunk.slice(0, i)); +}; + +var invalidEncoding = "invalid encoding"; + +/** + * Decodes a base64 encoded string to a buffer. + * @param {string} string Source string + * @param {Uint8Array} buffer Destination buffer + * @param {number} offset Destination offset + * @returns {number} Number of bytes written + * @throws {Error} If encoding is invalid + */ +base64.decode = function decode(string, buffer, offset) { + var start = offset; + var j = 0, // goto index + t; // temporary + for (var i = 0; i < string.length;) { + var c = string.charCodeAt(i++); + if (c === 61 && j > 1) + break; + if ((c = s64[c]) === undefined) + throw Error(invalidEncoding); + switch (j) { + case 0: + t = c; + j = 1; + break; + case 1: + buffer[offset++] = t << 2 | (c & 48) >> 4; + t = c; + j = 2; + break; + case 2: + buffer[offset++] = (t & 15) << 4 | (c & 60) >> 2; + t = c; + j = 3; + break; + case 3: + buffer[offset++] = (t & 3) << 6 | c; + j = 0; + break; + } + } + if (j === 1) + throw Error(invalidEncoding); + return offset - start; +}; + +/** + * Tests if the specified string appears to be base64 encoded. + * @param {string} string String to test + * @returns {boolean} `true` if probably base64 encoded, otherwise false + */ +base64.test = function test(string) { + return /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(string); +}; + +},{}],3:[function(require,module,exports){ +"use strict"; +module.exports = codegen; + +/** + * Begins generating a function. + * @memberof util + * @param {string[]} functionParams Function parameter names + * @param {string} [functionName] Function name if not anonymous + * @returns {Codegen} Appender that appends code to the function's body + */ +function codegen(functionParams, functionName) { + + /* istanbul ignore if */ + if (typeof functionParams === "string") { + functionName = functionParams; + functionParams = undefined; + } + + var body = []; + + /** + * Appends code to the function's body or finishes generation. + * @typedef Codegen + * @type {function} + * @param {string|Object.} [formatStringOrScope] Format string or, to finish the function, an object of additional scope variables, if any + * @param {...*} [formatParams] Format parameters + * @returns {Codegen|Function} Itself or the generated function if finished + * @throws {Error} If format parameter counts do not match + */ + + function Codegen(formatStringOrScope) { + // note that explicit array handling below makes this ~50% faster + + // finish the function + if (typeof formatStringOrScope !== "string") { + var source = toString(); + if (codegen.verbose) + console.log("codegen: " + source); // eslint-disable-line no-console + source = "return " + source; + if (formatStringOrScope) { + var scopeKeys = Object.keys(formatStringOrScope), + scopeParams = new Array(scopeKeys.length + 1), + scopeValues = new Array(scopeKeys.length), + scopeOffset = 0; + while (scopeOffset < scopeKeys.length) { + scopeParams[scopeOffset] = scopeKeys[scopeOffset]; + scopeValues[scopeOffset] = formatStringOrScope[scopeKeys[scopeOffset++]]; + } + scopeParams[scopeOffset] = source; + return Function.apply(null, scopeParams).apply(null, scopeValues); // eslint-disable-line no-new-func + } + return Function(source)(); // eslint-disable-line no-new-func + } + + // otherwise append to body + var formatParams = new Array(arguments.length - 1), + formatOffset = 0; + while (formatOffset < formatParams.length) + formatParams[formatOffset] = arguments[++formatOffset]; + formatOffset = 0; + formatStringOrScope = formatStringOrScope.replace(/%([%dfijs])/g, function replace($0, $1) { + var value = formatParams[formatOffset++]; + switch ($1) { + case "d": case "f": return String(Number(value)); + case "i": return String(Math.floor(value)); + case "j": return JSON.stringify(value); + case "s": return String(value); + } + return "%"; + }); + if (formatOffset !== formatParams.length) + throw Error("parameter count mismatch"); + body.push(formatStringOrScope); + return Codegen; + } + + function toString(functionNameOverride) { + return "function " + (functionNameOverride || functionName || "") + "(" + (functionParams && functionParams.join(",") || "") + "){\n " + body.join("\n ") + "\n}"; + } + + Codegen.toString = toString; + return Codegen; +} + +/** + * Begins generating a function. + * @memberof util + * @function codegen + * @param {string} [functionName] Function name if not anonymous + * @returns {Codegen} Appender that appends code to the function's body + * @variation 2 + */ + +/** + * When set to `true`, codegen will log generated code to console. Useful for debugging. + * @name util.codegen.verbose + * @type {boolean} + */ +codegen.verbose = false; + +},{}],4:[function(require,module,exports){ +"use strict"; +module.exports = EventEmitter; + +/** + * Constructs a new event emitter instance. + * @classdesc A minimal event emitter. + * @memberof util + * @constructor + */ +function EventEmitter() { + + /** + * Registered listeners. + * @type {Object.} + * @private + */ + this._listeners = {}; +} + +/** + * Registers an event listener. + * @param {string} evt Event name + * @param {function} fn Listener + * @param {*} [ctx] Listener context + * @returns {util.EventEmitter} `this` + */ +EventEmitter.prototype.on = function on(evt, fn, ctx) { + (this._listeners[evt] || (this._listeners[evt] = [])).push({ + fn : fn, + ctx : ctx || this + }); + return this; +}; + +/** + * Removes an event listener or any matching listeners if arguments are omitted. + * @param {string} [evt] Event name. Removes all listeners if omitted. + * @param {function} [fn] Listener to remove. Removes all listeners of `evt` if omitted. + * @returns {util.EventEmitter} `this` + */ +EventEmitter.prototype.off = function off(evt, fn) { + if (evt === undefined) + this._listeners = {}; + else { + if (fn === undefined) + this._listeners[evt] = []; + else { + var listeners = this._listeners[evt]; + for (var i = 0; i < listeners.length;) + if (listeners[i].fn === fn) + listeners.splice(i, 1); + else + ++i; + } + } + return this; +}; + +/** + * Emits an event by calling its listeners with the specified arguments. + * @param {string} evt Event name + * @param {...*} args Arguments + * @returns {util.EventEmitter} `this` + */ +EventEmitter.prototype.emit = function emit(evt) { + var listeners = this._listeners[evt]; + if (listeners) { + var args = [], + i = 1; + for (; i < arguments.length;) + args.push(arguments[i++]); + for (i = 0; i < listeners.length;) + listeners[i].fn.apply(listeners[i++].ctx, args); + } + return this; +}; + +},{}],5:[function(require,module,exports){ +"use strict"; +module.exports = fetch; + +var asPromise = require(1), + inquire = require(7); + +var fs = inquire("fs"); + +/** + * Node-style callback as used by {@link util.fetch}. + * @typedef FetchCallback + * @type {function} + * @param {?Error} error Error, if any, otherwise `null` + * @param {string} [contents] File contents, if there hasn't been an error + * @returns {undefined} + */ + +/** + * Options as used by {@link util.fetch}. + * @typedef FetchOptions + * @type {Object} + * @property {boolean} [binary=false] Whether expecting a binary response + * @property {boolean} [xhr=false] If `true`, forces the use of XMLHttpRequest + */ + +/** + * Fetches the contents of a file. + * @memberof util + * @param {string} filename File path or url + * @param {FetchOptions} options Fetch options + * @param {FetchCallback} callback Callback function + * @returns {undefined} + */ +function fetch(filename, options, callback) { + if (typeof options === "function") { + callback = options; + options = {}; + } else if (!options) + options = {}; + + if (!callback) + return asPromise(fetch, this, filename, options); // eslint-disable-line no-invalid-this + + // if a node-like filesystem is present, try it first but fall back to XHR if nothing is found. + if (!options.xhr && fs && fs.readFile) + return fs.readFile(filename, function fetchReadFileCallback(err, contents) { + return err && typeof XMLHttpRequest !== "undefined" + ? fetch.xhr(filename, options, callback) + : err + ? callback(err) + : callback(null, options.binary ? contents : contents.toString("utf8")); + }); + + // use the XHR version otherwise. + return fetch.xhr(filename, options, callback); +} + +/** + * Fetches the contents of a file. + * @name util.fetch + * @function + * @param {string} path File path or url + * @param {FetchCallback} callback Callback function + * @returns {undefined} + * @variation 2 + */ + +/** + * Fetches the contents of a file. + * @name util.fetch + * @function + * @param {string} path File path or url + * @param {FetchOptions} [options] Fetch options + * @returns {Promise} Promise + * @variation 3 + */ + +/**/ +fetch.xhr = function fetch_xhr(filename, options, callback) { + var xhr = new XMLHttpRequest(); + xhr.onreadystatechange /* works everywhere */ = function fetchOnReadyStateChange() { + + if (xhr.readyState !== 4) + return undefined; + + // local cors security errors return status 0 / empty string, too. afaik this cannot be + // reliably distinguished from an actually empty file for security reasons. feel free + // to send a pull request if you are aware of a solution. + if (xhr.status !== 0 && xhr.status !== 200) + return callback(Error("status " + xhr.status)); + + // if binary data is expected, make sure that some sort of array is returned, even if + // ArrayBuffers are not supported. the binary string fallback, however, is unsafe. + if (options.binary) { + var buffer = xhr.response; + if (!buffer) { + buffer = []; + for (var i = 0; i < xhr.responseText.length; ++i) + buffer.push(xhr.responseText.charCodeAt(i) & 255); + } + return callback(null, typeof Uint8Array !== "undefined" ? new Uint8Array(buffer) : buffer); + } + return callback(null, xhr.responseText); + }; + + if (options.binary) { + // ref: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Sending_and_Receiving_Binary_Data#Receiving_binary_data_in_older_browsers + if ("overrideMimeType" in xhr) + xhr.overrideMimeType("text/plain; charset=x-user-defined"); + xhr.responseType = "arraybuffer"; + } + + xhr.open("GET", filename); + xhr.send(); +}; + +},{"1":1,"7":7}],6:[function(require,module,exports){ +"use strict"; + +module.exports = factory(factory); + +/** + * Reads / writes floats / doubles from / to buffers. + * @name util.float + * @namespace + */ + +/** + * Writes a 32 bit float to a buffer using little endian byte order. + * @name util.float.writeFloatLE + * @function + * @param {number} val Value to write + * @param {Uint8Array} buf Target buffer + * @param {number} pos Target buffer offset + * @returns {undefined} + */ + +/** + * Writes a 32 bit float to a buffer using big endian byte order. + * @name util.float.writeFloatBE + * @function + * @param {number} val Value to write + * @param {Uint8Array} buf Target buffer + * @param {number} pos Target buffer offset + * @returns {undefined} + */ + +/** + * Reads a 32 bit float from a buffer using little endian byte order. + * @name util.float.readFloatLE + * @function + * @param {Uint8Array} buf Source buffer + * @param {number} pos Source buffer offset + * @returns {number} Value read + */ + +/** + * Reads a 32 bit float from a buffer using big endian byte order. + * @name util.float.readFloatBE + * @function + * @param {Uint8Array} buf Source buffer + * @param {number} pos Source buffer offset + * @returns {number} Value read + */ + +/** + * Writes a 64 bit double to a buffer using little endian byte order. + * @name util.float.writeDoubleLE + * @function + * @param {number} val Value to write + * @param {Uint8Array} buf Target buffer + * @param {number} pos Target buffer offset + * @returns {undefined} + */ + +/** + * Writes a 64 bit double to a buffer using big endian byte order. + * @name util.float.writeDoubleBE + * @function + * @param {number} val Value to write + * @param {Uint8Array} buf Target buffer + * @param {number} pos Target buffer offset + * @returns {undefined} + */ + +/** + * Reads a 64 bit double from a buffer using little endian byte order. + * @name util.float.readDoubleLE + * @function + * @param {Uint8Array} buf Source buffer + * @param {number} pos Source buffer offset + * @returns {number} Value read + */ + +/** + * Reads a 64 bit double from a buffer using big endian byte order. + * @name util.float.readDoubleBE + * @function + * @param {Uint8Array} buf Source buffer + * @param {number} pos Source buffer offset + * @returns {number} Value read + */ + +// Factory function for the purpose of node-based testing in modified global environments +function factory(exports) { + + // float: typed array + if (typeof Float32Array !== "undefined") (function() { + + var f32 = new Float32Array([ -0 ]), + f8b = new Uint8Array(f32.buffer), + le = f8b[3] === 128; + + function writeFloat_f32_cpy(val, buf, pos) { + f32[0] = val; + buf[pos ] = f8b[0]; + buf[pos + 1] = f8b[1]; + buf[pos + 2] = f8b[2]; + buf[pos + 3] = f8b[3]; + } + + function writeFloat_f32_rev(val, buf, pos) { + f32[0] = val; + buf[pos ] = f8b[3]; + buf[pos + 1] = f8b[2]; + buf[pos + 2] = f8b[1]; + buf[pos + 3] = f8b[0]; + } + + /* istanbul ignore next */ + exports.writeFloatLE = le ? writeFloat_f32_cpy : writeFloat_f32_rev; + /* istanbul ignore next */ + exports.writeFloatBE = le ? writeFloat_f32_rev : writeFloat_f32_cpy; + + function readFloat_f32_cpy(buf, pos) { + f8b[0] = buf[pos ]; + f8b[1] = buf[pos + 1]; + f8b[2] = buf[pos + 2]; + f8b[3] = buf[pos + 3]; + return f32[0]; + } + + function readFloat_f32_rev(buf, pos) { + f8b[3] = buf[pos ]; + f8b[2] = buf[pos + 1]; + f8b[1] = buf[pos + 2]; + f8b[0] = buf[pos + 3]; + return f32[0]; + } + + /* istanbul ignore next */ + exports.readFloatLE = le ? readFloat_f32_cpy : readFloat_f32_rev; + /* istanbul ignore next */ + exports.readFloatBE = le ? readFloat_f32_rev : readFloat_f32_cpy; + + // float: ieee754 + })(); else (function() { + + function writeFloat_ieee754(writeUint, val, buf, pos) { + var sign = val < 0 ? 1 : 0; + if (sign) + val = -val; + if (val === 0) + writeUint(1 / val > 0 ? /* positive */ 0 : /* negative 0 */ 2147483648, buf, pos); + else if (isNaN(val)) + writeUint(2143289344, buf, pos); + else if (val > 3.4028234663852886e+38) // +-Infinity + writeUint((sign << 31 | 2139095040) >>> 0, buf, pos); + else if (val < 1.1754943508222875e-38) // denormal + writeUint((sign << 31 | Math.round(val / 1.401298464324817e-45)) >>> 0, buf, pos); + else { + var exponent = Math.floor(Math.log(val) / Math.LN2), + mantissa = Math.round(val * Math.pow(2, -exponent) * 8388608) & 8388607; + writeUint((sign << 31 | exponent + 127 << 23 | mantissa) >>> 0, buf, pos); + } + } + + exports.writeFloatLE = writeFloat_ieee754.bind(null, writeUintLE); + exports.writeFloatBE = writeFloat_ieee754.bind(null, writeUintBE); + + function readFloat_ieee754(readUint, buf, pos) { + var uint = readUint(buf, pos), + sign = (uint >> 31) * 2 + 1, + exponent = uint >>> 23 & 255, + mantissa = uint & 8388607; + return exponent === 255 + ? mantissa + ? NaN + : sign * Infinity + : exponent === 0 // denormal + ? sign * 1.401298464324817e-45 * mantissa + : sign * Math.pow(2, exponent - 150) * (mantissa + 8388608); + } + + exports.readFloatLE = readFloat_ieee754.bind(null, readUintLE); + exports.readFloatBE = readFloat_ieee754.bind(null, readUintBE); + + })(); + + // double: typed array + if (typeof Float64Array !== "undefined") (function() { + + var f64 = new Float64Array([-0]), + f8b = new Uint8Array(f64.buffer), + le = f8b[7] === 128; + + function writeDouble_f64_cpy(val, buf, pos) { + f64[0] = val; + buf[pos ] = f8b[0]; + buf[pos + 1] = f8b[1]; + buf[pos + 2] = f8b[2]; + buf[pos + 3] = f8b[3]; + buf[pos + 4] = f8b[4]; + buf[pos + 5] = f8b[5]; + buf[pos + 6] = f8b[6]; + buf[pos + 7] = f8b[7]; + } + + function writeDouble_f64_rev(val, buf, pos) { + f64[0] = val; + buf[pos ] = f8b[7]; + buf[pos + 1] = f8b[6]; + buf[pos + 2] = f8b[5]; + buf[pos + 3] = f8b[4]; + buf[pos + 4] = f8b[3]; + buf[pos + 5] = f8b[2]; + buf[pos + 6] = f8b[1]; + buf[pos + 7] = f8b[0]; + } + + /* istanbul ignore next */ + exports.writeDoubleLE = le ? writeDouble_f64_cpy : writeDouble_f64_rev; + /* istanbul ignore next */ + exports.writeDoubleBE = le ? writeDouble_f64_rev : writeDouble_f64_cpy; + + function readDouble_f64_cpy(buf, pos) { + f8b[0] = buf[pos ]; + f8b[1] = buf[pos + 1]; + f8b[2] = buf[pos + 2]; + f8b[3] = buf[pos + 3]; + f8b[4] = buf[pos + 4]; + f8b[5] = buf[pos + 5]; + f8b[6] = buf[pos + 6]; + f8b[7] = buf[pos + 7]; + return f64[0]; + } + + function readDouble_f64_rev(buf, pos) { + f8b[7] = buf[pos ]; + f8b[6] = buf[pos + 1]; + f8b[5] = buf[pos + 2]; + f8b[4] = buf[pos + 3]; + f8b[3] = buf[pos + 4]; + f8b[2] = buf[pos + 5]; + f8b[1] = buf[pos + 6]; + f8b[0] = buf[pos + 7]; + return f64[0]; + } + + /* istanbul ignore next */ + exports.readDoubleLE = le ? readDouble_f64_cpy : readDouble_f64_rev; + /* istanbul ignore next */ + exports.readDoubleBE = le ? readDouble_f64_rev : readDouble_f64_cpy; + + // double: ieee754 + })(); else (function() { + + function writeDouble_ieee754(writeUint, off0, off1, val, buf, pos) { + var sign = val < 0 ? 1 : 0; + if (sign) + val = -val; + if (val === 0) { + writeUint(0, buf, pos + off0); + writeUint(1 / val > 0 ? /* positive */ 0 : /* negative 0 */ 2147483648, buf, pos + off1); + } else if (isNaN(val)) { + writeUint(0, buf, pos + off0); + writeUint(2146959360, buf, pos + off1); + } else if (val > 1.7976931348623157e+308) { // +-Infinity + writeUint(0, buf, pos + off0); + writeUint((sign << 31 | 2146435072) >>> 0, buf, pos + off1); + } else { + var mantissa; + if (val < 2.2250738585072014e-308) { // denormal + mantissa = val / 5e-324; + writeUint(mantissa >>> 0, buf, pos + off0); + writeUint((sign << 31 | mantissa / 4294967296) >>> 0, buf, pos + off1); + } else { + var exponent = Math.floor(Math.log(val) / Math.LN2); + if (exponent === 1024) + exponent = 1023; + mantissa = val * Math.pow(2, -exponent); + writeUint(mantissa * 4503599627370496 >>> 0, buf, pos + off0); + writeUint((sign << 31 | exponent + 1023 << 20 | mantissa * 1048576 & 1048575) >>> 0, buf, pos + off1); + } + } + } + + exports.writeDoubleLE = writeDouble_ieee754.bind(null, writeUintLE, 0, 4); + exports.writeDoubleBE = writeDouble_ieee754.bind(null, writeUintBE, 4, 0); + + function readDouble_ieee754(readUint, off0, off1, buf, pos) { + var lo = readUint(buf, pos + off0), + hi = readUint(buf, pos + off1); + var sign = (hi >> 31) * 2 + 1, + exponent = hi >>> 20 & 2047, + mantissa = 4294967296 * (hi & 1048575) + lo; + return exponent === 2047 + ? mantissa + ? NaN + : sign * Infinity + : exponent === 0 // denormal + ? sign * 5e-324 * mantissa + : sign * Math.pow(2, exponent - 1075) * (mantissa + 4503599627370496); + } + + exports.readDoubleLE = readDouble_ieee754.bind(null, readUintLE, 0, 4); + exports.readDoubleBE = readDouble_ieee754.bind(null, readUintBE, 4, 0); + + })(); + + return exports; +} + +// uint helpers + +function writeUintLE(val, buf, pos) { + buf[pos ] = val & 255; + buf[pos + 1] = val >>> 8 & 255; + buf[pos + 2] = val >>> 16 & 255; + buf[pos + 3] = val >>> 24; +} + +function writeUintBE(val, buf, pos) { + buf[pos ] = val >>> 24; + buf[pos + 1] = val >>> 16 & 255; + buf[pos + 2] = val >>> 8 & 255; + buf[pos + 3] = val & 255; +} + +function readUintLE(buf, pos) { + return (buf[pos ] + | buf[pos + 1] << 8 + | buf[pos + 2] << 16 + | buf[pos + 3] << 24) >>> 0; +} + +function readUintBE(buf, pos) { + return (buf[pos ] << 24 + | buf[pos + 1] << 16 + | buf[pos + 2] << 8 + | buf[pos + 3]) >>> 0; +} + +},{}],7:[function(require,module,exports){ +"use strict"; +module.exports = inquire; + +/** + * Requires a module only if available. + * @memberof util + * @param {string} moduleName Module to require + * @returns {?Object} Required module if available and not empty, otherwise `null` + */ +function inquire(moduleName) { + try { + var mod = eval("quire".replace(/^/,"re"))(moduleName); // eslint-disable-line no-eval + if (mod && (mod.length || Object.keys(mod).length)) + return mod; + } catch (e) {} // eslint-disable-line no-empty + return null; +} + +},{}],8:[function(require,module,exports){ +"use strict"; + +/** + * A minimal path module to resolve Unix, Windows and URL paths alike. + * @memberof util + * @namespace + */ +var path = exports; + +var isAbsolute = +/** + * Tests if the specified path is absolute. + * @param {string} path Path to test + * @returns {boolean} `true` if path is absolute + */ +path.isAbsolute = function isAbsolute(path) { + return /^(?:\/|\w+:)/.test(path); +}; + +var normalize = +/** + * Normalizes the specified path. + * @param {string} path Path to normalize + * @returns {string} Normalized path + */ +path.normalize = function normalize(path) { + path = path.replace(/\\/g, "/") + .replace(/\/{2,}/g, "/"); + var parts = path.split("/"), + absolute = isAbsolute(path), + prefix = ""; + if (absolute) + prefix = parts.shift() + "/"; + for (var i = 0; i < parts.length;) { + if (parts[i] === "..") { + if (i > 0 && parts[i - 1] !== "..") + parts.splice(--i, 2); + else if (absolute) + parts.splice(i, 1); + else + ++i; + } else if (parts[i] === ".") + parts.splice(i, 1); + else + ++i; + } + return prefix + parts.join("/"); +}; + +/** + * Resolves the specified include path against the specified origin path. + * @param {string} originPath Path to the origin file + * @param {string} includePath Include path relative to origin path + * @param {boolean} [alreadyNormalized=false] `true` if both paths are already known to be normalized + * @returns {string} Path to the include file + */ +path.resolve = function resolve(originPath, includePath, alreadyNormalized) { + if (!alreadyNormalized) + includePath = normalize(includePath); + if (isAbsolute(includePath)) + return includePath; + if (!alreadyNormalized) + originPath = normalize(originPath); + return (originPath = originPath.replace(/(?:\/|^)[^/]+$/, "")).length ? normalize(originPath + "/" + includePath) : includePath; +}; + +},{}],9:[function(require,module,exports){ +"use strict"; +module.exports = pool; + +/** + * An allocator as used by {@link util.pool}. + * @typedef PoolAllocator + * @type {function} + * @param {number} size Buffer size + * @returns {Uint8Array} Buffer + */ + +/** + * A slicer as used by {@link util.pool}. + * @typedef PoolSlicer + * @type {function} + * @param {number} start Start offset + * @param {number} end End offset + * @returns {Uint8Array} Buffer slice + * @this {Uint8Array} + */ + +/** + * A general purpose buffer pool. + * @memberof util + * @function + * @param {PoolAllocator} alloc Allocator + * @param {PoolSlicer} slice Slicer + * @param {number} [size=8192] Slab size + * @returns {PoolAllocator} Pooled allocator + */ +function pool(alloc, slice, size) { + var SIZE = size || 8192; + var MAX = SIZE >>> 1; + var slab = null; + var offset = SIZE; + return function pool_alloc(size) { + if (size < 1 || size > MAX) + return alloc(size); + if (offset + size > SIZE) { + slab = alloc(SIZE); + offset = 0; + } + var buf = slice.call(slab, offset, offset += size); + if (offset & 7) // align to 32 bit + offset = (offset | 7) + 1; + return buf; + }; +} + +},{}],10:[function(require,module,exports){ +"use strict"; + +/** + * A minimal UTF8 implementation for number arrays. + * @memberof util + * @namespace + */ +var utf8 = exports; + +/** + * Calculates the UTF8 byte length of a string. + * @param {string} string String + * @returns {number} Byte length + */ +utf8.length = function utf8_length(string) { + var len = 0, + c = 0; + for (var i = 0; i < string.length; ++i) { + c = string.charCodeAt(i); + if (c < 128) + len += 1; + else if (c < 2048) + len += 2; + else if ((c & 0xFC00) === 0xD800 && (string.charCodeAt(i + 1) & 0xFC00) === 0xDC00) { + ++i; + len += 4; + } else + len += 3; + } + return len; +}; + +/** + * Reads UTF8 bytes as a string. + * @param {Uint8Array} buffer Source buffer + * @param {number} start Source start + * @param {number} end Source end + * @returns {string} String read + */ +utf8.read = function utf8_read(buffer, start, end) { + var len = end - start; + if (len < 1) + return ""; + var parts = null, + chunk = [], + i = 0, // char offset + t; // temporary + while (start < end) { + t = buffer[start++]; + if (t < 128) + chunk[i++] = t; + else if (t > 191 && t < 224) + chunk[i++] = (t & 31) << 6 | buffer[start++] & 63; + else if (t > 239 && t < 365) { + t = ((t & 7) << 18 | (buffer[start++] & 63) << 12 | (buffer[start++] & 63) << 6 | buffer[start++] & 63) - 0x10000; + chunk[i++] = 0xD800 + (t >> 10); + chunk[i++] = 0xDC00 + (t & 1023); + } else + chunk[i++] = (t & 15) << 12 | (buffer[start++] & 63) << 6 | buffer[start++] & 63; + if (i > 8191) { + (parts || (parts = [])).push(String.fromCharCode.apply(String, chunk)); + i = 0; + } + } + if (parts) { + if (i) + parts.push(String.fromCharCode.apply(String, chunk.slice(0, i))); + return parts.join(""); + } + return String.fromCharCode.apply(String, chunk.slice(0, i)); +}; + +/** + * Writes a string as UTF8 bytes. + * @param {string} string Source string + * @param {Uint8Array} buffer Destination buffer + * @param {number} offset Destination offset + * @returns {number} Bytes written + */ +utf8.write = function utf8_write(string, buffer, offset) { + var start = offset, + c1, // character 1 + c2; // character 2 + for (var i = 0; i < string.length; ++i) { + c1 = string.charCodeAt(i); + if (c1 < 128) { + buffer[offset++] = c1; + } else if (c1 < 2048) { + buffer[offset++] = c1 >> 6 | 192; + buffer[offset++] = c1 & 63 | 128; + } else if ((c1 & 0xFC00) === 0xD800 && ((c2 = string.charCodeAt(i + 1)) & 0xFC00) === 0xDC00) { + c1 = 0x10000 + ((c1 & 0x03FF) << 10) + (c2 & 0x03FF); + ++i; + buffer[offset++] = c1 >> 18 | 240; + buffer[offset++] = c1 >> 12 & 63 | 128; + buffer[offset++] = c1 >> 6 & 63 | 128; + buffer[offset++] = c1 & 63 | 128; + } else { + buffer[offset++] = c1 >> 12 | 224; + buffer[offset++] = c1 >> 6 & 63 | 128; + buffer[offset++] = c1 & 63 | 128; + } + } + return offset - start; +}; + +},{}],11:[function(require,module,exports){ +"use strict"; +/** + * Runtime message from/to plain object converters. + * @namespace + */ +var converter = exports; + +var Enum = require(14), + util = require(33); + +/** + * Generates a partial value fromObject conveter. + * @param {Codegen} gen Codegen instance + * @param {Field} field Reflected field + * @param {number} fieldIndex Field index + * @param {string} prop Property reference + * @returns {Codegen} Codegen instance + * @ignore + */ +function genValuePartial_fromObject(gen, field, fieldIndex, prop) { + var defaultAlreadyEmitted = false; + /* eslint-disable no-unexpected-multiline, block-scoped-var, no-redeclare */ + if (field.resolvedType) { + if (field.resolvedType instanceof Enum) { gen + ("switch(d%s){", prop); + for (var values = field.resolvedType.values, keys = Object.keys(values), i = 0; i < keys.length; ++i) { + // enum unknown values passthrough + if (values[keys[i]] === field.typeDefault && !defaultAlreadyEmitted) { gen + ("default:") + ("if(typeof(d%s)===\"number\"){m%s=d%s;break}", prop, prop, prop); + if (!field.repeated) gen // fallback to default value only for + // arrays, to avoid leaving holes. + ("break"); // for non-repeated fields, just ignore + defaultAlreadyEmitted = true; + } + gen + ("case%j:", keys[i]) + ("case %i:", values[keys[i]]) + ("m%s=%j", prop, values[keys[i]]) + ("break"); + } gen + ("}"); + } else gen + ("if(typeof d%s!==\"object\")", prop) + ("throw TypeError(%j)", field.fullName + ": object expected") + ("m%s=types[%i].fromObject(d%s)", prop, fieldIndex, prop); + } else { + var isUnsigned = false; + switch (field.type) { + case "double": + case "float": gen + ("m%s=Number(d%s)", prop, prop); // also catches "NaN", "Infinity" + break; + case "uint32": + case "fixed32": gen + ("m%s=d%s>>>0", prop, prop); + break; + case "int32": + case "sint32": + case "sfixed32": gen + ("m%s=d%s|0", prop, prop); + break; + case "uint64": + isUnsigned = true; + // eslint-disable-next-line no-fallthrough + case "int64": + case "sint64": + case "fixed64": + case "sfixed64": gen + ("if(util.Long)") + ("(m%s=util.Long.fromValue(d%s)).unsigned=%j", prop, prop, isUnsigned) + ("else if(typeof d%s===\"string\")", prop) + ("m%s=parseInt(d%s,10)", prop, prop) + ("else if(typeof d%s===\"number\")", prop) + ("m%s=d%s", prop, prop) + ("else if(typeof d%s===\"object\")", prop) + ("m%s=new util.LongBits(d%s.low>>>0,d%s.high>>>0).toNumber(%s)", prop, prop, prop, isUnsigned ? "true" : ""); + break; + case "bytes": gen + ("if(typeof d%s===\"string\")", prop) + ("util.base64.decode(d%s,m%s=util.newBuffer(util.base64.length(d%s)),0)", prop, prop, prop) + ("else if(d%s.length >= 0)", prop) + ("m%s=d%s", prop, prop); + break; + case "string": gen + ("m%s=String(d%s)", prop, prop); + break; + case "bool": gen + ("m%s=Boolean(d%s)", prop, prop); + break; + /* default: gen + ("m%s=d%s", prop, prop); + break; */ + } + } + return gen; + /* eslint-enable no-unexpected-multiline, block-scoped-var, no-redeclare */ +} + +/** + * Generates a plain object to runtime message converter specific to the specified message type. + * @param {Type} mtype Message type + * @returns {Codegen} Codegen instance + */ +converter.fromObject = function fromObject(mtype) { + /* eslint-disable no-unexpected-multiline, block-scoped-var, no-redeclare */ + var fields = mtype.fieldsArray; + var gen = util.codegen(["d"], mtype.name + "$fromObject") + ("if(d instanceof this.ctor)") + ("return d"); + if (!fields.length) return gen + ("return new this.ctor"); + gen + ("var m=new this.ctor"); + for (var i = 0; i < fields.length; ++i) { + var field = fields[i].resolve(), + prop = util.safeProp(field.name); + + // Map fields + if (field.map) { gen + ("if(d%s){", prop) + ("if(typeof d%s!==\"object\")", prop) + ("throw TypeError(%j)", field.fullName + ": object expected") + ("m%s={}", prop) + ("for(var ks=Object.keys(d%s),i=0;i>>0,m%s.high>>>0).toNumber(%s):m%s", prop, prop, prop, prop, isUnsigned ? "true": "", prop); + break; + case "bytes": gen + ("d%s=o.bytes===String?util.base64.encode(m%s,0,m%s.length):o.bytes===Array?Array.prototype.slice.call(m%s):m%s", prop, prop, prop, prop, prop); + break; + default: gen + ("d%s=m%s", prop, prop); + break; + } + } + return gen; + /* eslint-enable no-unexpected-multiline, block-scoped-var, no-redeclare */ +} + +/** + * Generates a runtime message to plain object converter specific to the specified message type. + * @param {Type} mtype Message type + * @returns {Codegen} Codegen instance + */ +converter.toObject = function toObject(mtype) { + /* eslint-disable no-unexpected-multiline, block-scoped-var, no-redeclare */ + var fields = mtype.fieldsArray.slice().sort(util.compareFieldsById); + if (!fields.length) + return util.codegen()("return {}"); + var gen = util.codegen(["m", "o"], mtype.name + "$toObject") + ("if(!o)") + ("o={}") + ("var d={}"); + + var repeatedFields = [], + mapFields = [], + normalFields = [], + i = 0; + for (; i < fields.length; ++i) + if (!fields[i].partOf) + ( fields[i].resolve().repeated ? repeatedFields + : fields[i].map ? mapFields + : normalFields).push(fields[i]); + + if (repeatedFields.length) { gen + ("if(o.arrays||o.defaults){"); + for (i = 0; i < repeatedFields.length; ++i) gen + ("d%s=[]", util.safeProp(repeatedFields[i].name)); + gen + ("}"); + } + + if (mapFields.length) { gen + ("if(o.objects||o.defaults){"); + for (i = 0; i < mapFields.length; ++i) gen + ("d%s={}", util.safeProp(mapFields[i].name)); + gen + ("}"); + } + + if (normalFields.length) { gen + ("if(o.defaults){"); + for (i = 0; i < normalFields.length; ++i) { + var field = normalFields[i], + prop = util.safeProp(field.name); + if (field.resolvedType instanceof Enum) gen + ("d%s=o.enums===String?%j:%j", prop, field.resolvedType.valuesById[field.typeDefault], field.typeDefault); + else if (field.long) gen + ("if(util.Long){") + ("var n=new util.Long(%i,%i,%j)", field.typeDefault.low, field.typeDefault.high, field.typeDefault.unsigned) + ("d%s=o.longs===String?n.toString():o.longs===Number?n.toNumber():n", prop) + ("}else") + ("d%s=o.longs===String?%j:%i", prop, field.typeDefault.toString(), field.typeDefault.toNumber()); + else if (field.bytes) { + var arrayDefault = "[" + Array.prototype.slice.call(field.typeDefault).join(",") + "]"; + gen + ("if(o.bytes===String)d%s=%j", prop, String.fromCharCode.apply(String, field.typeDefault)) + ("else{") + ("d%s=%s", prop, arrayDefault) + ("if(o.bytes!==Array)d%s=util.newBuffer(d%s)", prop, prop) + ("}"); + } else gen + ("d%s=%j", prop, field.typeDefault); // also messages (=null) + } gen + ("}"); + } + var hasKs2 = false; + for (i = 0; i < fields.length; ++i) { + var field = fields[i], + index = mtype._fieldsArray.indexOf(field), + prop = util.safeProp(field.name); + if (field.map) { + if (!hasKs2) { hasKs2 = true; gen + ("var ks2"); + } gen + ("if(m%s&&(ks2=Object.keys(m%s)).length){", prop, prop) + ("d%s={}", prop) + ("for(var j=0;j>>3){"); + + var i = 0; + for (; i < /* initializes */ mtype.fieldsArray.length; ++i) { + var field = mtype._fieldsArray[i].resolve(), + type = field.resolvedType instanceof Enum ? "int32" : field.type, + ref = "m" + util.safeProp(field.name); gen + ("case %i: {", field.id); + + // Map fields + if (field.map) { gen + ("if(%s===util.emptyObject)", ref) + ("%s={}", ref) + ("var c2 = r.uint32()+r.pos"); + + if (types.defaults[field.keyType] !== undefined) gen + ("k=%j", types.defaults[field.keyType]); + else gen + ("k=null"); + + if (types.defaults[type] !== undefined) gen + ("value=%j", types.defaults[type]); + else gen + ("value=null"); + + gen + ("while(r.pos>>3){") + ("case 1: k=r.%s(); break", field.keyType) + ("case 2:"); + + if (types.basic[type] === undefined) gen + ("value=types[%i].decode(r,r.uint32())", i); // can't be groups + else gen + ("value=r.%s()", type); + + gen + ("break") + ("default:") + ("r.skipType(tag2&7)") + ("break") + ("}") + ("}"); + + if (types.long[field.keyType] !== undefined) gen + ("%s[typeof k===\"object\"?util.longToHash(k):k]=value", ref); + else gen + ("%s[k]=value", ref); + + // Repeated fields + } else if (field.repeated) { gen + + ("if(!(%s&&%s.length))", ref, ref) + ("%s=[]", ref); + + // Packable (always check for forward and backward compatiblity) + if (types.packed[type] !== undefined) gen + ("if((t&7)===2){") + ("var c2=r.uint32()+r.pos") + ("while(r.pos>> 0, (field.id << 3 | 4) >>> 0) + : gen("types[%i].encode(%s,w.uint32(%i).fork()).ldelim()", fieldIndex, ref, (field.id << 3 | 2) >>> 0); +} + +/** + * Generates an encoder specific to the specified message type. + * @param {Type} mtype Message type + * @returns {Codegen} Codegen instance + */ +function encoder(mtype) { + /* eslint-disable no-unexpected-multiline, block-scoped-var, no-redeclare */ + var gen = util.codegen(["m", "w"], mtype.name + "$encode") + ("if(!w)") + ("w=Writer.create()"); + + var i, ref; + + // "when a message is serialized its known fields should be written sequentially by field number" + var fields = /* initializes */ mtype.fieldsArray.slice().sort(util.compareFieldsById); + + for (var i = 0; i < fields.length; ++i) { + var field = fields[i].resolve(), + index = mtype._fieldsArray.indexOf(field), + type = field.resolvedType instanceof Enum ? "int32" : field.type, + wireType = types.basic[type]; + ref = "m" + util.safeProp(field.name); + + // Map fields + if (field.map) { + gen + ("if(%s!=null&&Object.hasOwnProperty.call(m,%j)){", ref, field.name) // !== undefined && !== null + ("for(var ks=Object.keys(%s),i=0;i>> 0, 8 | types.mapKey[field.keyType], field.keyType); + if (wireType === undefined) gen + ("types[%i].encode(%s[ks[i]],w.uint32(18).fork()).ldelim().ldelim()", index, ref); // can't be groups + else gen + (".uint32(%i).%s(%s[ks[i]]).ldelim()", 16 | wireType, type, ref); + gen + ("}") + ("}"); + + // Repeated fields + } else if (field.repeated) { gen + ("if(%s!=null&&%s.length){", ref, ref); // !== undefined && !== null + + // Packed repeated + if (field.packed && types.packed[type] !== undefined) { gen + + ("w.uint32(%i).fork()", (field.id << 3 | 2) >>> 0) + ("for(var i=0;i<%s.length;++i)", ref) + ("w.%s(%s[i])", type, ref) + ("w.ldelim()"); + + // Non-packed + } else { gen + + ("for(var i=0;i<%s.length;++i)", ref); + if (wireType === undefined) + genTypePartial(gen, field, index, ref + "[i]"); + else gen + ("w.uint32(%i).%s(%s[i])", (field.id << 3 | wireType) >>> 0, type, ref); + + } gen + ("}"); + + // Non-repeated + } else { + if (field.optional) gen + ("if(%s!=null&&Object.hasOwnProperty.call(m,%j))", ref, field.name); // !== undefined && !== null + + if (wireType === undefined) + genTypePartial(gen, field, index, ref); + else gen + ("w.uint32(%i).%s(%s)", (field.id << 3 | wireType) >>> 0, type, ref); + + } + } + + return gen + ("return w"); + /* eslint-enable no-unexpected-multiline, block-scoped-var, no-redeclare */ +} + +},{"14":14,"32":32,"33":33}],14:[function(require,module,exports){ +"use strict"; +module.exports = Enum; + +// extends ReflectionObject +var ReflectionObject = require(22); +((Enum.prototype = Object.create(ReflectionObject.prototype)).constructor = Enum).className = "Enum"; + +var Namespace = require(21), + util = require(33); + +/** + * Constructs a new enum instance. + * @classdesc Reflected enum. + * @extends ReflectionObject + * @constructor + * @param {string} name Unique name within its namespace + * @param {Object.} [values] Enum values as an object, by name + * @param {Object.} [options] Declared options + * @param {string} [comment] The comment for this enum + * @param {Object.} [comments] The value comments for this enum + * @param {Object.>|undefined} [valuesOptions] The value options for this enum + */ +function Enum(name, values, options, comment, comments, valuesOptions) { + ReflectionObject.call(this, name, options); + + if (values && typeof values !== "object") + throw TypeError("values must be an object"); + + /** + * Enum values by id. + * @type {Object.} + */ + this.valuesById = {}; + + /** + * Enum values by name. + * @type {Object.} + */ + this.values = Object.create(this.valuesById); // toJSON, marker + + /** + * Enum comment text. + * @type {string|null} + */ + this.comment = comment; + + /** + * Value comment texts, if any. + * @type {Object.} + */ + this.comments = comments || {}; + + /** + * Values options, if any + * @type {Object>|undefined} + */ + this.valuesOptions = valuesOptions; + + /** + * Reserved ranges, if any. + * @type {Array.} + */ + this.reserved = undefined; // toJSON + + // Note that values inherit valuesById on their prototype which makes them a TypeScript- + // compatible enum. This is used by pbts to write actual enum definitions that work for + // static and reflection code alike instead of emitting generic object definitions. + + if (values) + for (var keys = Object.keys(values), i = 0; i < keys.length; ++i) + if (typeof values[keys[i]] === "number") // use forward entries only + this.valuesById[ this.values[keys[i]] = values[keys[i]] ] = keys[i]; +} + +/** + * Enum descriptor. + * @interface IEnum + * @property {Object.} values Enum values + * @property {Object.} [options] Enum options + */ + +/** + * Constructs an enum from an enum descriptor. + * @param {string} name Enum name + * @param {IEnum} json Enum descriptor + * @returns {Enum} Created enum + * @throws {TypeError} If arguments are invalid + */ +Enum.fromJSON = function fromJSON(name, json) { + var enm = new Enum(name, json.values, json.options, json.comment, json.comments); + enm.reserved = json.reserved; + return enm; +}; + +/** + * Converts this enum to an enum descriptor. + * @param {IToJSONOptions} [toJSONOptions] JSON conversion options + * @returns {IEnum} Enum descriptor + */ +Enum.prototype.toJSON = function toJSON(toJSONOptions) { + var keepComments = toJSONOptions ? Boolean(toJSONOptions.keepComments) : false; + return util.toObject([ + "options" , this.options, + "valuesOptions" , this.valuesOptions, + "values" , this.values, + "reserved" , this.reserved && this.reserved.length ? this.reserved : undefined, + "comment" , keepComments ? this.comment : undefined, + "comments" , keepComments ? this.comments : undefined + ]); +}; + +/** + * Adds a value to this enum. + * @param {string} name Value name + * @param {number} id Value id + * @param {string} [comment] Comment, if any + * @param {Object.|undefined} [options] Options, if any + * @returns {Enum} `this` + * @throws {TypeError} If arguments are invalid + * @throws {Error} If there is already a value with this name or id + */ +Enum.prototype.add = function add(name, id, comment, options) { + // utilized by the parser but not by .fromJSON + + if (!util.isString(name)) + throw TypeError("name must be a string"); + + if (!util.isInteger(id)) + throw TypeError("id must be an integer"); + + if (this.values[name] !== undefined) + throw Error("duplicate name '" + name + "' in " + this); + + if (this.isReservedId(id)) + throw Error("id " + id + " is reserved in " + this); + + if (this.isReservedName(name)) + throw Error("name '" + name + "' is reserved in " + this); + + if (this.valuesById[id] !== undefined) { + if (!(this.options && this.options.allow_alias)) + throw Error("duplicate id " + id + " in " + this); + this.values[name] = id; + } else + this.valuesById[this.values[name] = id] = name; + + if (options) { + if (this.valuesOptions === undefined) + this.valuesOptions = {}; + this.valuesOptions[name] = options || null; + } + + this.comments[name] = comment || null; + return this; +}; + +/** + * Removes a value from this enum + * @param {string} name Value name + * @returns {Enum} `this` + * @throws {TypeError} If arguments are invalid + * @throws {Error} If `name` is not a name of this enum + */ +Enum.prototype.remove = function remove(name) { + + if (!util.isString(name)) + throw TypeError("name must be a string"); + + var val = this.values[name]; + if (val == null) + throw Error("name '" + name + "' does not exist in " + this); + + delete this.valuesById[val]; + delete this.values[name]; + delete this.comments[name]; + if (this.valuesOptions) + delete this.valuesOptions[name]; + + return this; +}; + +/** + * Tests if the specified id is reserved. + * @param {number} id Id to test + * @returns {boolean} `true` if reserved, otherwise `false` + */ +Enum.prototype.isReservedId = function isReservedId(id) { + return Namespace.isReservedId(this.reserved, id); +}; + +/** + * Tests if the specified name is reserved. + * @param {string} name Name to test + * @returns {boolean} `true` if reserved, otherwise `false` + */ +Enum.prototype.isReservedName = function isReservedName(name) { + return Namespace.isReservedName(this.reserved, name); +}; + +},{"21":21,"22":22,"33":33}],15:[function(require,module,exports){ +"use strict"; +module.exports = Field; + +// extends ReflectionObject +var ReflectionObject = require(22); +((Field.prototype = Object.create(ReflectionObject.prototype)).constructor = Field).className = "Field"; + +var Enum = require(14), + types = require(32), + util = require(33); + +var Type; // cyclic + +var ruleRe = /^required|optional|repeated$/; + +/** + * Constructs a new message field instance. Note that {@link MapField|map fields} have their own class. + * @name Field + * @classdesc Reflected message field. + * @extends FieldBase + * @constructor + * @param {string} name Unique name within its namespace + * @param {number} id Unique id within its namespace + * @param {string} type Value type + * @param {string|Object.} [rule="optional"] Field rule + * @param {string|Object.} [extend] Extended type if different from parent + * @param {Object.} [options] Declared options + */ + +/** + * Constructs a field from a field descriptor. + * @param {string} name Field name + * @param {IField} json Field descriptor + * @returns {Field} Created field + * @throws {TypeError} If arguments are invalid + */ +Field.fromJSON = function fromJSON(name, json) { + return new Field(name, json.id, json.type, json.rule, json.extend, json.options, json.comment); +}; + +/** + * Not an actual constructor. Use {@link Field} instead. + * @classdesc Base class of all reflected message fields. This is not an actual class but here for the sake of having consistent type definitions. + * @exports FieldBase + * @extends ReflectionObject + * @constructor + * @param {string} name Unique name within its namespace + * @param {number} id Unique id within its namespace + * @param {string} type Value type + * @param {string|Object.} [rule="optional"] Field rule + * @param {string|Object.} [extend] Extended type if different from parent + * @param {Object.} [options] Declared options + * @param {string} [comment] Comment associated with this field + */ +function Field(name, id, type, rule, extend, options, comment) { + + if (util.isObject(rule)) { + comment = extend; + options = rule; + rule = extend = undefined; + } else if (util.isObject(extend)) { + comment = options; + options = extend; + extend = undefined; + } + + ReflectionObject.call(this, name, options); + + if (!util.isInteger(id) || id < 0) + throw TypeError("id must be a non-negative integer"); + + if (!util.isString(type)) + throw TypeError("type must be a string"); + + if (rule !== undefined && !ruleRe.test(rule = rule.toString().toLowerCase())) + throw TypeError("rule must be a string rule"); + + if (extend !== undefined && !util.isString(extend)) + throw TypeError("extend must be a string"); + + /** + * Field rule, if any. + * @type {string|undefined} + */ + if (rule === "proto3_optional") { + rule = "optional"; + } + this.rule = rule && rule !== "optional" ? rule : undefined; // toJSON + + /** + * Field type. + * @type {string} + */ + this.type = type; // toJSON + + /** + * Unique field id. + * @type {number} + */ + this.id = id; // toJSON, marker + + /** + * Extended type if different from parent. + * @type {string|undefined} + */ + this.extend = extend || undefined; // toJSON + + /** + * Whether this field is required. + * @type {boolean} + */ + this.required = rule === "required"; + + /** + * Whether this field is optional. + * @type {boolean} + */ + this.optional = !this.required; + + /** + * Whether this field is repeated. + * @type {boolean} + */ + this.repeated = rule === "repeated"; + + /** + * Whether this field is a map or not. + * @type {boolean} + */ + this.map = false; + + /** + * Message this field belongs to. + * @type {Type|null} + */ + this.message = null; + + /** + * OneOf this field belongs to, if any, + * @type {OneOf|null} + */ + this.partOf = null; + + /** + * The field type's default value. + * @type {*} + */ + this.typeDefault = null; + + /** + * The field's default value on prototypes. + * @type {*} + */ + this.defaultValue = null; + + /** + * Whether this field's value should be treated as a long. + * @type {boolean} + */ + this.long = util.Long ? types.long[type] !== undefined : /* istanbul ignore next */ false; + + /** + * Whether this field's value is a buffer. + * @type {boolean} + */ + this.bytes = type === "bytes"; + + /** + * Resolved type if not a basic type. + * @type {Type|Enum|null} + */ + this.resolvedType = null; + + /** + * Sister-field within the extended type if a declaring extension field. + * @type {Field|null} + */ + this.extensionField = null; + + /** + * Sister-field within the declaring namespace if an extended field. + * @type {Field|null} + */ + this.declaringField = null; + + /** + * Internally remembers whether this field is packed. + * @type {boolean|null} + * @private + */ + this._packed = null; + + /** + * Comment for this field. + * @type {string|null} + */ + this.comment = comment; +} + +/** + * Determines whether this field is packed. Only relevant when repeated and working with proto2. + * @name Field#packed + * @type {boolean} + * @readonly + */ +Object.defineProperty(Field.prototype, "packed", { + get: function() { + // defaults to packed=true if not explicity set to false + if (this._packed === null) + this._packed = this.getOption("packed") !== false; + return this._packed; + } +}); + +/** + * @override + */ +Field.prototype.setOption = function setOption(name, value, ifNotSet) { + if (name === "packed") // clear cached before setting + this._packed = null; + return ReflectionObject.prototype.setOption.call(this, name, value, ifNotSet); +}; + +/** + * Field descriptor. + * @interface IField + * @property {string} [rule="optional"] Field rule + * @property {string} type Field type + * @property {number} id Field id + * @property {Object.} [options] Field options + */ + +/** + * Extension field descriptor. + * @interface IExtensionField + * @extends IField + * @property {string} extend Extended type + */ + +/** + * Converts this field to a field descriptor. + * @param {IToJSONOptions} [toJSONOptions] JSON conversion options + * @returns {IField} Field descriptor + */ +Field.prototype.toJSON = function toJSON(toJSONOptions) { + var keepComments = toJSONOptions ? Boolean(toJSONOptions.keepComments) : false; + return util.toObject([ + "rule" , this.rule !== "optional" && this.rule || undefined, + "type" , this.type, + "id" , this.id, + "extend" , this.extend, + "options" , this.options, + "comment" , keepComments ? this.comment : undefined + ]); +}; + +/** + * Resolves this field's type references. + * @returns {Field} `this` + * @throws {Error} If any reference cannot be resolved + */ +Field.prototype.resolve = function resolve() { + + if (this.resolved) + return this; + + if ((this.typeDefault = types.defaults[this.type]) === undefined) { // if not a basic type, resolve it + this.resolvedType = (this.declaringField ? this.declaringField.parent : this.parent).lookupTypeOrEnum(this.type); + if (this.resolvedType instanceof Type) + this.typeDefault = null; + else // instanceof Enum + this.typeDefault = this.resolvedType.values[Object.keys(this.resolvedType.values)[0]]; // first defined + } else if (this.options && this.options.proto3_optional) { + // proto3 scalar value marked optional; should default to null + this.typeDefault = null; + } + + // use explicitly set default value if present + if (this.options && this.options["default"] != null) { + this.typeDefault = this.options["default"]; + if (this.resolvedType instanceof Enum && typeof this.typeDefault === "string") + this.typeDefault = this.resolvedType.values[this.typeDefault]; + } + + // remove unnecessary options + if (this.options) { + if (this.options.packed === true || this.options.packed !== undefined && this.resolvedType && !(this.resolvedType instanceof Enum)) + delete this.options.packed; + if (!Object.keys(this.options).length) + this.options = undefined; + } + + // convert to internal data type if necesssary + if (this.long) { + this.typeDefault = util.Long.fromNumber(this.typeDefault, this.type.charAt(0) === "u"); + + /* istanbul ignore else */ + if (Object.freeze) + Object.freeze(this.typeDefault); // long instances are meant to be immutable anyway (i.e. use small int cache that even requires it) + + } else if (this.bytes && typeof this.typeDefault === "string") { + var buf; + if (util.base64.test(this.typeDefault)) + util.base64.decode(this.typeDefault, buf = util.newBuffer(util.base64.length(this.typeDefault)), 0); + else + util.utf8.write(this.typeDefault, buf = util.newBuffer(util.utf8.length(this.typeDefault)), 0); + this.typeDefault = buf; + } + + // take special care of maps and repeated fields + if (this.map) + this.defaultValue = util.emptyObject; + else if (this.repeated) + this.defaultValue = util.emptyArray; + else + this.defaultValue = this.typeDefault; + + // ensure proper value on prototype + if (this.parent instanceof Type) + this.parent.ctor.prototype[this.name] = this.defaultValue; + + return ReflectionObject.prototype.resolve.call(this); +}; + +/** + * Decorator function as returned by {@link Field.d} and {@link MapField.d} (TypeScript). + * @typedef FieldDecorator + * @type {function} + * @param {Object} prototype Target prototype + * @param {string} fieldName Field name + * @returns {undefined} + */ + +/** + * Field decorator (TypeScript). + * @name Field.d + * @function + * @param {number} fieldId Field id + * @param {"double"|"float"|"int32"|"uint32"|"sint32"|"fixed32"|"sfixed32"|"int64"|"uint64"|"sint64"|"fixed64"|"sfixed64"|"string"|"bool"|"bytes"|Object} fieldType Field type + * @param {"optional"|"required"|"repeated"} [fieldRule="optional"] Field rule + * @param {T} [defaultValue] Default value + * @returns {FieldDecorator} Decorator function + * @template T extends number | number[] | Long | Long[] | string | string[] | boolean | boolean[] | Uint8Array | Uint8Array[] | Buffer | Buffer[] + */ +Field.d = function decorateField(fieldId, fieldType, fieldRule, defaultValue) { + + // submessage: decorate the submessage and use its name as the type + if (typeof fieldType === "function") + fieldType = util.decorateType(fieldType).name; + + // enum reference: create a reflected copy of the enum and keep reuseing it + else if (fieldType && typeof fieldType === "object") + fieldType = util.decorateEnum(fieldType).name; + + return function fieldDecorator(prototype, fieldName) { + util.decorateType(prototype.constructor) + .add(new Field(fieldName, fieldId, fieldType, fieldRule, { "default": defaultValue })); + }; +}; + +/** + * Field decorator (TypeScript). + * @name Field.d + * @function + * @param {number} fieldId Field id + * @param {Constructor|string} fieldType Field type + * @param {"optional"|"required"|"repeated"} [fieldRule="optional"] Field rule + * @returns {FieldDecorator} Decorator function + * @template T extends Message + * @variation 2 + */ +// like Field.d but without a default value + +// Sets up cyclic dependencies (called in index-light) +Field._configure = function configure(Type_) { + Type = Type_; +}; + +},{"14":14,"22":22,"32":32,"33":33}],16:[function(require,module,exports){ +"use strict"; +var protobuf = module.exports = require(17); + +protobuf.build = "light"; + +/** + * A node-style callback as used by {@link load} and {@link Root#load}. + * @typedef LoadCallback + * @type {function} + * @param {Error|null} error Error, if any, otherwise `null` + * @param {Root} [root] Root, if there hasn't been an error + * @returns {undefined} + */ + +/** + * Loads one or multiple .proto or preprocessed .json files into a common root namespace and calls the callback. + * @param {string|string[]} filename One or multiple files to load + * @param {Root} root Root namespace, defaults to create a new one if omitted. + * @param {LoadCallback} callback Callback function + * @returns {undefined} + * @see {@link Root#load} + */ +function load(filename, root, callback) { + if (typeof root === "function") { + callback = root; + root = new protobuf.Root(); + } else if (!root) + root = new protobuf.Root(); + return root.load(filename, callback); +} + +/** + * Loads one or multiple .proto or preprocessed .json files into a common root namespace and calls the callback. + * @name load + * @function + * @param {string|string[]} filename One or multiple files to load + * @param {LoadCallback} callback Callback function + * @returns {undefined} + * @see {@link Root#load} + * @variation 2 + */ +// function load(filename:string, callback:LoadCallback):undefined + +/** + * Loads one or multiple .proto or preprocessed .json files into a common root namespace and returns a promise. + * @name load + * @function + * @param {string|string[]} filename One or multiple files to load + * @param {Root} [root] Root namespace, defaults to create a new one if omitted. + * @returns {Promise} Promise + * @see {@link Root#load} + * @variation 3 + */ +// function load(filename:string, [root:Root]):Promise + +protobuf.load = load; + +/** + * Synchronously loads one or multiple .proto or preprocessed .json files into a common root namespace (node only). + * @param {string|string[]} filename One or multiple files to load + * @param {Root} [root] Root namespace, defaults to create a new one if omitted. + * @returns {Root} Root namespace + * @throws {Error} If synchronous fetching is not supported (i.e. in browsers) or if a file's syntax is invalid + * @see {@link Root#loadSync} + */ +function loadSync(filename, root) { + if (!root) + root = new protobuf.Root(); + return root.loadSync(filename); +} + +protobuf.loadSync = loadSync; + +// Serialization +protobuf.encoder = require(13); +protobuf.decoder = require(12); +protobuf.verifier = require(36); +protobuf.converter = require(11); + +// Reflection +protobuf.ReflectionObject = require(22); +protobuf.Namespace = require(21); +protobuf.Root = require(26); +protobuf.Enum = require(14); +protobuf.Type = require(31); +protobuf.Field = require(15); +protobuf.OneOf = require(23); +protobuf.MapField = require(18); +protobuf.Service = require(30); +protobuf.Method = require(20); + +// Runtime +protobuf.Message = require(19); +protobuf.wrappers = require(37); + +// Utility +protobuf.types = require(32); +protobuf.util = require(33); + +// Set up possibly cyclic reflection dependencies +protobuf.ReflectionObject._configure(protobuf.Root); +protobuf.Namespace._configure(protobuf.Type, protobuf.Service, protobuf.Enum); +protobuf.Root._configure(protobuf.Type); +protobuf.Field._configure(protobuf.Type); + +},{"11":11,"12":12,"13":13,"14":14,"15":15,"17":17,"18":18,"19":19,"20":20,"21":21,"22":22,"23":23,"26":26,"30":30,"31":31,"32":32,"33":33,"36":36,"37":37}],17:[function(require,module,exports){ +"use strict"; +var protobuf = exports; + +/** + * Build type, one of `"full"`, `"light"` or `"minimal"`. + * @name build + * @type {string} + * @const + */ +protobuf.build = "minimal"; + +// Serialization +protobuf.Writer = require(38); +protobuf.BufferWriter = require(39); +protobuf.Reader = require(24); +protobuf.BufferReader = require(25); + +// Utility +protobuf.util = require(35); +protobuf.rpc = require(28); +protobuf.roots = require(27); +protobuf.configure = configure; + +/* istanbul ignore next */ +/** + * Reconfigures the library according to the environment. + * @returns {undefined} + */ +function configure() { + protobuf.util._configure(); + protobuf.Writer._configure(protobuf.BufferWriter); + protobuf.Reader._configure(protobuf.BufferReader); +} + +// Set up buffer utility according to the environment +configure(); + +},{"24":24,"25":25,"27":27,"28":28,"35":35,"38":38,"39":39}],18:[function(require,module,exports){ +"use strict"; +module.exports = MapField; + +// extends Field +var Field = require(15); +((MapField.prototype = Object.create(Field.prototype)).constructor = MapField).className = "MapField"; + +var types = require(32), + util = require(33); + +/** + * Constructs a new map field instance. + * @classdesc Reflected map field. + * @extends FieldBase + * @constructor + * @param {string} name Unique name within its namespace + * @param {number} id Unique id within its namespace + * @param {string} keyType Key type + * @param {string} type Value type + * @param {Object.} [options] Declared options + * @param {string} [comment] Comment associated with this field + */ +function MapField(name, id, keyType, type, options, comment) { + Field.call(this, name, id, type, undefined, undefined, options, comment); + + /* istanbul ignore if */ + if (!util.isString(keyType)) + throw TypeError("keyType must be a string"); + + /** + * Key type. + * @type {string} + */ + this.keyType = keyType; // toJSON, marker + + /** + * Resolved key type if not a basic type. + * @type {ReflectionObject|null} + */ + this.resolvedKeyType = null; + + // Overrides Field#map + this.map = true; +} + +/** + * Map field descriptor. + * @interface IMapField + * @extends {IField} + * @property {string} keyType Key type + */ + +/** + * Extension map field descriptor. + * @interface IExtensionMapField + * @extends IMapField + * @property {string} extend Extended type + */ + +/** + * Constructs a map field from a map field descriptor. + * @param {string} name Field name + * @param {IMapField} json Map field descriptor + * @returns {MapField} Created map field + * @throws {TypeError} If arguments are invalid + */ +MapField.fromJSON = function fromJSON(name, json) { + return new MapField(name, json.id, json.keyType, json.type, json.options, json.comment); +}; + +/** + * Converts this map field to a map field descriptor. + * @param {IToJSONOptions} [toJSONOptions] JSON conversion options + * @returns {IMapField} Map field descriptor + */ +MapField.prototype.toJSON = function toJSON(toJSONOptions) { + var keepComments = toJSONOptions ? Boolean(toJSONOptions.keepComments) : false; + return util.toObject([ + "keyType" , this.keyType, + "type" , this.type, + "id" , this.id, + "extend" , this.extend, + "options" , this.options, + "comment" , keepComments ? this.comment : undefined + ]); +}; + +/** + * @override + */ +MapField.prototype.resolve = function resolve() { + if (this.resolved) + return this; + + // Besides a value type, map fields have a key type that may be "any scalar type except for floating point types and bytes" + if (types.mapKey[this.keyType] === undefined) + throw Error("invalid key type: " + this.keyType); + + return Field.prototype.resolve.call(this); +}; + +/** + * Map field decorator (TypeScript). + * @name MapField.d + * @function + * @param {number} fieldId Field id + * @param {"int32"|"uint32"|"sint32"|"fixed32"|"sfixed32"|"int64"|"uint64"|"sint64"|"fixed64"|"sfixed64"|"bool"|"string"} fieldKeyType Field key type + * @param {"double"|"float"|"int32"|"uint32"|"sint32"|"fixed32"|"sfixed32"|"int64"|"uint64"|"sint64"|"fixed64"|"sfixed64"|"bool"|"string"|"bytes"|Object|Constructor<{}>} fieldValueType Field value type + * @returns {FieldDecorator} Decorator function + * @template T extends { [key: string]: number | Long | string | boolean | Uint8Array | Buffer | number[] | Message<{}> } + */ +MapField.d = function decorateMapField(fieldId, fieldKeyType, fieldValueType) { + + // submessage value: decorate the submessage and use its name as the type + if (typeof fieldValueType === "function") + fieldValueType = util.decorateType(fieldValueType).name; + + // enum reference value: create a reflected copy of the enum and keep reuseing it + else if (fieldValueType && typeof fieldValueType === "object") + fieldValueType = util.decorateEnum(fieldValueType).name; + + return function mapFieldDecorator(prototype, fieldName) { + util.decorateType(prototype.constructor) + .add(new MapField(fieldName, fieldId, fieldKeyType, fieldValueType)); + }; +}; + +},{"15":15,"32":32,"33":33}],19:[function(require,module,exports){ +"use strict"; +module.exports = Message; + +var util = require(35); + +/** + * Constructs a new message instance. + * @classdesc Abstract runtime message. + * @constructor + * @param {Properties} [properties] Properties to set + * @template T extends object = object + */ +function Message(properties) { + // not used internally + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + this[keys[i]] = properties[keys[i]]; +} + +/** + * Reference to the reflected type. + * @name Message.$type + * @type {Type} + * @readonly + */ + +/** + * Reference to the reflected type. + * @name Message#$type + * @type {Type} + * @readonly + */ + +/*eslint-disable valid-jsdoc*/ + +/** + * Creates a new message of this type using the specified properties. + * @param {Object.} [properties] Properties to set + * @returns {Message} Message instance + * @template T extends Message + * @this Constructor + */ +Message.create = function create(properties) { + return this.$type.create(properties); +}; + +/** + * Encodes a message of this type. + * @param {T|Object.} message Message to encode + * @param {Writer} [writer] Writer to use + * @returns {Writer} Writer + * @template T extends Message + * @this Constructor + */ +Message.encode = function encode(message, writer) { + return this.$type.encode(message, writer); +}; + +/** + * Encodes a message of this type preceeded by its length as a varint. + * @param {T|Object.} message Message to encode + * @param {Writer} [writer] Writer to use + * @returns {Writer} Writer + * @template T extends Message + * @this Constructor + */ +Message.encodeDelimited = function encodeDelimited(message, writer) { + return this.$type.encodeDelimited(message, writer); +}; + +/** + * Decodes a message of this type. + * @name Message.decode + * @function + * @param {Reader|Uint8Array} reader Reader or buffer to decode + * @returns {T} Decoded message + * @template T extends Message + * @this Constructor + */ +Message.decode = function decode(reader) { + return this.$type.decode(reader); +}; + +/** + * Decodes a message of this type preceeded by its length as a varint. + * @name Message.decodeDelimited + * @function + * @param {Reader|Uint8Array} reader Reader or buffer to decode + * @returns {T} Decoded message + * @template T extends Message + * @this Constructor + */ +Message.decodeDelimited = function decodeDelimited(reader) { + return this.$type.decodeDelimited(reader); +}; + +/** + * Verifies a message of this type. + * @name Message.verify + * @function + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ +Message.verify = function verify(message) { + return this.$type.verify(message); +}; + +/** + * Creates a new message of this type from a plain object. Also converts values to their respective internal types. + * @param {Object.} object Plain object + * @returns {T} Message instance + * @template T extends Message + * @this Constructor + */ +Message.fromObject = function fromObject(object) { + return this.$type.fromObject(object); +}; + +/** + * Creates a plain object from a message of this type. Also converts values to other types if specified. + * @param {T} message Message instance + * @param {IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + * @template T extends Message + * @this Constructor + */ +Message.toObject = function toObject(message, options) { + return this.$type.toObject(message, options); +}; + +/** + * Converts this message to JSON. + * @returns {Object.} JSON object + */ +Message.prototype.toJSON = function toJSON() { + return this.$type.toObject(this, util.toJSONOptions); +}; + +/*eslint-enable valid-jsdoc*/ +},{"35":35}],20:[function(require,module,exports){ +"use strict"; +module.exports = Method; + +// extends ReflectionObject +var ReflectionObject = require(22); +((Method.prototype = Object.create(ReflectionObject.prototype)).constructor = Method).className = "Method"; + +var util = require(33); + +/** + * Constructs a new service method instance. + * @classdesc Reflected service method. + * @extends ReflectionObject + * @constructor + * @param {string} name Method name + * @param {string|undefined} type Method type, usually `"rpc"` + * @param {string} requestType Request message type + * @param {string} responseType Response message type + * @param {boolean|Object.} [requestStream] Whether the request is streamed + * @param {boolean|Object.} [responseStream] Whether the response is streamed + * @param {Object.} [options] Declared options + * @param {string} [comment] The comment for this method + * @param {Object.} [parsedOptions] Declared options, properly parsed into an object + */ +function Method(name, type, requestType, responseType, requestStream, responseStream, options, comment, parsedOptions) { + + /* istanbul ignore next */ + if (util.isObject(requestStream)) { + options = requestStream; + requestStream = responseStream = undefined; + } else if (util.isObject(responseStream)) { + options = responseStream; + responseStream = undefined; + } + + /* istanbul ignore if */ + if (!(type === undefined || util.isString(type))) + throw TypeError("type must be a string"); + + /* istanbul ignore if */ + if (!util.isString(requestType)) + throw TypeError("requestType must be a string"); + + /* istanbul ignore if */ + if (!util.isString(responseType)) + throw TypeError("responseType must be a string"); + + ReflectionObject.call(this, name, options); + + /** + * Method type. + * @type {string} + */ + this.type = type || "rpc"; // toJSON + + /** + * Request type. + * @type {string} + */ + this.requestType = requestType; // toJSON, marker + + /** + * Whether requests are streamed or not. + * @type {boolean|undefined} + */ + this.requestStream = requestStream ? true : undefined; // toJSON + + /** + * Response type. + * @type {string} + */ + this.responseType = responseType; // toJSON + + /** + * Whether responses are streamed or not. + * @type {boolean|undefined} + */ + this.responseStream = responseStream ? true : undefined; // toJSON + + /** + * Resolved request type. + * @type {Type|null} + */ + this.resolvedRequestType = null; + + /** + * Resolved response type. + * @type {Type|null} + */ + this.resolvedResponseType = null; + + /** + * Comment for this method + * @type {string|null} + */ + this.comment = comment; + + /** + * Options properly parsed into an object + */ + this.parsedOptions = parsedOptions; +} + +/** + * Method descriptor. + * @interface IMethod + * @property {string} [type="rpc"] Method type + * @property {string} requestType Request type + * @property {string} responseType Response type + * @property {boolean} [requestStream=false] Whether requests are streamed + * @property {boolean} [responseStream=false] Whether responses are streamed + * @property {Object.} [options] Method options + * @property {string} comment Method comments + * @property {Object.} [parsedOptions] Method options properly parsed into an object + */ + +/** + * Constructs a method from a method descriptor. + * @param {string} name Method name + * @param {IMethod} json Method descriptor + * @returns {Method} Created method + * @throws {TypeError} If arguments are invalid + */ +Method.fromJSON = function fromJSON(name, json) { + return new Method(name, json.type, json.requestType, json.responseType, json.requestStream, json.responseStream, json.options, json.comment, json.parsedOptions); +}; + +/** + * Converts this method to a method descriptor. + * @param {IToJSONOptions} [toJSONOptions] JSON conversion options + * @returns {IMethod} Method descriptor + */ +Method.prototype.toJSON = function toJSON(toJSONOptions) { + var keepComments = toJSONOptions ? Boolean(toJSONOptions.keepComments) : false; + return util.toObject([ + "type" , this.type !== "rpc" && /* istanbul ignore next */ this.type || undefined, + "requestType" , this.requestType, + "requestStream" , this.requestStream, + "responseType" , this.responseType, + "responseStream" , this.responseStream, + "options" , this.options, + "comment" , keepComments ? this.comment : undefined, + "parsedOptions" , this.parsedOptions, + ]); +}; + +/** + * @override + */ +Method.prototype.resolve = function resolve() { + + /* istanbul ignore if */ + if (this.resolved) + return this; + + this.resolvedRequestType = this.parent.lookupType(this.requestType); + this.resolvedResponseType = this.parent.lookupType(this.responseType); + + return ReflectionObject.prototype.resolve.call(this); +}; + +},{"22":22,"33":33}],21:[function(require,module,exports){ +"use strict"; +module.exports = Namespace; + +// extends ReflectionObject +var ReflectionObject = require(22); +((Namespace.prototype = Object.create(ReflectionObject.prototype)).constructor = Namespace).className = "Namespace"; + +var Field = require(15), + util = require(33), + OneOf = require(23); + +var Type, // cyclic + Service, + Enum; + +/** + * Constructs a new namespace instance. + * @name Namespace + * @classdesc Reflected namespace. + * @extends NamespaceBase + * @constructor + * @param {string} name Namespace name + * @param {Object.} [options] Declared options + */ + +/** + * Constructs a namespace from JSON. + * @memberof Namespace + * @function + * @param {string} name Namespace name + * @param {Object.} json JSON object + * @returns {Namespace} Created namespace + * @throws {TypeError} If arguments are invalid + */ +Namespace.fromJSON = function fromJSON(name, json) { + return new Namespace(name, json.options).addJSON(json.nested); +}; + +/** + * Converts an array of reflection objects to JSON. + * @memberof Namespace + * @param {ReflectionObject[]} array Object array + * @param {IToJSONOptions} [toJSONOptions] JSON conversion options + * @returns {Object.|undefined} JSON object or `undefined` when array is empty + */ +function arrayToJSON(array, toJSONOptions) { + if (!(array && array.length)) + return undefined; + var obj = {}; + for (var i = 0; i < array.length; ++i) + obj[array[i].name] = array[i].toJSON(toJSONOptions); + return obj; +} + +Namespace.arrayToJSON = arrayToJSON; + +/** + * Tests if the specified id is reserved. + * @param {Array.|undefined} reserved Array of reserved ranges and names + * @param {number} id Id to test + * @returns {boolean} `true` if reserved, otherwise `false` + */ +Namespace.isReservedId = function isReservedId(reserved, id) { + if (reserved) + for (var i = 0; i < reserved.length; ++i) + if (typeof reserved[i] !== "string" && reserved[i][0] <= id && reserved[i][1] > id) + return true; + return false; +}; + +/** + * Tests if the specified name is reserved. + * @param {Array.|undefined} reserved Array of reserved ranges and names + * @param {string} name Name to test + * @returns {boolean} `true` if reserved, otherwise `false` + */ +Namespace.isReservedName = function isReservedName(reserved, name) { + if (reserved) + for (var i = 0; i < reserved.length; ++i) + if (reserved[i] === name) + return true; + return false; +}; + +/** + * Not an actual constructor. Use {@link Namespace} instead. + * @classdesc Base class of all reflection objects containing nested objects. This is not an actual class but here for the sake of having consistent type definitions. + * @exports NamespaceBase + * @extends ReflectionObject + * @abstract + * @constructor + * @param {string} name Namespace name + * @param {Object.} [options] Declared options + * @see {@link Namespace} + */ +function Namespace(name, options) { + ReflectionObject.call(this, name, options); + + /** + * Nested objects by name. + * @type {Object.|undefined} + */ + this.nested = undefined; // toJSON + + /** + * Cached nested objects as an array. + * @type {ReflectionObject[]|null} + * @private + */ + this._nestedArray = null; +} + +function clearCache(namespace) { + namespace._nestedArray = null; + return namespace; +} + +/** + * Nested objects of this namespace as an array for iteration. + * @name NamespaceBase#nestedArray + * @type {ReflectionObject[]} + * @readonly + */ +Object.defineProperty(Namespace.prototype, "nestedArray", { + get: function() { + return this._nestedArray || (this._nestedArray = util.toArray(this.nested)); + } +}); + +/** + * Namespace descriptor. + * @interface INamespace + * @property {Object.} [options] Namespace options + * @property {Object.} [nested] Nested object descriptors + */ + +/** + * Any extension field descriptor. + * @typedef AnyExtensionField + * @type {IExtensionField|IExtensionMapField} + */ + +/** + * Any nested object descriptor. + * @typedef AnyNestedObject + * @type {IEnum|IType|IService|AnyExtensionField|INamespace|IOneOf} + */ + +/** + * Converts this namespace to a namespace descriptor. + * @param {IToJSONOptions} [toJSONOptions] JSON conversion options + * @returns {INamespace} Namespace descriptor + */ +Namespace.prototype.toJSON = function toJSON(toJSONOptions) { + return util.toObject([ + "options" , this.options, + "nested" , arrayToJSON(this.nestedArray, toJSONOptions) + ]); +}; + +/** + * Adds nested objects to this namespace from nested object descriptors. + * @param {Object.} nestedJson Any nested object descriptors + * @returns {Namespace} `this` + */ +Namespace.prototype.addJSON = function addJSON(nestedJson) { + var ns = this; + /* istanbul ignore else */ + if (nestedJson) { + for (var names = Object.keys(nestedJson), i = 0, nested; i < names.length; ++i) { + nested = nestedJson[names[i]]; + ns.add( // most to least likely + ( nested.fields !== undefined + ? Type.fromJSON + : nested.values !== undefined + ? Enum.fromJSON + : nested.methods !== undefined + ? Service.fromJSON + : nested.id !== undefined + ? Field.fromJSON + : Namespace.fromJSON )(names[i], nested) + ); + } + } + return this; +}; + +/** + * Gets the nested object of the specified name. + * @param {string} name Nested object name + * @returns {ReflectionObject|null} The reflection object or `null` if it doesn't exist + */ +Namespace.prototype.get = function get(name) { + return this.nested && this.nested[name] + || null; +}; + +/** + * Gets the values of the nested {@link Enum|enum} of the specified name. + * This methods differs from {@link Namespace#get|get} in that it returns an enum's values directly and throws instead of returning `null`. + * @param {string} name Nested enum name + * @returns {Object.} Enum values + * @throws {Error} If there is no such enum + */ +Namespace.prototype.getEnum = function getEnum(name) { + if (this.nested && this.nested[name] instanceof Enum) + return this.nested[name].values; + throw Error("no such enum: " + name); +}; + +/** + * Adds a nested object to this namespace. + * @param {ReflectionObject} object Nested object to add + * @returns {Namespace} `this` + * @throws {TypeError} If arguments are invalid + * @throws {Error} If there is already a nested object with this name + */ +Namespace.prototype.add = function add(object) { + + if (!(object instanceof Field && object.extend !== undefined || object instanceof Type || object instanceof OneOf || object instanceof Enum || object instanceof Service || object instanceof Namespace)) + throw TypeError("object must be a valid nested object"); + + if (!this.nested) + this.nested = {}; + else { + var prev = this.get(object.name); + if (prev) { + if (prev instanceof Namespace && object instanceof Namespace && !(prev instanceof Type || prev instanceof Service)) { + // replace plain namespace but keep existing nested elements and options + var nested = prev.nestedArray; + for (var i = 0; i < nested.length; ++i) + object.add(nested[i]); + this.remove(prev); + if (!this.nested) + this.nested = {}; + object.setOptions(prev.options, true); + + } else + throw Error("duplicate name '" + object.name + "' in " + this); + } + } + this.nested[object.name] = object; + object.onAdd(this); + return clearCache(this); +}; + +/** + * Removes a nested object from this namespace. + * @param {ReflectionObject} object Nested object to remove + * @returns {Namespace} `this` + * @throws {TypeError} If arguments are invalid + * @throws {Error} If `object` is not a member of this namespace + */ +Namespace.prototype.remove = function remove(object) { + + if (!(object instanceof ReflectionObject)) + throw TypeError("object must be a ReflectionObject"); + if (object.parent !== this) + throw Error(object + " is not a member of " + this); + + delete this.nested[object.name]; + if (!Object.keys(this.nested).length) + this.nested = undefined; + + object.onRemove(this); + return clearCache(this); +}; + +/** + * Defines additial namespaces within this one if not yet existing. + * @param {string|string[]} path Path to create + * @param {*} [json] Nested types to create from JSON + * @returns {Namespace} Pointer to the last namespace created or `this` if path is empty + */ +Namespace.prototype.define = function define(path, json) { + + if (util.isString(path)) + path = path.split("."); + else if (!Array.isArray(path)) + throw TypeError("illegal path"); + if (path && path.length && path[0] === "") + throw Error("path must be relative"); + + var ptr = this; + while (path.length > 0) { + var part = path.shift(); + if (ptr.nested && ptr.nested[part]) { + ptr = ptr.nested[part]; + if (!(ptr instanceof Namespace)) + throw Error("path conflicts with non-namespace objects"); + } else + ptr.add(ptr = new Namespace(part)); + } + if (json) + ptr.addJSON(json); + return ptr; +}; + +/** + * Resolves this namespace's and all its nested objects' type references. Useful to validate a reflection tree, but comes at a cost. + * @returns {Namespace} `this` + */ +Namespace.prototype.resolveAll = function resolveAll() { + var nested = this.nestedArray, i = 0; + while (i < nested.length) + if (nested[i] instanceof Namespace) + nested[i++].resolveAll(); + else + nested[i++].resolve(); + return this.resolve(); +}; + +/** + * Recursively looks up the reflection object matching the specified path in the scope of this namespace. + * @param {string|string[]} path Path to look up + * @param {*|Array.<*>} filterTypes Filter types, any combination of the constructors of `protobuf.Type`, `protobuf.Enum`, `protobuf.Service` etc. + * @param {boolean} [parentAlreadyChecked=false] If known, whether the parent has already been checked + * @returns {ReflectionObject|null} Looked up object or `null` if none could be found + */ +Namespace.prototype.lookup = function lookup(path, filterTypes, parentAlreadyChecked) { + + /* istanbul ignore next */ + if (typeof filterTypes === "boolean") { + parentAlreadyChecked = filterTypes; + filterTypes = undefined; + } else if (filterTypes && !Array.isArray(filterTypes)) + filterTypes = [ filterTypes ]; + + if (util.isString(path) && path.length) { + if (path === ".") + return this.root; + path = path.split("."); + } else if (!path.length) + return this; + + // Start at root if path is absolute + if (path[0] === "") + return this.root.lookup(path.slice(1), filterTypes); + + // Test if the first part matches any nested object, and if so, traverse if path contains more + var found = this.get(path[0]); + if (found) { + if (path.length === 1) { + if (!filterTypes || filterTypes.indexOf(found.constructor) > -1) + return found; + } else if (found instanceof Namespace && (found = found.lookup(path.slice(1), filterTypes, true))) + return found; + + // Otherwise try each nested namespace + } else + for (var i = 0; i < this.nestedArray.length; ++i) + if (this._nestedArray[i] instanceof Namespace && (found = this._nestedArray[i].lookup(path, filterTypes, true))) + return found; + + // If there hasn't been a match, try again at the parent + if (this.parent === null || parentAlreadyChecked) + return null; + return this.parent.lookup(path, filterTypes); +}; + +/** + * Looks up the reflection object at the specified path, relative to this namespace. + * @name NamespaceBase#lookup + * @function + * @param {string|string[]} path Path to look up + * @param {boolean} [parentAlreadyChecked=false] Whether the parent has already been checked + * @returns {ReflectionObject|null} Looked up object or `null` if none could be found + * @variation 2 + */ +// lookup(path: string, [parentAlreadyChecked: boolean]) + +/** + * Looks up the {@link Type|type} at the specified path, relative to this namespace. + * Besides its signature, this methods differs from {@link Namespace#lookup|lookup} in that it throws instead of returning `null`. + * @param {string|string[]} path Path to look up + * @returns {Type} Looked up type + * @throws {Error} If `path` does not point to a type + */ +Namespace.prototype.lookupType = function lookupType(path) { + var found = this.lookup(path, [ Type ]); + if (!found) + throw Error("no such type: " + path); + return found; +}; + +/** + * Looks up the values of the {@link Enum|enum} at the specified path, relative to this namespace. + * Besides its signature, this methods differs from {@link Namespace#lookup|lookup} in that it throws instead of returning `null`. + * @param {string|string[]} path Path to look up + * @returns {Enum} Looked up enum + * @throws {Error} If `path` does not point to an enum + */ +Namespace.prototype.lookupEnum = function lookupEnum(path) { + var found = this.lookup(path, [ Enum ]); + if (!found) + throw Error("no such Enum '" + path + "' in " + this); + return found; +}; + +/** + * Looks up the {@link Type|type} or {@link Enum|enum} at the specified path, relative to this namespace. + * Besides its signature, this methods differs from {@link Namespace#lookup|lookup} in that it throws instead of returning `null`. + * @param {string|string[]} path Path to look up + * @returns {Type} Looked up type or enum + * @throws {Error} If `path` does not point to a type or enum + */ +Namespace.prototype.lookupTypeOrEnum = function lookupTypeOrEnum(path) { + var found = this.lookup(path, [ Type, Enum ]); + if (!found) + throw Error("no such Type or Enum '" + path + "' in " + this); + return found; +}; + +/** + * Looks up the {@link Service|service} at the specified path, relative to this namespace. + * Besides its signature, this methods differs from {@link Namespace#lookup|lookup} in that it throws instead of returning `null`. + * @param {string|string[]} path Path to look up + * @returns {Service} Looked up service + * @throws {Error} If `path` does not point to a service + */ +Namespace.prototype.lookupService = function lookupService(path) { + var found = this.lookup(path, [ Service ]); + if (!found) + throw Error("no such Service '" + path + "' in " + this); + return found; +}; + +// Sets up cyclic dependencies (called in index-light) +Namespace._configure = function(Type_, Service_, Enum_) { + Type = Type_; + Service = Service_; + Enum = Enum_; +}; + +},{"15":15,"22":22,"23":23,"33":33}],22:[function(require,module,exports){ +"use strict"; +module.exports = ReflectionObject; + +ReflectionObject.className = "ReflectionObject"; + +var util = require(33); + +var Root; // cyclic + +/** + * Constructs a new reflection object instance. + * @classdesc Base class of all reflection objects. + * @constructor + * @param {string} name Object name + * @param {Object.} [options] Declared options + * @abstract + */ +function ReflectionObject(name, options) { + + if (!util.isString(name)) + throw TypeError("name must be a string"); + + if (options && !util.isObject(options)) + throw TypeError("options must be an object"); + + /** + * Options. + * @type {Object.|undefined} + */ + this.options = options; // toJSON + + /** + * Parsed Options. + * @type {Array.>|undefined} + */ + this.parsedOptions = null; + + /** + * Unique name within its namespace. + * @type {string} + */ + this.name = name; + + /** + * Parent namespace. + * @type {Namespace|null} + */ + this.parent = null; + + /** + * Whether already resolved or not. + * @type {boolean} + */ + this.resolved = false; + + /** + * Comment text, if any. + * @type {string|null} + */ + this.comment = null; + + /** + * Defining file name. + * @type {string|null} + */ + this.filename = null; +} + +Object.defineProperties(ReflectionObject.prototype, { + + /** + * Reference to the root namespace. + * @name ReflectionObject#root + * @type {Root} + * @readonly + */ + root: { + get: function() { + var ptr = this; + while (ptr.parent !== null) + ptr = ptr.parent; + return ptr; + } + }, + + /** + * Full name including leading dot. + * @name ReflectionObject#fullName + * @type {string} + * @readonly + */ + fullName: { + get: function() { + var path = [ this.name ], + ptr = this.parent; + while (ptr) { + path.unshift(ptr.name); + ptr = ptr.parent; + } + return path.join("."); + } + } +}); + +/** + * Converts this reflection object to its descriptor representation. + * @returns {Object.} Descriptor + * @abstract + */ +ReflectionObject.prototype.toJSON = /* istanbul ignore next */ function toJSON() { + throw Error(); // not implemented, shouldn't happen +}; + +/** + * Called when this object is added to a parent. + * @param {ReflectionObject} parent Parent added to + * @returns {undefined} + */ +ReflectionObject.prototype.onAdd = function onAdd(parent) { + if (this.parent && this.parent !== parent) + this.parent.remove(this); + this.parent = parent; + this.resolved = false; + var root = parent.root; + if (root instanceof Root) + root._handleAdd(this); +}; + +/** + * Called when this object is removed from a parent. + * @param {ReflectionObject} parent Parent removed from + * @returns {undefined} + */ +ReflectionObject.prototype.onRemove = function onRemove(parent) { + var root = parent.root; + if (root instanceof Root) + root._handleRemove(this); + this.parent = null; + this.resolved = false; +}; + +/** + * Resolves this objects type references. + * @returns {ReflectionObject} `this` + */ +ReflectionObject.prototype.resolve = function resolve() { + if (this.resolved) + return this; + if (this.root instanceof Root) + this.resolved = true; // only if part of a root + return this; +}; + +/** + * Gets an option value. + * @param {string} name Option name + * @returns {*} Option value or `undefined` if not set + */ +ReflectionObject.prototype.getOption = function getOption(name) { + if (this.options) + return this.options[name]; + return undefined; +}; + +/** + * Sets an option. + * @param {string} name Option name + * @param {*} value Option value + * @param {boolean} [ifNotSet] Sets the option only if it isn't currently set + * @returns {ReflectionObject} `this` + */ +ReflectionObject.prototype.setOption = function setOption(name, value, ifNotSet) { + if (!ifNotSet || !this.options || this.options[name] === undefined) + (this.options || (this.options = {}))[name] = value; + return this; +}; + +/** + * Sets a parsed option. + * @param {string} name parsed Option name + * @param {*} value Option value + * @param {string} propName dot '.' delimited full path of property within the option to set. if undefined\empty, will add a new option with that value + * @returns {ReflectionObject} `this` + */ +ReflectionObject.prototype.setParsedOption = function setParsedOption(name, value, propName) { + if (!this.parsedOptions) { + this.parsedOptions = []; + } + var parsedOptions = this.parsedOptions; + if (propName) { + // If setting a sub property of an option then try to merge it + // with an existing option + var opt = parsedOptions.find(function (opt) { + return Object.prototype.hasOwnProperty.call(opt, name); + }); + if (opt) { + // If we found an existing option - just merge the property value + var newValue = opt[name]; + util.setProperty(newValue, propName, value); + } else { + // otherwise, create a new option, set it's property and add it to the list + opt = {}; + opt[name] = util.setProperty({}, propName, value); + parsedOptions.push(opt); + } + } else { + // Always create a new option when setting the value of the option itself + var newOpt = {}; + newOpt[name] = value; + parsedOptions.push(newOpt); + } + return this; +}; + +/** + * Sets multiple options. + * @param {Object.} options Options to set + * @param {boolean} [ifNotSet] Sets an option only if it isn't currently set + * @returns {ReflectionObject} `this` + */ +ReflectionObject.prototype.setOptions = function setOptions(options, ifNotSet) { + if (options) + for (var keys = Object.keys(options), i = 0; i < keys.length; ++i) + this.setOption(keys[i], options[keys[i]], ifNotSet); + return this; +}; + +/** + * Converts this instance to its string representation. + * @returns {string} Class name[, space, full name] + */ +ReflectionObject.prototype.toString = function toString() { + var className = this.constructor.className, + fullName = this.fullName; + if (fullName.length) + return className + " " + fullName; + return className; +}; + +// Sets up cyclic dependencies (called in index-light) +ReflectionObject._configure = function(Root_) { + Root = Root_; +}; + +},{"33":33}],23:[function(require,module,exports){ +"use strict"; +module.exports = OneOf; + +// extends ReflectionObject +var ReflectionObject = require(22); +((OneOf.prototype = Object.create(ReflectionObject.prototype)).constructor = OneOf).className = "OneOf"; + +var Field = require(15), + util = require(33); + +/** + * Constructs a new oneof instance. + * @classdesc Reflected oneof. + * @extends ReflectionObject + * @constructor + * @param {string} name Oneof name + * @param {string[]|Object.} [fieldNames] Field names + * @param {Object.} [options] Declared options + * @param {string} [comment] Comment associated with this field + */ +function OneOf(name, fieldNames, options, comment) { + if (!Array.isArray(fieldNames)) { + options = fieldNames; + fieldNames = undefined; + } + ReflectionObject.call(this, name, options); + + /* istanbul ignore if */ + if (!(fieldNames === undefined || Array.isArray(fieldNames))) + throw TypeError("fieldNames must be an Array"); + + /** + * Field names that belong to this oneof. + * @type {string[]} + */ + this.oneof = fieldNames || []; // toJSON, marker + + /** + * Fields that belong to this oneof as an array for iteration. + * @type {Field[]} + * @readonly + */ + this.fieldsArray = []; // declared readonly for conformance, possibly not yet added to parent + + /** + * Comment for this field. + * @type {string|null} + */ + this.comment = comment; +} + +/** + * Oneof descriptor. + * @interface IOneOf + * @property {Array.} oneof Oneof field names + * @property {Object.} [options] Oneof options + */ + +/** + * Constructs a oneof from a oneof descriptor. + * @param {string} name Oneof name + * @param {IOneOf} json Oneof descriptor + * @returns {OneOf} Created oneof + * @throws {TypeError} If arguments are invalid + */ +OneOf.fromJSON = function fromJSON(name, json) { + return new OneOf(name, json.oneof, json.options, json.comment); +}; + +/** + * Converts this oneof to a oneof descriptor. + * @param {IToJSONOptions} [toJSONOptions] JSON conversion options + * @returns {IOneOf} Oneof descriptor + */ +OneOf.prototype.toJSON = function toJSON(toJSONOptions) { + var keepComments = toJSONOptions ? Boolean(toJSONOptions.keepComments) : false; + return util.toObject([ + "options" , this.options, + "oneof" , this.oneof, + "comment" , keepComments ? this.comment : undefined + ]); +}; + +/** + * Adds the fields of the specified oneof to the parent if not already done so. + * @param {OneOf} oneof The oneof + * @returns {undefined} + * @inner + * @ignore + */ +function addFieldsToParent(oneof) { + if (oneof.parent) + for (var i = 0; i < oneof.fieldsArray.length; ++i) + if (!oneof.fieldsArray[i].parent) + oneof.parent.add(oneof.fieldsArray[i]); +} + +/** + * Adds a field to this oneof and removes it from its current parent, if any. + * @param {Field} field Field to add + * @returns {OneOf} `this` + */ +OneOf.prototype.add = function add(field) { + + /* istanbul ignore if */ + if (!(field instanceof Field)) + throw TypeError("field must be a Field"); + + if (field.parent && field.parent !== this.parent) + field.parent.remove(field); + this.oneof.push(field.name); + this.fieldsArray.push(field); + field.partOf = this; // field.parent remains null + addFieldsToParent(this); + return this; +}; + +/** + * Removes a field from this oneof and puts it back to the oneof's parent. + * @param {Field} field Field to remove + * @returns {OneOf} `this` + */ +OneOf.prototype.remove = function remove(field) { + + /* istanbul ignore if */ + if (!(field instanceof Field)) + throw TypeError("field must be a Field"); + + var index = this.fieldsArray.indexOf(field); + + /* istanbul ignore if */ + if (index < 0) + throw Error(field + " is not a member of " + this); + + this.fieldsArray.splice(index, 1); + index = this.oneof.indexOf(field.name); + + /* istanbul ignore else */ + if (index > -1) // theoretical + this.oneof.splice(index, 1); + + field.partOf = null; + return this; +}; + +/** + * @override + */ +OneOf.prototype.onAdd = function onAdd(parent) { + ReflectionObject.prototype.onAdd.call(this, parent); + var self = this; + // Collect present fields + for (var i = 0; i < this.oneof.length; ++i) { + var field = parent.get(this.oneof[i]); + if (field && !field.partOf) { + field.partOf = self; + self.fieldsArray.push(field); + } + } + // Add not yet present fields + addFieldsToParent(this); +}; + +/** + * @override + */ +OneOf.prototype.onRemove = function onRemove(parent) { + for (var i = 0, field; i < this.fieldsArray.length; ++i) + if ((field = this.fieldsArray[i]).parent) + field.parent.remove(field); + ReflectionObject.prototype.onRemove.call(this, parent); +}; + +/** + * Decorator function as returned by {@link OneOf.d} (TypeScript). + * @typedef OneOfDecorator + * @type {function} + * @param {Object} prototype Target prototype + * @param {string} oneofName OneOf name + * @returns {undefined} + */ + +/** + * OneOf decorator (TypeScript). + * @function + * @param {...string} fieldNames Field names + * @returns {OneOfDecorator} Decorator function + * @template T extends string + */ +OneOf.d = function decorateOneOf() { + var fieldNames = new Array(arguments.length), + index = 0; + while (index < arguments.length) + fieldNames[index] = arguments[index++]; + return function oneOfDecorator(prototype, oneofName) { + util.decorateType(prototype.constructor) + .add(new OneOf(oneofName, fieldNames)); + Object.defineProperty(prototype, oneofName, { + get: util.oneOfGetter(fieldNames), + set: util.oneOfSetter(fieldNames) + }); + }; +}; + +},{"15":15,"22":22,"33":33}],24:[function(require,module,exports){ +"use strict"; +module.exports = Reader; + +var util = require(35); + +var BufferReader; // cyclic + +var LongBits = util.LongBits, + utf8 = util.utf8; + +/* istanbul ignore next */ +function indexOutOfRange(reader, writeLength) { + return RangeError("index out of range: " + reader.pos + " + " + (writeLength || 1) + " > " + reader.len); +} + +/** + * Constructs a new reader instance using the specified buffer. + * @classdesc Wire format reader using `Uint8Array` if available, otherwise `Array`. + * @constructor + * @param {Uint8Array} buffer Buffer to read from + */ +function Reader(buffer) { + + /** + * Read buffer. + * @type {Uint8Array} + */ + this.buf = buffer; + + /** + * Read buffer position. + * @type {number} + */ + this.pos = 0; + + /** + * Read buffer length. + * @type {number} + */ + this.len = buffer.length; +} + +var create_array = typeof Uint8Array !== "undefined" + ? function create_typed_array(buffer) { + if (buffer instanceof Uint8Array || Array.isArray(buffer)) + return new Reader(buffer); + throw Error("illegal buffer"); + } + /* istanbul ignore next */ + : function create_array(buffer) { + if (Array.isArray(buffer)) + return new Reader(buffer); + throw Error("illegal buffer"); + }; + +var create = function create() { + return util.Buffer + ? function create_buffer_setup(buffer) { + return (Reader.create = function create_buffer(buffer) { + return util.Buffer.isBuffer(buffer) + ? new BufferReader(buffer) + /* istanbul ignore next */ + : create_array(buffer); + })(buffer); + } + /* istanbul ignore next */ + : create_array; +}; + +/** + * Creates a new reader using the specified buffer. + * @function + * @param {Uint8Array|Buffer} buffer Buffer to read from + * @returns {Reader|BufferReader} A {@link BufferReader} if `buffer` is a Buffer, otherwise a {@link Reader} + * @throws {Error} If `buffer` is not a valid buffer + */ +Reader.create = create(); + +Reader.prototype._slice = util.Array.prototype.subarray || /* istanbul ignore next */ util.Array.prototype.slice; + +/** + * Reads a varint as an unsigned 32 bit value. + * @function + * @returns {number} Value read + */ +Reader.prototype.uint32 = (function read_uint32_setup() { + var value = 4294967295; // optimizer type-hint, tends to deopt otherwise (?!) + return function read_uint32() { + value = ( this.buf[this.pos] & 127 ) >>> 0; if (this.buf[this.pos++] < 128) return value; + value = (value | (this.buf[this.pos] & 127) << 7) >>> 0; if (this.buf[this.pos++] < 128) return value; + value = (value | (this.buf[this.pos] & 127) << 14) >>> 0; if (this.buf[this.pos++] < 128) return value; + value = (value | (this.buf[this.pos] & 127) << 21) >>> 0; if (this.buf[this.pos++] < 128) return value; + value = (value | (this.buf[this.pos] & 15) << 28) >>> 0; if (this.buf[this.pos++] < 128) return value; + + /* istanbul ignore if */ + if ((this.pos += 5) > this.len) { + this.pos = this.len; + throw indexOutOfRange(this, 10); + } + return value; + }; +})(); + +/** + * Reads a varint as a signed 32 bit value. + * @returns {number} Value read + */ +Reader.prototype.int32 = function read_int32() { + return this.uint32() | 0; +}; + +/** + * Reads a zig-zag encoded varint as a signed 32 bit value. + * @returns {number} Value read + */ +Reader.prototype.sint32 = function read_sint32() { + var value = this.uint32(); + return value >>> 1 ^ -(value & 1) | 0; +}; + +/* eslint-disable no-invalid-this */ + +function readLongVarint() { + // tends to deopt with local vars for octet etc. + var bits = new LongBits(0, 0); + var i = 0; + if (this.len - this.pos > 4) { // fast route (lo) + for (; i < 4; ++i) { + // 1st..4th + bits.lo = (bits.lo | (this.buf[this.pos] & 127) << i * 7) >>> 0; + if (this.buf[this.pos++] < 128) + return bits; + } + // 5th + bits.lo = (bits.lo | (this.buf[this.pos] & 127) << 28) >>> 0; + bits.hi = (bits.hi | (this.buf[this.pos] & 127) >> 4) >>> 0; + if (this.buf[this.pos++] < 128) + return bits; + i = 0; + } else { + for (; i < 3; ++i) { + /* istanbul ignore if */ + if (this.pos >= this.len) + throw indexOutOfRange(this); + // 1st..3th + bits.lo = (bits.lo | (this.buf[this.pos] & 127) << i * 7) >>> 0; + if (this.buf[this.pos++] < 128) + return bits; + } + // 4th + bits.lo = (bits.lo | (this.buf[this.pos++] & 127) << i * 7) >>> 0; + return bits; + } + if (this.len - this.pos > 4) { // fast route (hi) + for (; i < 5; ++i) { + // 6th..10th + bits.hi = (bits.hi | (this.buf[this.pos] & 127) << i * 7 + 3) >>> 0; + if (this.buf[this.pos++] < 128) + return bits; + } + } else { + for (; i < 5; ++i) { + /* istanbul ignore if */ + if (this.pos >= this.len) + throw indexOutOfRange(this); + // 6th..10th + bits.hi = (bits.hi | (this.buf[this.pos] & 127) << i * 7 + 3) >>> 0; + if (this.buf[this.pos++] < 128) + return bits; + } + } + /* istanbul ignore next */ + throw Error("invalid varint encoding"); +} + +/* eslint-enable no-invalid-this */ + +/** + * Reads a varint as a signed 64 bit value. + * @name Reader#int64 + * @function + * @returns {Long} Value read + */ + +/** + * Reads a varint as an unsigned 64 bit value. + * @name Reader#uint64 + * @function + * @returns {Long} Value read + */ + +/** + * Reads a zig-zag encoded varint as a signed 64 bit value. + * @name Reader#sint64 + * @function + * @returns {Long} Value read + */ + +/** + * Reads a varint as a boolean. + * @returns {boolean} Value read + */ +Reader.prototype.bool = function read_bool() { + return this.uint32() !== 0; +}; + +function readFixed32_end(buf, end) { // note that this uses `end`, not `pos` + return (buf[end - 4] + | buf[end - 3] << 8 + | buf[end - 2] << 16 + | buf[end - 1] << 24) >>> 0; +} + +/** + * Reads fixed 32 bits as an unsigned 32 bit integer. + * @returns {number} Value read + */ +Reader.prototype.fixed32 = function read_fixed32() { + + /* istanbul ignore if */ + if (this.pos + 4 > this.len) + throw indexOutOfRange(this, 4); + + return readFixed32_end(this.buf, this.pos += 4); +}; + +/** + * Reads fixed 32 bits as a signed 32 bit integer. + * @returns {number} Value read + */ +Reader.prototype.sfixed32 = function read_sfixed32() { + + /* istanbul ignore if */ + if (this.pos + 4 > this.len) + throw indexOutOfRange(this, 4); + + return readFixed32_end(this.buf, this.pos += 4) | 0; +}; + +/* eslint-disable no-invalid-this */ + +function readFixed64(/* this: Reader */) { + + /* istanbul ignore if */ + if (this.pos + 8 > this.len) + throw indexOutOfRange(this, 8); + + return new LongBits(readFixed32_end(this.buf, this.pos += 4), readFixed32_end(this.buf, this.pos += 4)); +} + +/* eslint-enable no-invalid-this */ + +/** + * Reads fixed 64 bits. + * @name Reader#fixed64 + * @function + * @returns {Long} Value read + */ + +/** + * Reads zig-zag encoded fixed 64 bits. + * @name Reader#sfixed64 + * @function + * @returns {Long} Value read + */ + +/** + * Reads a float (32 bit) as a number. + * @function + * @returns {number} Value read + */ +Reader.prototype.float = function read_float() { + + /* istanbul ignore if */ + if (this.pos + 4 > this.len) + throw indexOutOfRange(this, 4); + + var value = util.float.readFloatLE(this.buf, this.pos); + this.pos += 4; + return value; +}; + +/** + * Reads a double (64 bit float) as a number. + * @function + * @returns {number} Value read + */ +Reader.prototype.double = function read_double() { + + /* istanbul ignore if */ + if (this.pos + 8 > this.len) + throw indexOutOfRange(this, 4); + + var value = util.float.readDoubleLE(this.buf, this.pos); + this.pos += 8; + return value; +}; + +/** + * Reads a sequence of bytes preceeded by its length as a varint. + * @returns {Uint8Array} Value read + */ +Reader.prototype.bytes = function read_bytes() { + var length = this.uint32(), + start = this.pos, + end = this.pos + length; + + /* istanbul ignore if */ + if (end > this.len) + throw indexOutOfRange(this, length); + + this.pos += length; + if (Array.isArray(this.buf)) // plain array + return this.buf.slice(start, end); + + if (start === end) { // fix for IE 10/Win8 and others' subarray returning array of size 1 + var nativeBuffer = util.Buffer; + return nativeBuffer + ? nativeBuffer.alloc(0) + : new this.buf.constructor(0); + } + return this._slice.call(this.buf, start, end); +}; + +/** + * Reads a string preceeded by its byte length as a varint. + * @returns {string} Value read + */ +Reader.prototype.string = function read_string() { + var bytes = this.bytes(); + return utf8.read(bytes, 0, bytes.length); +}; + +/** + * Skips the specified number of bytes if specified, otherwise skips a varint. + * @param {number} [length] Length if known, otherwise a varint is assumed + * @returns {Reader} `this` + */ +Reader.prototype.skip = function skip(length) { + if (typeof length === "number") { + /* istanbul ignore if */ + if (this.pos + length > this.len) + throw indexOutOfRange(this, length); + this.pos += length; + } else { + do { + /* istanbul ignore if */ + if (this.pos >= this.len) + throw indexOutOfRange(this); + } while (this.buf[this.pos++] & 128); + } + return this; +}; + +/** + * Skips the next element of the specified wire type. + * @param {number} wireType Wire type received + * @returns {Reader} `this` + */ +Reader.prototype.skipType = function(wireType) { + switch (wireType) { + case 0: + this.skip(); + break; + case 1: + this.skip(8); + break; + case 2: + this.skip(this.uint32()); + break; + case 3: + while ((wireType = this.uint32() & 7) !== 4) { + this.skipType(wireType); + } + break; + case 5: + this.skip(4); + break; + + /* istanbul ignore next */ + default: + throw Error("invalid wire type " + wireType + " at offset " + this.pos); + } + return this; +}; + +Reader._configure = function(BufferReader_) { + BufferReader = BufferReader_; + Reader.create = create(); + BufferReader._configure(); + + var fn = util.Long ? "toLong" : /* istanbul ignore next */ "toNumber"; + util.merge(Reader.prototype, { + + int64: function read_int64() { + return readLongVarint.call(this)[fn](false); + }, + + uint64: function read_uint64() { + return readLongVarint.call(this)[fn](true); + }, + + sint64: function read_sint64() { + return readLongVarint.call(this).zzDecode()[fn](false); + }, + + fixed64: function read_fixed64() { + return readFixed64.call(this)[fn](true); + }, + + sfixed64: function read_sfixed64() { + return readFixed64.call(this)[fn](false); + } + + }); +}; + +},{"35":35}],25:[function(require,module,exports){ +"use strict"; +module.exports = BufferReader; + +// extends Reader +var Reader = require(24); +(BufferReader.prototype = Object.create(Reader.prototype)).constructor = BufferReader; + +var util = require(35); + +/** + * Constructs a new buffer reader instance. + * @classdesc Wire format reader using node buffers. + * @extends Reader + * @constructor + * @param {Buffer} buffer Buffer to read from + */ +function BufferReader(buffer) { + Reader.call(this, buffer); + + /** + * Read buffer. + * @name BufferReader#buf + * @type {Buffer} + */ +} + +BufferReader._configure = function () { + /* istanbul ignore else */ + if (util.Buffer) + BufferReader.prototype._slice = util.Buffer.prototype.slice; +}; + + +/** + * @override + */ +BufferReader.prototype.string = function read_string_buffer() { + var len = this.uint32(); // modifies pos + return this.buf.utf8Slice + ? this.buf.utf8Slice(this.pos, this.pos = Math.min(this.pos + len, this.len)) + : this.buf.toString("utf-8", this.pos, this.pos = Math.min(this.pos + len, this.len)); +}; + +/** + * Reads a sequence of bytes preceeded by its length as a varint. + * @name BufferReader#bytes + * @function + * @returns {Buffer} Value read + */ + +BufferReader._configure(); + +},{"24":24,"35":35}],26:[function(require,module,exports){ +"use strict"; +module.exports = Root; + +// extends Namespace +var Namespace = require(21); +((Root.prototype = Object.create(Namespace.prototype)).constructor = Root).className = "Root"; + +var Field = require(15), + Enum = require(14), + OneOf = require(23), + util = require(33); + +var Type, // cyclic + parse, // might be excluded + common; // " + +/** + * Constructs a new root namespace instance. + * @classdesc Root namespace wrapping all types, enums, services, sub-namespaces etc. that belong together. + * @extends NamespaceBase + * @constructor + * @param {Object.} [options] Top level options + */ +function Root(options) { + Namespace.call(this, "", options); + + /** + * Deferred extension fields. + * @type {Field[]} + */ + this.deferred = []; + + /** + * Resolved file names of loaded files. + * @type {string[]} + */ + this.files = []; +} + +/** + * Loads a namespace descriptor into a root namespace. + * @param {INamespace} json Nameespace descriptor + * @param {Root} [root] Root namespace, defaults to create a new one if omitted + * @returns {Root} Root namespace + */ +Root.fromJSON = function fromJSON(json, root) { + if (!root) + root = new Root(); + if (json.options) + root.setOptions(json.options); + return root.addJSON(json.nested); +}; + +/** + * Resolves the path of an imported file, relative to the importing origin. + * This method exists so you can override it with your own logic in case your imports are scattered over multiple directories. + * @function + * @param {string} origin The file name of the importing file + * @param {string} target The file name being imported + * @returns {string|null} Resolved path to `target` or `null` to skip the file + */ +Root.prototype.resolvePath = util.path.resolve; + +/** + * Fetch content from file path or url + * This method exists so you can override it with your own logic. + * @function + * @param {string} path File path or url + * @param {FetchCallback} callback Callback function + * @returns {undefined} + */ +Root.prototype.fetch = util.fetch; + +// A symbol-like function to safely signal synchronous loading +/* istanbul ignore next */ +function SYNC() {} // eslint-disable-line no-empty-function + +/** + * Loads one or multiple .proto or preprocessed .json files into this root namespace and calls the callback. + * @param {string|string[]} filename Names of one or multiple files to load + * @param {IParseOptions} options Parse options + * @param {LoadCallback} callback Callback function + * @returns {undefined} + */ +Root.prototype.load = function load(filename, options, callback) { + if (typeof options === "function") { + callback = options; + options = undefined; + } + var self = this; + if (!callback) + return util.asPromise(load, self, filename, options); + + var sync = callback === SYNC; // undocumented + + // Finishes loading by calling the callback (exactly once) + function finish(err, root) { + /* istanbul ignore if */ + if (!callback) + return; + if (sync) + throw err; + var cb = callback; + callback = null; + cb(err, root); + } + + // Bundled definition existence checking + function getBundledFileName(filename) { + var idx = filename.lastIndexOf("google/protobuf/"); + if (idx > -1) { + var altname = filename.substring(idx); + if (altname in common) return altname; + } + return null; + } + + // Processes a single file + function process(filename, source) { + try { + if (util.isString(source) && source.charAt(0) === "{") + source = JSON.parse(source); + if (!util.isString(source)) + self.setOptions(source.options).addJSON(source.nested); + else { + parse.filename = filename; + var parsed = parse(source, self, options), + resolved, + i = 0; + if (parsed.imports) + for (; i < parsed.imports.length; ++i) + if (resolved = getBundledFileName(parsed.imports[i]) || self.resolvePath(filename, parsed.imports[i])) + fetch(resolved); + if (parsed.weakImports) + for (i = 0; i < parsed.weakImports.length; ++i) + if (resolved = getBundledFileName(parsed.weakImports[i]) || self.resolvePath(filename, parsed.weakImports[i])) + fetch(resolved, true); + } + } catch (err) { + finish(err); + } + if (!sync && !queued) + finish(null, self); // only once anyway + } + + // Fetches a single file + function fetch(filename, weak) { + filename = getBundledFileName(filename) || filename; + + // Skip if already loaded / attempted + if (self.files.indexOf(filename) > -1) + return; + self.files.push(filename); + + // Shortcut bundled definitions + if (filename in common) { + if (sync) + process(filename, common[filename]); + else { + ++queued; + setTimeout(function() { + --queued; + process(filename, common[filename]); + }); + } + return; + } + + // Otherwise fetch from disk or network + if (sync) { + var source; + try { + source = util.fs.readFileSync(filename).toString("utf8"); + } catch (err) { + if (!weak) + finish(err); + return; + } + process(filename, source); + } else { + ++queued; + self.fetch(filename, function(err, source) { + --queued; + /* istanbul ignore if */ + if (!callback) + return; // terminated meanwhile + if (err) { + /* istanbul ignore else */ + if (!weak) + finish(err); + else if (!queued) // can't be covered reliably + finish(null, self); + return; + } + process(filename, source); + }); + } + } + var queued = 0; + + // Assembling the root namespace doesn't require working type + // references anymore, so we can load everything in parallel + if (util.isString(filename)) + filename = [ filename ]; + for (var i = 0, resolved; i < filename.length; ++i) + if (resolved = self.resolvePath("", filename[i])) + fetch(resolved); + + if (sync) + return self; + if (!queued) + finish(null, self); + return undefined; +}; +// function load(filename:string, options:IParseOptions, callback:LoadCallback):undefined + +/** + * Loads one or multiple .proto or preprocessed .json files into this root namespace and calls the callback. + * @function Root#load + * @param {string|string[]} filename Names of one or multiple files to load + * @param {LoadCallback} callback Callback function + * @returns {undefined} + * @variation 2 + */ +// function load(filename:string, callback:LoadCallback):undefined + +/** + * Loads one or multiple .proto or preprocessed .json files into this root namespace and returns a promise. + * @function Root#load + * @param {string|string[]} filename Names of one or multiple files to load + * @param {IParseOptions} [options] Parse options. Defaults to {@link parse.defaults} when omitted. + * @returns {Promise} Promise + * @variation 3 + */ +// function load(filename:string, [options:IParseOptions]):Promise + +/** + * Synchronously loads one or multiple .proto or preprocessed .json files into this root namespace (node only). + * @function Root#loadSync + * @param {string|string[]} filename Names of one or multiple files to load + * @param {IParseOptions} [options] Parse options. Defaults to {@link parse.defaults} when omitted. + * @returns {Root} Root namespace + * @throws {Error} If synchronous fetching is not supported (i.e. in browsers) or if a file's syntax is invalid + */ +Root.prototype.loadSync = function loadSync(filename, options) { + if (!util.isNode) + throw Error("not supported"); + return this.load(filename, options, SYNC); +}; + +/** + * @override + */ +Root.prototype.resolveAll = function resolveAll() { + if (this.deferred.length) + throw Error("unresolvable extensions: " + this.deferred.map(function(field) { + return "'extend " + field.extend + "' in " + field.parent.fullName; + }).join(", ")); + return Namespace.prototype.resolveAll.call(this); +}; + +// only uppercased (and thus conflict-free) children are exposed, see below +var exposeRe = /^[A-Z]/; + +/** + * Handles a deferred declaring extension field by creating a sister field to represent it within its extended type. + * @param {Root} root Root instance + * @param {Field} field Declaring extension field witin the declaring type + * @returns {boolean} `true` if successfully added to the extended type, `false` otherwise + * @inner + * @ignore + */ +function tryHandleExtension(root, field) { + var extendedType = field.parent.lookup(field.extend); + if (extendedType) { + var sisterField = new Field(field.fullName, field.id, field.type, field.rule, undefined, field.options); + //do not allow to extend same field twice to prevent the error + if (extendedType.get(sisterField.name)) { + return true; + } + sisterField.declaringField = field; + field.extensionField = sisterField; + extendedType.add(sisterField); + return true; + } + return false; +} + +/** + * Called when any object is added to this root or its sub-namespaces. + * @param {ReflectionObject} object Object added + * @returns {undefined} + * @private + */ +Root.prototype._handleAdd = function _handleAdd(object) { + if (object instanceof Field) { + + if (/* an extension field (implies not part of a oneof) */ object.extend !== undefined && /* not already handled */ !object.extensionField) + if (!tryHandleExtension(this, object)) + this.deferred.push(object); + + } else if (object instanceof Enum) { + + if (exposeRe.test(object.name)) + object.parent[object.name] = object.values; // expose enum values as property of its parent + + } else if (!(object instanceof OneOf)) /* everything else is a namespace */ { + + if (object instanceof Type) // Try to handle any deferred extensions + for (var i = 0; i < this.deferred.length;) + if (tryHandleExtension(this, this.deferred[i])) + this.deferred.splice(i, 1); + else + ++i; + for (var j = 0; j < /* initializes */ object.nestedArray.length; ++j) // recurse into the namespace + this._handleAdd(object._nestedArray[j]); + if (exposeRe.test(object.name)) + object.parent[object.name] = object; // expose namespace as property of its parent + } + + // The above also adds uppercased (and thus conflict-free) nested types, services and enums as + // properties of namespaces just like static code does. This allows using a .d.ts generated for + // a static module with reflection-based solutions where the condition is met. +}; + +/** + * Called when any object is removed from this root or its sub-namespaces. + * @param {ReflectionObject} object Object removed + * @returns {undefined} + * @private + */ +Root.prototype._handleRemove = function _handleRemove(object) { + if (object instanceof Field) { + + if (/* an extension field */ object.extend !== undefined) { + if (/* already handled */ object.extensionField) { // remove its sister field + object.extensionField.parent.remove(object.extensionField); + object.extensionField = null; + } else { // cancel the extension + var index = this.deferred.indexOf(object); + /* istanbul ignore else */ + if (index > -1) + this.deferred.splice(index, 1); + } + } + + } else if (object instanceof Enum) { + + if (exposeRe.test(object.name)) + delete object.parent[object.name]; // unexpose enum values + + } else if (object instanceof Namespace) { + + for (var i = 0; i < /* initializes */ object.nestedArray.length; ++i) // recurse into the namespace + this._handleRemove(object._nestedArray[i]); + + if (exposeRe.test(object.name)) + delete object.parent[object.name]; // unexpose namespaces + + } +}; + +// Sets up cyclic dependencies (called in index-light) +Root._configure = function(Type_, parse_, common_) { + Type = Type_; + parse = parse_; + common = common_; +}; + +},{"14":14,"15":15,"21":21,"23":23,"33":33}],27:[function(require,module,exports){ +"use strict"; +module.exports = {}; + +/** + * Named roots. + * This is where pbjs stores generated structures (the option `-r, --root` specifies a name). + * Can also be used manually to make roots available across modules. + * @name roots + * @type {Object.} + * @example + * // pbjs -r myroot -o compiled.js ... + * + * // in another module: + * require("./compiled.js"); + * + * // in any subsequent module: + * var root = protobuf.roots["myroot"]; + */ + +},{}],28:[function(require,module,exports){ +"use strict"; + +/** + * Streaming RPC helpers. + * @namespace + */ +var rpc = exports; + +/** + * RPC implementation passed to {@link Service#create} performing a service request on network level, i.e. by utilizing http requests or websockets. + * @typedef RPCImpl + * @type {function} + * @param {Method|rpc.ServiceMethod,Message<{}>>} method Reflected or static method being called + * @param {Uint8Array} requestData Request data + * @param {RPCImplCallback} callback Callback function + * @returns {undefined} + * @example + * function rpcImpl(method, requestData, callback) { + * if (protobuf.util.lcFirst(method.name) !== "myMethod") // compatible with static code + * throw Error("no such method"); + * asynchronouslyObtainAResponse(requestData, function(err, responseData) { + * callback(err, responseData); + * }); + * } + */ + +/** + * Node-style callback as used by {@link RPCImpl}. + * @typedef RPCImplCallback + * @type {function} + * @param {Error|null} error Error, if any, otherwise `null` + * @param {Uint8Array|null} [response] Response data or `null` to signal end of stream, if there hasn't been an error + * @returns {undefined} + */ + +rpc.Service = require(29); + +},{"29":29}],29:[function(require,module,exports){ +"use strict"; +module.exports = Service; + +var util = require(35); + +// Extends EventEmitter +(Service.prototype = Object.create(util.EventEmitter.prototype)).constructor = Service; + +/** + * A service method callback as used by {@link rpc.ServiceMethod|ServiceMethod}. + * + * Differs from {@link RPCImplCallback} in that it is an actual callback of a service method which may not return `response = null`. + * @typedef rpc.ServiceMethodCallback + * @template TRes extends Message + * @type {function} + * @param {Error|null} error Error, if any + * @param {TRes} [response] Response message + * @returns {undefined} + */ + +/** + * A service method part of a {@link rpc.Service} as created by {@link Service.create}. + * @typedef rpc.ServiceMethod + * @template TReq extends Message + * @template TRes extends Message + * @type {function} + * @param {TReq|Properties} request Request message or plain object + * @param {rpc.ServiceMethodCallback} [callback] Node-style callback called with the error, if any, and the response message + * @returns {Promise>} Promise if `callback` has been omitted, otherwise `undefined` + */ + +/** + * Constructs a new RPC service instance. + * @classdesc An RPC service as returned by {@link Service#create}. + * @exports rpc.Service + * @extends util.EventEmitter + * @constructor + * @param {RPCImpl} rpcImpl RPC implementation + * @param {boolean} [requestDelimited=false] Whether requests are length-delimited + * @param {boolean} [responseDelimited=false] Whether responses are length-delimited + */ +function Service(rpcImpl, requestDelimited, responseDelimited) { + + if (typeof rpcImpl !== "function") + throw TypeError("rpcImpl must be a function"); + + util.EventEmitter.call(this); + + /** + * RPC implementation. Becomes `null` once the service is ended. + * @type {RPCImpl|null} + */ + this.rpcImpl = rpcImpl; + + /** + * Whether requests are length-delimited. + * @type {boolean} + */ + this.requestDelimited = Boolean(requestDelimited); + + /** + * Whether responses are length-delimited. + * @type {boolean} + */ + this.responseDelimited = Boolean(responseDelimited); +} + +/** + * Calls a service method through {@link rpc.Service#rpcImpl|rpcImpl}. + * @param {Method|rpc.ServiceMethod} method Reflected or static method + * @param {Constructor} requestCtor Request constructor + * @param {Constructor} responseCtor Response constructor + * @param {TReq|Properties} request Request message or plain object + * @param {rpc.ServiceMethodCallback} callback Service callback + * @returns {undefined} + * @template TReq extends Message + * @template TRes extends Message + */ +Service.prototype.rpcCall = function rpcCall(method, requestCtor, responseCtor, request, callback) { + + if (!request) + throw TypeError("request must be specified"); + + var self = this; + if (!callback) + return util.asPromise(rpcCall, self, method, requestCtor, responseCtor, request); + + if (!self.rpcImpl) { + setTimeout(function() { callback(Error("already ended")); }, 0); + return undefined; + } + + try { + return self.rpcImpl( + method, + requestCtor[self.requestDelimited ? "encodeDelimited" : "encode"](request).finish(), + function rpcCallback(err, response) { + + if (err) { + self.emit("error", err, method); + return callback(err); + } + + if (response === null) { + self.end(/* endedByRPC */ true); + return undefined; + } + + if (!(response instanceof responseCtor)) { + try { + response = responseCtor[self.responseDelimited ? "decodeDelimited" : "decode"](response); + } catch (err) { + self.emit("error", err, method); + return callback(err); + } + } + + self.emit("data", response, method); + return callback(null, response); + } + ); + } catch (err) { + self.emit("error", err, method); + setTimeout(function() { callback(err); }, 0); + return undefined; + } +}; + +/** + * Ends this service and emits the `end` event. + * @param {boolean} [endedByRPC=false] Whether the service has been ended by the RPC implementation. + * @returns {rpc.Service} `this` + */ +Service.prototype.end = function end(endedByRPC) { + if (this.rpcImpl) { + if (!endedByRPC) // signal end to rpcImpl + this.rpcImpl(null, null, null); + this.rpcImpl = null; + this.emit("end").off(); + } + return this; +}; + +},{"35":35}],30:[function(require,module,exports){ +"use strict"; +module.exports = Service; + +// extends Namespace +var Namespace = require(21); +((Service.prototype = Object.create(Namespace.prototype)).constructor = Service).className = "Service"; + +var Method = require(20), + util = require(33), + rpc = require(28); + +/** + * Constructs a new service instance. + * @classdesc Reflected service. + * @extends NamespaceBase + * @constructor + * @param {string} name Service name + * @param {Object.} [options] Service options + * @throws {TypeError} If arguments are invalid + */ +function Service(name, options) { + Namespace.call(this, name, options); + + /** + * Service methods. + * @type {Object.} + */ + this.methods = {}; // toJSON, marker + + /** + * Cached methods as an array. + * @type {Method[]|null} + * @private + */ + this._methodsArray = null; +} + +/** + * Service descriptor. + * @interface IService + * @extends INamespace + * @property {Object.} methods Method descriptors + */ + +/** + * Constructs a service from a service descriptor. + * @param {string} name Service name + * @param {IService} json Service descriptor + * @returns {Service} Created service + * @throws {TypeError} If arguments are invalid + */ +Service.fromJSON = function fromJSON(name, json) { + var service = new Service(name, json.options); + /* istanbul ignore else */ + if (json.methods) + for (var names = Object.keys(json.methods), i = 0; i < names.length; ++i) + service.add(Method.fromJSON(names[i], json.methods[names[i]])); + if (json.nested) + service.addJSON(json.nested); + service.comment = json.comment; + return service; +}; + +/** + * Converts this service to a service descriptor. + * @param {IToJSONOptions} [toJSONOptions] JSON conversion options + * @returns {IService} Service descriptor + */ +Service.prototype.toJSON = function toJSON(toJSONOptions) { + var inherited = Namespace.prototype.toJSON.call(this, toJSONOptions); + var keepComments = toJSONOptions ? Boolean(toJSONOptions.keepComments) : false; + return util.toObject([ + "options" , inherited && inherited.options || undefined, + "methods" , Namespace.arrayToJSON(this.methodsArray, toJSONOptions) || /* istanbul ignore next */ {}, + "nested" , inherited && inherited.nested || undefined, + "comment" , keepComments ? this.comment : undefined + ]); +}; + +/** + * Methods of this service as an array for iteration. + * @name Service#methodsArray + * @type {Method[]} + * @readonly + */ +Object.defineProperty(Service.prototype, "methodsArray", { + get: function() { + return this._methodsArray || (this._methodsArray = util.toArray(this.methods)); + } +}); + +function clearCache(service) { + service._methodsArray = null; + return service; +} + +/** + * @override + */ +Service.prototype.get = function get(name) { + return this.methods[name] + || Namespace.prototype.get.call(this, name); +}; + +/** + * @override + */ +Service.prototype.resolveAll = function resolveAll() { + var methods = this.methodsArray; + for (var i = 0; i < methods.length; ++i) + methods[i].resolve(); + return Namespace.prototype.resolve.call(this); +}; + +/** + * @override + */ +Service.prototype.add = function add(object) { + + /* istanbul ignore if */ + if (this.get(object.name)) + throw Error("duplicate name '" + object.name + "' in " + this); + + if (object instanceof Method) { + this.methods[object.name] = object; + object.parent = this; + return clearCache(this); + } + return Namespace.prototype.add.call(this, object); +}; + +/** + * @override + */ +Service.prototype.remove = function remove(object) { + if (object instanceof Method) { + + /* istanbul ignore if */ + if (this.methods[object.name] !== object) + throw Error(object + " is not a member of " + this); + + delete this.methods[object.name]; + object.parent = null; + return clearCache(this); + } + return Namespace.prototype.remove.call(this, object); +}; + +/** + * Creates a runtime service using the specified rpc implementation. + * @param {RPCImpl} rpcImpl RPC implementation + * @param {boolean} [requestDelimited=false] Whether requests are length-delimited + * @param {boolean} [responseDelimited=false] Whether responses are length-delimited + * @returns {rpc.Service} RPC service. Useful where requests and/or responses are streamed. + */ +Service.prototype.create = function create(rpcImpl, requestDelimited, responseDelimited) { + var rpcService = new rpc.Service(rpcImpl, requestDelimited, responseDelimited); + for (var i = 0, method; i < /* initializes */ this.methodsArray.length; ++i) { + var methodName = util.lcFirst((method = this._methodsArray[i]).resolve().name).replace(/[^$\w_]/g, ""); + rpcService[methodName] = util.codegen(["r","c"], util.isReserved(methodName) ? methodName + "_" : methodName)("return this.rpcCall(m,q,s,r,c)")({ + m: method, + q: method.resolvedRequestType.ctor, + s: method.resolvedResponseType.ctor + }); + } + return rpcService; +}; + +},{"20":20,"21":21,"28":28,"33":33}],31:[function(require,module,exports){ +"use strict"; +module.exports = Type; + +// extends Namespace +var Namespace = require(21); +((Type.prototype = Object.create(Namespace.prototype)).constructor = Type).className = "Type"; + +var Enum = require(14), + OneOf = require(23), + Field = require(15), + MapField = require(18), + Service = require(30), + Message = require(19), + Reader = require(24), + Writer = require(38), + util = require(33), + encoder = require(13), + decoder = require(12), + verifier = require(36), + converter = require(11), + wrappers = require(37); + +/** + * Constructs a new reflected message type instance. + * @classdesc Reflected message type. + * @extends NamespaceBase + * @constructor + * @param {string} name Message name + * @param {Object.} [options] Declared options + */ +function Type(name, options) { + Namespace.call(this, name, options); + + /** + * Message fields. + * @type {Object.} + */ + this.fields = {}; // toJSON, marker + + /** + * Oneofs declared within this namespace, if any. + * @type {Object.} + */ + this.oneofs = undefined; // toJSON + + /** + * Extension ranges, if any. + * @type {number[][]} + */ + this.extensions = undefined; // toJSON + + /** + * Reserved ranges, if any. + * @type {Array.} + */ + this.reserved = undefined; // toJSON + + /*? + * Whether this type is a legacy group. + * @type {boolean|undefined} + */ + this.group = undefined; // toJSON + + /** + * Cached fields by id. + * @type {Object.|null} + * @private + */ + this._fieldsById = null; + + /** + * Cached fields as an array. + * @type {Field[]|null} + * @private + */ + this._fieldsArray = null; + + /** + * Cached oneofs as an array. + * @type {OneOf[]|null} + * @private + */ + this._oneofsArray = null; + + /** + * Cached constructor. + * @type {Constructor<{}>} + * @private + */ + this._ctor = null; +} + +Object.defineProperties(Type.prototype, { + + /** + * Message fields by id. + * @name Type#fieldsById + * @type {Object.} + * @readonly + */ + fieldsById: { + get: function() { + + /* istanbul ignore if */ + if (this._fieldsById) + return this._fieldsById; + + this._fieldsById = {}; + for (var names = Object.keys(this.fields), i = 0; i < names.length; ++i) { + var field = this.fields[names[i]], + id = field.id; + + /* istanbul ignore if */ + if (this._fieldsById[id]) + throw Error("duplicate id " + id + " in " + this); + + this._fieldsById[id] = field; + } + return this._fieldsById; + } + }, + + /** + * Fields of this message as an array for iteration. + * @name Type#fieldsArray + * @type {Field[]} + * @readonly + */ + fieldsArray: { + get: function() { + return this._fieldsArray || (this._fieldsArray = util.toArray(this.fields)); + } + }, + + /** + * Oneofs of this message as an array for iteration. + * @name Type#oneofsArray + * @type {OneOf[]} + * @readonly + */ + oneofsArray: { + get: function() { + return this._oneofsArray || (this._oneofsArray = util.toArray(this.oneofs)); + } + }, + + /** + * The registered constructor, if any registered, otherwise a generic constructor. + * Assigning a function replaces the internal constructor. If the function does not extend {@link Message} yet, its prototype will be setup accordingly and static methods will be populated. If it already extends {@link Message}, it will just replace the internal constructor. + * @name Type#ctor + * @type {Constructor<{}>} + */ + ctor: { + get: function() { + return this._ctor || (this.ctor = Type.generateConstructor(this)()); + }, + set: function(ctor) { + + // Ensure proper prototype + var prototype = ctor.prototype; + if (!(prototype instanceof Message)) { + (ctor.prototype = new Message()).constructor = ctor; + util.merge(ctor.prototype, prototype); + } + + // Classes and messages reference their reflected type + ctor.$type = ctor.prototype.$type = this; + + // Mix in static methods + util.merge(ctor, Message, true); + + this._ctor = ctor; + + // Messages have non-enumerable default values on their prototype + var i = 0; + for (; i < /* initializes */ this.fieldsArray.length; ++i) + this._fieldsArray[i].resolve(); // ensures a proper value + + // Messages have non-enumerable getters and setters for each virtual oneof field + var ctorProperties = {}; + for (i = 0; i < /* initializes */ this.oneofsArray.length; ++i) + ctorProperties[this._oneofsArray[i].resolve().name] = { + get: util.oneOfGetter(this._oneofsArray[i].oneof), + set: util.oneOfSetter(this._oneofsArray[i].oneof) + }; + if (i) + Object.defineProperties(ctor.prototype, ctorProperties); + } + } +}); + +/** + * Generates a constructor function for the specified type. + * @param {Type} mtype Message type + * @returns {Codegen} Codegen instance + */ +Type.generateConstructor = function generateConstructor(mtype) { + /* eslint-disable no-unexpected-multiline */ + var gen = util.codegen(["p"], mtype.name); + // explicitly initialize mutable object/array fields so that these aren't just inherited from the prototype + for (var i = 0, field; i < mtype.fieldsArray.length; ++i) + if ((field = mtype._fieldsArray[i]).map) gen + ("this%s={}", util.safeProp(field.name)); + else if (field.repeated) gen + ("this%s=[]", util.safeProp(field.name)); + return gen + ("if(p)for(var ks=Object.keys(p),i=0;i} [oneofs] Oneof descriptors + * @property {Object.} fields Field descriptors + * @property {number[][]} [extensions] Extension ranges + * @property {number[][]} [reserved] Reserved ranges + * @property {boolean} [group=false] Whether a legacy group or not + */ + +/** + * Creates a message type from a message type descriptor. + * @param {string} name Message name + * @param {IType} json Message type descriptor + * @returns {Type} Created message type + */ +Type.fromJSON = function fromJSON(name, json) { + var type = new Type(name, json.options); + type.extensions = json.extensions; + type.reserved = json.reserved; + var names = Object.keys(json.fields), + i = 0; + for (; i < names.length; ++i) + type.add( + ( typeof json.fields[names[i]].keyType !== "undefined" + ? MapField.fromJSON + : Field.fromJSON )(names[i], json.fields[names[i]]) + ); + if (json.oneofs) + for (names = Object.keys(json.oneofs), i = 0; i < names.length; ++i) + type.add(OneOf.fromJSON(names[i], json.oneofs[names[i]])); + if (json.nested) + for (names = Object.keys(json.nested), i = 0; i < names.length; ++i) { + var nested = json.nested[names[i]]; + type.add( // most to least likely + ( nested.id !== undefined + ? Field.fromJSON + : nested.fields !== undefined + ? Type.fromJSON + : nested.values !== undefined + ? Enum.fromJSON + : nested.methods !== undefined + ? Service.fromJSON + : Namespace.fromJSON )(names[i], nested) + ); + } + if (json.extensions && json.extensions.length) + type.extensions = json.extensions; + if (json.reserved && json.reserved.length) + type.reserved = json.reserved; + if (json.group) + type.group = true; + if (json.comment) + type.comment = json.comment; + return type; +}; + +/** + * Converts this message type to a message type descriptor. + * @param {IToJSONOptions} [toJSONOptions] JSON conversion options + * @returns {IType} Message type descriptor + */ +Type.prototype.toJSON = function toJSON(toJSONOptions) { + var inherited = Namespace.prototype.toJSON.call(this, toJSONOptions); + var keepComments = toJSONOptions ? Boolean(toJSONOptions.keepComments) : false; + return util.toObject([ + "options" , inherited && inherited.options || undefined, + "oneofs" , Namespace.arrayToJSON(this.oneofsArray, toJSONOptions), + "fields" , Namespace.arrayToJSON(this.fieldsArray.filter(function(obj) { return !obj.declaringField; }), toJSONOptions) || {}, + "extensions" , this.extensions && this.extensions.length ? this.extensions : undefined, + "reserved" , this.reserved && this.reserved.length ? this.reserved : undefined, + "group" , this.group || undefined, + "nested" , inherited && inherited.nested || undefined, + "comment" , keepComments ? this.comment : undefined + ]); +}; + +/** + * @override + */ +Type.prototype.resolveAll = function resolveAll() { + var fields = this.fieldsArray, i = 0; + while (i < fields.length) + fields[i++].resolve(); + var oneofs = this.oneofsArray; i = 0; + while (i < oneofs.length) + oneofs[i++].resolve(); + return Namespace.prototype.resolveAll.call(this); +}; + +/** + * @override + */ +Type.prototype.get = function get(name) { + return this.fields[name] + || this.oneofs && this.oneofs[name] + || this.nested && this.nested[name] + || null; +}; + +/** + * Adds a nested object to this type. + * @param {ReflectionObject} object Nested object to add + * @returns {Type} `this` + * @throws {TypeError} If arguments are invalid + * @throws {Error} If there is already a nested object with this name or, if a field, when there is already a field with this id + */ +Type.prototype.add = function add(object) { + + if (this.get(object.name)) + throw Error("duplicate name '" + object.name + "' in " + this); + + if (object instanceof Field && object.extend === undefined) { + // NOTE: Extension fields aren't actual fields on the declaring type, but nested objects. + // The root object takes care of adding distinct sister-fields to the respective extended + // type instead. + + // avoids calling the getter if not absolutely necessary because it's called quite frequently + if (this._fieldsById ? /* istanbul ignore next */ this._fieldsById[object.id] : this.fieldsById[object.id]) + throw Error("duplicate id " + object.id + " in " + this); + if (this.isReservedId(object.id)) + throw Error("id " + object.id + " is reserved in " + this); + if (this.isReservedName(object.name)) + throw Error("name '" + object.name + "' is reserved in " + this); + + if (object.parent) + object.parent.remove(object); + this.fields[object.name] = object; + object.message = this; + object.onAdd(this); + return clearCache(this); + } + if (object instanceof OneOf) { + if (!this.oneofs) + this.oneofs = {}; + this.oneofs[object.name] = object; + object.onAdd(this); + return clearCache(this); + } + return Namespace.prototype.add.call(this, object); +}; + +/** + * Removes a nested object from this type. + * @param {ReflectionObject} object Nested object to remove + * @returns {Type} `this` + * @throws {TypeError} If arguments are invalid + * @throws {Error} If `object` is not a member of this type + */ +Type.prototype.remove = function remove(object) { + if (object instanceof Field && object.extend === undefined) { + // See Type#add for the reason why extension fields are excluded here. + + /* istanbul ignore if */ + if (!this.fields || this.fields[object.name] !== object) + throw Error(object + " is not a member of " + this); + + delete this.fields[object.name]; + object.parent = null; + object.onRemove(this); + return clearCache(this); + } + if (object instanceof OneOf) { + + /* istanbul ignore if */ + if (!this.oneofs || this.oneofs[object.name] !== object) + throw Error(object + " is not a member of " + this); + + delete this.oneofs[object.name]; + object.parent = null; + object.onRemove(this); + return clearCache(this); + } + return Namespace.prototype.remove.call(this, object); +}; + +/** + * Tests if the specified id is reserved. + * @param {number} id Id to test + * @returns {boolean} `true` if reserved, otherwise `false` + */ +Type.prototype.isReservedId = function isReservedId(id) { + return Namespace.isReservedId(this.reserved, id); +}; + +/** + * Tests if the specified name is reserved. + * @param {string} name Name to test + * @returns {boolean} `true` if reserved, otherwise `false` + */ +Type.prototype.isReservedName = function isReservedName(name) { + return Namespace.isReservedName(this.reserved, name); +}; + +/** + * Creates a new message of this type using the specified properties. + * @param {Object.} [properties] Properties to set + * @returns {Message<{}>} Message instance + */ +Type.prototype.create = function create(properties) { + return new this.ctor(properties); +}; + +/** + * Sets up {@link Type#encode|encode}, {@link Type#decode|decode} and {@link Type#verify|verify}. + * @returns {Type} `this` + */ +Type.prototype.setup = function setup() { + // Sets up everything at once so that the prototype chain does not have to be re-evaluated + // multiple times (V8, soft-deopt prototype-check). + + var fullName = this.fullName, + types = []; + for (var i = 0; i < /* initializes */ this.fieldsArray.length; ++i) + types.push(this._fieldsArray[i].resolve().resolvedType); + + // Replace setup methods with type-specific generated functions + this.encode = encoder(this)({ + Writer : Writer, + types : types, + util : util + }); + this.decode = decoder(this)({ + Reader : Reader, + types : types, + util : util + }); + this.verify = verifier(this)({ + types : types, + util : util + }); + this.fromObject = converter.fromObject(this)({ + types : types, + util : util + }); + this.toObject = converter.toObject(this)({ + types : types, + util : util + }); + + // Inject custom wrappers for common types + var wrapper = wrappers[fullName]; + if (wrapper) { + var originalThis = Object.create(this); + // if (wrapper.fromObject) { + originalThis.fromObject = this.fromObject; + this.fromObject = wrapper.fromObject.bind(originalThis); + // } + // if (wrapper.toObject) { + originalThis.toObject = this.toObject; + this.toObject = wrapper.toObject.bind(originalThis); + // } + } + + return this; +}; + +/** + * Encodes a message of this type. Does not implicitly {@link Type#verify|verify} messages. + * @param {Message<{}>|Object.} message Message instance or plain object + * @param {Writer} [writer] Writer to encode to + * @returns {Writer} writer + */ +Type.prototype.encode = function encode_setup(message, writer) { + return this.setup().encode(message, writer); // overrides this method +}; + +/** + * Encodes a message of this type preceeded by its byte length as a varint. Does not implicitly {@link Type#verify|verify} messages. + * @param {Message<{}>|Object.} message Message instance or plain object + * @param {Writer} [writer] Writer to encode to + * @returns {Writer} writer + */ +Type.prototype.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer && writer.len ? writer.fork() : writer).ldelim(); +}; + +/** + * Decodes a message of this type. + * @param {Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Length of the message, if known beforehand + * @returns {Message<{}>} Decoded message + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {util.ProtocolError<{}>} If required fields are missing + */ +Type.prototype.decode = function decode_setup(reader, length) { + return this.setup().decode(reader, length); // overrides this method +}; + +/** + * Decodes a message of this type preceeded by its byte length as a varint. + * @param {Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {Message<{}>} Decoded message + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {util.ProtocolError} If required fields are missing + */ +Type.prototype.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof Reader)) + reader = Reader.create(reader); + return this.decode(reader, reader.uint32()); +}; + +/** + * Verifies that field values are valid and that required fields are present. + * @param {Object.} message Plain object to verify + * @returns {null|string} `null` if valid, otherwise the reason why it is not + */ +Type.prototype.verify = function verify_setup(message) { + return this.setup().verify(message); // overrides this method +}; + +/** + * Creates a new message of this type from a plain object. Also converts values to their respective internal types. + * @param {Object.} object Plain object to convert + * @returns {Message<{}>} Message instance + */ +Type.prototype.fromObject = function fromObject(object) { + return this.setup().fromObject(object); +}; + +/** + * Conversion options as used by {@link Type#toObject} and {@link Message.toObject}. + * @interface IConversionOptions + * @property {Function} [longs] Long conversion type. + * Valid values are `String` and `Number` (the global types). + * Defaults to copy the present value, which is a possibly unsafe number without and a {@link Long} with a long library. + * @property {Function} [enums] Enum value conversion type. + * Only valid value is `String` (the global type). + * Defaults to copy the present value, which is the numeric id. + * @property {Function} [bytes] Bytes value conversion type. + * Valid values are `Array` and (a base64 encoded) `String` (the global types). + * Defaults to copy the present value, which usually is a Buffer under node and an Uint8Array in the browser. + * @property {boolean} [defaults=false] Also sets default values on the resulting object + * @property {boolean} [arrays=false] Sets empty arrays for missing repeated fields even if `defaults=false` + * @property {boolean} [objects=false] Sets empty objects for missing map fields even if `defaults=false` + * @property {boolean} [oneofs=false] Includes virtual oneof properties set to the present field's name, if any + * @property {boolean} [json=false] Performs additional JSON compatibility conversions, i.e. NaN and Infinity to strings + */ + +/** + * Creates a plain object from a message of this type. Also converts values to other types if specified. + * @param {Message<{}>} message Message instance + * @param {IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ +Type.prototype.toObject = function toObject(message, options) { + return this.setup().toObject(message, options); +}; + +/** + * Decorator function as returned by {@link Type.d} (TypeScript). + * @typedef TypeDecorator + * @type {function} + * @param {Constructor} target Target constructor + * @returns {undefined} + * @template T extends Message + */ + +/** + * Type decorator (TypeScript). + * @param {string} [typeName] Type name, defaults to the constructor's name + * @returns {TypeDecorator} Decorator function + * @template T extends Message + */ +Type.d = function decorateType(typeName) { + return function typeDecorator(target) { + util.decorateType(target, typeName); + }; +}; + +},{"11":11,"12":12,"13":13,"14":14,"15":15,"18":18,"19":19,"21":21,"23":23,"24":24,"30":30,"33":33,"36":36,"37":37,"38":38}],32:[function(require,module,exports){ +"use strict"; + +/** + * Common type constants. + * @namespace + */ +var types = exports; + +var util = require(33); + +var s = [ + "double", // 0 + "float", // 1 + "int32", // 2 + "uint32", // 3 + "sint32", // 4 + "fixed32", // 5 + "sfixed32", // 6 + "int64", // 7 + "uint64", // 8 + "sint64", // 9 + "fixed64", // 10 + "sfixed64", // 11 + "bool", // 12 + "string", // 13 + "bytes" // 14 +]; + +function bake(values, offset) { + var i = 0, o = {}; + offset |= 0; + while (i < values.length) o[s[i + offset]] = values[i++]; + return o; +} + +/** + * Basic type wire types. + * @type {Object.} + * @const + * @property {number} double=1 Fixed64 wire type + * @property {number} float=5 Fixed32 wire type + * @property {number} int32=0 Varint wire type + * @property {number} uint32=0 Varint wire type + * @property {number} sint32=0 Varint wire type + * @property {number} fixed32=5 Fixed32 wire type + * @property {number} sfixed32=5 Fixed32 wire type + * @property {number} int64=0 Varint wire type + * @property {number} uint64=0 Varint wire type + * @property {number} sint64=0 Varint wire type + * @property {number} fixed64=1 Fixed64 wire type + * @property {number} sfixed64=1 Fixed64 wire type + * @property {number} bool=0 Varint wire type + * @property {number} string=2 Ldelim wire type + * @property {number} bytes=2 Ldelim wire type + */ +types.basic = bake([ + /* double */ 1, + /* float */ 5, + /* int32 */ 0, + /* uint32 */ 0, + /* sint32 */ 0, + /* fixed32 */ 5, + /* sfixed32 */ 5, + /* int64 */ 0, + /* uint64 */ 0, + /* sint64 */ 0, + /* fixed64 */ 1, + /* sfixed64 */ 1, + /* bool */ 0, + /* string */ 2, + /* bytes */ 2 +]); + +/** + * Basic type defaults. + * @type {Object.} + * @const + * @property {number} double=0 Double default + * @property {number} float=0 Float default + * @property {number} int32=0 Int32 default + * @property {number} uint32=0 Uint32 default + * @property {number} sint32=0 Sint32 default + * @property {number} fixed32=0 Fixed32 default + * @property {number} sfixed32=0 Sfixed32 default + * @property {number} int64=0 Int64 default + * @property {number} uint64=0 Uint64 default + * @property {number} sint64=0 Sint32 default + * @property {number} fixed64=0 Fixed64 default + * @property {number} sfixed64=0 Sfixed64 default + * @property {boolean} bool=false Bool default + * @property {string} string="" String default + * @property {Array.} bytes=Array(0) Bytes default + * @property {null} message=null Message default + */ +types.defaults = bake([ + /* double */ 0, + /* float */ 0, + /* int32 */ 0, + /* uint32 */ 0, + /* sint32 */ 0, + /* fixed32 */ 0, + /* sfixed32 */ 0, + /* int64 */ 0, + /* uint64 */ 0, + /* sint64 */ 0, + /* fixed64 */ 0, + /* sfixed64 */ 0, + /* bool */ false, + /* string */ "", + /* bytes */ util.emptyArray, + /* message */ null +]); + +/** + * Basic long type wire types. + * @type {Object.} + * @const + * @property {number} int64=0 Varint wire type + * @property {number} uint64=0 Varint wire type + * @property {number} sint64=0 Varint wire type + * @property {number} fixed64=1 Fixed64 wire type + * @property {number} sfixed64=1 Fixed64 wire type + */ +types.long = bake([ + /* int64 */ 0, + /* uint64 */ 0, + /* sint64 */ 0, + /* fixed64 */ 1, + /* sfixed64 */ 1 +], 7); + +/** + * Allowed types for map keys with their associated wire type. + * @type {Object.} + * @const + * @property {number} int32=0 Varint wire type + * @property {number} uint32=0 Varint wire type + * @property {number} sint32=0 Varint wire type + * @property {number} fixed32=5 Fixed32 wire type + * @property {number} sfixed32=5 Fixed32 wire type + * @property {number} int64=0 Varint wire type + * @property {number} uint64=0 Varint wire type + * @property {number} sint64=0 Varint wire type + * @property {number} fixed64=1 Fixed64 wire type + * @property {number} sfixed64=1 Fixed64 wire type + * @property {number} bool=0 Varint wire type + * @property {number} string=2 Ldelim wire type + */ +types.mapKey = bake([ + /* int32 */ 0, + /* uint32 */ 0, + /* sint32 */ 0, + /* fixed32 */ 5, + /* sfixed32 */ 5, + /* int64 */ 0, + /* uint64 */ 0, + /* sint64 */ 0, + /* fixed64 */ 1, + /* sfixed64 */ 1, + /* bool */ 0, + /* string */ 2 +], 2); + +/** + * Allowed types for packed repeated fields with their associated wire type. + * @type {Object.} + * @const + * @property {number} double=1 Fixed64 wire type + * @property {number} float=5 Fixed32 wire type + * @property {number} int32=0 Varint wire type + * @property {number} uint32=0 Varint wire type + * @property {number} sint32=0 Varint wire type + * @property {number} fixed32=5 Fixed32 wire type + * @property {number} sfixed32=5 Fixed32 wire type + * @property {number} int64=0 Varint wire type + * @property {number} uint64=0 Varint wire type + * @property {number} sint64=0 Varint wire type + * @property {number} fixed64=1 Fixed64 wire type + * @property {number} sfixed64=1 Fixed64 wire type + * @property {number} bool=0 Varint wire type + */ +types.packed = bake([ + /* double */ 1, + /* float */ 5, + /* int32 */ 0, + /* uint32 */ 0, + /* sint32 */ 0, + /* fixed32 */ 5, + /* sfixed32 */ 5, + /* int64 */ 0, + /* uint64 */ 0, + /* sint64 */ 0, + /* fixed64 */ 1, + /* sfixed64 */ 1, + /* bool */ 0 +]); + +},{"33":33}],33:[function(require,module,exports){ +"use strict"; + +/** + * Various utility functions. + * @namespace + */ +var util = module.exports = require(35); + +var roots = require(27); + +var Type, // cyclic + Enum; + +util.codegen = require(3); +util.fetch = require(5); +util.path = require(8); + +/** + * Node's fs module if available. + * @type {Object.} + */ +util.fs = util.inquire("fs"); + +/** + * Converts an object's values to an array. + * @param {Object.} object Object to convert + * @returns {Array.<*>} Converted array + */ +util.toArray = function toArray(object) { + if (object) { + var keys = Object.keys(object), + array = new Array(keys.length), + index = 0; + while (index < keys.length) + array[index] = object[keys[index++]]; + return array; + } + return []; +}; + +/** + * Converts an array of keys immediately followed by their respective value to an object, omitting undefined values. + * @param {Array.<*>} array Array to convert + * @returns {Object.} Converted object + */ +util.toObject = function toObject(array) { + var object = {}, + index = 0; + while (index < array.length) { + var key = array[index++], + val = array[index++]; + if (val !== undefined) + object[key] = val; + } + return object; +}; + +var safePropBackslashRe = /\\/g, + safePropQuoteRe = /"/g; + +/** + * Tests whether the specified name is a reserved word in JS. + * @param {string} name Name to test + * @returns {boolean} `true` if reserved, otherwise `false` + */ +util.isReserved = function isReserved(name) { + return /^(?:do|if|in|for|let|new|try|var|case|else|enum|eval|false|null|this|true|void|with|break|catch|class|const|super|throw|while|yield|delete|export|import|public|return|static|switch|typeof|default|extends|finally|package|private|continue|debugger|function|arguments|interface|protected|implements|instanceof)$/.test(name); +}; + +/** + * Returns a safe property accessor for the specified property name. + * @param {string} prop Property name + * @returns {string} Safe accessor + */ +util.safeProp = function safeProp(prop) { + if (!/^[$\w_]+$/.test(prop) || util.isReserved(prop)) + return "[\"" + prop.replace(safePropBackslashRe, "\\\\").replace(safePropQuoteRe, "\\\"") + "\"]"; + return "." + prop; +}; + +/** + * Converts the first character of a string to upper case. + * @param {string} str String to convert + * @returns {string} Converted string + */ +util.ucFirst = function ucFirst(str) { + return str.charAt(0).toUpperCase() + str.substring(1); +}; + +var camelCaseRe = /_([a-z])/g; + +/** + * Converts a string to camel case. + * @param {string} str String to convert + * @returns {string} Converted string + */ +util.camelCase = function camelCase(str) { + return str.substring(0, 1) + + str.substring(1) + .replace(camelCaseRe, function($0, $1) { return $1.toUpperCase(); }); +}; + +/** + * Compares reflected fields by id. + * @param {Field} a First field + * @param {Field} b Second field + * @returns {number} Comparison value + */ +util.compareFieldsById = function compareFieldsById(a, b) { + return a.id - b.id; +}; + +/** + * Decorator helper for types (TypeScript). + * @param {Constructor} ctor Constructor function + * @param {string} [typeName] Type name, defaults to the constructor's name + * @returns {Type} Reflected type + * @template T extends Message + * @property {Root} root Decorators root + */ +util.decorateType = function decorateType(ctor, typeName) { + + /* istanbul ignore if */ + if (ctor.$type) { + if (typeName && ctor.$type.name !== typeName) { + util.decorateRoot.remove(ctor.$type); + ctor.$type.name = typeName; + util.decorateRoot.add(ctor.$type); + } + return ctor.$type; + } + + /* istanbul ignore next */ + if (!Type) + Type = require(31); + + var type = new Type(typeName || ctor.name); + util.decorateRoot.add(type); + type.ctor = ctor; // sets up .encode, .decode etc. + Object.defineProperty(ctor, "$type", { value: type, enumerable: false }); + Object.defineProperty(ctor.prototype, "$type", { value: type, enumerable: false }); + return type; +}; + +var decorateEnumIndex = 0; + +/** + * Decorator helper for enums (TypeScript). + * @param {Object} object Enum object + * @returns {Enum} Reflected enum + */ +util.decorateEnum = function decorateEnum(object) { + + /* istanbul ignore if */ + if (object.$type) + return object.$type; + + /* istanbul ignore next */ + if (!Enum) + Enum = require(14); + + var enm = new Enum("Enum" + decorateEnumIndex++, object); + util.decorateRoot.add(enm); + Object.defineProperty(object, "$type", { value: enm, enumerable: false }); + return enm; +}; + + +/** + * Sets the value of a property by property path. If a value already exists, it is turned to an array + * @param {Object.} dst Destination object + * @param {string} path dot '.' delimited path of the property to set + * @param {Object} value the value to set + * @returns {Object.} Destination object + */ +util.setProperty = function setProperty(dst, path, value) { + function setProp(dst, path, value) { + var part = path.shift(); + if (part === "__proto__" || part === "prototype") { + return dst; + } + if (path.length > 0) { + dst[part] = setProp(dst[part] || {}, path, value); + } else { + var prevValue = dst[part]; + if (prevValue) + value = [].concat(prevValue).concat(value); + dst[part] = value; + } + return dst; + } + + if (typeof dst !== "object") + throw TypeError("dst must be an object"); + if (!path) + throw TypeError("path must be specified"); + + path = path.split("."); + return setProp(dst, path, value); +}; + +/** + * Decorator root (TypeScript). + * @name util.decorateRoot + * @type {Root} + * @readonly + */ +Object.defineProperty(util, "decorateRoot", { + get: function() { + return roots["decorated"] || (roots["decorated"] = new (require(26))()); + } +}); + +},{"14":14,"26":26,"27":27,"3":3,"31":31,"35":35,"5":5,"8":8}],34:[function(require,module,exports){ +"use strict"; +module.exports = LongBits; + +var util = require(35); + +/** + * Constructs new long bits. + * @classdesc Helper class for working with the low and high bits of a 64 bit value. + * @memberof util + * @constructor + * @param {number} lo Low 32 bits, unsigned + * @param {number} hi High 32 bits, unsigned + */ +function LongBits(lo, hi) { + + // note that the casts below are theoretically unnecessary as of today, but older statically + // generated converter code might still call the ctor with signed 32bits. kept for compat. + + /** + * Low bits. + * @type {number} + */ + this.lo = lo >>> 0; + + /** + * High bits. + * @type {number} + */ + this.hi = hi >>> 0; +} + +/** + * Zero bits. + * @memberof util.LongBits + * @type {util.LongBits} + */ +var zero = LongBits.zero = new LongBits(0, 0); + +zero.toNumber = function() { return 0; }; +zero.zzEncode = zero.zzDecode = function() { return this; }; +zero.length = function() { return 1; }; + +/** + * Zero hash. + * @memberof util.LongBits + * @type {string} + */ +var zeroHash = LongBits.zeroHash = "\0\0\0\0\0\0\0\0"; + +/** + * Constructs new long bits from the specified number. + * @param {number} value Value + * @returns {util.LongBits} Instance + */ +LongBits.fromNumber = function fromNumber(value) { + if (value === 0) + return zero; + var sign = value < 0; + if (sign) + value = -value; + var lo = value >>> 0, + hi = (value - lo) / 4294967296 >>> 0; + if (sign) { + hi = ~hi >>> 0; + lo = ~lo >>> 0; + if (++lo > 4294967295) { + lo = 0; + if (++hi > 4294967295) + hi = 0; + } + } + return new LongBits(lo, hi); +}; + +/** + * Constructs new long bits from a number, long or string. + * @param {Long|number|string} value Value + * @returns {util.LongBits} Instance + */ +LongBits.from = function from(value) { + if (typeof value === "number") + return LongBits.fromNumber(value); + if (util.isString(value)) { + /* istanbul ignore else */ + if (util.Long) + value = util.Long.fromString(value); + else + return LongBits.fromNumber(parseInt(value, 10)); + } + return value.low || value.high ? new LongBits(value.low >>> 0, value.high >>> 0) : zero; +}; + +/** + * Converts this long bits to a possibly unsafe JavaScript number. + * @param {boolean} [unsigned=false] Whether unsigned or not + * @returns {number} Possibly unsafe number + */ +LongBits.prototype.toNumber = function toNumber(unsigned) { + if (!unsigned && this.hi >>> 31) { + var lo = ~this.lo + 1 >>> 0, + hi = ~this.hi >>> 0; + if (!lo) + hi = hi + 1 >>> 0; + return -(lo + hi * 4294967296); + } + return this.lo + this.hi * 4294967296; +}; + +/** + * Converts this long bits to a long. + * @param {boolean} [unsigned=false] Whether unsigned or not + * @returns {Long} Long + */ +LongBits.prototype.toLong = function toLong(unsigned) { + return util.Long + ? new util.Long(this.lo | 0, this.hi | 0, Boolean(unsigned)) + /* istanbul ignore next */ + : { low: this.lo | 0, high: this.hi | 0, unsigned: Boolean(unsigned) }; +}; + +var charCodeAt = String.prototype.charCodeAt; + +/** + * Constructs new long bits from the specified 8 characters long hash. + * @param {string} hash Hash + * @returns {util.LongBits} Bits + */ +LongBits.fromHash = function fromHash(hash) { + if (hash === zeroHash) + return zero; + return new LongBits( + ( charCodeAt.call(hash, 0) + | charCodeAt.call(hash, 1) << 8 + | charCodeAt.call(hash, 2) << 16 + | charCodeAt.call(hash, 3) << 24) >>> 0 + , + ( charCodeAt.call(hash, 4) + | charCodeAt.call(hash, 5) << 8 + | charCodeAt.call(hash, 6) << 16 + | charCodeAt.call(hash, 7) << 24) >>> 0 + ); +}; + +/** + * Converts this long bits to a 8 characters long hash. + * @returns {string} Hash + */ +LongBits.prototype.toHash = function toHash() { + return String.fromCharCode( + this.lo & 255, + this.lo >>> 8 & 255, + this.lo >>> 16 & 255, + this.lo >>> 24 , + this.hi & 255, + this.hi >>> 8 & 255, + this.hi >>> 16 & 255, + this.hi >>> 24 + ); +}; + +/** + * Zig-zag encodes this long bits. + * @returns {util.LongBits} `this` + */ +LongBits.prototype.zzEncode = function zzEncode() { + var mask = this.hi >> 31; + this.hi = ((this.hi << 1 | this.lo >>> 31) ^ mask) >>> 0; + this.lo = ( this.lo << 1 ^ mask) >>> 0; + return this; +}; + +/** + * Zig-zag decodes this long bits. + * @returns {util.LongBits} `this` + */ +LongBits.prototype.zzDecode = function zzDecode() { + var mask = -(this.lo & 1); + this.lo = ((this.lo >>> 1 | this.hi << 31) ^ mask) >>> 0; + this.hi = ( this.hi >>> 1 ^ mask) >>> 0; + return this; +}; + +/** + * Calculates the length of this longbits when encoded as a varint. + * @returns {number} Length + */ +LongBits.prototype.length = function length() { + var part0 = this.lo, + part1 = (this.lo >>> 28 | this.hi << 4) >>> 0, + part2 = this.hi >>> 24; + return part2 === 0 + ? part1 === 0 + ? part0 < 16384 + ? part0 < 128 ? 1 : 2 + : part0 < 2097152 ? 3 : 4 + : part1 < 16384 + ? part1 < 128 ? 5 : 6 + : part1 < 2097152 ? 7 : 8 + : part2 < 128 ? 9 : 10; +}; + +},{"35":35}],35:[function(require,module,exports){ +"use strict"; +var util = exports; + +// used to return a Promise where callback is omitted +util.asPromise = require(1); + +// converts to / from base64 encoded strings +util.base64 = require(2); + +// base class of rpc.Service +util.EventEmitter = require(4); + +// float handling accross browsers +util.float = require(6); + +// requires modules optionally and hides the call from bundlers +util.inquire = require(7); + +// converts to / from utf8 encoded strings +util.utf8 = require(10); + +// provides a node-like buffer pool in the browser +util.pool = require(9); + +// utility to work with the low and high bits of a 64 bit value +util.LongBits = require(34); + +/** + * Whether running within node or not. + * @memberof util + * @type {boolean} + */ +util.isNode = Boolean(typeof global !== "undefined" + && global + && global.process + && global.process.versions + && global.process.versions.node); + +/** + * Global object reference. + * @memberof util + * @type {Object} + */ +util.global = util.isNode && global + || typeof window !== "undefined" && window + || typeof self !== "undefined" && self + || this; // eslint-disable-line no-invalid-this + +/** + * An immuable empty array. + * @memberof util + * @type {Array.<*>} + * @const + */ +util.emptyArray = Object.freeze ? Object.freeze([]) : /* istanbul ignore next */ []; // used on prototypes + +/** + * An immutable empty object. + * @type {Object} + * @const + */ +util.emptyObject = Object.freeze ? Object.freeze({}) : /* istanbul ignore next */ {}; // used on prototypes + +/** + * Tests if the specified value is an integer. + * @function + * @param {*} value Value to test + * @returns {boolean} `true` if the value is an integer + */ +util.isInteger = Number.isInteger || /* istanbul ignore next */ function isInteger(value) { + return typeof value === "number" && isFinite(value) && Math.floor(value) === value; +}; + +/** + * Tests if the specified value is a string. + * @param {*} value Value to test + * @returns {boolean} `true` if the value is a string + */ +util.isString = function isString(value) { + return typeof value === "string" || value instanceof String; +}; + +/** + * Tests if the specified value is a non-null object. + * @param {*} value Value to test + * @returns {boolean} `true` if the value is a non-null object + */ +util.isObject = function isObject(value) { + return value && typeof value === "object"; +}; + +/** + * Checks if a property on a message is considered to be present. + * This is an alias of {@link util.isSet}. + * @function + * @param {Object} obj Plain object or message instance + * @param {string} prop Property name + * @returns {boolean} `true` if considered to be present, otherwise `false` + */ +util.isset = + +/** + * Checks if a property on a message is considered to be present. + * @param {Object} obj Plain object or message instance + * @param {string} prop Property name + * @returns {boolean} `true` if considered to be present, otherwise `false` + */ +util.isSet = function isSet(obj, prop) { + var value = obj[prop]; + if (value != null && obj.hasOwnProperty(prop)) // eslint-disable-line eqeqeq, no-prototype-builtins + return typeof value !== "object" || (Array.isArray(value) ? value.length : Object.keys(value).length) > 0; + return false; +}; + +/** + * Any compatible Buffer instance. + * This is a minimal stand-alone definition of a Buffer instance. The actual type is that exported by node's typings. + * @interface Buffer + * @extends Uint8Array + */ + +/** + * Node's Buffer class if available. + * @type {Constructor} + */ +util.Buffer = (function() { + try { + var Buffer = util.inquire("buffer").Buffer; + // refuse to use non-node buffers if not explicitly assigned (perf reasons): + return Buffer.prototype.utf8Write ? Buffer : /* istanbul ignore next */ null; + } catch (e) { + /* istanbul ignore next */ + return null; + } +})(); + +// Internal alias of or polyfull for Buffer.from. +util._Buffer_from = null; + +// Internal alias of or polyfill for Buffer.allocUnsafe. +util._Buffer_allocUnsafe = null; + +/** + * Creates a new buffer of whatever type supported by the environment. + * @param {number|number[]} [sizeOrArray=0] Buffer size or number array + * @returns {Uint8Array|Buffer} Buffer + */ +util.newBuffer = function newBuffer(sizeOrArray) { + /* istanbul ignore next */ + return typeof sizeOrArray === "number" + ? util.Buffer + ? util._Buffer_allocUnsafe(sizeOrArray) + : new util.Array(sizeOrArray) + : util.Buffer + ? util._Buffer_from(sizeOrArray) + : typeof Uint8Array === "undefined" + ? sizeOrArray + : new Uint8Array(sizeOrArray); +}; + +/** + * Array implementation used in the browser. `Uint8Array` if supported, otherwise `Array`. + * @type {Constructor} + */ +util.Array = typeof Uint8Array !== "undefined" ? Uint8Array /* istanbul ignore next */ : Array; + +/** + * Any compatible Long instance. + * This is a minimal stand-alone definition of a Long instance. The actual type is that exported by long.js. + * @interface Long + * @property {number} low Low bits + * @property {number} high High bits + * @property {boolean} unsigned Whether unsigned or not + */ + +/** + * Long.js's Long class if available. + * @type {Constructor} + */ +util.Long = /* istanbul ignore next */ util.global.dcodeIO && /* istanbul ignore next */ util.global.dcodeIO.Long + || /* istanbul ignore next */ util.global.Long + || util.inquire("long"); + +/** + * Regular expression used to verify 2 bit (`bool`) map keys. + * @type {RegExp} + * @const + */ +util.key2Re = /^true|false|0|1$/; + +/** + * Regular expression used to verify 32 bit (`int32` etc.) map keys. + * @type {RegExp} + * @const + */ +util.key32Re = /^-?(?:0|[1-9][0-9]*)$/; + +/** + * Regular expression used to verify 64 bit (`int64` etc.) map keys. + * @type {RegExp} + * @const + */ +util.key64Re = /^(?:[\\x00-\\xff]{8}|-?(?:0|[1-9][0-9]*))$/; + +/** + * Converts a number or long to an 8 characters long hash string. + * @param {Long|number} value Value to convert + * @returns {string} Hash + */ +util.longToHash = function longToHash(value) { + return value + ? util.LongBits.from(value).toHash() + : util.LongBits.zeroHash; +}; + +/** + * Converts an 8 characters long hash string to a long or number. + * @param {string} hash Hash + * @param {boolean} [unsigned=false] Whether unsigned or not + * @returns {Long|number} Original value + */ +util.longFromHash = function longFromHash(hash, unsigned) { + var bits = util.LongBits.fromHash(hash); + if (util.Long) + return util.Long.fromBits(bits.lo, bits.hi, unsigned); + return bits.toNumber(Boolean(unsigned)); +}; + +/** + * Merges the properties of the source object into the destination object. + * @memberof util + * @param {Object.} dst Destination object + * @param {Object.} src Source object + * @param {boolean} [ifNotSet=false] Merges only if the key is not already set + * @returns {Object.} Destination object + */ +function merge(dst, src, ifNotSet) { // used by converters + for (var keys = Object.keys(src), i = 0; i < keys.length; ++i) + if (dst[keys[i]] === undefined || !ifNotSet) + dst[keys[i]] = src[keys[i]]; + return dst; +} + +util.merge = merge; + +/** + * Converts the first character of a string to lower case. + * @param {string} str String to convert + * @returns {string} Converted string + */ +util.lcFirst = function lcFirst(str) { + return str.charAt(0).toLowerCase() + str.substring(1); +}; + +/** + * Creates a custom error constructor. + * @memberof util + * @param {string} name Error name + * @returns {Constructor} Custom error constructor + */ +function newError(name) { + + function CustomError(message, properties) { + + if (!(this instanceof CustomError)) + return new CustomError(message, properties); + + // Error.call(this, message); + // ^ just returns a new error instance because the ctor can be called as a function + + Object.defineProperty(this, "message", { get: function() { return message; } }); + + /* istanbul ignore next */ + if (Error.captureStackTrace) // node + Error.captureStackTrace(this, CustomError); + else + Object.defineProperty(this, "stack", { value: new Error().stack || "" }); + + if (properties) + merge(this, properties); + } + + CustomError.prototype = Object.create(Error.prototype, { + constructor: { + value: CustomError, + writable: true, + enumerable: false, + configurable: true, + }, + name: { + get: function get() { return name; }, + set: undefined, + enumerable: false, + // configurable: false would accurately preserve the behavior of + // the original, but I'm guessing that was not intentional. + // For an actual error subclass, this property would + // be configurable. + configurable: true, + }, + toString: { + value: function value() { return this.name + ": " + this.message; }, + writable: true, + enumerable: false, + configurable: true, + }, + }); + + return CustomError; +} + +util.newError = newError; + +/** + * Constructs a new protocol error. + * @classdesc Error subclass indicating a protocol specifc error. + * @memberof util + * @extends Error + * @template T extends Message + * @constructor + * @param {string} message Error message + * @param {Object.} [properties] Additional properties + * @example + * try { + * MyMessage.decode(someBuffer); // throws if required fields are missing + * } catch (e) { + * if (e instanceof ProtocolError && e.instance) + * console.log("decoded so far: " + JSON.stringify(e.instance)); + * } + */ +util.ProtocolError = newError("ProtocolError"); + +/** + * So far decoded message instance. + * @name util.ProtocolError#instance + * @type {Message} + */ + +/** + * A OneOf getter as returned by {@link util.oneOfGetter}. + * @typedef OneOfGetter + * @type {function} + * @returns {string|undefined} Set field name, if any + */ + +/** + * Builds a getter for a oneof's present field name. + * @param {string[]} fieldNames Field names + * @returns {OneOfGetter} Unbound getter + */ +util.oneOfGetter = function getOneOf(fieldNames) { + var fieldMap = {}; + for (var i = 0; i < fieldNames.length; ++i) + fieldMap[fieldNames[i]] = 1; + + /** + * @returns {string|undefined} Set field name, if any + * @this Object + * @ignore + */ + return function() { // eslint-disable-line consistent-return + for (var keys = Object.keys(this), i = keys.length - 1; i > -1; --i) + if (fieldMap[keys[i]] === 1 && this[keys[i]] !== undefined && this[keys[i]] !== null) + return keys[i]; + }; +}; + +/** + * A OneOf setter as returned by {@link util.oneOfSetter}. + * @typedef OneOfSetter + * @type {function} + * @param {string|undefined} value Field name + * @returns {undefined} + */ + +/** + * Builds a setter for a oneof's present field name. + * @param {string[]} fieldNames Field names + * @returns {OneOfSetter} Unbound setter + */ +util.oneOfSetter = function setOneOf(fieldNames) { + + /** + * @param {string} name Field name + * @returns {undefined} + * @this Object + * @ignore + */ + return function(name) { + for (var i = 0; i < fieldNames.length; ++i) + if (fieldNames[i] !== name) + delete this[fieldNames[i]]; + }; +}; + +/** + * Default conversion options used for {@link Message#toJSON} implementations. + * + * These options are close to proto3's JSON mapping with the exception that internal types like Any are handled just like messages. More precisely: + * + * - Longs become strings + * - Enums become string keys + * - Bytes become base64 encoded strings + * - (Sub-)Messages become plain objects + * - Maps become plain objects with all string keys + * - Repeated fields become arrays + * - NaN and Infinity for float and double fields become strings + * + * @type {IConversionOptions} + * @see https://developers.google.com/protocol-buffers/docs/proto3?hl=en#json + */ +util.toJSONOptions = { + longs: String, + enums: String, + bytes: String, + json: true +}; + +// Sets up buffer utility according to the environment (called in index-minimal) +util._configure = function() { + var Buffer = util.Buffer; + /* istanbul ignore if */ + if (!Buffer) { + util._Buffer_from = util._Buffer_allocUnsafe = null; + return; + } + // because node 4.x buffers are incompatible & immutable + // see: https://github.com/dcodeIO/protobuf.js/pull/665 + util._Buffer_from = Buffer.from !== Uint8Array.from && Buffer.from || + /* istanbul ignore next */ + function Buffer_from(value, encoding) { + return new Buffer(value, encoding); + }; + util._Buffer_allocUnsafe = Buffer.allocUnsafe || + /* istanbul ignore next */ + function Buffer_allocUnsafe(size) { + return new Buffer(size); + }; +}; + +},{"1":1,"10":10,"2":2,"34":34,"4":4,"6":6,"7":7,"9":9}],36:[function(require,module,exports){ +"use strict"; +module.exports = verifier; + +var Enum = require(14), + util = require(33); + +function invalid(field, expected) { + return field.name + ": " + expected + (field.repeated && expected !== "array" ? "[]" : field.map && expected !== "object" ? "{k:"+field.keyType+"}" : "") + " expected"; +} + +/** + * Generates a partial value verifier. + * @param {Codegen} gen Codegen instance + * @param {Field} field Reflected field + * @param {number} fieldIndex Field index + * @param {string} ref Variable reference + * @returns {Codegen} Codegen instance + * @ignore + */ +function genVerifyValue(gen, field, fieldIndex, ref) { + /* eslint-disable no-unexpected-multiline */ + if (field.resolvedType) { + if (field.resolvedType instanceof Enum) { gen + ("switch(%s){", ref) + ("default:") + ("return%j", invalid(field, "enum value")); + for (var keys = Object.keys(field.resolvedType.values), j = 0; j < keys.length; ++j) gen + ("case %i:", field.resolvedType.values[keys[j]]); + gen + ("break") + ("}"); + } else { + gen + ("{") + ("var e=types[%i].verify(%s);", fieldIndex, ref) + ("if(e)") + ("return%j+e", field.name + ".") + ("}"); + } + } else { + switch (field.type) { + case "int32": + case "uint32": + case "sint32": + case "fixed32": + case "sfixed32": gen + ("if(!util.isInteger(%s))", ref) + ("return%j", invalid(field, "integer")); + break; + case "int64": + case "uint64": + case "sint64": + case "fixed64": + case "sfixed64": gen + ("if(!util.isInteger(%s)&&!(%s&&util.isInteger(%s.low)&&util.isInteger(%s.high)))", ref, ref, ref, ref) + ("return%j", invalid(field, "integer|Long")); + break; + case "float": + case "double": gen + ("if(typeof %s!==\"number\")", ref) + ("return%j", invalid(field, "number")); + break; + case "bool": gen + ("if(typeof %s!==\"boolean\")", ref) + ("return%j", invalid(field, "boolean")); + break; + case "string": gen + ("if(!util.isString(%s))", ref) + ("return%j", invalid(field, "string")); + break; + case "bytes": gen + ("if(!(%s&&typeof %s.length===\"number\"||util.isString(%s)))", ref, ref, ref) + ("return%j", invalid(field, "buffer")); + break; + } + } + return gen; + /* eslint-enable no-unexpected-multiline */ +} + +/** + * Generates a partial key verifier. + * @param {Codegen} gen Codegen instance + * @param {Field} field Reflected field + * @param {string} ref Variable reference + * @returns {Codegen} Codegen instance + * @ignore + */ +function genVerifyKey(gen, field, ref) { + /* eslint-disable no-unexpected-multiline */ + switch (field.keyType) { + case "int32": + case "uint32": + case "sint32": + case "fixed32": + case "sfixed32": gen + ("if(!util.key32Re.test(%s))", ref) + ("return%j", invalid(field, "integer key")); + break; + case "int64": + case "uint64": + case "sint64": + case "fixed64": + case "sfixed64": gen + ("if(!util.key64Re.test(%s))", ref) // see comment above: x is ok, d is not + ("return%j", invalid(field, "integer|Long key")); + break; + case "bool": gen + ("if(!util.key2Re.test(%s))", ref) + ("return%j", invalid(field, "boolean key")); + break; + } + return gen; + /* eslint-enable no-unexpected-multiline */ +} + +/** + * Generates a verifier specific to the specified message type. + * @param {Type} mtype Message type + * @returns {Codegen} Codegen instance + */ +function verifier(mtype) { + /* eslint-disable no-unexpected-multiline */ + + var gen = util.codegen(["m"], mtype.name + "$verify") + ("if(typeof m!==\"object\"||m===null)") + ("return%j", "object expected"); + var oneofs = mtype.oneofsArray, + seenFirstField = {}; + if (oneofs.length) gen + ("var p={}"); + + for (var i = 0; i < /* initializes */ mtype.fieldsArray.length; ++i) { + var field = mtype._fieldsArray[i].resolve(), + ref = "m" + util.safeProp(field.name); + + if (field.optional) gen + ("if(%s!=null&&m.hasOwnProperty(%j)){", ref, field.name); // !== undefined && !== null + + // map fields + if (field.map) { gen + ("if(!util.isObject(%s))", ref) + ("return%j", invalid(field, "object")) + ("var k=Object.keys(%s)", ref) + ("for(var i=0;i} + * @const + */ +var wrappers = exports; + +var Message = require(19); + +/** + * From object converter part of an {@link IWrapper}. + * @typedef WrapperFromObjectConverter + * @type {function} + * @param {Object.} object Plain object + * @returns {Message<{}>} Message instance + * @this Type + */ + +/** + * To object converter part of an {@link IWrapper}. + * @typedef WrapperToObjectConverter + * @type {function} + * @param {Message<{}>} message Message instance + * @param {IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + * @this Type + */ + +/** + * Common type wrapper part of {@link wrappers}. + * @interface IWrapper + * @property {WrapperFromObjectConverter} [fromObject] From object converter + * @property {WrapperToObjectConverter} [toObject] To object converter + */ + +// Custom wrapper for Any +wrappers[".google.protobuf.Any"] = { + + fromObject: function(object) { + + // unwrap value type if mapped + if (object && object["@type"]) { + // Only use fully qualified type name after the last '/' + var name = object["@type"].substring(object["@type"].lastIndexOf("/") + 1); + var type = this.lookup(name); + /* istanbul ignore else */ + if (type) { + // type_url does not accept leading "." + var type_url = object["@type"].charAt(0) === "." ? + object["@type"].slice(1) : object["@type"]; + // type_url prefix is optional, but path seperator is required + if (type_url.indexOf("/") === -1) { + type_url = "/" + type_url; + } + return this.create({ + type_url: type_url, + value: type.encode(type.fromObject(object)).finish() + }); + } + } + + return this.fromObject(object); + }, + + toObject: function(message, options) { + + // Default prefix + var googleApi = "type.googleapis.com/"; + var prefix = ""; + var name = ""; + + // decode value if requested and unmapped + if (options && options.json && message.type_url && message.value) { + // Only use fully qualified type name after the last '/' + name = message.type_url.substring(message.type_url.lastIndexOf("/") + 1); + // Separate the prefix used + prefix = message.type_url.substring(0, message.type_url.lastIndexOf("/") + 1); + var type = this.lookup(name); + /* istanbul ignore else */ + if (type) + message = type.decode(message.value); + } + + // wrap value if unmapped + if (!(message instanceof this.ctor) && message instanceof Message) { + var object = message.$type.toObject(message, options); + var messageName = message.$type.fullName[0] === "." ? + message.$type.fullName.slice(1) : message.$type.fullName; + // Default to type.googleapis.com prefix if no prefix is used + if (prefix === "") { + prefix = googleApi; + } + name = prefix + messageName; + object["@type"] = name; + return object; + } + + return this.toObject(message, options); + } +}; + +},{"19":19}],38:[function(require,module,exports){ +"use strict"; +module.exports = Writer; + +var util = require(35); + +var BufferWriter; // cyclic + +var LongBits = util.LongBits, + base64 = util.base64, + utf8 = util.utf8; + +/** + * Constructs a new writer operation instance. + * @classdesc Scheduled writer operation. + * @constructor + * @param {function(*, Uint8Array, number)} fn Function to call + * @param {number} len Value byte length + * @param {*} val Value to write + * @ignore + */ +function Op(fn, len, val) { + + /** + * Function to call. + * @type {function(Uint8Array, number, *)} + */ + this.fn = fn; + + /** + * Value byte length. + * @type {number} + */ + this.len = len; + + /** + * Next operation. + * @type {Writer.Op|undefined} + */ + this.next = undefined; + + /** + * Value to write. + * @type {*} + */ + this.val = val; // type varies +} + +/* istanbul ignore next */ +function noop() {} // eslint-disable-line no-empty-function + +/** + * Constructs a new writer state instance. + * @classdesc Copied writer state. + * @memberof Writer + * @constructor + * @param {Writer} writer Writer to copy state from + * @ignore + */ +function State(writer) { + + /** + * Current head. + * @type {Writer.Op} + */ + this.head = writer.head; + + /** + * Current tail. + * @type {Writer.Op} + */ + this.tail = writer.tail; + + /** + * Current buffer length. + * @type {number} + */ + this.len = writer.len; + + /** + * Next state. + * @type {State|null} + */ + this.next = writer.states; +} + +/** + * Constructs a new writer instance. + * @classdesc Wire format writer using `Uint8Array` if available, otherwise `Array`. + * @constructor + */ +function Writer() { + + /** + * Current length. + * @type {number} + */ + this.len = 0; + + /** + * Operations head. + * @type {Object} + */ + this.head = new Op(noop, 0, 0); + + /** + * Operations tail + * @type {Object} + */ + this.tail = this.head; + + /** + * Linked forked states. + * @type {Object|null} + */ + this.states = null; + + // When a value is written, the writer calculates its byte length and puts it into a linked + // list of operations to perform when finish() is called. This both allows us to allocate + // buffers of the exact required size and reduces the amount of work we have to do compared + // to first calculating over objects and then encoding over objects. In our case, the encoding + // part is just a linked list walk calling operations with already prepared values. +} + +var create = function create() { + return util.Buffer + ? function create_buffer_setup() { + return (Writer.create = function create_buffer() { + return new BufferWriter(); + })(); + } + /* istanbul ignore next */ + : function create_array() { + return new Writer(); + }; +}; + +/** + * Creates a new writer. + * @function + * @returns {BufferWriter|Writer} A {@link BufferWriter} when Buffers are supported, otherwise a {@link Writer} + */ +Writer.create = create(); + +/** + * Allocates a buffer of the specified size. + * @param {number} size Buffer size + * @returns {Uint8Array} Buffer + */ +Writer.alloc = function alloc(size) { + return new util.Array(size); +}; + +// Use Uint8Array buffer pool in the browser, just like node does with buffers +/* istanbul ignore else */ +if (util.Array !== Array) + Writer.alloc = util.pool(Writer.alloc, util.Array.prototype.subarray); + +/** + * Pushes a new operation to the queue. + * @param {function(Uint8Array, number, *)} fn Function to call + * @param {number} len Value byte length + * @param {number} val Value to write + * @returns {Writer} `this` + * @private + */ +Writer.prototype._push = function push(fn, len, val) { + this.tail = this.tail.next = new Op(fn, len, val); + this.len += len; + return this; +}; + +function writeByte(val, buf, pos) { + buf[pos] = val & 255; +} + +function writeVarint32(val, buf, pos) { + while (val > 127) { + buf[pos++] = val & 127 | 128; + val >>>= 7; + } + buf[pos] = val; +} + +/** + * Constructs a new varint writer operation instance. + * @classdesc Scheduled varint writer operation. + * @extends Op + * @constructor + * @param {number} len Value byte length + * @param {number} val Value to write + * @ignore + */ +function VarintOp(len, val) { + this.len = len; + this.next = undefined; + this.val = val; +} + +VarintOp.prototype = Object.create(Op.prototype); +VarintOp.prototype.fn = writeVarint32; + +/** + * Writes an unsigned 32 bit value as a varint. + * @param {number} value Value to write + * @returns {Writer} `this` + */ +Writer.prototype.uint32 = function write_uint32(value) { + // here, the call to this.push has been inlined and a varint specific Op subclass is used. + // uint32 is by far the most frequently used operation and benefits significantly from this. + this.len += (this.tail = this.tail.next = new VarintOp( + (value = value >>> 0) + < 128 ? 1 + : value < 16384 ? 2 + : value < 2097152 ? 3 + : value < 268435456 ? 4 + : 5, + value)).len; + return this; +}; + +/** + * Writes a signed 32 bit value as a varint. + * @function + * @param {number} value Value to write + * @returns {Writer} `this` + */ +Writer.prototype.int32 = function write_int32(value) { + return value < 0 + ? this._push(writeVarint64, 10, LongBits.fromNumber(value)) // 10 bytes per spec + : this.uint32(value); +}; + +/** + * Writes a 32 bit value as a varint, zig-zag encoded. + * @param {number} value Value to write + * @returns {Writer} `this` + */ +Writer.prototype.sint32 = function write_sint32(value) { + return this.uint32((value << 1 ^ value >> 31) >>> 0); +}; + +function writeVarint64(val, buf, pos) { + while (val.hi) { + buf[pos++] = val.lo & 127 | 128; + val.lo = (val.lo >>> 7 | val.hi << 25) >>> 0; + val.hi >>>= 7; + } + while (val.lo > 127) { + buf[pos++] = val.lo & 127 | 128; + val.lo = val.lo >>> 7; + } + buf[pos++] = val.lo; +} + +/** + * Writes an unsigned 64 bit value as a varint. + * @param {Long|number|string} value Value to write + * @returns {Writer} `this` + * @throws {TypeError} If `value` is a string and no long library is present. + */ +Writer.prototype.uint64 = function write_uint64(value) { + var bits = LongBits.from(value); + return this._push(writeVarint64, bits.length(), bits); +}; + +/** + * Writes a signed 64 bit value as a varint. + * @function + * @param {Long|number|string} value Value to write + * @returns {Writer} `this` + * @throws {TypeError} If `value` is a string and no long library is present. + */ +Writer.prototype.int64 = Writer.prototype.uint64; + +/** + * Writes a signed 64 bit value as a varint, zig-zag encoded. + * @param {Long|number|string} value Value to write + * @returns {Writer} `this` + * @throws {TypeError} If `value` is a string and no long library is present. + */ +Writer.prototype.sint64 = function write_sint64(value) { + var bits = LongBits.from(value).zzEncode(); + return this._push(writeVarint64, bits.length(), bits); +}; + +/** + * Writes a boolish value as a varint. + * @param {boolean} value Value to write + * @returns {Writer} `this` + */ +Writer.prototype.bool = function write_bool(value) { + return this._push(writeByte, 1, value ? 1 : 0); +}; + +function writeFixed32(val, buf, pos) { + buf[pos ] = val & 255; + buf[pos + 1] = val >>> 8 & 255; + buf[pos + 2] = val >>> 16 & 255; + buf[pos + 3] = val >>> 24; +} + +/** + * Writes an unsigned 32 bit value as fixed 32 bits. + * @param {number} value Value to write + * @returns {Writer} `this` + */ +Writer.prototype.fixed32 = function write_fixed32(value) { + return this._push(writeFixed32, 4, value >>> 0); +}; + +/** + * Writes a signed 32 bit value as fixed 32 bits. + * @function + * @param {number} value Value to write + * @returns {Writer} `this` + */ +Writer.prototype.sfixed32 = Writer.prototype.fixed32; + +/** + * Writes an unsigned 64 bit value as fixed 64 bits. + * @param {Long|number|string} value Value to write + * @returns {Writer} `this` + * @throws {TypeError} If `value` is a string and no long library is present. + */ +Writer.prototype.fixed64 = function write_fixed64(value) { + var bits = LongBits.from(value); + return this._push(writeFixed32, 4, bits.lo)._push(writeFixed32, 4, bits.hi); +}; + +/** + * Writes a signed 64 bit value as fixed 64 bits. + * @function + * @param {Long|number|string} value Value to write + * @returns {Writer} `this` + * @throws {TypeError} If `value` is a string and no long library is present. + */ +Writer.prototype.sfixed64 = Writer.prototype.fixed64; + +/** + * Writes a float (32 bit). + * @function + * @param {number} value Value to write + * @returns {Writer} `this` + */ +Writer.prototype.float = function write_float(value) { + return this._push(util.float.writeFloatLE, 4, value); +}; + +/** + * Writes a double (64 bit float). + * @function + * @param {number} value Value to write + * @returns {Writer} `this` + */ +Writer.prototype.double = function write_double(value) { + return this._push(util.float.writeDoubleLE, 8, value); +}; + +var writeBytes = util.Array.prototype.set + ? function writeBytes_set(val, buf, pos) { + buf.set(val, pos); // also works for plain array values + } + /* istanbul ignore next */ + : function writeBytes_for(val, buf, pos) { + for (var i = 0; i < val.length; ++i) + buf[pos + i] = val[i]; + }; + +/** + * Writes a sequence of bytes. + * @param {Uint8Array|string} value Buffer or base64 encoded string to write + * @returns {Writer} `this` + */ +Writer.prototype.bytes = function write_bytes(value) { + var len = value.length >>> 0; + if (!len) + return this._push(writeByte, 1, 0); + if (util.isString(value)) { + var buf = Writer.alloc(len = base64.length(value)); + base64.decode(value, buf, 0); + value = buf; + } + return this.uint32(len)._push(writeBytes, len, value); +}; + +/** + * Writes a string. + * @param {string} value Value to write + * @returns {Writer} `this` + */ +Writer.prototype.string = function write_string(value) { + var len = utf8.length(value); + return len + ? this.uint32(len)._push(utf8.write, len, value) + : this._push(writeByte, 1, 0); +}; + +/** + * Forks this writer's state by pushing it to a stack. + * Calling {@link Writer#reset|reset} or {@link Writer#ldelim|ldelim} resets the writer to the previous state. + * @returns {Writer} `this` + */ +Writer.prototype.fork = function fork() { + this.states = new State(this); + this.head = this.tail = new Op(noop, 0, 0); + this.len = 0; + return this; +}; + +/** + * Resets this instance to the last state. + * @returns {Writer} `this` + */ +Writer.prototype.reset = function reset() { + if (this.states) { + this.head = this.states.head; + this.tail = this.states.tail; + this.len = this.states.len; + this.states = this.states.next; + } else { + this.head = this.tail = new Op(noop, 0, 0); + this.len = 0; + } + return this; +}; + +/** + * Resets to the last state and appends the fork state's current write length as a varint followed by its operations. + * @returns {Writer} `this` + */ +Writer.prototype.ldelim = function ldelim() { + var head = this.head, + tail = this.tail, + len = this.len; + this.reset().uint32(len); + if (len) { + this.tail.next = head.next; // skip noop + this.tail = tail; + this.len += len; + } + return this; +}; + +/** + * Finishes the write operation. + * @returns {Uint8Array} Finished buffer + */ +Writer.prototype.finish = function finish() { + var head = this.head.next, // skip noop + buf = this.constructor.alloc(this.len), + pos = 0; + while (head) { + head.fn(head.val, buf, pos); + pos += head.len; + head = head.next; + } + // this.head = this.tail = null; + return buf; +}; + +Writer._configure = function(BufferWriter_) { + BufferWriter = BufferWriter_; + Writer.create = create(); + BufferWriter._configure(); +}; + +},{"35":35}],39:[function(require,module,exports){ +"use strict"; +module.exports = BufferWriter; + +// extends Writer +var Writer = require(38); +(BufferWriter.prototype = Object.create(Writer.prototype)).constructor = BufferWriter; + +var util = require(35); + +/** + * Constructs a new buffer writer instance. + * @classdesc Wire format writer using node buffers. + * @extends Writer + * @constructor + */ +function BufferWriter() { + Writer.call(this); +} + +BufferWriter._configure = function () { + /** + * Allocates a buffer of the specified size. + * @function + * @param {number} size Buffer size + * @returns {Buffer} Buffer + */ + BufferWriter.alloc = util._Buffer_allocUnsafe; + + BufferWriter.writeBytesBuffer = util.Buffer && util.Buffer.prototype instanceof Uint8Array && util.Buffer.prototype.set.name === "set" + ? function writeBytesBuffer_set(val, buf, pos) { + buf.set(val, pos); // faster than copy (requires node >= 4 where Buffers extend Uint8Array and set is properly inherited) + // also works for plain array values + } + /* istanbul ignore next */ + : function writeBytesBuffer_copy(val, buf, pos) { + if (val.copy) // Buffer values + val.copy(buf, pos, 0, val.length); + else for (var i = 0; i < val.length;) // plain array values + buf[pos++] = val[i++]; + }; +}; + + +/** + * @override + */ +BufferWriter.prototype.bytes = function write_bytes_buffer(value) { + if (util.isString(value)) + value = util._Buffer_from(value, "base64"); + var len = value.length >>> 0; + this.uint32(len); + if (len) + this._push(BufferWriter.writeBytesBuffer, len, value); + return this; +}; + +function writeStringBuffer(val, buf, pos) { + if (val.length < 40) // plain js is faster for short strings (probably due to redundant assertions) + util.utf8.write(val, buf, pos); + else if (buf.utf8Write) + buf.utf8Write(val, pos); + else + buf.write(val, pos); +} + +/** + * @override + */ +BufferWriter.prototype.string = function write_string_buffer(value) { + var len = util.Buffer.byteLength(value); + this.uint32(len); + if (len) + this._push(writeStringBuffer, len, value); + return this; +}; + + +/** + * Finishes the write operation. + * @name BufferWriter#finish + * @function + * @returns {Buffer} Finished buffer + */ + +BufferWriter._configure(); + +},{"35":35,"38":38}]},{},[16]) + +})(); +//# sourceMappingURL=protobuf.js.map diff --git a/node_modules/protobufjs/dist/light/protobuf.js.map b/node_modules/protobufjs/dist/light/protobuf.js.map new file mode 100644 index 0000000..e323edc --- /dev/null +++ b/node_modules/protobufjs/dist/light/protobuf.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["lib/prelude.js","../node_modules/@protobufjs/aspromise/index.js","../node_modules/@protobufjs/base64/index.js","../node_modules/@protobufjs/codegen/index.js","../node_modules/@protobufjs/eventemitter/index.js","../node_modules/@protobufjs/fetch/index.js","../node_modules/@protobufjs/float/index.js","../node_modules/@protobufjs/inquire/index.js","../node_modules/@protobufjs/path/index.js","../node_modules/@protobufjs/pool/index.js","../node_modules/@protobufjs/utf8/index.js","../src/converter.js","../src/decoder.js","../src/encoder.js","../src/enum.js","../src/field.js","../src/index-light","../src/index-minimal.js","../src/mapfield.js","../src/message.js","../src/method.js","../src/namespace.js","../src/object.js","../src/oneof.js","../src/reader.js","../src/reader_buffer.js","../src/root.js","../src/roots.js","../src/rpc.js","../src/rpc/service.js","../src/service.js","../src/type.js","../src/types.js","../src/util.js","../src/util/longbits.js","../src/util/minimal.js","../src/verifier.js","../src/wrappers.js","../src/writer.js","../src/writer_buffer.js"],"names":[],"mappings":";;;;;;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;ACjCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACpDA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC3IA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACnGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC5EA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACnHA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC/UA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACjBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACjEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AChDA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACzGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC7SA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACjIA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACpGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACtMA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACzXA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACxGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACpCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC9HA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC1IA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AChKA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACjbA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACnPA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC3MA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AChaA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACnDA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AChXA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AClBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACpCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC9IA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACvKA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC7kBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACpMA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACpNA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACxMA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACtbA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AChLA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACtGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACjdA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA","file":"protobuf.js","sourcesContent":["(function prelude(modules, cache, entries) {\n\n // This is the prelude used to bundle protobuf.js for the browser. Wraps up the CommonJS\n // sources through a conflict-free require shim and is again wrapped within an iife that\n // provides a minification-friendly `undefined` var plus a global \"use strict\" directive\n // so that minification can remove the directives of each module.\n\n function $require(name) {\n var $module = cache[name];\n if (!$module)\n modules[name][0].call($module = cache[name] = { exports: {} }, $require, $module, $module.exports);\n return $module.exports;\n }\n\n var protobuf = $require(entries[0]);\n\n // Expose globally\n protobuf.util.global.protobuf = protobuf;\n\n // Be nice to AMD\n if (typeof define === \"function\" && define.amd)\n define([\"long\"], function(Long) {\n if (Long && Long.isLong) {\n protobuf.util.Long = Long;\n protobuf.configure();\n }\n return protobuf;\n });\n\n // Be nice to CommonJS\n if (typeof module === \"object\" && module && module.exports)\n module.exports = protobuf;\n\n})/* end of prelude */","\"use strict\";\r\nmodule.exports = asPromise;\r\n\r\n/**\r\n * Callback as used by {@link util.asPromise}.\r\n * @typedef asPromiseCallback\r\n * @type {function}\r\n * @param {Error|null} error Error, if any\r\n * @param {...*} params Additional arguments\r\n * @returns {undefined}\r\n */\r\n\r\n/**\r\n * Returns a promise from a node-style callback function.\r\n * @memberof util\r\n * @param {asPromiseCallback} fn Function to call\r\n * @param {*} ctx Function context\r\n * @param {...*} params Function arguments\r\n * @returns {Promise<*>} Promisified function\r\n */\r\nfunction asPromise(fn, ctx/*, varargs */) {\r\n var params = new Array(arguments.length - 1),\r\n offset = 0,\r\n index = 2,\r\n pending = true;\r\n while (index < arguments.length)\r\n params[offset++] = arguments[index++];\r\n return new Promise(function executor(resolve, reject) {\r\n params[offset] = function callback(err/*, varargs */) {\r\n if (pending) {\r\n pending = false;\r\n if (err)\r\n reject(err);\r\n else {\r\n var params = new Array(arguments.length - 1),\r\n offset = 0;\r\n while (offset < params.length)\r\n params[offset++] = arguments[offset];\r\n resolve.apply(null, params);\r\n }\r\n }\r\n };\r\n try {\r\n fn.apply(ctx || null, params);\r\n } catch (err) {\r\n if (pending) {\r\n pending = false;\r\n reject(err);\r\n }\r\n }\r\n });\r\n}\r\n","\"use strict\";\r\n\r\n/**\r\n * A minimal base64 implementation for number arrays.\r\n * @memberof util\r\n * @namespace\r\n */\r\nvar base64 = exports;\r\n\r\n/**\r\n * Calculates the byte length of a base64 encoded string.\r\n * @param {string} string Base64 encoded string\r\n * @returns {number} Byte length\r\n */\r\nbase64.length = function length(string) {\r\n var p = string.length;\r\n if (!p)\r\n return 0;\r\n var n = 0;\r\n while (--p % 4 > 1 && string.charAt(p) === \"=\")\r\n ++n;\r\n return Math.ceil(string.length * 3) / 4 - n;\r\n};\r\n\r\n// Base64 encoding table\r\nvar b64 = new Array(64);\r\n\r\n// Base64 decoding table\r\nvar s64 = new Array(123);\r\n\r\n// 65..90, 97..122, 48..57, 43, 47\r\nfor (var i = 0; i < 64;)\r\n s64[b64[i] = i < 26 ? i + 65 : i < 52 ? i + 71 : i < 62 ? i - 4 : i - 59 | 43] = i++;\r\n\r\n/**\r\n * Encodes a buffer to a base64 encoded string.\r\n * @param {Uint8Array} buffer Source buffer\r\n * @param {number} start Source start\r\n * @param {number} end Source end\r\n * @returns {string} Base64 encoded string\r\n */\r\nbase64.encode = function encode(buffer, start, end) {\r\n var parts = null,\r\n chunk = [];\r\n var i = 0, // output index\r\n j = 0, // goto index\r\n t; // temporary\r\n while (start < end) {\r\n var b = buffer[start++];\r\n switch (j) {\r\n case 0:\r\n chunk[i++] = b64[b >> 2];\r\n t = (b & 3) << 4;\r\n j = 1;\r\n break;\r\n case 1:\r\n chunk[i++] = b64[t | b >> 4];\r\n t = (b & 15) << 2;\r\n j = 2;\r\n break;\r\n case 2:\r\n chunk[i++] = b64[t | b >> 6];\r\n chunk[i++] = b64[b & 63];\r\n j = 0;\r\n break;\r\n }\r\n if (i > 8191) {\r\n (parts || (parts = [])).push(String.fromCharCode.apply(String, chunk));\r\n i = 0;\r\n }\r\n }\r\n if (j) {\r\n chunk[i++] = b64[t];\r\n chunk[i++] = 61;\r\n if (j === 1)\r\n chunk[i++] = 61;\r\n }\r\n if (parts) {\r\n if (i)\r\n parts.push(String.fromCharCode.apply(String, chunk.slice(0, i)));\r\n return parts.join(\"\");\r\n }\r\n return String.fromCharCode.apply(String, chunk.slice(0, i));\r\n};\r\n\r\nvar invalidEncoding = \"invalid encoding\";\r\n\r\n/**\r\n * Decodes a base64 encoded string to a buffer.\r\n * @param {string} string Source string\r\n * @param {Uint8Array} buffer Destination buffer\r\n * @param {number} offset Destination offset\r\n * @returns {number} Number of bytes written\r\n * @throws {Error} If encoding is invalid\r\n */\r\nbase64.decode = function decode(string, buffer, offset) {\r\n var start = offset;\r\n var j = 0, // goto index\r\n t; // temporary\r\n for (var i = 0; i < string.length;) {\r\n var c = string.charCodeAt(i++);\r\n if (c === 61 && j > 1)\r\n break;\r\n if ((c = s64[c]) === undefined)\r\n throw Error(invalidEncoding);\r\n switch (j) {\r\n case 0:\r\n t = c;\r\n j = 1;\r\n break;\r\n case 1:\r\n buffer[offset++] = t << 2 | (c & 48) >> 4;\r\n t = c;\r\n j = 2;\r\n break;\r\n case 2:\r\n buffer[offset++] = (t & 15) << 4 | (c & 60) >> 2;\r\n t = c;\r\n j = 3;\r\n break;\r\n case 3:\r\n buffer[offset++] = (t & 3) << 6 | c;\r\n j = 0;\r\n break;\r\n }\r\n }\r\n if (j === 1)\r\n throw Error(invalidEncoding);\r\n return offset - start;\r\n};\r\n\r\n/**\r\n * Tests if the specified string appears to be base64 encoded.\r\n * @param {string} string String to test\r\n * @returns {boolean} `true` if probably base64 encoded, otherwise false\r\n */\r\nbase64.test = function test(string) {\r\n return /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(string);\r\n};\r\n","\"use strict\";\r\nmodule.exports = codegen;\r\n\r\n/**\r\n * Begins generating a function.\r\n * @memberof util\r\n * @param {string[]} functionParams Function parameter names\r\n * @param {string} [functionName] Function name if not anonymous\r\n * @returns {Codegen} Appender that appends code to the function's body\r\n */\r\nfunction codegen(functionParams, functionName) {\r\n\r\n /* istanbul ignore if */\r\n if (typeof functionParams === \"string\") {\r\n functionName = functionParams;\r\n functionParams = undefined;\r\n }\r\n\r\n var body = [];\r\n\r\n /**\r\n * Appends code to the function's body or finishes generation.\r\n * @typedef Codegen\r\n * @type {function}\r\n * @param {string|Object.} [formatStringOrScope] Format string or, to finish the function, an object of additional scope variables, if any\r\n * @param {...*} [formatParams] Format parameters\r\n * @returns {Codegen|Function} Itself or the generated function if finished\r\n * @throws {Error} If format parameter counts do not match\r\n */\r\n\r\n function Codegen(formatStringOrScope) {\r\n // note that explicit array handling below makes this ~50% faster\r\n\r\n // finish the function\r\n if (typeof formatStringOrScope !== \"string\") {\r\n var source = toString();\r\n if (codegen.verbose)\r\n console.log(\"codegen: \" + source); // eslint-disable-line no-console\r\n source = \"return \" + source;\r\n if (formatStringOrScope) {\r\n var scopeKeys = Object.keys(formatStringOrScope),\r\n scopeParams = new Array(scopeKeys.length + 1),\r\n scopeValues = new Array(scopeKeys.length),\r\n scopeOffset = 0;\r\n while (scopeOffset < scopeKeys.length) {\r\n scopeParams[scopeOffset] = scopeKeys[scopeOffset];\r\n scopeValues[scopeOffset] = formatStringOrScope[scopeKeys[scopeOffset++]];\r\n }\r\n scopeParams[scopeOffset] = source;\r\n return Function.apply(null, scopeParams).apply(null, scopeValues); // eslint-disable-line no-new-func\r\n }\r\n return Function(source)(); // eslint-disable-line no-new-func\r\n }\r\n\r\n // otherwise append to body\r\n var formatParams = new Array(arguments.length - 1),\r\n formatOffset = 0;\r\n while (formatOffset < formatParams.length)\r\n formatParams[formatOffset] = arguments[++formatOffset];\r\n formatOffset = 0;\r\n formatStringOrScope = formatStringOrScope.replace(/%([%dfijs])/g, function replace($0, $1) {\r\n var value = formatParams[formatOffset++];\r\n switch ($1) {\r\n case \"d\": case \"f\": return String(Number(value));\r\n case \"i\": return String(Math.floor(value));\r\n case \"j\": return JSON.stringify(value);\r\n case \"s\": return String(value);\r\n }\r\n return \"%\";\r\n });\r\n if (formatOffset !== formatParams.length)\r\n throw Error(\"parameter count mismatch\");\r\n body.push(formatStringOrScope);\r\n return Codegen;\r\n }\r\n\r\n function toString(functionNameOverride) {\r\n return \"function \" + (functionNameOverride || functionName || \"\") + \"(\" + (functionParams && functionParams.join(\",\") || \"\") + \"){\\n \" + body.join(\"\\n \") + \"\\n}\";\r\n }\r\n\r\n Codegen.toString = toString;\r\n return Codegen;\r\n}\r\n\r\n/**\r\n * Begins generating a function.\r\n * @memberof util\r\n * @function codegen\r\n * @param {string} [functionName] Function name if not anonymous\r\n * @returns {Codegen} Appender that appends code to the function's body\r\n * @variation 2\r\n */\r\n\r\n/**\r\n * When set to `true`, codegen will log generated code to console. Useful for debugging.\r\n * @name util.codegen.verbose\r\n * @type {boolean}\r\n */\r\ncodegen.verbose = false;\r\n","\"use strict\";\r\nmodule.exports = EventEmitter;\r\n\r\n/**\r\n * Constructs a new event emitter instance.\r\n * @classdesc A minimal event emitter.\r\n * @memberof util\r\n * @constructor\r\n */\r\nfunction EventEmitter() {\r\n\r\n /**\r\n * Registered listeners.\r\n * @type {Object.}\r\n * @private\r\n */\r\n this._listeners = {};\r\n}\r\n\r\n/**\r\n * Registers an event listener.\r\n * @param {string} evt Event name\r\n * @param {function} fn Listener\r\n * @param {*} [ctx] Listener context\r\n * @returns {util.EventEmitter} `this`\r\n */\r\nEventEmitter.prototype.on = function on(evt, fn, ctx) {\r\n (this._listeners[evt] || (this._listeners[evt] = [])).push({\r\n fn : fn,\r\n ctx : ctx || this\r\n });\r\n return this;\r\n};\r\n\r\n/**\r\n * Removes an event listener or any matching listeners if arguments are omitted.\r\n * @param {string} [evt] Event name. Removes all listeners if omitted.\r\n * @param {function} [fn] Listener to remove. Removes all listeners of `evt` if omitted.\r\n * @returns {util.EventEmitter} `this`\r\n */\r\nEventEmitter.prototype.off = function off(evt, fn) {\r\n if (evt === undefined)\r\n this._listeners = {};\r\n else {\r\n if (fn === undefined)\r\n this._listeners[evt] = [];\r\n else {\r\n var listeners = this._listeners[evt];\r\n for (var i = 0; i < listeners.length;)\r\n if (listeners[i].fn === fn)\r\n listeners.splice(i, 1);\r\n else\r\n ++i;\r\n }\r\n }\r\n return this;\r\n};\r\n\r\n/**\r\n * Emits an event by calling its listeners with the specified arguments.\r\n * @param {string} evt Event name\r\n * @param {...*} args Arguments\r\n * @returns {util.EventEmitter} `this`\r\n */\r\nEventEmitter.prototype.emit = function emit(evt) {\r\n var listeners = this._listeners[evt];\r\n if (listeners) {\r\n var args = [],\r\n i = 1;\r\n for (; i < arguments.length;)\r\n args.push(arguments[i++]);\r\n for (i = 0; i < listeners.length;)\r\n listeners[i].fn.apply(listeners[i++].ctx, args);\r\n }\r\n return this;\r\n};\r\n","\"use strict\";\r\nmodule.exports = fetch;\r\n\r\nvar asPromise = require(1),\r\n inquire = require(7);\r\n\r\nvar fs = inquire(\"fs\");\r\n\r\n/**\r\n * Node-style callback as used by {@link util.fetch}.\r\n * @typedef FetchCallback\r\n * @type {function}\r\n * @param {?Error} error Error, if any, otherwise `null`\r\n * @param {string} [contents] File contents, if there hasn't been an error\r\n * @returns {undefined}\r\n */\r\n\r\n/**\r\n * Options as used by {@link util.fetch}.\r\n * @typedef FetchOptions\r\n * @type {Object}\r\n * @property {boolean} [binary=false] Whether expecting a binary response\r\n * @property {boolean} [xhr=false] If `true`, forces the use of XMLHttpRequest\r\n */\r\n\r\n/**\r\n * Fetches the contents of a file.\r\n * @memberof util\r\n * @param {string} filename File path or url\r\n * @param {FetchOptions} options Fetch options\r\n * @param {FetchCallback} callback Callback function\r\n * @returns {undefined}\r\n */\r\nfunction fetch(filename, options, callback) {\r\n if (typeof options === \"function\") {\r\n callback = options;\r\n options = {};\r\n } else if (!options)\r\n options = {};\r\n\r\n if (!callback)\r\n return asPromise(fetch, this, filename, options); // eslint-disable-line no-invalid-this\r\n\r\n // if a node-like filesystem is present, try it first but fall back to XHR if nothing is found.\r\n if (!options.xhr && fs && fs.readFile)\r\n return fs.readFile(filename, function fetchReadFileCallback(err, contents) {\r\n return err && typeof XMLHttpRequest !== \"undefined\"\r\n ? fetch.xhr(filename, options, callback)\r\n : err\r\n ? callback(err)\r\n : callback(null, options.binary ? contents : contents.toString(\"utf8\"));\r\n });\r\n\r\n // use the XHR version otherwise.\r\n return fetch.xhr(filename, options, callback);\r\n}\r\n\r\n/**\r\n * Fetches the contents of a file.\r\n * @name util.fetch\r\n * @function\r\n * @param {string} path File path or url\r\n * @param {FetchCallback} callback Callback function\r\n * @returns {undefined}\r\n * @variation 2\r\n */\r\n\r\n/**\r\n * Fetches the contents of a file.\r\n * @name util.fetch\r\n * @function\r\n * @param {string} path File path or url\r\n * @param {FetchOptions} [options] Fetch options\r\n * @returns {Promise} Promise\r\n * @variation 3\r\n */\r\n\r\n/**/\r\nfetch.xhr = function fetch_xhr(filename, options, callback) {\r\n var xhr = new XMLHttpRequest();\r\n xhr.onreadystatechange /* works everywhere */ = function fetchOnReadyStateChange() {\r\n\r\n if (xhr.readyState !== 4)\r\n return undefined;\r\n\r\n // local cors security errors return status 0 / empty string, too. afaik this cannot be\r\n // reliably distinguished from an actually empty file for security reasons. feel free\r\n // to send a pull request if you are aware of a solution.\r\n if (xhr.status !== 0 && xhr.status !== 200)\r\n return callback(Error(\"status \" + xhr.status));\r\n\r\n // if binary data is expected, make sure that some sort of array is returned, even if\r\n // ArrayBuffers are not supported. the binary string fallback, however, is unsafe.\r\n if (options.binary) {\r\n var buffer = xhr.response;\r\n if (!buffer) {\r\n buffer = [];\r\n for (var i = 0; i < xhr.responseText.length; ++i)\r\n buffer.push(xhr.responseText.charCodeAt(i) & 255);\r\n }\r\n return callback(null, typeof Uint8Array !== \"undefined\" ? new Uint8Array(buffer) : buffer);\r\n }\r\n return callback(null, xhr.responseText);\r\n };\r\n\r\n if (options.binary) {\r\n // ref: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Sending_and_Receiving_Binary_Data#Receiving_binary_data_in_older_browsers\r\n if (\"overrideMimeType\" in xhr)\r\n xhr.overrideMimeType(\"text/plain; charset=x-user-defined\");\r\n xhr.responseType = \"arraybuffer\";\r\n }\r\n\r\n xhr.open(\"GET\", filename);\r\n xhr.send();\r\n};\r\n","\"use strict\";\r\n\r\nmodule.exports = factory(factory);\r\n\r\n/**\r\n * Reads / writes floats / doubles from / to buffers.\r\n * @name util.float\r\n * @namespace\r\n */\r\n\r\n/**\r\n * Writes a 32 bit float to a buffer using little endian byte order.\r\n * @name util.float.writeFloatLE\r\n * @function\r\n * @param {number} val Value to write\r\n * @param {Uint8Array} buf Target buffer\r\n * @param {number} pos Target buffer offset\r\n * @returns {undefined}\r\n */\r\n\r\n/**\r\n * Writes a 32 bit float to a buffer using big endian byte order.\r\n * @name util.float.writeFloatBE\r\n * @function\r\n * @param {number} val Value to write\r\n * @param {Uint8Array} buf Target buffer\r\n * @param {number} pos Target buffer offset\r\n * @returns {undefined}\r\n */\r\n\r\n/**\r\n * Reads a 32 bit float from a buffer using little endian byte order.\r\n * @name util.float.readFloatLE\r\n * @function\r\n * @param {Uint8Array} buf Source buffer\r\n * @param {number} pos Source buffer offset\r\n * @returns {number} Value read\r\n */\r\n\r\n/**\r\n * Reads a 32 bit float from a buffer using big endian byte order.\r\n * @name util.float.readFloatBE\r\n * @function\r\n * @param {Uint8Array} buf Source buffer\r\n * @param {number} pos Source buffer offset\r\n * @returns {number} Value read\r\n */\r\n\r\n/**\r\n * Writes a 64 bit double to a buffer using little endian byte order.\r\n * @name util.float.writeDoubleLE\r\n * @function\r\n * @param {number} val Value to write\r\n * @param {Uint8Array} buf Target buffer\r\n * @param {number} pos Target buffer offset\r\n * @returns {undefined}\r\n */\r\n\r\n/**\r\n * Writes a 64 bit double to a buffer using big endian byte order.\r\n * @name util.float.writeDoubleBE\r\n * @function\r\n * @param {number} val Value to write\r\n * @param {Uint8Array} buf Target buffer\r\n * @param {number} pos Target buffer offset\r\n * @returns {undefined}\r\n */\r\n\r\n/**\r\n * Reads a 64 bit double from a buffer using little endian byte order.\r\n * @name util.float.readDoubleLE\r\n * @function\r\n * @param {Uint8Array} buf Source buffer\r\n * @param {number} pos Source buffer offset\r\n * @returns {number} Value read\r\n */\r\n\r\n/**\r\n * Reads a 64 bit double from a buffer using big endian byte order.\r\n * @name util.float.readDoubleBE\r\n * @function\r\n * @param {Uint8Array} buf Source buffer\r\n * @param {number} pos Source buffer offset\r\n * @returns {number} Value read\r\n */\r\n\r\n// Factory function for the purpose of node-based testing in modified global environments\r\nfunction factory(exports) {\r\n\r\n // float: typed array\r\n if (typeof Float32Array !== \"undefined\") (function() {\r\n\r\n var f32 = new Float32Array([ -0 ]),\r\n f8b = new Uint8Array(f32.buffer),\r\n le = f8b[3] === 128;\r\n\r\n function writeFloat_f32_cpy(val, buf, pos) {\r\n f32[0] = val;\r\n buf[pos ] = f8b[0];\r\n buf[pos + 1] = f8b[1];\r\n buf[pos + 2] = f8b[2];\r\n buf[pos + 3] = f8b[3];\r\n }\r\n\r\n function writeFloat_f32_rev(val, buf, pos) {\r\n f32[0] = val;\r\n buf[pos ] = f8b[3];\r\n buf[pos + 1] = f8b[2];\r\n buf[pos + 2] = f8b[1];\r\n buf[pos + 3] = f8b[0];\r\n }\r\n\r\n /* istanbul ignore next */\r\n exports.writeFloatLE = le ? writeFloat_f32_cpy : writeFloat_f32_rev;\r\n /* istanbul ignore next */\r\n exports.writeFloatBE = le ? writeFloat_f32_rev : writeFloat_f32_cpy;\r\n\r\n function readFloat_f32_cpy(buf, pos) {\r\n f8b[0] = buf[pos ];\r\n f8b[1] = buf[pos + 1];\r\n f8b[2] = buf[pos + 2];\r\n f8b[3] = buf[pos + 3];\r\n return f32[0];\r\n }\r\n\r\n function readFloat_f32_rev(buf, pos) {\r\n f8b[3] = buf[pos ];\r\n f8b[2] = buf[pos + 1];\r\n f8b[1] = buf[pos + 2];\r\n f8b[0] = buf[pos + 3];\r\n return f32[0];\r\n }\r\n\r\n /* istanbul ignore next */\r\n exports.readFloatLE = le ? readFloat_f32_cpy : readFloat_f32_rev;\r\n /* istanbul ignore next */\r\n exports.readFloatBE = le ? readFloat_f32_rev : readFloat_f32_cpy;\r\n\r\n // float: ieee754\r\n })(); else (function() {\r\n\r\n function writeFloat_ieee754(writeUint, val, buf, pos) {\r\n var sign = val < 0 ? 1 : 0;\r\n if (sign)\r\n val = -val;\r\n if (val === 0)\r\n writeUint(1 / val > 0 ? /* positive */ 0 : /* negative 0 */ 2147483648, buf, pos);\r\n else if (isNaN(val))\r\n writeUint(2143289344, buf, pos);\r\n else if (val > 3.4028234663852886e+38) // +-Infinity\r\n writeUint((sign << 31 | 2139095040) >>> 0, buf, pos);\r\n else if (val < 1.1754943508222875e-38) // denormal\r\n writeUint((sign << 31 | Math.round(val / 1.401298464324817e-45)) >>> 0, buf, pos);\r\n else {\r\n var exponent = Math.floor(Math.log(val) / Math.LN2),\r\n mantissa = Math.round(val * Math.pow(2, -exponent) * 8388608) & 8388607;\r\n writeUint((sign << 31 | exponent + 127 << 23 | mantissa) >>> 0, buf, pos);\r\n }\r\n }\r\n\r\n exports.writeFloatLE = writeFloat_ieee754.bind(null, writeUintLE);\r\n exports.writeFloatBE = writeFloat_ieee754.bind(null, writeUintBE);\r\n\r\n function readFloat_ieee754(readUint, buf, pos) {\r\n var uint = readUint(buf, pos),\r\n sign = (uint >> 31) * 2 + 1,\r\n exponent = uint >>> 23 & 255,\r\n mantissa = uint & 8388607;\r\n return exponent === 255\r\n ? mantissa\r\n ? NaN\r\n : sign * Infinity\r\n : exponent === 0 // denormal\r\n ? sign * 1.401298464324817e-45 * mantissa\r\n : sign * Math.pow(2, exponent - 150) * (mantissa + 8388608);\r\n }\r\n\r\n exports.readFloatLE = readFloat_ieee754.bind(null, readUintLE);\r\n exports.readFloatBE = readFloat_ieee754.bind(null, readUintBE);\r\n\r\n })();\r\n\r\n // double: typed array\r\n if (typeof Float64Array !== \"undefined\") (function() {\r\n\r\n var f64 = new Float64Array([-0]),\r\n f8b = new Uint8Array(f64.buffer),\r\n le = f8b[7] === 128;\r\n\r\n function writeDouble_f64_cpy(val, buf, pos) {\r\n f64[0] = val;\r\n buf[pos ] = f8b[0];\r\n buf[pos + 1] = f8b[1];\r\n buf[pos + 2] = f8b[2];\r\n buf[pos + 3] = f8b[3];\r\n buf[pos + 4] = f8b[4];\r\n buf[pos + 5] = f8b[5];\r\n buf[pos + 6] = f8b[6];\r\n buf[pos + 7] = f8b[7];\r\n }\r\n\r\n function writeDouble_f64_rev(val, buf, pos) {\r\n f64[0] = val;\r\n buf[pos ] = f8b[7];\r\n buf[pos + 1] = f8b[6];\r\n buf[pos + 2] = f8b[5];\r\n buf[pos + 3] = f8b[4];\r\n buf[pos + 4] = f8b[3];\r\n buf[pos + 5] = f8b[2];\r\n buf[pos + 6] = f8b[1];\r\n buf[pos + 7] = f8b[0];\r\n }\r\n\r\n /* istanbul ignore next */\r\n exports.writeDoubleLE = le ? writeDouble_f64_cpy : writeDouble_f64_rev;\r\n /* istanbul ignore next */\r\n exports.writeDoubleBE = le ? writeDouble_f64_rev : writeDouble_f64_cpy;\r\n\r\n function readDouble_f64_cpy(buf, pos) {\r\n f8b[0] = buf[pos ];\r\n f8b[1] = buf[pos + 1];\r\n f8b[2] = buf[pos + 2];\r\n f8b[3] = buf[pos + 3];\r\n f8b[4] = buf[pos + 4];\r\n f8b[5] = buf[pos + 5];\r\n f8b[6] = buf[pos + 6];\r\n f8b[7] = buf[pos + 7];\r\n return f64[0];\r\n }\r\n\r\n function readDouble_f64_rev(buf, pos) {\r\n f8b[7] = buf[pos ];\r\n f8b[6] = buf[pos + 1];\r\n f8b[5] = buf[pos + 2];\r\n f8b[4] = buf[pos + 3];\r\n f8b[3] = buf[pos + 4];\r\n f8b[2] = buf[pos + 5];\r\n f8b[1] = buf[pos + 6];\r\n f8b[0] = buf[pos + 7];\r\n return f64[0];\r\n }\r\n\r\n /* istanbul ignore next */\r\n exports.readDoubleLE = le ? readDouble_f64_cpy : readDouble_f64_rev;\r\n /* istanbul ignore next */\r\n exports.readDoubleBE = le ? readDouble_f64_rev : readDouble_f64_cpy;\r\n\r\n // double: ieee754\r\n })(); else (function() {\r\n\r\n function writeDouble_ieee754(writeUint, off0, off1, val, buf, pos) {\r\n var sign = val < 0 ? 1 : 0;\r\n if (sign)\r\n val = -val;\r\n if (val === 0) {\r\n writeUint(0, buf, pos + off0);\r\n writeUint(1 / val > 0 ? /* positive */ 0 : /* negative 0 */ 2147483648, buf, pos + off1);\r\n } else if (isNaN(val)) {\r\n writeUint(0, buf, pos + off0);\r\n writeUint(2146959360, buf, pos + off1);\r\n } else if (val > 1.7976931348623157e+308) { // +-Infinity\r\n writeUint(0, buf, pos + off0);\r\n writeUint((sign << 31 | 2146435072) >>> 0, buf, pos + off1);\r\n } else {\r\n var mantissa;\r\n if (val < 2.2250738585072014e-308) { // denormal\r\n mantissa = val / 5e-324;\r\n writeUint(mantissa >>> 0, buf, pos + off0);\r\n writeUint((sign << 31 | mantissa / 4294967296) >>> 0, buf, pos + off1);\r\n } else {\r\n var exponent = Math.floor(Math.log(val) / Math.LN2);\r\n if (exponent === 1024)\r\n exponent = 1023;\r\n mantissa = val * Math.pow(2, -exponent);\r\n writeUint(mantissa * 4503599627370496 >>> 0, buf, pos + off0);\r\n writeUint((sign << 31 | exponent + 1023 << 20 | mantissa * 1048576 & 1048575) >>> 0, buf, pos + off1);\r\n }\r\n }\r\n }\r\n\r\n exports.writeDoubleLE = writeDouble_ieee754.bind(null, writeUintLE, 0, 4);\r\n exports.writeDoubleBE = writeDouble_ieee754.bind(null, writeUintBE, 4, 0);\r\n\r\n function readDouble_ieee754(readUint, off0, off1, buf, pos) {\r\n var lo = readUint(buf, pos + off0),\r\n hi = readUint(buf, pos + off1);\r\n var sign = (hi >> 31) * 2 + 1,\r\n exponent = hi >>> 20 & 2047,\r\n mantissa = 4294967296 * (hi & 1048575) + lo;\r\n return exponent === 2047\r\n ? mantissa\r\n ? NaN\r\n : sign * Infinity\r\n : exponent === 0 // denormal\r\n ? sign * 5e-324 * mantissa\r\n : sign * Math.pow(2, exponent - 1075) * (mantissa + 4503599627370496);\r\n }\r\n\r\n exports.readDoubleLE = readDouble_ieee754.bind(null, readUintLE, 0, 4);\r\n exports.readDoubleBE = readDouble_ieee754.bind(null, readUintBE, 4, 0);\r\n\r\n })();\r\n\r\n return exports;\r\n}\r\n\r\n// uint helpers\r\n\r\nfunction writeUintLE(val, buf, pos) {\r\n buf[pos ] = val & 255;\r\n buf[pos + 1] = val >>> 8 & 255;\r\n buf[pos + 2] = val >>> 16 & 255;\r\n buf[pos + 3] = val >>> 24;\r\n}\r\n\r\nfunction writeUintBE(val, buf, pos) {\r\n buf[pos ] = val >>> 24;\r\n buf[pos + 1] = val >>> 16 & 255;\r\n buf[pos + 2] = val >>> 8 & 255;\r\n buf[pos + 3] = val & 255;\r\n}\r\n\r\nfunction readUintLE(buf, pos) {\r\n return (buf[pos ]\r\n | buf[pos + 1] << 8\r\n | buf[pos + 2] << 16\r\n | buf[pos + 3] << 24) >>> 0;\r\n}\r\n\r\nfunction readUintBE(buf, pos) {\r\n return (buf[pos ] << 24\r\n | buf[pos + 1] << 16\r\n | buf[pos + 2] << 8\r\n | buf[pos + 3]) >>> 0;\r\n}\r\n","\"use strict\";\r\nmodule.exports = inquire;\r\n\r\n/**\r\n * Requires a module only if available.\r\n * @memberof util\r\n * @param {string} moduleName Module to require\r\n * @returns {?Object} Required module if available and not empty, otherwise `null`\r\n */\r\nfunction inquire(moduleName) {\r\n try {\r\n var mod = eval(\"quire\".replace(/^/,\"re\"))(moduleName); // eslint-disable-line no-eval\r\n if (mod && (mod.length || Object.keys(mod).length))\r\n return mod;\r\n } catch (e) {} // eslint-disable-line no-empty\r\n return null;\r\n}\r\n","\"use strict\";\r\n\r\n/**\r\n * A minimal path module to resolve Unix, Windows and URL paths alike.\r\n * @memberof util\r\n * @namespace\r\n */\r\nvar path = exports;\r\n\r\nvar isAbsolute =\r\n/**\r\n * Tests if the specified path is absolute.\r\n * @param {string} path Path to test\r\n * @returns {boolean} `true` if path is absolute\r\n */\r\npath.isAbsolute = function isAbsolute(path) {\r\n return /^(?:\\/|\\w+:)/.test(path);\r\n};\r\n\r\nvar normalize =\r\n/**\r\n * Normalizes the specified path.\r\n * @param {string} path Path to normalize\r\n * @returns {string} Normalized path\r\n */\r\npath.normalize = function normalize(path) {\r\n path = path.replace(/\\\\/g, \"/\")\r\n .replace(/\\/{2,}/g, \"/\");\r\n var parts = path.split(\"/\"),\r\n absolute = isAbsolute(path),\r\n prefix = \"\";\r\n if (absolute)\r\n prefix = parts.shift() + \"/\";\r\n for (var i = 0; i < parts.length;) {\r\n if (parts[i] === \"..\") {\r\n if (i > 0 && parts[i - 1] !== \"..\")\r\n parts.splice(--i, 2);\r\n else if (absolute)\r\n parts.splice(i, 1);\r\n else\r\n ++i;\r\n } else if (parts[i] === \".\")\r\n parts.splice(i, 1);\r\n else\r\n ++i;\r\n }\r\n return prefix + parts.join(\"/\");\r\n};\r\n\r\n/**\r\n * Resolves the specified include path against the specified origin path.\r\n * @param {string} originPath Path to the origin file\r\n * @param {string} includePath Include path relative to origin path\r\n * @param {boolean} [alreadyNormalized=false] `true` if both paths are already known to be normalized\r\n * @returns {string} Path to the include file\r\n */\r\npath.resolve = function resolve(originPath, includePath, alreadyNormalized) {\r\n if (!alreadyNormalized)\r\n includePath = normalize(includePath);\r\n if (isAbsolute(includePath))\r\n return includePath;\r\n if (!alreadyNormalized)\r\n originPath = normalize(originPath);\r\n return (originPath = originPath.replace(/(?:\\/|^)[^/]+$/, \"\")).length ? normalize(originPath + \"/\" + includePath) : includePath;\r\n};\r\n","\"use strict\";\r\nmodule.exports = pool;\r\n\r\n/**\r\n * An allocator as used by {@link util.pool}.\r\n * @typedef PoolAllocator\r\n * @type {function}\r\n * @param {number} size Buffer size\r\n * @returns {Uint8Array} Buffer\r\n */\r\n\r\n/**\r\n * A slicer as used by {@link util.pool}.\r\n * @typedef PoolSlicer\r\n * @type {function}\r\n * @param {number} start Start offset\r\n * @param {number} end End offset\r\n * @returns {Uint8Array} Buffer slice\r\n * @this {Uint8Array}\r\n */\r\n\r\n/**\r\n * A general purpose buffer pool.\r\n * @memberof util\r\n * @function\r\n * @param {PoolAllocator} alloc Allocator\r\n * @param {PoolSlicer} slice Slicer\r\n * @param {number} [size=8192] Slab size\r\n * @returns {PoolAllocator} Pooled allocator\r\n */\r\nfunction pool(alloc, slice, size) {\r\n var SIZE = size || 8192;\r\n var MAX = SIZE >>> 1;\r\n var slab = null;\r\n var offset = SIZE;\r\n return function pool_alloc(size) {\r\n if (size < 1 || size > MAX)\r\n return alloc(size);\r\n if (offset + size > SIZE) {\r\n slab = alloc(SIZE);\r\n offset = 0;\r\n }\r\n var buf = slice.call(slab, offset, offset += size);\r\n if (offset & 7) // align to 32 bit\r\n offset = (offset | 7) + 1;\r\n return buf;\r\n };\r\n}\r\n","\"use strict\";\r\n\r\n/**\r\n * A minimal UTF8 implementation for number arrays.\r\n * @memberof util\r\n * @namespace\r\n */\r\nvar utf8 = exports;\r\n\r\n/**\r\n * Calculates the UTF8 byte length of a string.\r\n * @param {string} string String\r\n * @returns {number} Byte length\r\n */\r\nutf8.length = function utf8_length(string) {\r\n var len = 0,\r\n c = 0;\r\n for (var i = 0; i < string.length; ++i) {\r\n c = string.charCodeAt(i);\r\n if (c < 128)\r\n len += 1;\r\n else if (c < 2048)\r\n len += 2;\r\n else if ((c & 0xFC00) === 0xD800 && (string.charCodeAt(i + 1) & 0xFC00) === 0xDC00) {\r\n ++i;\r\n len += 4;\r\n } else\r\n len += 3;\r\n }\r\n return len;\r\n};\r\n\r\n/**\r\n * Reads UTF8 bytes as a string.\r\n * @param {Uint8Array} buffer Source buffer\r\n * @param {number} start Source start\r\n * @param {number} end Source end\r\n * @returns {string} String read\r\n */\r\nutf8.read = function utf8_read(buffer, start, end) {\r\n var len = end - start;\r\n if (len < 1)\r\n return \"\";\r\n var parts = null,\r\n chunk = [],\r\n i = 0, // char offset\r\n t; // temporary\r\n while (start < end) {\r\n t = buffer[start++];\r\n if (t < 128)\r\n chunk[i++] = t;\r\n else if (t > 191 && t < 224)\r\n chunk[i++] = (t & 31) << 6 | buffer[start++] & 63;\r\n else if (t > 239 && t < 365) {\r\n t = ((t & 7) << 18 | (buffer[start++] & 63) << 12 | (buffer[start++] & 63) << 6 | buffer[start++] & 63) - 0x10000;\r\n chunk[i++] = 0xD800 + (t >> 10);\r\n chunk[i++] = 0xDC00 + (t & 1023);\r\n } else\r\n chunk[i++] = (t & 15) << 12 | (buffer[start++] & 63) << 6 | buffer[start++] & 63;\r\n if (i > 8191) {\r\n (parts || (parts = [])).push(String.fromCharCode.apply(String, chunk));\r\n i = 0;\r\n }\r\n }\r\n if (parts) {\r\n if (i)\r\n parts.push(String.fromCharCode.apply(String, chunk.slice(0, i)));\r\n return parts.join(\"\");\r\n }\r\n return String.fromCharCode.apply(String, chunk.slice(0, i));\r\n};\r\n\r\n/**\r\n * Writes a string as UTF8 bytes.\r\n * @param {string} string Source string\r\n * @param {Uint8Array} buffer Destination buffer\r\n * @param {number} offset Destination offset\r\n * @returns {number} Bytes written\r\n */\r\nutf8.write = function utf8_write(string, buffer, offset) {\r\n var start = offset,\r\n c1, // character 1\r\n c2; // character 2\r\n for (var i = 0; i < string.length; ++i) {\r\n c1 = string.charCodeAt(i);\r\n if (c1 < 128) {\r\n buffer[offset++] = c1;\r\n } else if (c1 < 2048) {\r\n buffer[offset++] = c1 >> 6 | 192;\r\n buffer[offset++] = c1 & 63 | 128;\r\n } else if ((c1 & 0xFC00) === 0xD800 && ((c2 = string.charCodeAt(i + 1)) & 0xFC00) === 0xDC00) {\r\n c1 = 0x10000 + ((c1 & 0x03FF) << 10) + (c2 & 0x03FF);\r\n ++i;\r\n buffer[offset++] = c1 >> 18 | 240;\r\n buffer[offset++] = c1 >> 12 & 63 | 128;\r\n buffer[offset++] = c1 >> 6 & 63 | 128;\r\n buffer[offset++] = c1 & 63 | 128;\r\n } else {\r\n buffer[offset++] = c1 >> 12 | 224;\r\n buffer[offset++] = c1 >> 6 & 63 | 128;\r\n buffer[offset++] = c1 & 63 | 128;\r\n }\r\n }\r\n return offset - start;\r\n};\r\n","\"use strict\";\n/**\n * Runtime message from/to plain object converters.\n * @namespace\n */\nvar converter = exports;\n\nvar Enum = require(14),\n util = require(33);\n\n/**\n * Generates a partial value fromObject conveter.\n * @param {Codegen} gen Codegen instance\n * @param {Field} field Reflected field\n * @param {number} fieldIndex Field index\n * @param {string} prop Property reference\n * @returns {Codegen} Codegen instance\n * @ignore\n */\nfunction genValuePartial_fromObject(gen, field, fieldIndex, prop) {\n var defaultAlreadyEmitted = false;\n /* eslint-disable no-unexpected-multiline, block-scoped-var, no-redeclare */\n if (field.resolvedType) {\n if (field.resolvedType instanceof Enum) { gen\n (\"switch(d%s){\", prop);\n for (var values = field.resolvedType.values, keys = Object.keys(values), i = 0; i < keys.length; ++i) {\n // enum unknown values passthrough\n if (values[keys[i]] === field.typeDefault && !defaultAlreadyEmitted) { gen\n (\"default:\")\n (\"if(typeof(d%s)===\\\"number\\\"){m%s=d%s;break}\", prop, prop, prop);\n if (!field.repeated) gen // fallback to default value only for\n // arrays, to avoid leaving holes.\n (\"break\"); // for non-repeated fields, just ignore\n defaultAlreadyEmitted = true;\n }\n gen\n (\"case%j:\", keys[i])\n (\"case %i:\", values[keys[i]])\n (\"m%s=%j\", prop, values[keys[i]])\n (\"break\");\n } gen\n (\"}\");\n } else gen\n (\"if(typeof d%s!==\\\"object\\\")\", prop)\n (\"throw TypeError(%j)\", field.fullName + \": object expected\")\n (\"m%s=types[%i].fromObject(d%s)\", prop, fieldIndex, prop);\n } else {\n var isUnsigned = false;\n switch (field.type) {\n case \"double\":\n case \"float\": gen\n (\"m%s=Number(d%s)\", prop, prop); // also catches \"NaN\", \"Infinity\"\n break;\n case \"uint32\":\n case \"fixed32\": gen\n (\"m%s=d%s>>>0\", prop, prop);\n break;\n case \"int32\":\n case \"sint32\":\n case \"sfixed32\": gen\n (\"m%s=d%s|0\", prop, prop);\n break;\n case \"uint64\":\n isUnsigned = true;\n // eslint-disable-next-line no-fallthrough\n case \"int64\":\n case \"sint64\":\n case \"fixed64\":\n case \"sfixed64\": gen\n (\"if(util.Long)\")\n (\"(m%s=util.Long.fromValue(d%s)).unsigned=%j\", prop, prop, isUnsigned)\n (\"else if(typeof d%s===\\\"string\\\")\", prop)\n (\"m%s=parseInt(d%s,10)\", prop, prop)\n (\"else if(typeof d%s===\\\"number\\\")\", prop)\n (\"m%s=d%s\", prop, prop)\n (\"else if(typeof d%s===\\\"object\\\")\", prop)\n (\"m%s=new util.LongBits(d%s.low>>>0,d%s.high>>>0).toNumber(%s)\", prop, prop, prop, isUnsigned ? \"true\" : \"\");\n break;\n case \"bytes\": gen\n (\"if(typeof d%s===\\\"string\\\")\", prop)\n (\"util.base64.decode(d%s,m%s=util.newBuffer(util.base64.length(d%s)),0)\", prop, prop, prop)\n (\"else if(d%s.length >= 0)\", prop)\n (\"m%s=d%s\", prop, prop);\n break;\n case \"string\": gen\n (\"m%s=String(d%s)\", prop, prop);\n break;\n case \"bool\": gen\n (\"m%s=Boolean(d%s)\", prop, prop);\n break;\n /* default: gen\n (\"m%s=d%s\", prop, prop);\n break; */\n }\n }\n return gen;\n /* eslint-enable no-unexpected-multiline, block-scoped-var, no-redeclare */\n}\n\n/**\n * Generates a plain object to runtime message converter specific to the specified message type.\n * @param {Type} mtype Message type\n * @returns {Codegen} Codegen instance\n */\nconverter.fromObject = function fromObject(mtype) {\n /* eslint-disable no-unexpected-multiline, block-scoped-var, no-redeclare */\n var fields = mtype.fieldsArray;\n var gen = util.codegen([\"d\"], mtype.name + \"$fromObject\")\n (\"if(d instanceof this.ctor)\")\n (\"return d\");\n if (!fields.length) return gen\n (\"return new this.ctor\");\n gen\n (\"var m=new this.ctor\");\n for (var i = 0; i < fields.length; ++i) {\n var field = fields[i].resolve(),\n prop = util.safeProp(field.name);\n\n // Map fields\n if (field.map) { gen\n (\"if(d%s){\", prop)\n (\"if(typeof d%s!==\\\"object\\\")\", prop)\n (\"throw TypeError(%j)\", field.fullName + \": object expected\")\n (\"m%s={}\", prop)\n (\"for(var ks=Object.keys(d%s),i=0;i>>0,m%s.high>>>0).toNumber(%s):m%s\", prop, prop, prop, prop, isUnsigned ? \"true\": \"\", prop);\n break;\n case \"bytes\": gen\n (\"d%s=o.bytes===String?util.base64.encode(m%s,0,m%s.length):o.bytes===Array?Array.prototype.slice.call(m%s):m%s\", prop, prop, prop, prop, prop);\n break;\n default: gen\n (\"d%s=m%s\", prop, prop);\n break;\n }\n }\n return gen;\n /* eslint-enable no-unexpected-multiline, block-scoped-var, no-redeclare */\n}\n\n/**\n * Generates a runtime message to plain object converter specific to the specified message type.\n * @param {Type} mtype Message type\n * @returns {Codegen} Codegen instance\n */\nconverter.toObject = function toObject(mtype) {\n /* eslint-disable no-unexpected-multiline, block-scoped-var, no-redeclare */\n var fields = mtype.fieldsArray.slice().sort(util.compareFieldsById);\n if (!fields.length)\n return util.codegen()(\"return {}\");\n var gen = util.codegen([\"m\", \"o\"], mtype.name + \"$toObject\")\n (\"if(!o)\")\n (\"o={}\")\n (\"var d={}\");\n\n var repeatedFields = [],\n mapFields = [],\n normalFields = [],\n i = 0;\n for (; i < fields.length; ++i)\n if (!fields[i].partOf)\n ( fields[i].resolve().repeated ? repeatedFields\n : fields[i].map ? mapFields\n : normalFields).push(fields[i]);\n\n if (repeatedFields.length) { gen\n (\"if(o.arrays||o.defaults){\");\n for (i = 0; i < repeatedFields.length; ++i) gen\n (\"d%s=[]\", util.safeProp(repeatedFields[i].name));\n gen\n (\"}\");\n }\n\n if (mapFields.length) { gen\n (\"if(o.objects||o.defaults){\");\n for (i = 0; i < mapFields.length; ++i) gen\n (\"d%s={}\", util.safeProp(mapFields[i].name));\n gen\n (\"}\");\n }\n\n if (normalFields.length) { gen\n (\"if(o.defaults){\");\n for (i = 0; i < normalFields.length; ++i) {\n var field = normalFields[i],\n prop = util.safeProp(field.name);\n if (field.resolvedType instanceof Enum) gen\n (\"d%s=o.enums===String?%j:%j\", prop, field.resolvedType.valuesById[field.typeDefault], field.typeDefault);\n else if (field.long) gen\n (\"if(util.Long){\")\n (\"var n=new util.Long(%i,%i,%j)\", field.typeDefault.low, field.typeDefault.high, field.typeDefault.unsigned)\n (\"d%s=o.longs===String?n.toString():o.longs===Number?n.toNumber():n\", prop)\n (\"}else\")\n (\"d%s=o.longs===String?%j:%i\", prop, field.typeDefault.toString(), field.typeDefault.toNumber());\n else if (field.bytes) {\n var arrayDefault = \"[\" + Array.prototype.slice.call(field.typeDefault).join(\",\") + \"]\";\n gen\n (\"if(o.bytes===String)d%s=%j\", prop, String.fromCharCode.apply(String, field.typeDefault))\n (\"else{\")\n (\"d%s=%s\", prop, arrayDefault)\n (\"if(o.bytes!==Array)d%s=util.newBuffer(d%s)\", prop, prop)\n (\"}\");\n } else gen\n (\"d%s=%j\", prop, field.typeDefault); // also messages (=null)\n } gen\n (\"}\");\n }\n var hasKs2 = false;\n for (i = 0; i < fields.length; ++i) {\n var field = fields[i],\n index = mtype._fieldsArray.indexOf(field),\n prop = util.safeProp(field.name);\n if (field.map) {\n if (!hasKs2) { hasKs2 = true; gen\n (\"var ks2\");\n } gen\n (\"if(m%s&&(ks2=Object.keys(m%s)).length){\", prop, prop)\n (\"d%s={}\", prop)\n (\"for(var j=0;j>>3){\");\n\n var i = 0;\n for (; i < /* initializes */ mtype.fieldsArray.length; ++i) {\n var field = mtype._fieldsArray[i].resolve(),\n type = field.resolvedType instanceof Enum ? \"int32\" : field.type,\n ref = \"m\" + util.safeProp(field.name); gen\n (\"case %i: {\", field.id);\n\n // Map fields\n if (field.map) { gen\n (\"if(%s===util.emptyObject)\", ref)\n (\"%s={}\", ref)\n (\"var c2 = r.uint32()+r.pos\");\n\n if (types.defaults[field.keyType] !== undefined) gen\n (\"k=%j\", types.defaults[field.keyType]);\n else gen\n (\"k=null\");\n\n if (types.defaults[type] !== undefined) gen\n (\"value=%j\", types.defaults[type]);\n else gen\n (\"value=null\");\n\n gen\n (\"while(r.pos>>3){\")\n (\"case 1: k=r.%s(); break\", field.keyType)\n (\"case 2:\");\n\n if (types.basic[type] === undefined) gen\n (\"value=types[%i].decode(r,r.uint32())\", i); // can't be groups\n else gen\n (\"value=r.%s()\", type);\n\n gen\n (\"break\")\n (\"default:\")\n (\"r.skipType(tag2&7)\")\n (\"break\")\n (\"}\")\n (\"}\");\n\n if (types.long[field.keyType] !== undefined) gen\n (\"%s[typeof k===\\\"object\\\"?util.longToHash(k):k]=value\", ref);\n else gen\n (\"%s[k]=value\", ref);\n\n // Repeated fields\n } else if (field.repeated) { gen\n\n (\"if(!(%s&&%s.length))\", ref, ref)\n (\"%s=[]\", ref);\n\n // Packable (always check for forward and backward compatiblity)\n if (types.packed[type] !== undefined) gen\n (\"if((t&7)===2){\")\n (\"var c2=r.uint32()+r.pos\")\n (\"while(r.pos>> 0, (field.id << 3 | 4) >>> 0)\n : gen(\"types[%i].encode(%s,w.uint32(%i).fork()).ldelim()\", fieldIndex, ref, (field.id << 3 | 2) >>> 0);\n}\n\n/**\n * Generates an encoder specific to the specified message type.\n * @param {Type} mtype Message type\n * @returns {Codegen} Codegen instance\n */\nfunction encoder(mtype) {\n /* eslint-disable no-unexpected-multiline, block-scoped-var, no-redeclare */\n var gen = util.codegen([\"m\", \"w\"], mtype.name + \"$encode\")\n (\"if(!w)\")\n (\"w=Writer.create()\");\n\n var i, ref;\n\n // \"when a message is serialized its known fields should be written sequentially by field number\"\n var fields = /* initializes */ mtype.fieldsArray.slice().sort(util.compareFieldsById);\n\n for (var i = 0; i < fields.length; ++i) {\n var field = fields[i].resolve(),\n index = mtype._fieldsArray.indexOf(field),\n type = field.resolvedType instanceof Enum ? \"int32\" : field.type,\n wireType = types.basic[type];\n ref = \"m\" + util.safeProp(field.name);\n\n // Map fields\n if (field.map) {\n gen\n (\"if(%s!=null&&Object.hasOwnProperty.call(m,%j)){\", ref, field.name) // !== undefined && !== null\n (\"for(var ks=Object.keys(%s),i=0;i>> 0, 8 | types.mapKey[field.keyType], field.keyType);\n if (wireType === undefined) gen\n (\"types[%i].encode(%s[ks[i]],w.uint32(18).fork()).ldelim().ldelim()\", index, ref); // can't be groups\n else gen\n (\".uint32(%i).%s(%s[ks[i]]).ldelim()\", 16 | wireType, type, ref);\n gen\n (\"}\")\n (\"}\");\n\n // Repeated fields\n } else if (field.repeated) { gen\n (\"if(%s!=null&&%s.length){\", ref, ref); // !== undefined && !== null\n\n // Packed repeated\n if (field.packed && types.packed[type] !== undefined) { gen\n\n (\"w.uint32(%i).fork()\", (field.id << 3 | 2) >>> 0)\n (\"for(var i=0;i<%s.length;++i)\", ref)\n (\"w.%s(%s[i])\", type, ref)\n (\"w.ldelim()\");\n\n // Non-packed\n } else { gen\n\n (\"for(var i=0;i<%s.length;++i)\", ref);\n if (wireType === undefined)\n genTypePartial(gen, field, index, ref + \"[i]\");\n else gen\n (\"w.uint32(%i).%s(%s[i])\", (field.id << 3 | wireType) >>> 0, type, ref);\n\n } gen\n (\"}\");\n\n // Non-repeated\n } else {\n if (field.optional) gen\n (\"if(%s!=null&&Object.hasOwnProperty.call(m,%j))\", ref, field.name); // !== undefined && !== null\n\n if (wireType === undefined)\n genTypePartial(gen, field, index, ref);\n else gen\n (\"w.uint32(%i).%s(%s)\", (field.id << 3 | wireType) >>> 0, type, ref);\n\n }\n }\n\n return gen\n (\"return w\");\n /* eslint-enable no-unexpected-multiline, block-scoped-var, no-redeclare */\n}\n","\"use strict\";\nmodule.exports = Enum;\n\n// extends ReflectionObject\nvar ReflectionObject = require(22);\n((Enum.prototype = Object.create(ReflectionObject.prototype)).constructor = Enum).className = \"Enum\";\n\nvar Namespace = require(21),\n util = require(33);\n\n/**\n * Constructs a new enum instance.\n * @classdesc Reflected enum.\n * @extends ReflectionObject\n * @constructor\n * @param {string} name Unique name within its namespace\n * @param {Object.} [values] Enum values as an object, by name\n * @param {Object.} [options] Declared options\n * @param {string} [comment] The comment for this enum\n * @param {Object.} [comments] The value comments for this enum\n * @param {Object.>|undefined} [valuesOptions] The value options for this enum\n */\nfunction Enum(name, values, options, comment, comments, valuesOptions) {\n ReflectionObject.call(this, name, options);\n\n if (values && typeof values !== \"object\")\n throw TypeError(\"values must be an object\");\n\n /**\n * Enum values by id.\n * @type {Object.}\n */\n this.valuesById = {};\n\n /**\n * Enum values by name.\n * @type {Object.}\n */\n this.values = Object.create(this.valuesById); // toJSON, marker\n\n /**\n * Enum comment text.\n * @type {string|null}\n */\n this.comment = comment;\n\n /**\n * Value comment texts, if any.\n * @type {Object.}\n */\n this.comments = comments || {};\n\n /**\n * Values options, if any\n * @type {Object>|undefined}\n */\n this.valuesOptions = valuesOptions;\n\n /**\n * Reserved ranges, if any.\n * @type {Array.}\n */\n this.reserved = undefined; // toJSON\n\n // Note that values inherit valuesById on their prototype which makes them a TypeScript-\n // compatible enum. This is used by pbts to write actual enum definitions that work for\n // static and reflection code alike instead of emitting generic object definitions.\n\n if (values)\n for (var keys = Object.keys(values), i = 0; i < keys.length; ++i)\n if (typeof values[keys[i]] === \"number\") // use forward entries only\n this.valuesById[ this.values[keys[i]] = values[keys[i]] ] = keys[i];\n}\n\n/**\n * Enum descriptor.\n * @interface IEnum\n * @property {Object.} values Enum values\n * @property {Object.} [options] Enum options\n */\n\n/**\n * Constructs an enum from an enum descriptor.\n * @param {string} name Enum name\n * @param {IEnum} json Enum descriptor\n * @returns {Enum} Created enum\n * @throws {TypeError} If arguments are invalid\n */\nEnum.fromJSON = function fromJSON(name, json) {\n var enm = new Enum(name, json.values, json.options, json.comment, json.comments);\n enm.reserved = json.reserved;\n return enm;\n};\n\n/**\n * Converts this enum to an enum descriptor.\n * @param {IToJSONOptions} [toJSONOptions] JSON conversion options\n * @returns {IEnum} Enum descriptor\n */\nEnum.prototype.toJSON = function toJSON(toJSONOptions) {\n var keepComments = toJSONOptions ? Boolean(toJSONOptions.keepComments) : false;\n return util.toObject([\n \"options\" , this.options,\n \"valuesOptions\" , this.valuesOptions,\n \"values\" , this.values,\n \"reserved\" , this.reserved && this.reserved.length ? this.reserved : undefined,\n \"comment\" , keepComments ? this.comment : undefined,\n \"comments\" , keepComments ? this.comments : undefined\n ]);\n};\n\n/**\n * Adds a value to this enum.\n * @param {string} name Value name\n * @param {number} id Value id\n * @param {string} [comment] Comment, if any\n * @param {Object.|undefined} [options] Options, if any\n * @returns {Enum} `this`\n * @throws {TypeError} If arguments are invalid\n * @throws {Error} If there is already a value with this name or id\n */\nEnum.prototype.add = function add(name, id, comment, options) {\n // utilized by the parser but not by .fromJSON\n\n if (!util.isString(name))\n throw TypeError(\"name must be a string\");\n\n if (!util.isInteger(id))\n throw TypeError(\"id must be an integer\");\n\n if (this.values[name] !== undefined)\n throw Error(\"duplicate name '\" + name + \"' in \" + this);\n\n if (this.isReservedId(id))\n throw Error(\"id \" + id + \" is reserved in \" + this);\n\n if (this.isReservedName(name))\n throw Error(\"name '\" + name + \"' is reserved in \" + this);\n\n if (this.valuesById[id] !== undefined) {\n if (!(this.options && this.options.allow_alias))\n throw Error(\"duplicate id \" + id + \" in \" + this);\n this.values[name] = id;\n } else\n this.valuesById[this.values[name] = id] = name;\n\n if (options) {\n if (this.valuesOptions === undefined)\n this.valuesOptions = {};\n this.valuesOptions[name] = options || null;\n }\n\n this.comments[name] = comment || null;\n return this;\n};\n\n/**\n * Removes a value from this enum\n * @param {string} name Value name\n * @returns {Enum} `this`\n * @throws {TypeError} If arguments are invalid\n * @throws {Error} If `name` is not a name of this enum\n */\nEnum.prototype.remove = function remove(name) {\n\n if (!util.isString(name))\n throw TypeError(\"name must be a string\");\n\n var val = this.values[name];\n if (val == null)\n throw Error(\"name '\" + name + \"' does not exist in \" + this);\n\n delete this.valuesById[val];\n delete this.values[name];\n delete this.comments[name];\n if (this.valuesOptions)\n delete this.valuesOptions[name];\n\n return this;\n};\n\n/**\n * Tests if the specified id is reserved.\n * @param {number} id Id to test\n * @returns {boolean} `true` if reserved, otherwise `false`\n */\nEnum.prototype.isReservedId = function isReservedId(id) {\n return Namespace.isReservedId(this.reserved, id);\n};\n\n/**\n * Tests if the specified name is reserved.\n * @param {string} name Name to test\n * @returns {boolean} `true` if reserved, otherwise `false`\n */\nEnum.prototype.isReservedName = function isReservedName(name) {\n return Namespace.isReservedName(this.reserved, name);\n};\n","\"use strict\";\nmodule.exports = Field;\n\n// extends ReflectionObject\nvar ReflectionObject = require(22);\n((Field.prototype = Object.create(ReflectionObject.prototype)).constructor = Field).className = \"Field\";\n\nvar Enum = require(14),\n types = require(32),\n util = require(33);\n\nvar Type; // cyclic\n\nvar ruleRe = /^required|optional|repeated$/;\n\n/**\n * Constructs a new message field instance. Note that {@link MapField|map fields} have their own class.\n * @name Field\n * @classdesc Reflected message field.\n * @extends FieldBase\n * @constructor\n * @param {string} name Unique name within its namespace\n * @param {number} id Unique id within its namespace\n * @param {string} type Value type\n * @param {string|Object.} [rule=\"optional\"] Field rule\n * @param {string|Object.} [extend] Extended type if different from parent\n * @param {Object.} [options] Declared options\n */\n\n/**\n * Constructs a field from a field descriptor.\n * @param {string} name Field name\n * @param {IField} json Field descriptor\n * @returns {Field} Created field\n * @throws {TypeError} If arguments are invalid\n */\nField.fromJSON = function fromJSON(name, json) {\n return new Field(name, json.id, json.type, json.rule, json.extend, json.options, json.comment);\n};\n\n/**\n * Not an actual constructor. Use {@link Field} instead.\n * @classdesc Base class of all reflected message fields. This is not an actual class but here for the sake of having consistent type definitions.\n * @exports FieldBase\n * @extends ReflectionObject\n * @constructor\n * @param {string} name Unique name within its namespace\n * @param {number} id Unique id within its namespace\n * @param {string} type Value type\n * @param {string|Object.} [rule=\"optional\"] Field rule\n * @param {string|Object.} [extend] Extended type if different from parent\n * @param {Object.} [options] Declared options\n * @param {string} [comment] Comment associated with this field\n */\nfunction Field(name, id, type, rule, extend, options, comment) {\n\n if (util.isObject(rule)) {\n comment = extend;\n options = rule;\n rule = extend = undefined;\n } else if (util.isObject(extend)) {\n comment = options;\n options = extend;\n extend = undefined;\n }\n\n ReflectionObject.call(this, name, options);\n\n if (!util.isInteger(id) || id < 0)\n throw TypeError(\"id must be a non-negative integer\");\n\n if (!util.isString(type))\n throw TypeError(\"type must be a string\");\n\n if (rule !== undefined && !ruleRe.test(rule = rule.toString().toLowerCase()))\n throw TypeError(\"rule must be a string rule\");\n\n if (extend !== undefined && !util.isString(extend))\n throw TypeError(\"extend must be a string\");\n\n /**\n * Field rule, if any.\n * @type {string|undefined}\n */\n if (rule === \"proto3_optional\") {\n rule = \"optional\";\n }\n this.rule = rule && rule !== \"optional\" ? rule : undefined; // toJSON\n\n /**\n * Field type.\n * @type {string}\n */\n this.type = type; // toJSON\n\n /**\n * Unique field id.\n * @type {number}\n */\n this.id = id; // toJSON, marker\n\n /**\n * Extended type if different from parent.\n * @type {string|undefined}\n */\n this.extend = extend || undefined; // toJSON\n\n /**\n * Whether this field is required.\n * @type {boolean}\n */\n this.required = rule === \"required\";\n\n /**\n * Whether this field is optional.\n * @type {boolean}\n */\n this.optional = !this.required;\n\n /**\n * Whether this field is repeated.\n * @type {boolean}\n */\n this.repeated = rule === \"repeated\";\n\n /**\n * Whether this field is a map or not.\n * @type {boolean}\n */\n this.map = false;\n\n /**\n * Message this field belongs to.\n * @type {Type|null}\n */\n this.message = null;\n\n /**\n * OneOf this field belongs to, if any,\n * @type {OneOf|null}\n */\n this.partOf = null;\n\n /**\n * The field type's default value.\n * @type {*}\n */\n this.typeDefault = null;\n\n /**\n * The field's default value on prototypes.\n * @type {*}\n */\n this.defaultValue = null;\n\n /**\n * Whether this field's value should be treated as a long.\n * @type {boolean}\n */\n this.long = util.Long ? types.long[type] !== undefined : /* istanbul ignore next */ false;\n\n /**\n * Whether this field's value is a buffer.\n * @type {boolean}\n */\n this.bytes = type === \"bytes\";\n\n /**\n * Resolved type if not a basic type.\n * @type {Type|Enum|null}\n */\n this.resolvedType = null;\n\n /**\n * Sister-field within the extended type if a declaring extension field.\n * @type {Field|null}\n */\n this.extensionField = null;\n\n /**\n * Sister-field within the declaring namespace if an extended field.\n * @type {Field|null}\n */\n this.declaringField = null;\n\n /**\n * Internally remembers whether this field is packed.\n * @type {boolean|null}\n * @private\n */\n this._packed = null;\n\n /**\n * Comment for this field.\n * @type {string|null}\n */\n this.comment = comment;\n}\n\n/**\n * Determines whether this field is packed. Only relevant when repeated and working with proto2.\n * @name Field#packed\n * @type {boolean}\n * @readonly\n */\nObject.defineProperty(Field.prototype, \"packed\", {\n get: function() {\n // defaults to packed=true if not explicity set to false\n if (this._packed === null)\n this._packed = this.getOption(\"packed\") !== false;\n return this._packed;\n }\n});\n\n/**\n * @override\n */\nField.prototype.setOption = function setOption(name, value, ifNotSet) {\n if (name === \"packed\") // clear cached before setting\n this._packed = null;\n return ReflectionObject.prototype.setOption.call(this, name, value, ifNotSet);\n};\n\n/**\n * Field descriptor.\n * @interface IField\n * @property {string} [rule=\"optional\"] Field rule\n * @property {string} type Field type\n * @property {number} id Field id\n * @property {Object.} [options] Field options\n */\n\n/**\n * Extension field descriptor.\n * @interface IExtensionField\n * @extends IField\n * @property {string} extend Extended type\n */\n\n/**\n * Converts this field to a field descriptor.\n * @param {IToJSONOptions} [toJSONOptions] JSON conversion options\n * @returns {IField} Field descriptor\n */\nField.prototype.toJSON = function toJSON(toJSONOptions) {\n var keepComments = toJSONOptions ? Boolean(toJSONOptions.keepComments) : false;\n return util.toObject([\n \"rule\" , this.rule !== \"optional\" && this.rule || undefined,\n \"type\" , this.type,\n \"id\" , this.id,\n \"extend\" , this.extend,\n \"options\" , this.options,\n \"comment\" , keepComments ? this.comment : undefined\n ]);\n};\n\n/**\n * Resolves this field's type references.\n * @returns {Field} `this`\n * @throws {Error} If any reference cannot be resolved\n */\nField.prototype.resolve = function resolve() {\n\n if (this.resolved)\n return this;\n\n if ((this.typeDefault = types.defaults[this.type]) === undefined) { // if not a basic type, resolve it\n this.resolvedType = (this.declaringField ? this.declaringField.parent : this.parent).lookupTypeOrEnum(this.type);\n if (this.resolvedType instanceof Type)\n this.typeDefault = null;\n else // instanceof Enum\n this.typeDefault = this.resolvedType.values[Object.keys(this.resolvedType.values)[0]]; // first defined\n } else if (this.options && this.options.proto3_optional) {\n // proto3 scalar value marked optional; should default to null\n this.typeDefault = null;\n }\n\n // use explicitly set default value if present\n if (this.options && this.options[\"default\"] != null) {\n this.typeDefault = this.options[\"default\"];\n if (this.resolvedType instanceof Enum && typeof this.typeDefault === \"string\")\n this.typeDefault = this.resolvedType.values[this.typeDefault];\n }\n\n // remove unnecessary options\n if (this.options) {\n if (this.options.packed === true || this.options.packed !== undefined && this.resolvedType && !(this.resolvedType instanceof Enum))\n delete this.options.packed;\n if (!Object.keys(this.options).length)\n this.options = undefined;\n }\n\n // convert to internal data type if necesssary\n if (this.long) {\n this.typeDefault = util.Long.fromNumber(this.typeDefault, this.type.charAt(0) === \"u\");\n\n /* istanbul ignore else */\n if (Object.freeze)\n Object.freeze(this.typeDefault); // long instances are meant to be immutable anyway (i.e. use small int cache that even requires it)\n\n } else if (this.bytes && typeof this.typeDefault === \"string\") {\n var buf;\n if (util.base64.test(this.typeDefault))\n util.base64.decode(this.typeDefault, buf = util.newBuffer(util.base64.length(this.typeDefault)), 0);\n else\n util.utf8.write(this.typeDefault, buf = util.newBuffer(util.utf8.length(this.typeDefault)), 0);\n this.typeDefault = buf;\n }\n\n // take special care of maps and repeated fields\n if (this.map)\n this.defaultValue = util.emptyObject;\n else if (this.repeated)\n this.defaultValue = util.emptyArray;\n else\n this.defaultValue = this.typeDefault;\n\n // ensure proper value on prototype\n if (this.parent instanceof Type)\n this.parent.ctor.prototype[this.name] = this.defaultValue;\n\n return ReflectionObject.prototype.resolve.call(this);\n};\n\n/**\n * Decorator function as returned by {@link Field.d} and {@link MapField.d} (TypeScript).\n * @typedef FieldDecorator\n * @type {function}\n * @param {Object} prototype Target prototype\n * @param {string} fieldName Field name\n * @returns {undefined}\n */\n\n/**\n * Field decorator (TypeScript).\n * @name Field.d\n * @function\n * @param {number} fieldId Field id\n * @param {\"double\"|\"float\"|\"int32\"|\"uint32\"|\"sint32\"|\"fixed32\"|\"sfixed32\"|\"int64\"|\"uint64\"|\"sint64\"|\"fixed64\"|\"sfixed64\"|\"string\"|\"bool\"|\"bytes\"|Object} fieldType Field type\n * @param {\"optional\"|\"required\"|\"repeated\"} [fieldRule=\"optional\"] Field rule\n * @param {T} [defaultValue] Default value\n * @returns {FieldDecorator} Decorator function\n * @template T extends number | number[] | Long | Long[] | string | string[] | boolean | boolean[] | Uint8Array | Uint8Array[] | Buffer | Buffer[]\n */\nField.d = function decorateField(fieldId, fieldType, fieldRule, defaultValue) {\n\n // submessage: decorate the submessage and use its name as the type\n if (typeof fieldType === \"function\")\n fieldType = util.decorateType(fieldType).name;\n\n // enum reference: create a reflected copy of the enum and keep reuseing it\n else if (fieldType && typeof fieldType === \"object\")\n fieldType = util.decorateEnum(fieldType).name;\n\n return function fieldDecorator(prototype, fieldName) {\n util.decorateType(prototype.constructor)\n .add(new Field(fieldName, fieldId, fieldType, fieldRule, { \"default\": defaultValue }));\n };\n};\n\n/**\n * Field decorator (TypeScript).\n * @name Field.d\n * @function\n * @param {number} fieldId Field id\n * @param {Constructor|string} fieldType Field type\n * @param {\"optional\"|\"required\"|\"repeated\"} [fieldRule=\"optional\"] Field rule\n * @returns {FieldDecorator} Decorator function\n * @template T extends Message\n * @variation 2\n */\n// like Field.d but without a default value\n\n// Sets up cyclic dependencies (called in index-light)\nField._configure = function configure(Type_) {\n Type = Type_;\n};\n","\"use strict\";\nvar protobuf = module.exports = require(17);\n\nprotobuf.build = \"light\";\n\n/**\n * A node-style callback as used by {@link load} and {@link Root#load}.\n * @typedef LoadCallback\n * @type {function}\n * @param {Error|null} error Error, if any, otherwise `null`\n * @param {Root} [root] Root, if there hasn't been an error\n * @returns {undefined}\n */\n\n/**\n * Loads one or multiple .proto or preprocessed .json files into a common root namespace and calls the callback.\n * @param {string|string[]} filename One or multiple files to load\n * @param {Root} root Root namespace, defaults to create a new one if omitted.\n * @param {LoadCallback} callback Callback function\n * @returns {undefined}\n * @see {@link Root#load}\n */\nfunction load(filename, root, callback) {\n if (typeof root === \"function\") {\n callback = root;\n root = new protobuf.Root();\n } else if (!root)\n root = new protobuf.Root();\n return root.load(filename, callback);\n}\n\n/**\n * Loads one or multiple .proto or preprocessed .json files into a common root namespace and calls the callback.\n * @name load\n * @function\n * @param {string|string[]} filename One or multiple files to load\n * @param {LoadCallback} callback Callback function\n * @returns {undefined}\n * @see {@link Root#load}\n * @variation 2\n */\n// function load(filename:string, callback:LoadCallback):undefined\n\n/**\n * Loads one or multiple .proto or preprocessed .json files into a common root namespace and returns a promise.\n * @name load\n * @function\n * @param {string|string[]} filename One or multiple files to load\n * @param {Root} [root] Root namespace, defaults to create a new one if omitted.\n * @returns {Promise} Promise\n * @see {@link Root#load}\n * @variation 3\n */\n// function load(filename:string, [root:Root]):Promise\n\nprotobuf.load = load;\n\n/**\n * Synchronously loads one or multiple .proto or preprocessed .json files into a common root namespace (node only).\n * @param {string|string[]} filename One or multiple files to load\n * @param {Root} [root] Root namespace, defaults to create a new one if omitted.\n * @returns {Root} Root namespace\n * @throws {Error} If synchronous fetching is not supported (i.e. in browsers) or if a file's syntax is invalid\n * @see {@link Root#loadSync}\n */\nfunction loadSync(filename, root) {\n if (!root)\n root = new protobuf.Root();\n return root.loadSync(filename);\n}\n\nprotobuf.loadSync = loadSync;\n\n// Serialization\nprotobuf.encoder = require(13);\nprotobuf.decoder = require(12);\nprotobuf.verifier = require(36);\nprotobuf.converter = require(11);\n\n// Reflection\nprotobuf.ReflectionObject = require(22);\nprotobuf.Namespace = require(21);\nprotobuf.Root = require(26);\nprotobuf.Enum = require(14);\nprotobuf.Type = require(31);\nprotobuf.Field = require(15);\nprotobuf.OneOf = require(23);\nprotobuf.MapField = require(18);\nprotobuf.Service = require(30);\nprotobuf.Method = require(20);\n\n// Runtime\nprotobuf.Message = require(19);\nprotobuf.wrappers = require(37);\n\n// Utility\nprotobuf.types = require(32);\nprotobuf.util = require(33);\n\n// Set up possibly cyclic reflection dependencies\nprotobuf.ReflectionObject._configure(protobuf.Root);\nprotobuf.Namespace._configure(protobuf.Type, protobuf.Service, protobuf.Enum);\nprotobuf.Root._configure(protobuf.Type);\nprotobuf.Field._configure(protobuf.Type);\n","\"use strict\";\nvar protobuf = exports;\n\n/**\n * Build type, one of `\"full\"`, `\"light\"` or `\"minimal\"`.\n * @name build\n * @type {string}\n * @const\n */\nprotobuf.build = \"minimal\";\n\n// Serialization\nprotobuf.Writer = require(38);\nprotobuf.BufferWriter = require(39);\nprotobuf.Reader = require(24);\nprotobuf.BufferReader = require(25);\n\n// Utility\nprotobuf.util = require(35);\nprotobuf.rpc = require(28);\nprotobuf.roots = require(27);\nprotobuf.configure = configure;\n\n/* istanbul ignore next */\n/**\n * Reconfigures the library according to the environment.\n * @returns {undefined}\n */\nfunction configure() {\n protobuf.util._configure();\n protobuf.Writer._configure(protobuf.BufferWriter);\n protobuf.Reader._configure(protobuf.BufferReader);\n}\n\n// Set up buffer utility according to the environment\nconfigure();\n","\"use strict\";\nmodule.exports = MapField;\n\n// extends Field\nvar Field = require(15);\n((MapField.prototype = Object.create(Field.prototype)).constructor = MapField).className = \"MapField\";\n\nvar types = require(32),\n util = require(33);\n\n/**\n * Constructs a new map field instance.\n * @classdesc Reflected map field.\n * @extends FieldBase\n * @constructor\n * @param {string} name Unique name within its namespace\n * @param {number} id Unique id within its namespace\n * @param {string} keyType Key type\n * @param {string} type Value type\n * @param {Object.} [options] Declared options\n * @param {string} [comment] Comment associated with this field\n */\nfunction MapField(name, id, keyType, type, options, comment) {\n Field.call(this, name, id, type, undefined, undefined, options, comment);\n\n /* istanbul ignore if */\n if (!util.isString(keyType))\n throw TypeError(\"keyType must be a string\");\n\n /**\n * Key type.\n * @type {string}\n */\n this.keyType = keyType; // toJSON, marker\n\n /**\n * Resolved key type if not a basic type.\n * @type {ReflectionObject|null}\n */\n this.resolvedKeyType = null;\n\n // Overrides Field#map\n this.map = true;\n}\n\n/**\n * Map field descriptor.\n * @interface IMapField\n * @extends {IField}\n * @property {string} keyType Key type\n */\n\n/**\n * Extension map field descriptor.\n * @interface IExtensionMapField\n * @extends IMapField\n * @property {string} extend Extended type\n */\n\n/**\n * Constructs a map field from a map field descriptor.\n * @param {string} name Field name\n * @param {IMapField} json Map field descriptor\n * @returns {MapField} Created map field\n * @throws {TypeError} If arguments are invalid\n */\nMapField.fromJSON = function fromJSON(name, json) {\n return new MapField(name, json.id, json.keyType, json.type, json.options, json.comment);\n};\n\n/**\n * Converts this map field to a map field descriptor.\n * @param {IToJSONOptions} [toJSONOptions] JSON conversion options\n * @returns {IMapField} Map field descriptor\n */\nMapField.prototype.toJSON = function toJSON(toJSONOptions) {\n var keepComments = toJSONOptions ? Boolean(toJSONOptions.keepComments) : false;\n return util.toObject([\n \"keyType\" , this.keyType,\n \"type\" , this.type,\n \"id\" , this.id,\n \"extend\" , this.extend,\n \"options\" , this.options,\n \"comment\" , keepComments ? this.comment : undefined\n ]);\n};\n\n/**\n * @override\n */\nMapField.prototype.resolve = function resolve() {\n if (this.resolved)\n return this;\n\n // Besides a value type, map fields have a key type that may be \"any scalar type except for floating point types and bytes\"\n if (types.mapKey[this.keyType] === undefined)\n throw Error(\"invalid key type: \" + this.keyType);\n\n return Field.prototype.resolve.call(this);\n};\n\n/**\n * Map field decorator (TypeScript).\n * @name MapField.d\n * @function\n * @param {number} fieldId Field id\n * @param {\"int32\"|\"uint32\"|\"sint32\"|\"fixed32\"|\"sfixed32\"|\"int64\"|\"uint64\"|\"sint64\"|\"fixed64\"|\"sfixed64\"|\"bool\"|\"string\"} fieldKeyType Field key type\n * @param {\"double\"|\"float\"|\"int32\"|\"uint32\"|\"sint32\"|\"fixed32\"|\"sfixed32\"|\"int64\"|\"uint64\"|\"sint64\"|\"fixed64\"|\"sfixed64\"|\"bool\"|\"string\"|\"bytes\"|Object|Constructor<{}>} fieldValueType Field value type\n * @returns {FieldDecorator} Decorator function\n * @template T extends { [key: string]: number | Long | string | boolean | Uint8Array | Buffer | number[] | Message<{}> }\n */\nMapField.d = function decorateMapField(fieldId, fieldKeyType, fieldValueType) {\n\n // submessage value: decorate the submessage and use its name as the type\n if (typeof fieldValueType === \"function\")\n fieldValueType = util.decorateType(fieldValueType).name;\n\n // enum reference value: create a reflected copy of the enum and keep reuseing it\n else if (fieldValueType && typeof fieldValueType === \"object\")\n fieldValueType = util.decorateEnum(fieldValueType).name;\n\n return function mapFieldDecorator(prototype, fieldName) {\n util.decorateType(prototype.constructor)\n .add(new MapField(fieldName, fieldId, fieldKeyType, fieldValueType));\n };\n};\n","\"use strict\";\nmodule.exports = Message;\n\nvar util = require(35);\n\n/**\n * Constructs a new message instance.\n * @classdesc Abstract runtime message.\n * @constructor\n * @param {Properties} [properties] Properties to set\n * @template T extends object = object\n */\nfunction Message(properties) {\n // not used internally\n if (properties)\n for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i)\n this[keys[i]] = properties[keys[i]];\n}\n\n/**\n * Reference to the reflected type.\n * @name Message.$type\n * @type {Type}\n * @readonly\n */\n\n/**\n * Reference to the reflected type.\n * @name Message#$type\n * @type {Type}\n * @readonly\n */\n\n/*eslint-disable valid-jsdoc*/\n\n/**\n * Creates a new message of this type using the specified properties.\n * @param {Object.} [properties] Properties to set\n * @returns {Message} Message instance\n * @template T extends Message\n * @this Constructor\n */\nMessage.create = function create(properties) {\n return this.$type.create(properties);\n};\n\n/**\n * Encodes a message of this type.\n * @param {T|Object.} message Message to encode\n * @param {Writer} [writer] Writer to use\n * @returns {Writer} Writer\n * @template T extends Message\n * @this Constructor\n */\nMessage.encode = function encode(message, writer) {\n return this.$type.encode(message, writer);\n};\n\n/**\n * Encodes a message of this type preceeded by its length as a varint.\n * @param {T|Object.} message Message to encode\n * @param {Writer} [writer] Writer to use\n * @returns {Writer} Writer\n * @template T extends Message\n * @this Constructor\n */\nMessage.encodeDelimited = function encodeDelimited(message, writer) {\n return this.$type.encodeDelimited(message, writer);\n};\n\n/**\n * Decodes a message of this type.\n * @name Message.decode\n * @function\n * @param {Reader|Uint8Array} reader Reader or buffer to decode\n * @returns {T} Decoded message\n * @template T extends Message\n * @this Constructor\n */\nMessage.decode = function decode(reader) {\n return this.$type.decode(reader);\n};\n\n/**\n * Decodes a message of this type preceeded by its length as a varint.\n * @name Message.decodeDelimited\n * @function\n * @param {Reader|Uint8Array} reader Reader or buffer to decode\n * @returns {T} Decoded message\n * @template T extends Message\n * @this Constructor\n */\nMessage.decodeDelimited = function decodeDelimited(reader) {\n return this.$type.decodeDelimited(reader);\n};\n\n/**\n * Verifies a message of this type.\n * @name Message.verify\n * @function\n * @param {Object.} message Plain object to verify\n * @returns {string|null} `null` if valid, otherwise the reason why it is not\n */\nMessage.verify = function verify(message) {\n return this.$type.verify(message);\n};\n\n/**\n * Creates a new message of this type from a plain object. Also converts values to their respective internal types.\n * @param {Object.} object Plain object\n * @returns {T} Message instance\n * @template T extends Message\n * @this Constructor\n */\nMessage.fromObject = function fromObject(object) {\n return this.$type.fromObject(object);\n};\n\n/**\n * Creates a plain object from a message of this type. Also converts values to other types if specified.\n * @param {T} message Message instance\n * @param {IConversionOptions} [options] Conversion options\n * @returns {Object.} Plain object\n * @template T extends Message\n * @this Constructor\n */\nMessage.toObject = function toObject(message, options) {\n return this.$type.toObject(message, options);\n};\n\n/**\n * Converts this message to JSON.\n * @returns {Object.} JSON object\n */\nMessage.prototype.toJSON = function toJSON() {\n return this.$type.toObject(this, util.toJSONOptions);\n};\n\n/*eslint-enable valid-jsdoc*/","\"use strict\";\nmodule.exports = Method;\n\n// extends ReflectionObject\nvar ReflectionObject = require(22);\n((Method.prototype = Object.create(ReflectionObject.prototype)).constructor = Method).className = \"Method\";\n\nvar util = require(33);\n\n/**\n * Constructs a new service method instance.\n * @classdesc Reflected service method.\n * @extends ReflectionObject\n * @constructor\n * @param {string} name Method name\n * @param {string|undefined} type Method type, usually `\"rpc\"`\n * @param {string} requestType Request message type\n * @param {string} responseType Response message type\n * @param {boolean|Object.} [requestStream] Whether the request is streamed\n * @param {boolean|Object.} [responseStream] Whether the response is streamed\n * @param {Object.} [options] Declared options\n * @param {string} [comment] The comment for this method\n * @param {Object.} [parsedOptions] Declared options, properly parsed into an object\n */\nfunction Method(name, type, requestType, responseType, requestStream, responseStream, options, comment, parsedOptions) {\n\n /* istanbul ignore next */\n if (util.isObject(requestStream)) {\n options = requestStream;\n requestStream = responseStream = undefined;\n } else if (util.isObject(responseStream)) {\n options = responseStream;\n responseStream = undefined;\n }\n\n /* istanbul ignore if */\n if (!(type === undefined || util.isString(type)))\n throw TypeError(\"type must be a string\");\n\n /* istanbul ignore if */\n if (!util.isString(requestType))\n throw TypeError(\"requestType must be a string\");\n\n /* istanbul ignore if */\n if (!util.isString(responseType))\n throw TypeError(\"responseType must be a string\");\n\n ReflectionObject.call(this, name, options);\n\n /**\n * Method type.\n * @type {string}\n */\n this.type = type || \"rpc\"; // toJSON\n\n /**\n * Request type.\n * @type {string}\n */\n this.requestType = requestType; // toJSON, marker\n\n /**\n * Whether requests are streamed or not.\n * @type {boolean|undefined}\n */\n this.requestStream = requestStream ? true : undefined; // toJSON\n\n /**\n * Response type.\n * @type {string}\n */\n this.responseType = responseType; // toJSON\n\n /**\n * Whether responses are streamed or not.\n * @type {boolean|undefined}\n */\n this.responseStream = responseStream ? true : undefined; // toJSON\n\n /**\n * Resolved request type.\n * @type {Type|null}\n */\n this.resolvedRequestType = null;\n\n /**\n * Resolved response type.\n * @type {Type|null}\n */\n this.resolvedResponseType = null;\n\n /**\n * Comment for this method\n * @type {string|null}\n */\n this.comment = comment;\n\n /**\n * Options properly parsed into an object\n */\n this.parsedOptions = parsedOptions;\n}\n\n/**\n * Method descriptor.\n * @interface IMethod\n * @property {string} [type=\"rpc\"] Method type\n * @property {string} requestType Request type\n * @property {string} responseType Response type\n * @property {boolean} [requestStream=false] Whether requests are streamed\n * @property {boolean} [responseStream=false] Whether responses are streamed\n * @property {Object.} [options] Method options\n * @property {string} comment Method comments\n * @property {Object.} [parsedOptions] Method options properly parsed into an object\n */\n\n/**\n * Constructs a method from a method descriptor.\n * @param {string} name Method name\n * @param {IMethod} json Method descriptor\n * @returns {Method} Created method\n * @throws {TypeError} If arguments are invalid\n */\nMethod.fromJSON = function fromJSON(name, json) {\n return new Method(name, json.type, json.requestType, json.responseType, json.requestStream, json.responseStream, json.options, json.comment, json.parsedOptions);\n};\n\n/**\n * Converts this method to a method descriptor.\n * @param {IToJSONOptions} [toJSONOptions] JSON conversion options\n * @returns {IMethod} Method descriptor\n */\nMethod.prototype.toJSON = function toJSON(toJSONOptions) {\n var keepComments = toJSONOptions ? Boolean(toJSONOptions.keepComments) : false;\n return util.toObject([\n \"type\" , this.type !== \"rpc\" && /* istanbul ignore next */ this.type || undefined,\n \"requestType\" , this.requestType,\n \"requestStream\" , this.requestStream,\n \"responseType\" , this.responseType,\n \"responseStream\" , this.responseStream,\n \"options\" , this.options,\n \"comment\" , keepComments ? this.comment : undefined,\n \"parsedOptions\" , this.parsedOptions,\n ]);\n};\n\n/**\n * @override\n */\nMethod.prototype.resolve = function resolve() {\n\n /* istanbul ignore if */\n if (this.resolved)\n return this;\n\n this.resolvedRequestType = this.parent.lookupType(this.requestType);\n this.resolvedResponseType = this.parent.lookupType(this.responseType);\n\n return ReflectionObject.prototype.resolve.call(this);\n};\n","\"use strict\";\nmodule.exports = Namespace;\n\n// extends ReflectionObject\nvar ReflectionObject = require(22);\n((Namespace.prototype = Object.create(ReflectionObject.prototype)).constructor = Namespace).className = \"Namespace\";\n\nvar Field = require(15),\n util = require(33),\n OneOf = require(23);\n\nvar Type, // cyclic\n Service,\n Enum;\n\n/**\n * Constructs a new namespace instance.\n * @name Namespace\n * @classdesc Reflected namespace.\n * @extends NamespaceBase\n * @constructor\n * @param {string} name Namespace name\n * @param {Object.} [options] Declared options\n */\n\n/**\n * Constructs a namespace from JSON.\n * @memberof Namespace\n * @function\n * @param {string} name Namespace name\n * @param {Object.} json JSON object\n * @returns {Namespace} Created namespace\n * @throws {TypeError} If arguments are invalid\n */\nNamespace.fromJSON = function fromJSON(name, json) {\n return new Namespace(name, json.options).addJSON(json.nested);\n};\n\n/**\n * Converts an array of reflection objects to JSON.\n * @memberof Namespace\n * @param {ReflectionObject[]} array Object array\n * @param {IToJSONOptions} [toJSONOptions] JSON conversion options\n * @returns {Object.|undefined} JSON object or `undefined` when array is empty\n */\nfunction arrayToJSON(array, toJSONOptions) {\n if (!(array && array.length))\n return undefined;\n var obj = {};\n for (var i = 0; i < array.length; ++i)\n obj[array[i].name] = array[i].toJSON(toJSONOptions);\n return obj;\n}\n\nNamespace.arrayToJSON = arrayToJSON;\n\n/**\n * Tests if the specified id is reserved.\n * @param {Array.|undefined} reserved Array of reserved ranges and names\n * @param {number} id Id to test\n * @returns {boolean} `true` if reserved, otherwise `false`\n */\nNamespace.isReservedId = function isReservedId(reserved, id) {\n if (reserved)\n for (var i = 0; i < reserved.length; ++i)\n if (typeof reserved[i] !== \"string\" && reserved[i][0] <= id && reserved[i][1] > id)\n return true;\n return false;\n};\n\n/**\n * Tests if the specified name is reserved.\n * @param {Array.|undefined} reserved Array of reserved ranges and names\n * @param {string} name Name to test\n * @returns {boolean} `true` if reserved, otherwise `false`\n */\nNamespace.isReservedName = function isReservedName(reserved, name) {\n if (reserved)\n for (var i = 0; i < reserved.length; ++i)\n if (reserved[i] === name)\n return true;\n return false;\n};\n\n/**\n * Not an actual constructor. Use {@link Namespace} instead.\n * @classdesc Base class of all reflection objects containing nested objects. This is not an actual class but here for the sake of having consistent type definitions.\n * @exports NamespaceBase\n * @extends ReflectionObject\n * @abstract\n * @constructor\n * @param {string} name Namespace name\n * @param {Object.} [options] Declared options\n * @see {@link Namespace}\n */\nfunction Namespace(name, options) {\n ReflectionObject.call(this, name, options);\n\n /**\n * Nested objects by name.\n * @type {Object.|undefined}\n */\n this.nested = undefined; // toJSON\n\n /**\n * Cached nested objects as an array.\n * @type {ReflectionObject[]|null}\n * @private\n */\n this._nestedArray = null;\n}\n\nfunction clearCache(namespace) {\n namespace._nestedArray = null;\n return namespace;\n}\n\n/**\n * Nested objects of this namespace as an array for iteration.\n * @name NamespaceBase#nestedArray\n * @type {ReflectionObject[]}\n * @readonly\n */\nObject.defineProperty(Namespace.prototype, \"nestedArray\", {\n get: function() {\n return this._nestedArray || (this._nestedArray = util.toArray(this.nested));\n }\n});\n\n/**\n * Namespace descriptor.\n * @interface INamespace\n * @property {Object.} [options] Namespace options\n * @property {Object.} [nested] Nested object descriptors\n */\n\n/**\n * Any extension field descriptor.\n * @typedef AnyExtensionField\n * @type {IExtensionField|IExtensionMapField}\n */\n\n/**\n * Any nested object descriptor.\n * @typedef AnyNestedObject\n * @type {IEnum|IType|IService|AnyExtensionField|INamespace|IOneOf}\n */\n\n/**\n * Converts this namespace to a namespace descriptor.\n * @param {IToJSONOptions} [toJSONOptions] JSON conversion options\n * @returns {INamespace} Namespace descriptor\n */\nNamespace.prototype.toJSON = function toJSON(toJSONOptions) {\n return util.toObject([\n \"options\" , this.options,\n \"nested\" , arrayToJSON(this.nestedArray, toJSONOptions)\n ]);\n};\n\n/**\n * Adds nested objects to this namespace from nested object descriptors.\n * @param {Object.} nestedJson Any nested object descriptors\n * @returns {Namespace} `this`\n */\nNamespace.prototype.addJSON = function addJSON(nestedJson) {\n var ns = this;\n /* istanbul ignore else */\n if (nestedJson) {\n for (var names = Object.keys(nestedJson), i = 0, nested; i < names.length; ++i) {\n nested = nestedJson[names[i]];\n ns.add( // most to least likely\n ( nested.fields !== undefined\n ? Type.fromJSON\n : nested.values !== undefined\n ? Enum.fromJSON\n : nested.methods !== undefined\n ? Service.fromJSON\n : nested.id !== undefined\n ? Field.fromJSON\n : Namespace.fromJSON )(names[i], nested)\n );\n }\n }\n return this;\n};\n\n/**\n * Gets the nested object of the specified name.\n * @param {string} name Nested object name\n * @returns {ReflectionObject|null} The reflection object or `null` if it doesn't exist\n */\nNamespace.prototype.get = function get(name) {\n return this.nested && this.nested[name]\n || null;\n};\n\n/**\n * Gets the values of the nested {@link Enum|enum} of the specified name.\n * This methods differs from {@link Namespace#get|get} in that it returns an enum's values directly and throws instead of returning `null`.\n * @param {string} name Nested enum name\n * @returns {Object.} Enum values\n * @throws {Error} If there is no such enum\n */\nNamespace.prototype.getEnum = function getEnum(name) {\n if (this.nested && this.nested[name] instanceof Enum)\n return this.nested[name].values;\n throw Error(\"no such enum: \" + name);\n};\n\n/**\n * Adds a nested object to this namespace.\n * @param {ReflectionObject} object Nested object to add\n * @returns {Namespace} `this`\n * @throws {TypeError} If arguments are invalid\n * @throws {Error} If there is already a nested object with this name\n */\nNamespace.prototype.add = function add(object) {\n\n if (!(object instanceof Field && object.extend !== undefined || object instanceof Type || object instanceof OneOf || object instanceof Enum || object instanceof Service || object instanceof Namespace))\n throw TypeError(\"object must be a valid nested object\");\n\n if (!this.nested)\n this.nested = {};\n else {\n var prev = this.get(object.name);\n if (prev) {\n if (prev instanceof Namespace && object instanceof Namespace && !(prev instanceof Type || prev instanceof Service)) {\n // replace plain namespace but keep existing nested elements and options\n var nested = prev.nestedArray;\n for (var i = 0; i < nested.length; ++i)\n object.add(nested[i]);\n this.remove(prev);\n if (!this.nested)\n this.nested = {};\n object.setOptions(prev.options, true);\n\n } else\n throw Error(\"duplicate name '\" + object.name + \"' in \" + this);\n }\n }\n this.nested[object.name] = object;\n object.onAdd(this);\n return clearCache(this);\n};\n\n/**\n * Removes a nested object from this namespace.\n * @param {ReflectionObject} object Nested object to remove\n * @returns {Namespace} `this`\n * @throws {TypeError} If arguments are invalid\n * @throws {Error} If `object` is not a member of this namespace\n */\nNamespace.prototype.remove = function remove(object) {\n\n if (!(object instanceof ReflectionObject))\n throw TypeError(\"object must be a ReflectionObject\");\n if (object.parent !== this)\n throw Error(object + \" is not a member of \" + this);\n\n delete this.nested[object.name];\n if (!Object.keys(this.nested).length)\n this.nested = undefined;\n\n object.onRemove(this);\n return clearCache(this);\n};\n\n/**\n * Defines additial namespaces within this one if not yet existing.\n * @param {string|string[]} path Path to create\n * @param {*} [json] Nested types to create from JSON\n * @returns {Namespace} Pointer to the last namespace created or `this` if path is empty\n */\nNamespace.prototype.define = function define(path, json) {\n\n if (util.isString(path))\n path = path.split(\".\");\n else if (!Array.isArray(path))\n throw TypeError(\"illegal path\");\n if (path && path.length && path[0] === \"\")\n throw Error(\"path must be relative\");\n\n var ptr = this;\n while (path.length > 0) {\n var part = path.shift();\n if (ptr.nested && ptr.nested[part]) {\n ptr = ptr.nested[part];\n if (!(ptr instanceof Namespace))\n throw Error(\"path conflicts with non-namespace objects\");\n } else\n ptr.add(ptr = new Namespace(part));\n }\n if (json)\n ptr.addJSON(json);\n return ptr;\n};\n\n/**\n * Resolves this namespace's and all its nested objects' type references. Useful to validate a reflection tree, but comes at a cost.\n * @returns {Namespace} `this`\n */\nNamespace.prototype.resolveAll = function resolveAll() {\n var nested = this.nestedArray, i = 0;\n while (i < nested.length)\n if (nested[i] instanceof Namespace)\n nested[i++].resolveAll();\n else\n nested[i++].resolve();\n return this.resolve();\n};\n\n/**\n * Recursively looks up the reflection object matching the specified path in the scope of this namespace.\n * @param {string|string[]} path Path to look up\n * @param {*|Array.<*>} filterTypes Filter types, any combination of the constructors of `protobuf.Type`, `protobuf.Enum`, `protobuf.Service` etc.\n * @param {boolean} [parentAlreadyChecked=false] If known, whether the parent has already been checked\n * @returns {ReflectionObject|null} Looked up object or `null` if none could be found\n */\nNamespace.prototype.lookup = function lookup(path, filterTypes, parentAlreadyChecked) {\n\n /* istanbul ignore next */\n if (typeof filterTypes === \"boolean\") {\n parentAlreadyChecked = filterTypes;\n filterTypes = undefined;\n } else if (filterTypes && !Array.isArray(filterTypes))\n filterTypes = [ filterTypes ];\n\n if (util.isString(path) && path.length) {\n if (path === \".\")\n return this.root;\n path = path.split(\".\");\n } else if (!path.length)\n return this;\n\n // Start at root if path is absolute\n if (path[0] === \"\")\n return this.root.lookup(path.slice(1), filterTypes);\n\n // Test if the first part matches any nested object, and if so, traverse if path contains more\n var found = this.get(path[0]);\n if (found) {\n if (path.length === 1) {\n if (!filterTypes || filterTypes.indexOf(found.constructor) > -1)\n return found;\n } else if (found instanceof Namespace && (found = found.lookup(path.slice(1), filterTypes, true)))\n return found;\n\n // Otherwise try each nested namespace\n } else\n for (var i = 0; i < this.nestedArray.length; ++i)\n if (this._nestedArray[i] instanceof Namespace && (found = this._nestedArray[i].lookup(path, filterTypes, true)))\n return found;\n\n // If there hasn't been a match, try again at the parent\n if (this.parent === null || parentAlreadyChecked)\n return null;\n return this.parent.lookup(path, filterTypes);\n};\n\n/**\n * Looks up the reflection object at the specified path, relative to this namespace.\n * @name NamespaceBase#lookup\n * @function\n * @param {string|string[]} path Path to look up\n * @param {boolean} [parentAlreadyChecked=false] Whether the parent has already been checked\n * @returns {ReflectionObject|null} Looked up object or `null` if none could be found\n * @variation 2\n */\n// lookup(path: string, [parentAlreadyChecked: boolean])\n\n/**\n * Looks up the {@link Type|type} at the specified path, relative to this namespace.\n * Besides its signature, this methods differs from {@link Namespace#lookup|lookup} in that it throws instead of returning `null`.\n * @param {string|string[]} path Path to look up\n * @returns {Type} Looked up type\n * @throws {Error} If `path` does not point to a type\n */\nNamespace.prototype.lookupType = function lookupType(path) {\n var found = this.lookup(path, [ Type ]);\n if (!found)\n throw Error(\"no such type: \" + path);\n return found;\n};\n\n/**\n * Looks up the values of the {@link Enum|enum} at the specified path, relative to this namespace.\n * Besides its signature, this methods differs from {@link Namespace#lookup|lookup} in that it throws instead of returning `null`.\n * @param {string|string[]} path Path to look up\n * @returns {Enum} Looked up enum\n * @throws {Error} If `path` does not point to an enum\n */\nNamespace.prototype.lookupEnum = function lookupEnum(path) {\n var found = this.lookup(path, [ Enum ]);\n if (!found)\n throw Error(\"no such Enum '\" + path + \"' in \" + this);\n return found;\n};\n\n/**\n * Looks up the {@link Type|type} or {@link Enum|enum} at the specified path, relative to this namespace.\n * Besides its signature, this methods differs from {@link Namespace#lookup|lookup} in that it throws instead of returning `null`.\n * @param {string|string[]} path Path to look up\n * @returns {Type} Looked up type or enum\n * @throws {Error} If `path` does not point to a type or enum\n */\nNamespace.prototype.lookupTypeOrEnum = function lookupTypeOrEnum(path) {\n var found = this.lookup(path, [ Type, Enum ]);\n if (!found)\n throw Error(\"no such Type or Enum '\" + path + \"' in \" + this);\n return found;\n};\n\n/**\n * Looks up the {@link Service|service} at the specified path, relative to this namespace.\n * Besides its signature, this methods differs from {@link Namespace#lookup|lookup} in that it throws instead of returning `null`.\n * @param {string|string[]} path Path to look up\n * @returns {Service} Looked up service\n * @throws {Error} If `path` does not point to a service\n */\nNamespace.prototype.lookupService = function lookupService(path) {\n var found = this.lookup(path, [ Service ]);\n if (!found)\n throw Error(\"no such Service '\" + path + \"' in \" + this);\n return found;\n};\n\n// Sets up cyclic dependencies (called in index-light)\nNamespace._configure = function(Type_, Service_, Enum_) {\n Type = Type_;\n Service = Service_;\n Enum = Enum_;\n};\n","\"use strict\";\nmodule.exports = ReflectionObject;\n\nReflectionObject.className = \"ReflectionObject\";\n\nvar util = require(33);\n\nvar Root; // cyclic\n\n/**\n * Constructs a new reflection object instance.\n * @classdesc Base class of all reflection objects.\n * @constructor\n * @param {string} name Object name\n * @param {Object.} [options] Declared options\n * @abstract\n */\nfunction ReflectionObject(name, options) {\n\n if (!util.isString(name))\n throw TypeError(\"name must be a string\");\n\n if (options && !util.isObject(options))\n throw TypeError(\"options must be an object\");\n\n /**\n * Options.\n * @type {Object.|undefined}\n */\n this.options = options; // toJSON\n\n /**\n * Parsed Options.\n * @type {Array.>|undefined}\n */\n this.parsedOptions = null;\n\n /**\n * Unique name within its namespace.\n * @type {string}\n */\n this.name = name;\n\n /**\n * Parent namespace.\n * @type {Namespace|null}\n */\n this.parent = null;\n\n /**\n * Whether already resolved or not.\n * @type {boolean}\n */\n this.resolved = false;\n\n /**\n * Comment text, if any.\n * @type {string|null}\n */\n this.comment = null;\n\n /**\n * Defining file name.\n * @type {string|null}\n */\n this.filename = null;\n}\n\nObject.defineProperties(ReflectionObject.prototype, {\n\n /**\n * Reference to the root namespace.\n * @name ReflectionObject#root\n * @type {Root}\n * @readonly\n */\n root: {\n get: function() {\n var ptr = this;\n while (ptr.parent !== null)\n ptr = ptr.parent;\n return ptr;\n }\n },\n\n /**\n * Full name including leading dot.\n * @name ReflectionObject#fullName\n * @type {string}\n * @readonly\n */\n fullName: {\n get: function() {\n var path = [ this.name ],\n ptr = this.parent;\n while (ptr) {\n path.unshift(ptr.name);\n ptr = ptr.parent;\n }\n return path.join(\".\");\n }\n }\n});\n\n/**\n * Converts this reflection object to its descriptor representation.\n * @returns {Object.} Descriptor\n * @abstract\n */\nReflectionObject.prototype.toJSON = /* istanbul ignore next */ function toJSON() {\n throw Error(); // not implemented, shouldn't happen\n};\n\n/**\n * Called when this object is added to a parent.\n * @param {ReflectionObject} parent Parent added to\n * @returns {undefined}\n */\nReflectionObject.prototype.onAdd = function onAdd(parent) {\n if (this.parent && this.parent !== parent)\n this.parent.remove(this);\n this.parent = parent;\n this.resolved = false;\n var root = parent.root;\n if (root instanceof Root)\n root._handleAdd(this);\n};\n\n/**\n * Called when this object is removed from a parent.\n * @param {ReflectionObject} parent Parent removed from\n * @returns {undefined}\n */\nReflectionObject.prototype.onRemove = function onRemove(parent) {\n var root = parent.root;\n if (root instanceof Root)\n root._handleRemove(this);\n this.parent = null;\n this.resolved = false;\n};\n\n/**\n * Resolves this objects type references.\n * @returns {ReflectionObject} `this`\n */\nReflectionObject.prototype.resolve = function resolve() {\n if (this.resolved)\n return this;\n if (this.root instanceof Root)\n this.resolved = true; // only if part of a root\n return this;\n};\n\n/**\n * Gets an option value.\n * @param {string} name Option name\n * @returns {*} Option value or `undefined` if not set\n */\nReflectionObject.prototype.getOption = function getOption(name) {\n if (this.options)\n return this.options[name];\n return undefined;\n};\n\n/**\n * Sets an option.\n * @param {string} name Option name\n * @param {*} value Option value\n * @param {boolean} [ifNotSet] Sets the option only if it isn't currently set\n * @returns {ReflectionObject} `this`\n */\nReflectionObject.prototype.setOption = function setOption(name, value, ifNotSet) {\n if (!ifNotSet || !this.options || this.options[name] === undefined)\n (this.options || (this.options = {}))[name] = value;\n return this;\n};\n\n/**\n * Sets a parsed option.\n * @param {string} name parsed Option name\n * @param {*} value Option value\n * @param {string} propName dot '.' delimited full path of property within the option to set. if undefined\\empty, will add a new option with that value\n * @returns {ReflectionObject} `this`\n */\nReflectionObject.prototype.setParsedOption = function setParsedOption(name, value, propName) {\n if (!this.parsedOptions) {\n this.parsedOptions = [];\n }\n var parsedOptions = this.parsedOptions;\n if (propName) {\n // If setting a sub property of an option then try to merge it\n // with an existing option\n var opt = parsedOptions.find(function (opt) {\n return Object.prototype.hasOwnProperty.call(opt, name);\n });\n if (opt) {\n // If we found an existing option - just merge the property value\n var newValue = opt[name];\n util.setProperty(newValue, propName, value);\n } else {\n // otherwise, create a new option, set it's property and add it to the list\n opt = {};\n opt[name] = util.setProperty({}, propName, value);\n parsedOptions.push(opt);\n }\n } else {\n // Always create a new option when setting the value of the option itself\n var newOpt = {};\n newOpt[name] = value;\n parsedOptions.push(newOpt);\n }\n return this;\n};\n\n/**\n * Sets multiple options.\n * @param {Object.} options Options to set\n * @param {boolean} [ifNotSet] Sets an option only if it isn't currently set\n * @returns {ReflectionObject} `this`\n */\nReflectionObject.prototype.setOptions = function setOptions(options, ifNotSet) {\n if (options)\n for (var keys = Object.keys(options), i = 0; i < keys.length; ++i)\n this.setOption(keys[i], options[keys[i]], ifNotSet);\n return this;\n};\n\n/**\n * Converts this instance to its string representation.\n * @returns {string} Class name[, space, full name]\n */\nReflectionObject.prototype.toString = function toString() {\n var className = this.constructor.className,\n fullName = this.fullName;\n if (fullName.length)\n return className + \" \" + fullName;\n return className;\n};\n\n// Sets up cyclic dependencies (called in index-light)\nReflectionObject._configure = function(Root_) {\n Root = Root_;\n};\n","\"use strict\";\nmodule.exports = OneOf;\n\n// extends ReflectionObject\nvar ReflectionObject = require(22);\n((OneOf.prototype = Object.create(ReflectionObject.prototype)).constructor = OneOf).className = \"OneOf\";\n\nvar Field = require(15),\n util = require(33);\n\n/**\n * Constructs a new oneof instance.\n * @classdesc Reflected oneof.\n * @extends ReflectionObject\n * @constructor\n * @param {string} name Oneof name\n * @param {string[]|Object.} [fieldNames] Field names\n * @param {Object.} [options] Declared options\n * @param {string} [comment] Comment associated with this field\n */\nfunction OneOf(name, fieldNames, options, comment) {\n if (!Array.isArray(fieldNames)) {\n options = fieldNames;\n fieldNames = undefined;\n }\n ReflectionObject.call(this, name, options);\n\n /* istanbul ignore if */\n if (!(fieldNames === undefined || Array.isArray(fieldNames)))\n throw TypeError(\"fieldNames must be an Array\");\n\n /**\n * Field names that belong to this oneof.\n * @type {string[]}\n */\n this.oneof = fieldNames || []; // toJSON, marker\n\n /**\n * Fields that belong to this oneof as an array for iteration.\n * @type {Field[]}\n * @readonly\n */\n this.fieldsArray = []; // declared readonly for conformance, possibly not yet added to parent\n\n /**\n * Comment for this field.\n * @type {string|null}\n */\n this.comment = comment;\n}\n\n/**\n * Oneof descriptor.\n * @interface IOneOf\n * @property {Array.} oneof Oneof field names\n * @property {Object.} [options] Oneof options\n */\n\n/**\n * Constructs a oneof from a oneof descriptor.\n * @param {string} name Oneof name\n * @param {IOneOf} json Oneof descriptor\n * @returns {OneOf} Created oneof\n * @throws {TypeError} If arguments are invalid\n */\nOneOf.fromJSON = function fromJSON(name, json) {\n return new OneOf(name, json.oneof, json.options, json.comment);\n};\n\n/**\n * Converts this oneof to a oneof descriptor.\n * @param {IToJSONOptions} [toJSONOptions] JSON conversion options\n * @returns {IOneOf} Oneof descriptor\n */\nOneOf.prototype.toJSON = function toJSON(toJSONOptions) {\n var keepComments = toJSONOptions ? Boolean(toJSONOptions.keepComments) : false;\n return util.toObject([\n \"options\" , this.options,\n \"oneof\" , this.oneof,\n \"comment\" , keepComments ? this.comment : undefined\n ]);\n};\n\n/**\n * Adds the fields of the specified oneof to the parent if not already done so.\n * @param {OneOf} oneof The oneof\n * @returns {undefined}\n * @inner\n * @ignore\n */\nfunction addFieldsToParent(oneof) {\n if (oneof.parent)\n for (var i = 0; i < oneof.fieldsArray.length; ++i)\n if (!oneof.fieldsArray[i].parent)\n oneof.parent.add(oneof.fieldsArray[i]);\n}\n\n/**\n * Adds a field to this oneof and removes it from its current parent, if any.\n * @param {Field} field Field to add\n * @returns {OneOf} `this`\n */\nOneOf.prototype.add = function add(field) {\n\n /* istanbul ignore if */\n if (!(field instanceof Field))\n throw TypeError(\"field must be a Field\");\n\n if (field.parent && field.parent !== this.parent)\n field.parent.remove(field);\n this.oneof.push(field.name);\n this.fieldsArray.push(field);\n field.partOf = this; // field.parent remains null\n addFieldsToParent(this);\n return this;\n};\n\n/**\n * Removes a field from this oneof and puts it back to the oneof's parent.\n * @param {Field} field Field to remove\n * @returns {OneOf} `this`\n */\nOneOf.prototype.remove = function remove(field) {\n\n /* istanbul ignore if */\n if (!(field instanceof Field))\n throw TypeError(\"field must be a Field\");\n\n var index = this.fieldsArray.indexOf(field);\n\n /* istanbul ignore if */\n if (index < 0)\n throw Error(field + \" is not a member of \" + this);\n\n this.fieldsArray.splice(index, 1);\n index = this.oneof.indexOf(field.name);\n\n /* istanbul ignore else */\n if (index > -1) // theoretical\n this.oneof.splice(index, 1);\n\n field.partOf = null;\n return this;\n};\n\n/**\n * @override\n */\nOneOf.prototype.onAdd = function onAdd(parent) {\n ReflectionObject.prototype.onAdd.call(this, parent);\n var self = this;\n // Collect present fields\n for (var i = 0; i < this.oneof.length; ++i) {\n var field = parent.get(this.oneof[i]);\n if (field && !field.partOf) {\n field.partOf = self;\n self.fieldsArray.push(field);\n }\n }\n // Add not yet present fields\n addFieldsToParent(this);\n};\n\n/**\n * @override\n */\nOneOf.prototype.onRemove = function onRemove(parent) {\n for (var i = 0, field; i < this.fieldsArray.length; ++i)\n if ((field = this.fieldsArray[i]).parent)\n field.parent.remove(field);\n ReflectionObject.prototype.onRemove.call(this, parent);\n};\n\n/**\n * Decorator function as returned by {@link OneOf.d} (TypeScript).\n * @typedef OneOfDecorator\n * @type {function}\n * @param {Object} prototype Target prototype\n * @param {string} oneofName OneOf name\n * @returns {undefined}\n */\n\n/**\n * OneOf decorator (TypeScript).\n * @function\n * @param {...string} fieldNames Field names\n * @returns {OneOfDecorator} Decorator function\n * @template T extends string\n */\nOneOf.d = function decorateOneOf() {\n var fieldNames = new Array(arguments.length),\n index = 0;\n while (index < arguments.length)\n fieldNames[index] = arguments[index++];\n return function oneOfDecorator(prototype, oneofName) {\n util.decorateType(prototype.constructor)\n .add(new OneOf(oneofName, fieldNames));\n Object.defineProperty(prototype, oneofName, {\n get: util.oneOfGetter(fieldNames),\n set: util.oneOfSetter(fieldNames)\n });\n };\n};\n","\"use strict\";\nmodule.exports = Reader;\n\nvar util = require(35);\n\nvar BufferReader; // cyclic\n\nvar LongBits = util.LongBits,\n utf8 = util.utf8;\n\n/* istanbul ignore next */\nfunction indexOutOfRange(reader, writeLength) {\n return RangeError(\"index out of range: \" + reader.pos + \" + \" + (writeLength || 1) + \" > \" + reader.len);\n}\n\n/**\n * Constructs a new reader instance using the specified buffer.\n * @classdesc Wire format reader using `Uint8Array` if available, otherwise `Array`.\n * @constructor\n * @param {Uint8Array} buffer Buffer to read from\n */\nfunction Reader(buffer) {\n\n /**\n * Read buffer.\n * @type {Uint8Array}\n */\n this.buf = buffer;\n\n /**\n * Read buffer position.\n * @type {number}\n */\n this.pos = 0;\n\n /**\n * Read buffer length.\n * @type {number}\n */\n this.len = buffer.length;\n}\n\nvar create_array = typeof Uint8Array !== \"undefined\"\n ? function create_typed_array(buffer) {\n if (buffer instanceof Uint8Array || Array.isArray(buffer))\n return new Reader(buffer);\n throw Error(\"illegal buffer\");\n }\n /* istanbul ignore next */\n : function create_array(buffer) {\n if (Array.isArray(buffer))\n return new Reader(buffer);\n throw Error(\"illegal buffer\");\n };\n\nvar create = function create() {\n return util.Buffer\n ? function create_buffer_setup(buffer) {\n return (Reader.create = function create_buffer(buffer) {\n return util.Buffer.isBuffer(buffer)\n ? new BufferReader(buffer)\n /* istanbul ignore next */\n : create_array(buffer);\n })(buffer);\n }\n /* istanbul ignore next */\n : create_array;\n};\n\n/**\n * Creates a new reader using the specified buffer.\n * @function\n * @param {Uint8Array|Buffer} buffer Buffer to read from\n * @returns {Reader|BufferReader} A {@link BufferReader} if `buffer` is a Buffer, otherwise a {@link Reader}\n * @throws {Error} If `buffer` is not a valid buffer\n */\nReader.create = create();\n\nReader.prototype._slice = util.Array.prototype.subarray || /* istanbul ignore next */ util.Array.prototype.slice;\n\n/**\n * Reads a varint as an unsigned 32 bit value.\n * @function\n * @returns {number} Value read\n */\nReader.prototype.uint32 = (function read_uint32_setup() {\n var value = 4294967295; // optimizer type-hint, tends to deopt otherwise (?!)\n return function read_uint32() {\n value = ( this.buf[this.pos] & 127 ) >>> 0; if (this.buf[this.pos++] < 128) return value;\n value = (value | (this.buf[this.pos] & 127) << 7) >>> 0; if (this.buf[this.pos++] < 128) return value;\n value = (value | (this.buf[this.pos] & 127) << 14) >>> 0; if (this.buf[this.pos++] < 128) return value;\n value = (value | (this.buf[this.pos] & 127) << 21) >>> 0; if (this.buf[this.pos++] < 128) return value;\n value = (value | (this.buf[this.pos] & 15) << 28) >>> 0; if (this.buf[this.pos++] < 128) return value;\n\n /* istanbul ignore if */\n if ((this.pos += 5) > this.len) {\n this.pos = this.len;\n throw indexOutOfRange(this, 10);\n }\n return value;\n };\n})();\n\n/**\n * Reads a varint as a signed 32 bit value.\n * @returns {number} Value read\n */\nReader.prototype.int32 = function read_int32() {\n return this.uint32() | 0;\n};\n\n/**\n * Reads a zig-zag encoded varint as a signed 32 bit value.\n * @returns {number} Value read\n */\nReader.prototype.sint32 = function read_sint32() {\n var value = this.uint32();\n return value >>> 1 ^ -(value & 1) | 0;\n};\n\n/* eslint-disable no-invalid-this */\n\nfunction readLongVarint() {\n // tends to deopt with local vars for octet etc.\n var bits = new LongBits(0, 0);\n var i = 0;\n if (this.len - this.pos > 4) { // fast route (lo)\n for (; i < 4; ++i) {\n // 1st..4th\n bits.lo = (bits.lo | (this.buf[this.pos] & 127) << i * 7) >>> 0;\n if (this.buf[this.pos++] < 128)\n return bits;\n }\n // 5th\n bits.lo = (bits.lo | (this.buf[this.pos] & 127) << 28) >>> 0;\n bits.hi = (bits.hi | (this.buf[this.pos] & 127) >> 4) >>> 0;\n if (this.buf[this.pos++] < 128)\n return bits;\n i = 0;\n } else {\n for (; i < 3; ++i) {\n /* istanbul ignore if */\n if (this.pos >= this.len)\n throw indexOutOfRange(this);\n // 1st..3th\n bits.lo = (bits.lo | (this.buf[this.pos] & 127) << i * 7) >>> 0;\n if (this.buf[this.pos++] < 128)\n return bits;\n }\n // 4th\n bits.lo = (bits.lo | (this.buf[this.pos++] & 127) << i * 7) >>> 0;\n return bits;\n }\n if (this.len - this.pos > 4) { // fast route (hi)\n for (; i < 5; ++i) {\n // 6th..10th\n bits.hi = (bits.hi | (this.buf[this.pos] & 127) << i * 7 + 3) >>> 0;\n if (this.buf[this.pos++] < 128)\n return bits;\n }\n } else {\n for (; i < 5; ++i) {\n /* istanbul ignore if */\n if (this.pos >= this.len)\n throw indexOutOfRange(this);\n // 6th..10th\n bits.hi = (bits.hi | (this.buf[this.pos] & 127) << i * 7 + 3) >>> 0;\n if (this.buf[this.pos++] < 128)\n return bits;\n }\n }\n /* istanbul ignore next */\n throw Error(\"invalid varint encoding\");\n}\n\n/* eslint-enable no-invalid-this */\n\n/**\n * Reads a varint as a signed 64 bit value.\n * @name Reader#int64\n * @function\n * @returns {Long} Value read\n */\n\n/**\n * Reads a varint as an unsigned 64 bit value.\n * @name Reader#uint64\n * @function\n * @returns {Long} Value read\n */\n\n/**\n * Reads a zig-zag encoded varint as a signed 64 bit value.\n * @name Reader#sint64\n * @function\n * @returns {Long} Value read\n */\n\n/**\n * Reads a varint as a boolean.\n * @returns {boolean} Value read\n */\nReader.prototype.bool = function read_bool() {\n return this.uint32() !== 0;\n};\n\nfunction readFixed32_end(buf, end) { // note that this uses `end`, not `pos`\n return (buf[end - 4]\n | buf[end - 3] << 8\n | buf[end - 2] << 16\n | buf[end - 1] << 24) >>> 0;\n}\n\n/**\n * Reads fixed 32 bits as an unsigned 32 bit integer.\n * @returns {number} Value read\n */\nReader.prototype.fixed32 = function read_fixed32() {\n\n /* istanbul ignore if */\n if (this.pos + 4 > this.len)\n throw indexOutOfRange(this, 4);\n\n return readFixed32_end(this.buf, this.pos += 4);\n};\n\n/**\n * Reads fixed 32 bits as a signed 32 bit integer.\n * @returns {number} Value read\n */\nReader.prototype.sfixed32 = function read_sfixed32() {\n\n /* istanbul ignore if */\n if (this.pos + 4 > this.len)\n throw indexOutOfRange(this, 4);\n\n return readFixed32_end(this.buf, this.pos += 4) | 0;\n};\n\n/* eslint-disable no-invalid-this */\n\nfunction readFixed64(/* this: Reader */) {\n\n /* istanbul ignore if */\n if (this.pos + 8 > this.len)\n throw indexOutOfRange(this, 8);\n\n return new LongBits(readFixed32_end(this.buf, this.pos += 4), readFixed32_end(this.buf, this.pos += 4));\n}\n\n/* eslint-enable no-invalid-this */\n\n/**\n * Reads fixed 64 bits.\n * @name Reader#fixed64\n * @function\n * @returns {Long} Value read\n */\n\n/**\n * Reads zig-zag encoded fixed 64 bits.\n * @name Reader#sfixed64\n * @function\n * @returns {Long} Value read\n */\n\n/**\n * Reads a float (32 bit) as a number.\n * @function\n * @returns {number} Value read\n */\nReader.prototype.float = function read_float() {\n\n /* istanbul ignore if */\n if (this.pos + 4 > this.len)\n throw indexOutOfRange(this, 4);\n\n var value = util.float.readFloatLE(this.buf, this.pos);\n this.pos += 4;\n return value;\n};\n\n/**\n * Reads a double (64 bit float) as a number.\n * @function\n * @returns {number} Value read\n */\nReader.prototype.double = function read_double() {\n\n /* istanbul ignore if */\n if (this.pos + 8 > this.len)\n throw indexOutOfRange(this, 4);\n\n var value = util.float.readDoubleLE(this.buf, this.pos);\n this.pos += 8;\n return value;\n};\n\n/**\n * Reads a sequence of bytes preceeded by its length as a varint.\n * @returns {Uint8Array} Value read\n */\nReader.prototype.bytes = function read_bytes() {\n var length = this.uint32(),\n start = this.pos,\n end = this.pos + length;\n\n /* istanbul ignore if */\n if (end > this.len)\n throw indexOutOfRange(this, length);\n\n this.pos += length;\n if (Array.isArray(this.buf)) // plain array\n return this.buf.slice(start, end);\n\n if (start === end) { // fix for IE 10/Win8 and others' subarray returning array of size 1\n var nativeBuffer = util.Buffer;\n return nativeBuffer\n ? nativeBuffer.alloc(0)\n : new this.buf.constructor(0);\n }\n return this._slice.call(this.buf, start, end);\n};\n\n/**\n * Reads a string preceeded by its byte length as a varint.\n * @returns {string} Value read\n */\nReader.prototype.string = function read_string() {\n var bytes = this.bytes();\n return utf8.read(bytes, 0, bytes.length);\n};\n\n/**\n * Skips the specified number of bytes if specified, otherwise skips a varint.\n * @param {number} [length] Length if known, otherwise a varint is assumed\n * @returns {Reader} `this`\n */\nReader.prototype.skip = function skip(length) {\n if (typeof length === \"number\") {\n /* istanbul ignore if */\n if (this.pos + length > this.len)\n throw indexOutOfRange(this, length);\n this.pos += length;\n } else {\n do {\n /* istanbul ignore if */\n if (this.pos >= this.len)\n throw indexOutOfRange(this);\n } while (this.buf[this.pos++] & 128);\n }\n return this;\n};\n\n/**\n * Skips the next element of the specified wire type.\n * @param {number} wireType Wire type received\n * @returns {Reader} `this`\n */\nReader.prototype.skipType = function(wireType) {\n switch (wireType) {\n case 0:\n this.skip();\n break;\n case 1:\n this.skip(8);\n break;\n case 2:\n this.skip(this.uint32());\n break;\n case 3:\n while ((wireType = this.uint32() & 7) !== 4) {\n this.skipType(wireType);\n }\n break;\n case 5:\n this.skip(4);\n break;\n\n /* istanbul ignore next */\n default:\n throw Error(\"invalid wire type \" + wireType + \" at offset \" + this.pos);\n }\n return this;\n};\n\nReader._configure = function(BufferReader_) {\n BufferReader = BufferReader_;\n Reader.create = create();\n BufferReader._configure();\n\n var fn = util.Long ? \"toLong\" : /* istanbul ignore next */ \"toNumber\";\n util.merge(Reader.prototype, {\n\n int64: function read_int64() {\n return readLongVarint.call(this)[fn](false);\n },\n\n uint64: function read_uint64() {\n return readLongVarint.call(this)[fn](true);\n },\n\n sint64: function read_sint64() {\n return readLongVarint.call(this).zzDecode()[fn](false);\n },\n\n fixed64: function read_fixed64() {\n return readFixed64.call(this)[fn](true);\n },\n\n sfixed64: function read_sfixed64() {\n return readFixed64.call(this)[fn](false);\n }\n\n });\n};\n","\"use strict\";\nmodule.exports = BufferReader;\n\n// extends Reader\nvar Reader = require(24);\n(BufferReader.prototype = Object.create(Reader.prototype)).constructor = BufferReader;\n\nvar util = require(35);\n\n/**\n * Constructs a new buffer reader instance.\n * @classdesc Wire format reader using node buffers.\n * @extends Reader\n * @constructor\n * @param {Buffer} buffer Buffer to read from\n */\nfunction BufferReader(buffer) {\n Reader.call(this, buffer);\n\n /**\n * Read buffer.\n * @name BufferReader#buf\n * @type {Buffer}\n */\n}\n\nBufferReader._configure = function () {\n /* istanbul ignore else */\n if (util.Buffer)\n BufferReader.prototype._slice = util.Buffer.prototype.slice;\n};\n\n\n/**\n * @override\n */\nBufferReader.prototype.string = function read_string_buffer() {\n var len = this.uint32(); // modifies pos\n return this.buf.utf8Slice\n ? this.buf.utf8Slice(this.pos, this.pos = Math.min(this.pos + len, this.len))\n : this.buf.toString(\"utf-8\", this.pos, this.pos = Math.min(this.pos + len, this.len));\n};\n\n/**\n * Reads a sequence of bytes preceeded by its length as a varint.\n * @name BufferReader#bytes\n * @function\n * @returns {Buffer} Value read\n */\n\nBufferReader._configure();\n","\"use strict\";\nmodule.exports = Root;\n\n// extends Namespace\nvar Namespace = require(21);\n((Root.prototype = Object.create(Namespace.prototype)).constructor = Root).className = \"Root\";\n\nvar Field = require(15),\n Enum = require(14),\n OneOf = require(23),\n util = require(33);\n\nvar Type, // cyclic\n parse, // might be excluded\n common; // \"\n\n/**\n * Constructs a new root namespace instance.\n * @classdesc Root namespace wrapping all types, enums, services, sub-namespaces etc. that belong together.\n * @extends NamespaceBase\n * @constructor\n * @param {Object.} [options] Top level options\n */\nfunction Root(options) {\n Namespace.call(this, \"\", options);\n\n /**\n * Deferred extension fields.\n * @type {Field[]}\n */\n this.deferred = [];\n\n /**\n * Resolved file names of loaded files.\n * @type {string[]}\n */\n this.files = [];\n}\n\n/**\n * Loads a namespace descriptor into a root namespace.\n * @param {INamespace} json Nameespace descriptor\n * @param {Root} [root] Root namespace, defaults to create a new one if omitted\n * @returns {Root} Root namespace\n */\nRoot.fromJSON = function fromJSON(json, root) {\n if (!root)\n root = new Root();\n if (json.options)\n root.setOptions(json.options);\n return root.addJSON(json.nested);\n};\n\n/**\n * Resolves the path of an imported file, relative to the importing origin.\n * This method exists so you can override it with your own logic in case your imports are scattered over multiple directories.\n * @function\n * @param {string} origin The file name of the importing file\n * @param {string} target The file name being imported\n * @returns {string|null} Resolved path to `target` or `null` to skip the file\n */\nRoot.prototype.resolvePath = util.path.resolve;\n\n/**\n * Fetch content from file path or url\n * This method exists so you can override it with your own logic.\n * @function\n * @param {string} path File path or url\n * @param {FetchCallback} callback Callback function\n * @returns {undefined}\n */\nRoot.prototype.fetch = util.fetch;\n\n// A symbol-like function to safely signal synchronous loading\n/* istanbul ignore next */\nfunction SYNC() {} // eslint-disable-line no-empty-function\n\n/**\n * Loads one or multiple .proto or preprocessed .json files into this root namespace and calls the callback.\n * @param {string|string[]} filename Names of one or multiple files to load\n * @param {IParseOptions} options Parse options\n * @param {LoadCallback} callback Callback function\n * @returns {undefined}\n */\nRoot.prototype.load = function load(filename, options, callback) {\n if (typeof options === \"function\") {\n callback = options;\n options = undefined;\n }\n var self = this;\n if (!callback)\n return util.asPromise(load, self, filename, options);\n\n var sync = callback === SYNC; // undocumented\n\n // Finishes loading by calling the callback (exactly once)\n function finish(err, root) {\n /* istanbul ignore if */\n if (!callback)\n return;\n if (sync)\n throw err;\n var cb = callback;\n callback = null;\n cb(err, root);\n }\n\n // Bundled definition existence checking\n function getBundledFileName(filename) {\n var idx = filename.lastIndexOf(\"google/protobuf/\");\n if (idx > -1) {\n var altname = filename.substring(idx);\n if (altname in common) return altname;\n }\n return null;\n }\n\n // Processes a single file\n function process(filename, source) {\n try {\n if (util.isString(source) && source.charAt(0) === \"{\")\n source = JSON.parse(source);\n if (!util.isString(source))\n self.setOptions(source.options).addJSON(source.nested);\n else {\n parse.filename = filename;\n var parsed = parse(source, self, options),\n resolved,\n i = 0;\n if (parsed.imports)\n for (; i < parsed.imports.length; ++i)\n if (resolved = getBundledFileName(parsed.imports[i]) || self.resolvePath(filename, parsed.imports[i]))\n fetch(resolved);\n if (parsed.weakImports)\n for (i = 0; i < parsed.weakImports.length; ++i)\n if (resolved = getBundledFileName(parsed.weakImports[i]) || self.resolvePath(filename, parsed.weakImports[i]))\n fetch(resolved, true);\n }\n } catch (err) {\n finish(err);\n }\n if (!sync && !queued)\n finish(null, self); // only once anyway\n }\n\n // Fetches a single file\n function fetch(filename, weak) {\n filename = getBundledFileName(filename) || filename;\n\n // Skip if already loaded / attempted\n if (self.files.indexOf(filename) > -1)\n return;\n self.files.push(filename);\n\n // Shortcut bundled definitions\n if (filename in common) {\n if (sync)\n process(filename, common[filename]);\n else {\n ++queued;\n setTimeout(function() {\n --queued;\n process(filename, common[filename]);\n });\n }\n return;\n }\n\n // Otherwise fetch from disk or network\n if (sync) {\n var source;\n try {\n source = util.fs.readFileSync(filename).toString(\"utf8\");\n } catch (err) {\n if (!weak)\n finish(err);\n return;\n }\n process(filename, source);\n } else {\n ++queued;\n self.fetch(filename, function(err, source) {\n --queued;\n /* istanbul ignore if */\n if (!callback)\n return; // terminated meanwhile\n if (err) {\n /* istanbul ignore else */\n if (!weak)\n finish(err);\n else if (!queued) // can't be covered reliably\n finish(null, self);\n return;\n }\n process(filename, source);\n });\n }\n }\n var queued = 0;\n\n // Assembling the root namespace doesn't require working type\n // references anymore, so we can load everything in parallel\n if (util.isString(filename))\n filename = [ filename ];\n for (var i = 0, resolved; i < filename.length; ++i)\n if (resolved = self.resolvePath(\"\", filename[i]))\n fetch(resolved);\n\n if (sync)\n return self;\n if (!queued)\n finish(null, self);\n return undefined;\n};\n// function load(filename:string, options:IParseOptions, callback:LoadCallback):undefined\n\n/**\n * Loads one or multiple .proto or preprocessed .json files into this root namespace and calls the callback.\n * @function Root#load\n * @param {string|string[]} filename Names of one or multiple files to load\n * @param {LoadCallback} callback Callback function\n * @returns {undefined}\n * @variation 2\n */\n// function load(filename:string, callback:LoadCallback):undefined\n\n/**\n * Loads one or multiple .proto or preprocessed .json files into this root namespace and returns a promise.\n * @function Root#load\n * @param {string|string[]} filename Names of one or multiple files to load\n * @param {IParseOptions} [options] Parse options. Defaults to {@link parse.defaults} when omitted.\n * @returns {Promise} Promise\n * @variation 3\n */\n// function load(filename:string, [options:IParseOptions]):Promise\n\n/**\n * Synchronously loads one or multiple .proto or preprocessed .json files into this root namespace (node only).\n * @function Root#loadSync\n * @param {string|string[]} filename Names of one or multiple files to load\n * @param {IParseOptions} [options] Parse options. Defaults to {@link parse.defaults} when omitted.\n * @returns {Root} Root namespace\n * @throws {Error} If synchronous fetching is not supported (i.e. in browsers) or if a file's syntax is invalid\n */\nRoot.prototype.loadSync = function loadSync(filename, options) {\n if (!util.isNode)\n throw Error(\"not supported\");\n return this.load(filename, options, SYNC);\n};\n\n/**\n * @override\n */\nRoot.prototype.resolveAll = function resolveAll() {\n if (this.deferred.length)\n throw Error(\"unresolvable extensions: \" + this.deferred.map(function(field) {\n return \"'extend \" + field.extend + \"' in \" + field.parent.fullName;\n }).join(\", \"));\n return Namespace.prototype.resolveAll.call(this);\n};\n\n// only uppercased (and thus conflict-free) children are exposed, see below\nvar exposeRe = /^[A-Z]/;\n\n/**\n * Handles a deferred declaring extension field by creating a sister field to represent it within its extended type.\n * @param {Root} root Root instance\n * @param {Field} field Declaring extension field witin the declaring type\n * @returns {boolean} `true` if successfully added to the extended type, `false` otherwise\n * @inner\n * @ignore\n */\nfunction tryHandleExtension(root, field) {\n var extendedType = field.parent.lookup(field.extend);\n if (extendedType) {\n var sisterField = new Field(field.fullName, field.id, field.type, field.rule, undefined, field.options);\n //do not allow to extend same field twice to prevent the error\n if (extendedType.get(sisterField.name)) {\n return true;\n }\n sisterField.declaringField = field;\n field.extensionField = sisterField;\n extendedType.add(sisterField);\n return true;\n }\n return false;\n}\n\n/**\n * Called when any object is added to this root or its sub-namespaces.\n * @param {ReflectionObject} object Object added\n * @returns {undefined}\n * @private\n */\nRoot.prototype._handleAdd = function _handleAdd(object) {\n if (object instanceof Field) {\n\n if (/* an extension field (implies not part of a oneof) */ object.extend !== undefined && /* not already handled */ !object.extensionField)\n if (!tryHandleExtension(this, object))\n this.deferred.push(object);\n\n } else if (object instanceof Enum) {\n\n if (exposeRe.test(object.name))\n object.parent[object.name] = object.values; // expose enum values as property of its parent\n\n } else if (!(object instanceof OneOf)) /* everything else is a namespace */ {\n\n if (object instanceof Type) // Try to handle any deferred extensions\n for (var i = 0; i < this.deferred.length;)\n if (tryHandleExtension(this, this.deferred[i]))\n this.deferred.splice(i, 1);\n else\n ++i;\n for (var j = 0; j < /* initializes */ object.nestedArray.length; ++j) // recurse into the namespace\n this._handleAdd(object._nestedArray[j]);\n if (exposeRe.test(object.name))\n object.parent[object.name] = object; // expose namespace as property of its parent\n }\n\n // The above also adds uppercased (and thus conflict-free) nested types, services and enums as\n // properties of namespaces just like static code does. This allows using a .d.ts generated for\n // a static module with reflection-based solutions where the condition is met.\n};\n\n/**\n * Called when any object is removed from this root or its sub-namespaces.\n * @param {ReflectionObject} object Object removed\n * @returns {undefined}\n * @private\n */\nRoot.prototype._handleRemove = function _handleRemove(object) {\n if (object instanceof Field) {\n\n if (/* an extension field */ object.extend !== undefined) {\n if (/* already handled */ object.extensionField) { // remove its sister field\n object.extensionField.parent.remove(object.extensionField);\n object.extensionField = null;\n } else { // cancel the extension\n var index = this.deferred.indexOf(object);\n /* istanbul ignore else */\n if (index > -1)\n this.deferred.splice(index, 1);\n }\n }\n\n } else if (object instanceof Enum) {\n\n if (exposeRe.test(object.name))\n delete object.parent[object.name]; // unexpose enum values\n\n } else if (object instanceof Namespace) {\n\n for (var i = 0; i < /* initializes */ object.nestedArray.length; ++i) // recurse into the namespace\n this._handleRemove(object._nestedArray[i]);\n\n if (exposeRe.test(object.name))\n delete object.parent[object.name]; // unexpose namespaces\n\n }\n};\n\n// Sets up cyclic dependencies (called in index-light)\nRoot._configure = function(Type_, parse_, common_) {\n Type = Type_;\n parse = parse_;\n common = common_;\n};\n","\"use strict\";\nmodule.exports = {};\n\n/**\n * Named roots.\n * This is where pbjs stores generated structures (the option `-r, --root` specifies a name).\n * Can also be used manually to make roots available across modules.\n * @name roots\n * @type {Object.}\n * @example\n * // pbjs -r myroot -o compiled.js ...\n *\n * // in another module:\n * require(\"./compiled.js\");\n *\n * // in any subsequent module:\n * var root = protobuf.roots[\"myroot\"];\n */\n","\"use strict\";\n\n/**\n * Streaming RPC helpers.\n * @namespace\n */\nvar rpc = exports;\n\n/**\n * RPC implementation passed to {@link Service#create} performing a service request on network level, i.e. by utilizing http requests or websockets.\n * @typedef RPCImpl\n * @type {function}\n * @param {Method|rpc.ServiceMethod,Message<{}>>} method Reflected or static method being called\n * @param {Uint8Array} requestData Request data\n * @param {RPCImplCallback} callback Callback function\n * @returns {undefined}\n * @example\n * function rpcImpl(method, requestData, callback) {\n * if (protobuf.util.lcFirst(method.name) !== \"myMethod\") // compatible with static code\n * throw Error(\"no such method\");\n * asynchronouslyObtainAResponse(requestData, function(err, responseData) {\n * callback(err, responseData);\n * });\n * }\n */\n\n/**\n * Node-style callback as used by {@link RPCImpl}.\n * @typedef RPCImplCallback\n * @type {function}\n * @param {Error|null} error Error, if any, otherwise `null`\n * @param {Uint8Array|null} [response] Response data or `null` to signal end of stream, if there hasn't been an error\n * @returns {undefined}\n */\n\nrpc.Service = require(29);\n","\"use strict\";\nmodule.exports = Service;\n\nvar util = require(35);\n\n// Extends EventEmitter\n(Service.prototype = Object.create(util.EventEmitter.prototype)).constructor = Service;\n\n/**\n * A service method callback as used by {@link rpc.ServiceMethod|ServiceMethod}.\n *\n * Differs from {@link RPCImplCallback} in that it is an actual callback of a service method which may not return `response = null`.\n * @typedef rpc.ServiceMethodCallback\n * @template TRes extends Message\n * @type {function}\n * @param {Error|null} error Error, if any\n * @param {TRes} [response] Response message\n * @returns {undefined}\n */\n\n/**\n * A service method part of a {@link rpc.Service} as created by {@link Service.create}.\n * @typedef rpc.ServiceMethod\n * @template TReq extends Message\n * @template TRes extends Message\n * @type {function}\n * @param {TReq|Properties} request Request message or plain object\n * @param {rpc.ServiceMethodCallback} [callback] Node-style callback called with the error, if any, and the response message\n * @returns {Promise>} Promise if `callback` has been omitted, otherwise `undefined`\n */\n\n/**\n * Constructs a new RPC service instance.\n * @classdesc An RPC service as returned by {@link Service#create}.\n * @exports rpc.Service\n * @extends util.EventEmitter\n * @constructor\n * @param {RPCImpl} rpcImpl RPC implementation\n * @param {boolean} [requestDelimited=false] Whether requests are length-delimited\n * @param {boolean} [responseDelimited=false] Whether responses are length-delimited\n */\nfunction Service(rpcImpl, requestDelimited, responseDelimited) {\n\n if (typeof rpcImpl !== \"function\")\n throw TypeError(\"rpcImpl must be a function\");\n\n util.EventEmitter.call(this);\n\n /**\n * RPC implementation. Becomes `null` once the service is ended.\n * @type {RPCImpl|null}\n */\n this.rpcImpl = rpcImpl;\n\n /**\n * Whether requests are length-delimited.\n * @type {boolean}\n */\n this.requestDelimited = Boolean(requestDelimited);\n\n /**\n * Whether responses are length-delimited.\n * @type {boolean}\n */\n this.responseDelimited = Boolean(responseDelimited);\n}\n\n/**\n * Calls a service method through {@link rpc.Service#rpcImpl|rpcImpl}.\n * @param {Method|rpc.ServiceMethod} method Reflected or static method\n * @param {Constructor} requestCtor Request constructor\n * @param {Constructor} responseCtor Response constructor\n * @param {TReq|Properties} request Request message or plain object\n * @param {rpc.ServiceMethodCallback} callback Service callback\n * @returns {undefined}\n * @template TReq extends Message\n * @template TRes extends Message\n */\nService.prototype.rpcCall = function rpcCall(method, requestCtor, responseCtor, request, callback) {\n\n if (!request)\n throw TypeError(\"request must be specified\");\n\n var self = this;\n if (!callback)\n return util.asPromise(rpcCall, self, method, requestCtor, responseCtor, request);\n\n if (!self.rpcImpl) {\n setTimeout(function() { callback(Error(\"already ended\")); }, 0);\n return undefined;\n }\n\n try {\n return self.rpcImpl(\n method,\n requestCtor[self.requestDelimited ? \"encodeDelimited\" : \"encode\"](request).finish(),\n function rpcCallback(err, response) {\n\n if (err) {\n self.emit(\"error\", err, method);\n return callback(err);\n }\n\n if (response === null) {\n self.end(/* endedByRPC */ true);\n return undefined;\n }\n\n if (!(response instanceof responseCtor)) {\n try {\n response = responseCtor[self.responseDelimited ? \"decodeDelimited\" : \"decode\"](response);\n } catch (err) {\n self.emit(\"error\", err, method);\n return callback(err);\n }\n }\n\n self.emit(\"data\", response, method);\n return callback(null, response);\n }\n );\n } catch (err) {\n self.emit(\"error\", err, method);\n setTimeout(function() { callback(err); }, 0);\n return undefined;\n }\n};\n\n/**\n * Ends this service and emits the `end` event.\n * @param {boolean} [endedByRPC=false] Whether the service has been ended by the RPC implementation.\n * @returns {rpc.Service} `this`\n */\nService.prototype.end = function end(endedByRPC) {\n if (this.rpcImpl) {\n if (!endedByRPC) // signal end to rpcImpl\n this.rpcImpl(null, null, null);\n this.rpcImpl = null;\n this.emit(\"end\").off();\n }\n return this;\n};\n","\"use strict\";\nmodule.exports = Service;\n\n// extends Namespace\nvar Namespace = require(21);\n((Service.prototype = Object.create(Namespace.prototype)).constructor = Service).className = \"Service\";\n\nvar Method = require(20),\n util = require(33),\n rpc = require(28);\n\n/**\n * Constructs a new service instance.\n * @classdesc Reflected service.\n * @extends NamespaceBase\n * @constructor\n * @param {string} name Service name\n * @param {Object.} [options] Service options\n * @throws {TypeError} If arguments are invalid\n */\nfunction Service(name, options) {\n Namespace.call(this, name, options);\n\n /**\n * Service methods.\n * @type {Object.}\n */\n this.methods = {}; // toJSON, marker\n\n /**\n * Cached methods as an array.\n * @type {Method[]|null}\n * @private\n */\n this._methodsArray = null;\n}\n\n/**\n * Service descriptor.\n * @interface IService\n * @extends INamespace\n * @property {Object.} methods Method descriptors\n */\n\n/**\n * Constructs a service from a service descriptor.\n * @param {string} name Service name\n * @param {IService} json Service descriptor\n * @returns {Service} Created service\n * @throws {TypeError} If arguments are invalid\n */\nService.fromJSON = function fromJSON(name, json) {\n var service = new Service(name, json.options);\n /* istanbul ignore else */\n if (json.methods)\n for (var names = Object.keys(json.methods), i = 0; i < names.length; ++i)\n service.add(Method.fromJSON(names[i], json.methods[names[i]]));\n if (json.nested)\n service.addJSON(json.nested);\n service.comment = json.comment;\n return service;\n};\n\n/**\n * Converts this service to a service descriptor.\n * @param {IToJSONOptions} [toJSONOptions] JSON conversion options\n * @returns {IService} Service descriptor\n */\nService.prototype.toJSON = function toJSON(toJSONOptions) {\n var inherited = Namespace.prototype.toJSON.call(this, toJSONOptions);\n var keepComments = toJSONOptions ? Boolean(toJSONOptions.keepComments) : false;\n return util.toObject([\n \"options\" , inherited && inherited.options || undefined,\n \"methods\" , Namespace.arrayToJSON(this.methodsArray, toJSONOptions) || /* istanbul ignore next */ {},\n \"nested\" , inherited && inherited.nested || undefined,\n \"comment\" , keepComments ? this.comment : undefined\n ]);\n};\n\n/**\n * Methods of this service as an array for iteration.\n * @name Service#methodsArray\n * @type {Method[]}\n * @readonly\n */\nObject.defineProperty(Service.prototype, \"methodsArray\", {\n get: function() {\n return this._methodsArray || (this._methodsArray = util.toArray(this.methods));\n }\n});\n\nfunction clearCache(service) {\n service._methodsArray = null;\n return service;\n}\n\n/**\n * @override\n */\nService.prototype.get = function get(name) {\n return this.methods[name]\n || Namespace.prototype.get.call(this, name);\n};\n\n/**\n * @override\n */\nService.prototype.resolveAll = function resolveAll() {\n var methods = this.methodsArray;\n for (var i = 0; i < methods.length; ++i)\n methods[i].resolve();\n return Namespace.prototype.resolve.call(this);\n};\n\n/**\n * @override\n */\nService.prototype.add = function add(object) {\n\n /* istanbul ignore if */\n if (this.get(object.name))\n throw Error(\"duplicate name '\" + object.name + \"' in \" + this);\n\n if (object instanceof Method) {\n this.methods[object.name] = object;\n object.parent = this;\n return clearCache(this);\n }\n return Namespace.prototype.add.call(this, object);\n};\n\n/**\n * @override\n */\nService.prototype.remove = function remove(object) {\n if (object instanceof Method) {\n\n /* istanbul ignore if */\n if (this.methods[object.name] !== object)\n throw Error(object + \" is not a member of \" + this);\n\n delete this.methods[object.name];\n object.parent = null;\n return clearCache(this);\n }\n return Namespace.prototype.remove.call(this, object);\n};\n\n/**\n * Creates a runtime service using the specified rpc implementation.\n * @param {RPCImpl} rpcImpl RPC implementation\n * @param {boolean} [requestDelimited=false] Whether requests are length-delimited\n * @param {boolean} [responseDelimited=false] Whether responses are length-delimited\n * @returns {rpc.Service} RPC service. Useful where requests and/or responses are streamed.\n */\nService.prototype.create = function create(rpcImpl, requestDelimited, responseDelimited) {\n var rpcService = new rpc.Service(rpcImpl, requestDelimited, responseDelimited);\n for (var i = 0, method; i < /* initializes */ this.methodsArray.length; ++i) {\n var methodName = util.lcFirst((method = this._methodsArray[i]).resolve().name).replace(/[^$\\w_]/g, \"\");\n rpcService[methodName] = util.codegen([\"r\",\"c\"], util.isReserved(methodName) ? methodName + \"_\" : methodName)(\"return this.rpcCall(m,q,s,r,c)\")({\n m: method,\n q: method.resolvedRequestType.ctor,\n s: method.resolvedResponseType.ctor\n });\n }\n return rpcService;\n};\n","\"use strict\";\nmodule.exports = Type;\n\n// extends Namespace\nvar Namespace = require(21);\n((Type.prototype = Object.create(Namespace.prototype)).constructor = Type).className = \"Type\";\n\nvar Enum = require(14),\n OneOf = require(23),\n Field = require(15),\n MapField = require(18),\n Service = require(30),\n Message = require(19),\n Reader = require(24),\n Writer = require(38),\n util = require(33),\n encoder = require(13),\n decoder = require(12),\n verifier = require(36),\n converter = require(11),\n wrappers = require(37);\n\n/**\n * Constructs a new reflected message type instance.\n * @classdesc Reflected message type.\n * @extends NamespaceBase\n * @constructor\n * @param {string} name Message name\n * @param {Object.} [options] Declared options\n */\nfunction Type(name, options) {\n Namespace.call(this, name, options);\n\n /**\n * Message fields.\n * @type {Object.}\n */\n this.fields = {}; // toJSON, marker\n\n /**\n * Oneofs declared within this namespace, if any.\n * @type {Object.}\n */\n this.oneofs = undefined; // toJSON\n\n /**\n * Extension ranges, if any.\n * @type {number[][]}\n */\n this.extensions = undefined; // toJSON\n\n /**\n * Reserved ranges, if any.\n * @type {Array.}\n */\n this.reserved = undefined; // toJSON\n\n /*?\n * Whether this type is a legacy group.\n * @type {boolean|undefined}\n */\n this.group = undefined; // toJSON\n\n /**\n * Cached fields by id.\n * @type {Object.|null}\n * @private\n */\n this._fieldsById = null;\n\n /**\n * Cached fields as an array.\n * @type {Field[]|null}\n * @private\n */\n this._fieldsArray = null;\n\n /**\n * Cached oneofs as an array.\n * @type {OneOf[]|null}\n * @private\n */\n this._oneofsArray = null;\n\n /**\n * Cached constructor.\n * @type {Constructor<{}>}\n * @private\n */\n this._ctor = null;\n}\n\nObject.defineProperties(Type.prototype, {\n\n /**\n * Message fields by id.\n * @name Type#fieldsById\n * @type {Object.}\n * @readonly\n */\n fieldsById: {\n get: function() {\n\n /* istanbul ignore if */\n if (this._fieldsById)\n return this._fieldsById;\n\n this._fieldsById = {};\n for (var names = Object.keys(this.fields), i = 0; i < names.length; ++i) {\n var field = this.fields[names[i]],\n id = field.id;\n\n /* istanbul ignore if */\n if (this._fieldsById[id])\n throw Error(\"duplicate id \" + id + \" in \" + this);\n\n this._fieldsById[id] = field;\n }\n return this._fieldsById;\n }\n },\n\n /**\n * Fields of this message as an array for iteration.\n * @name Type#fieldsArray\n * @type {Field[]}\n * @readonly\n */\n fieldsArray: {\n get: function() {\n return this._fieldsArray || (this._fieldsArray = util.toArray(this.fields));\n }\n },\n\n /**\n * Oneofs of this message as an array for iteration.\n * @name Type#oneofsArray\n * @type {OneOf[]}\n * @readonly\n */\n oneofsArray: {\n get: function() {\n return this._oneofsArray || (this._oneofsArray = util.toArray(this.oneofs));\n }\n },\n\n /**\n * The registered constructor, if any registered, otherwise a generic constructor.\n * Assigning a function replaces the internal constructor. If the function does not extend {@link Message} yet, its prototype will be setup accordingly and static methods will be populated. If it already extends {@link Message}, it will just replace the internal constructor.\n * @name Type#ctor\n * @type {Constructor<{}>}\n */\n ctor: {\n get: function() {\n return this._ctor || (this.ctor = Type.generateConstructor(this)());\n },\n set: function(ctor) {\n\n // Ensure proper prototype\n var prototype = ctor.prototype;\n if (!(prototype instanceof Message)) {\n (ctor.prototype = new Message()).constructor = ctor;\n util.merge(ctor.prototype, prototype);\n }\n\n // Classes and messages reference their reflected type\n ctor.$type = ctor.prototype.$type = this;\n\n // Mix in static methods\n util.merge(ctor, Message, true);\n\n this._ctor = ctor;\n\n // Messages have non-enumerable default values on their prototype\n var i = 0;\n for (; i < /* initializes */ this.fieldsArray.length; ++i)\n this._fieldsArray[i].resolve(); // ensures a proper value\n\n // Messages have non-enumerable getters and setters for each virtual oneof field\n var ctorProperties = {};\n for (i = 0; i < /* initializes */ this.oneofsArray.length; ++i)\n ctorProperties[this._oneofsArray[i].resolve().name] = {\n get: util.oneOfGetter(this._oneofsArray[i].oneof),\n set: util.oneOfSetter(this._oneofsArray[i].oneof)\n };\n if (i)\n Object.defineProperties(ctor.prototype, ctorProperties);\n }\n }\n});\n\n/**\n * Generates a constructor function for the specified type.\n * @param {Type} mtype Message type\n * @returns {Codegen} Codegen instance\n */\nType.generateConstructor = function generateConstructor(mtype) {\n /* eslint-disable no-unexpected-multiline */\n var gen = util.codegen([\"p\"], mtype.name);\n // explicitly initialize mutable object/array fields so that these aren't just inherited from the prototype\n for (var i = 0, field; i < mtype.fieldsArray.length; ++i)\n if ((field = mtype._fieldsArray[i]).map) gen\n (\"this%s={}\", util.safeProp(field.name));\n else if (field.repeated) gen\n (\"this%s=[]\", util.safeProp(field.name));\n return gen\n (\"if(p)for(var ks=Object.keys(p),i=0;i} [oneofs] Oneof descriptors\n * @property {Object.} fields Field descriptors\n * @property {number[][]} [extensions] Extension ranges\n * @property {number[][]} [reserved] Reserved ranges\n * @property {boolean} [group=false] Whether a legacy group or not\n */\n\n/**\n * Creates a message type from a message type descriptor.\n * @param {string} name Message name\n * @param {IType} json Message type descriptor\n * @returns {Type} Created message type\n */\nType.fromJSON = function fromJSON(name, json) {\n var type = new Type(name, json.options);\n type.extensions = json.extensions;\n type.reserved = json.reserved;\n var names = Object.keys(json.fields),\n i = 0;\n for (; i < names.length; ++i)\n type.add(\n ( typeof json.fields[names[i]].keyType !== \"undefined\"\n ? MapField.fromJSON\n : Field.fromJSON )(names[i], json.fields[names[i]])\n );\n if (json.oneofs)\n for (names = Object.keys(json.oneofs), i = 0; i < names.length; ++i)\n type.add(OneOf.fromJSON(names[i], json.oneofs[names[i]]));\n if (json.nested)\n for (names = Object.keys(json.nested), i = 0; i < names.length; ++i) {\n var nested = json.nested[names[i]];\n type.add( // most to least likely\n ( nested.id !== undefined\n ? Field.fromJSON\n : nested.fields !== undefined\n ? Type.fromJSON\n : nested.values !== undefined\n ? Enum.fromJSON\n : nested.methods !== undefined\n ? Service.fromJSON\n : Namespace.fromJSON )(names[i], nested)\n );\n }\n if (json.extensions && json.extensions.length)\n type.extensions = json.extensions;\n if (json.reserved && json.reserved.length)\n type.reserved = json.reserved;\n if (json.group)\n type.group = true;\n if (json.comment)\n type.comment = json.comment;\n return type;\n};\n\n/**\n * Converts this message type to a message type descriptor.\n * @param {IToJSONOptions} [toJSONOptions] JSON conversion options\n * @returns {IType} Message type descriptor\n */\nType.prototype.toJSON = function toJSON(toJSONOptions) {\n var inherited = Namespace.prototype.toJSON.call(this, toJSONOptions);\n var keepComments = toJSONOptions ? Boolean(toJSONOptions.keepComments) : false;\n return util.toObject([\n \"options\" , inherited && inherited.options || undefined,\n \"oneofs\" , Namespace.arrayToJSON(this.oneofsArray, toJSONOptions),\n \"fields\" , Namespace.arrayToJSON(this.fieldsArray.filter(function(obj) { return !obj.declaringField; }), toJSONOptions) || {},\n \"extensions\" , this.extensions && this.extensions.length ? this.extensions : undefined,\n \"reserved\" , this.reserved && this.reserved.length ? this.reserved : undefined,\n \"group\" , this.group || undefined,\n \"nested\" , inherited && inherited.nested || undefined,\n \"comment\" , keepComments ? this.comment : undefined\n ]);\n};\n\n/**\n * @override\n */\nType.prototype.resolveAll = function resolveAll() {\n var fields = this.fieldsArray, i = 0;\n while (i < fields.length)\n fields[i++].resolve();\n var oneofs = this.oneofsArray; i = 0;\n while (i < oneofs.length)\n oneofs[i++].resolve();\n return Namespace.prototype.resolveAll.call(this);\n};\n\n/**\n * @override\n */\nType.prototype.get = function get(name) {\n return this.fields[name]\n || this.oneofs && this.oneofs[name]\n || this.nested && this.nested[name]\n || null;\n};\n\n/**\n * Adds a nested object to this type.\n * @param {ReflectionObject} object Nested object to add\n * @returns {Type} `this`\n * @throws {TypeError} If arguments are invalid\n * @throws {Error} If there is already a nested object with this name or, if a field, when there is already a field with this id\n */\nType.prototype.add = function add(object) {\n\n if (this.get(object.name))\n throw Error(\"duplicate name '\" + object.name + \"' in \" + this);\n\n if (object instanceof Field && object.extend === undefined) {\n // NOTE: Extension fields aren't actual fields on the declaring type, but nested objects.\n // The root object takes care of adding distinct sister-fields to the respective extended\n // type instead.\n\n // avoids calling the getter if not absolutely necessary because it's called quite frequently\n if (this._fieldsById ? /* istanbul ignore next */ this._fieldsById[object.id] : this.fieldsById[object.id])\n throw Error(\"duplicate id \" + object.id + \" in \" + this);\n if (this.isReservedId(object.id))\n throw Error(\"id \" + object.id + \" is reserved in \" + this);\n if (this.isReservedName(object.name))\n throw Error(\"name '\" + object.name + \"' is reserved in \" + this);\n\n if (object.parent)\n object.parent.remove(object);\n this.fields[object.name] = object;\n object.message = this;\n object.onAdd(this);\n return clearCache(this);\n }\n if (object instanceof OneOf) {\n if (!this.oneofs)\n this.oneofs = {};\n this.oneofs[object.name] = object;\n object.onAdd(this);\n return clearCache(this);\n }\n return Namespace.prototype.add.call(this, object);\n};\n\n/**\n * Removes a nested object from this type.\n * @param {ReflectionObject} object Nested object to remove\n * @returns {Type} `this`\n * @throws {TypeError} If arguments are invalid\n * @throws {Error} If `object` is not a member of this type\n */\nType.prototype.remove = function remove(object) {\n if (object instanceof Field && object.extend === undefined) {\n // See Type#add for the reason why extension fields are excluded here.\n\n /* istanbul ignore if */\n if (!this.fields || this.fields[object.name] !== object)\n throw Error(object + \" is not a member of \" + this);\n\n delete this.fields[object.name];\n object.parent = null;\n object.onRemove(this);\n return clearCache(this);\n }\n if (object instanceof OneOf) {\n\n /* istanbul ignore if */\n if (!this.oneofs || this.oneofs[object.name] !== object)\n throw Error(object + \" is not a member of \" + this);\n\n delete this.oneofs[object.name];\n object.parent = null;\n object.onRemove(this);\n return clearCache(this);\n }\n return Namespace.prototype.remove.call(this, object);\n};\n\n/**\n * Tests if the specified id is reserved.\n * @param {number} id Id to test\n * @returns {boolean} `true` if reserved, otherwise `false`\n */\nType.prototype.isReservedId = function isReservedId(id) {\n return Namespace.isReservedId(this.reserved, id);\n};\n\n/**\n * Tests if the specified name is reserved.\n * @param {string} name Name to test\n * @returns {boolean} `true` if reserved, otherwise `false`\n */\nType.prototype.isReservedName = function isReservedName(name) {\n return Namespace.isReservedName(this.reserved, name);\n};\n\n/**\n * Creates a new message of this type using the specified properties.\n * @param {Object.} [properties] Properties to set\n * @returns {Message<{}>} Message instance\n */\nType.prototype.create = function create(properties) {\n return new this.ctor(properties);\n};\n\n/**\n * Sets up {@link Type#encode|encode}, {@link Type#decode|decode} and {@link Type#verify|verify}.\n * @returns {Type} `this`\n */\nType.prototype.setup = function setup() {\n // Sets up everything at once so that the prototype chain does not have to be re-evaluated\n // multiple times (V8, soft-deopt prototype-check).\n\n var fullName = this.fullName,\n types = [];\n for (var i = 0; i < /* initializes */ this.fieldsArray.length; ++i)\n types.push(this._fieldsArray[i].resolve().resolvedType);\n\n // Replace setup methods with type-specific generated functions\n this.encode = encoder(this)({\n Writer : Writer,\n types : types,\n util : util\n });\n this.decode = decoder(this)({\n Reader : Reader,\n types : types,\n util : util\n });\n this.verify = verifier(this)({\n types : types,\n util : util\n });\n this.fromObject = converter.fromObject(this)({\n types : types,\n util : util\n });\n this.toObject = converter.toObject(this)({\n types : types,\n util : util\n });\n\n // Inject custom wrappers for common types\n var wrapper = wrappers[fullName];\n if (wrapper) {\n var originalThis = Object.create(this);\n // if (wrapper.fromObject) {\n originalThis.fromObject = this.fromObject;\n this.fromObject = wrapper.fromObject.bind(originalThis);\n // }\n // if (wrapper.toObject) {\n originalThis.toObject = this.toObject;\n this.toObject = wrapper.toObject.bind(originalThis);\n // }\n }\n\n return this;\n};\n\n/**\n * Encodes a message of this type. Does not implicitly {@link Type#verify|verify} messages.\n * @param {Message<{}>|Object.} message Message instance or plain object\n * @param {Writer} [writer] Writer to encode to\n * @returns {Writer} writer\n */\nType.prototype.encode = function encode_setup(message, writer) {\n return this.setup().encode(message, writer); // overrides this method\n};\n\n/**\n * Encodes a message of this type preceeded by its byte length as a varint. Does not implicitly {@link Type#verify|verify} messages.\n * @param {Message<{}>|Object.} message Message instance or plain object\n * @param {Writer} [writer] Writer to encode to\n * @returns {Writer} writer\n */\nType.prototype.encodeDelimited = function encodeDelimited(message, writer) {\n return this.encode(message, writer && writer.len ? writer.fork() : writer).ldelim();\n};\n\n/**\n * Decodes a message of this type.\n * @param {Reader|Uint8Array} reader Reader or buffer to decode from\n * @param {number} [length] Length of the message, if known beforehand\n * @returns {Message<{}>} Decoded message\n * @throws {Error} If the payload is not a reader or valid buffer\n * @throws {util.ProtocolError<{}>} If required fields are missing\n */\nType.prototype.decode = function decode_setup(reader, length) {\n return this.setup().decode(reader, length); // overrides this method\n};\n\n/**\n * Decodes a message of this type preceeded by its byte length as a varint.\n * @param {Reader|Uint8Array} reader Reader or buffer to decode from\n * @returns {Message<{}>} Decoded message\n * @throws {Error} If the payload is not a reader or valid buffer\n * @throws {util.ProtocolError} If required fields are missing\n */\nType.prototype.decodeDelimited = function decodeDelimited(reader) {\n if (!(reader instanceof Reader))\n reader = Reader.create(reader);\n return this.decode(reader, reader.uint32());\n};\n\n/**\n * Verifies that field values are valid and that required fields are present.\n * @param {Object.} message Plain object to verify\n * @returns {null|string} `null` if valid, otherwise the reason why it is not\n */\nType.prototype.verify = function verify_setup(message) {\n return this.setup().verify(message); // overrides this method\n};\n\n/**\n * Creates a new message of this type from a plain object. Also converts values to their respective internal types.\n * @param {Object.} object Plain object to convert\n * @returns {Message<{}>} Message instance\n */\nType.prototype.fromObject = function fromObject(object) {\n return this.setup().fromObject(object);\n};\n\n/**\n * Conversion options as used by {@link Type#toObject} and {@link Message.toObject}.\n * @interface IConversionOptions\n * @property {Function} [longs] Long conversion type.\n * Valid values are `String` and `Number` (the global types).\n * Defaults to copy the present value, which is a possibly unsafe number without and a {@link Long} with a long library.\n * @property {Function} [enums] Enum value conversion type.\n * Only valid value is `String` (the global type).\n * Defaults to copy the present value, which is the numeric id.\n * @property {Function} [bytes] Bytes value conversion type.\n * Valid values are `Array` and (a base64 encoded) `String` (the global types).\n * Defaults to copy the present value, which usually is a Buffer under node and an Uint8Array in the browser.\n * @property {boolean} [defaults=false] Also sets default values on the resulting object\n * @property {boolean} [arrays=false] Sets empty arrays for missing repeated fields even if `defaults=false`\n * @property {boolean} [objects=false] Sets empty objects for missing map fields even if `defaults=false`\n * @property {boolean} [oneofs=false] Includes virtual oneof properties set to the present field's name, if any\n * @property {boolean} [json=false] Performs additional JSON compatibility conversions, i.e. NaN and Infinity to strings\n */\n\n/**\n * Creates a plain object from a message of this type. Also converts values to other types if specified.\n * @param {Message<{}>} message Message instance\n * @param {IConversionOptions} [options] Conversion options\n * @returns {Object.} Plain object\n */\nType.prototype.toObject = function toObject(message, options) {\n return this.setup().toObject(message, options);\n};\n\n/**\n * Decorator function as returned by {@link Type.d} (TypeScript).\n * @typedef TypeDecorator\n * @type {function}\n * @param {Constructor} target Target constructor\n * @returns {undefined}\n * @template T extends Message\n */\n\n/**\n * Type decorator (TypeScript).\n * @param {string} [typeName] Type name, defaults to the constructor's name\n * @returns {TypeDecorator} Decorator function\n * @template T extends Message\n */\nType.d = function decorateType(typeName) {\n return function typeDecorator(target) {\n util.decorateType(target, typeName);\n };\n};\n","\"use strict\";\n\n/**\n * Common type constants.\n * @namespace\n */\nvar types = exports;\n\nvar util = require(33);\n\nvar s = [\n \"double\", // 0\n \"float\", // 1\n \"int32\", // 2\n \"uint32\", // 3\n \"sint32\", // 4\n \"fixed32\", // 5\n \"sfixed32\", // 6\n \"int64\", // 7\n \"uint64\", // 8\n \"sint64\", // 9\n \"fixed64\", // 10\n \"sfixed64\", // 11\n \"bool\", // 12\n \"string\", // 13\n \"bytes\" // 14\n];\n\nfunction bake(values, offset) {\n var i = 0, o = {};\n offset |= 0;\n while (i < values.length) o[s[i + offset]] = values[i++];\n return o;\n}\n\n/**\n * Basic type wire types.\n * @type {Object.}\n * @const\n * @property {number} double=1 Fixed64 wire type\n * @property {number} float=5 Fixed32 wire type\n * @property {number} int32=0 Varint wire type\n * @property {number} uint32=0 Varint wire type\n * @property {number} sint32=0 Varint wire type\n * @property {number} fixed32=5 Fixed32 wire type\n * @property {number} sfixed32=5 Fixed32 wire type\n * @property {number} int64=0 Varint wire type\n * @property {number} uint64=0 Varint wire type\n * @property {number} sint64=0 Varint wire type\n * @property {number} fixed64=1 Fixed64 wire type\n * @property {number} sfixed64=1 Fixed64 wire type\n * @property {number} bool=0 Varint wire type\n * @property {number} string=2 Ldelim wire type\n * @property {number} bytes=2 Ldelim wire type\n */\ntypes.basic = bake([\n /* double */ 1,\n /* float */ 5,\n /* int32 */ 0,\n /* uint32 */ 0,\n /* sint32 */ 0,\n /* fixed32 */ 5,\n /* sfixed32 */ 5,\n /* int64 */ 0,\n /* uint64 */ 0,\n /* sint64 */ 0,\n /* fixed64 */ 1,\n /* sfixed64 */ 1,\n /* bool */ 0,\n /* string */ 2,\n /* bytes */ 2\n]);\n\n/**\n * Basic type defaults.\n * @type {Object.}\n * @const\n * @property {number} double=0 Double default\n * @property {number} float=0 Float default\n * @property {number} int32=0 Int32 default\n * @property {number} uint32=0 Uint32 default\n * @property {number} sint32=0 Sint32 default\n * @property {number} fixed32=0 Fixed32 default\n * @property {number} sfixed32=0 Sfixed32 default\n * @property {number} int64=0 Int64 default\n * @property {number} uint64=0 Uint64 default\n * @property {number} sint64=0 Sint32 default\n * @property {number} fixed64=0 Fixed64 default\n * @property {number} sfixed64=0 Sfixed64 default\n * @property {boolean} bool=false Bool default\n * @property {string} string=\"\" String default\n * @property {Array.} bytes=Array(0) Bytes default\n * @property {null} message=null Message default\n */\ntypes.defaults = bake([\n /* double */ 0,\n /* float */ 0,\n /* int32 */ 0,\n /* uint32 */ 0,\n /* sint32 */ 0,\n /* fixed32 */ 0,\n /* sfixed32 */ 0,\n /* int64 */ 0,\n /* uint64 */ 0,\n /* sint64 */ 0,\n /* fixed64 */ 0,\n /* sfixed64 */ 0,\n /* bool */ false,\n /* string */ \"\",\n /* bytes */ util.emptyArray,\n /* message */ null\n]);\n\n/**\n * Basic long type wire types.\n * @type {Object.}\n * @const\n * @property {number} int64=0 Varint wire type\n * @property {number} uint64=0 Varint wire type\n * @property {number} sint64=0 Varint wire type\n * @property {number} fixed64=1 Fixed64 wire type\n * @property {number} sfixed64=1 Fixed64 wire type\n */\ntypes.long = bake([\n /* int64 */ 0,\n /* uint64 */ 0,\n /* sint64 */ 0,\n /* fixed64 */ 1,\n /* sfixed64 */ 1\n], 7);\n\n/**\n * Allowed types for map keys with their associated wire type.\n * @type {Object.}\n * @const\n * @property {number} int32=0 Varint wire type\n * @property {number} uint32=0 Varint wire type\n * @property {number} sint32=0 Varint wire type\n * @property {number} fixed32=5 Fixed32 wire type\n * @property {number} sfixed32=5 Fixed32 wire type\n * @property {number} int64=0 Varint wire type\n * @property {number} uint64=0 Varint wire type\n * @property {number} sint64=0 Varint wire type\n * @property {number} fixed64=1 Fixed64 wire type\n * @property {number} sfixed64=1 Fixed64 wire type\n * @property {number} bool=0 Varint wire type\n * @property {number} string=2 Ldelim wire type\n */\ntypes.mapKey = bake([\n /* int32 */ 0,\n /* uint32 */ 0,\n /* sint32 */ 0,\n /* fixed32 */ 5,\n /* sfixed32 */ 5,\n /* int64 */ 0,\n /* uint64 */ 0,\n /* sint64 */ 0,\n /* fixed64 */ 1,\n /* sfixed64 */ 1,\n /* bool */ 0,\n /* string */ 2\n], 2);\n\n/**\n * Allowed types for packed repeated fields with their associated wire type.\n * @type {Object.}\n * @const\n * @property {number} double=1 Fixed64 wire type\n * @property {number} float=5 Fixed32 wire type\n * @property {number} int32=0 Varint wire type\n * @property {number} uint32=0 Varint wire type\n * @property {number} sint32=0 Varint wire type\n * @property {number} fixed32=5 Fixed32 wire type\n * @property {number} sfixed32=5 Fixed32 wire type\n * @property {number} int64=0 Varint wire type\n * @property {number} uint64=0 Varint wire type\n * @property {number} sint64=0 Varint wire type\n * @property {number} fixed64=1 Fixed64 wire type\n * @property {number} sfixed64=1 Fixed64 wire type\n * @property {number} bool=0 Varint wire type\n */\ntypes.packed = bake([\n /* double */ 1,\n /* float */ 5,\n /* int32 */ 0,\n /* uint32 */ 0,\n /* sint32 */ 0,\n /* fixed32 */ 5,\n /* sfixed32 */ 5,\n /* int64 */ 0,\n /* uint64 */ 0,\n /* sint64 */ 0,\n /* fixed64 */ 1,\n /* sfixed64 */ 1,\n /* bool */ 0\n]);\n","\"use strict\";\n\n/**\n * Various utility functions.\n * @namespace\n */\nvar util = module.exports = require(35);\n\nvar roots = require(27);\n\nvar Type, // cyclic\n Enum;\n\nutil.codegen = require(3);\nutil.fetch = require(5);\nutil.path = require(8);\n\n/**\n * Node's fs module if available.\n * @type {Object.}\n */\nutil.fs = util.inquire(\"fs\");\n\n/**\n * Converts an object's values to an array.\n * @param {Object.} object Object to convert\n * @returns {Array.<*>} Converted array\n */\nutil.toArray = function toArray(object) {\n if (object) {\n var keys = Object.keys(object),\n array = new Array(keys.length),\n index = 0;\n while (index < keys.length)\n array[index] = object[keys[index++]];\n return array;\n }\n return [];\n};\n\n/**\n * Converts an array of keys immediately followed by their respective value to an object, omitting undefined values.\n * @param {Array.<*>} array Array to convert\n * @returns {Object.} Converted object\n */\nutil.toObject = function toObject(array) {\n var object = {},\n index = 0;\n while (index < array.length) {\n var key = array[index++],\n val = array[index++];\n if (val !== undefined)\n object[key] = val;\n }\n return object;\n};\n\nvar safePropBackslashRe = /\\\\/g,\n safePropQuoteRe = /\"/g;\n\n/**\n * Tests whether the specified name is a reserved word in JS.\n * @param {string} name Name to test\n * @returns {boolean} `true` if reserved, otherwise `false`\n */\nutil.isReserved = function isReserved(name) {\n return /^(?:do|if|in|for|let|new|try|var|case|else|enum|eval|false|null|this|true|void|with|break|catch|class|const|super|throw|while|yield|delete|export|import|public|return|static|switch|typeof|default|extends|finally|package|private|continue|debugger|function|arguments|interface|protected|implements|instanceof)$/.test(name);\n};\n\n/**\n * Returns a safe property accessor for the specified property name.\n * @param {string} prop Property name\n * @returns {string} Safe accessor\n */\nutil.safeProp = function safeProp(prop) {\n if (!/^[$\\w_]+$/.test(prop) || util.isReserved(prop))\n return \"[\\\"\" + prop.replace(safePropBackslashRe, \"\\\\\\\\\").replace(safePropQuoteRe, \"\\\\\\\"\") + \"\\\"]\";\n return \".\" + prop;\n};\n\n/**\n * Converts the first character of a string to upper case.\n * @param {string} str String to convert\n * @returns {string} Converted string\n */\nutil.ucFirst = function ucFirst(str) {\n return str.charAt(0).toUpperCase() + str.substring(1);\n};\n\nvar camelCaseRe = /_([a-z])/g;\n\n/**\n * Converts a string to camel case.\n * @param {string} str String to convert\n * @returns {string} Converted string\n */\nutil.camelCase = function camelCase(str) {\n return str.substring(0, 1)\n + str.substring(1)\n .replace(camelCaseRe, function($0, $1) { return $1.toUpperCase(); });\n};\n\n/**\n * Compares reflected fields by id.\n * @param {Field} a First field\n * @param {Field} b Second field\n * @returns {number} Comparison value\n */\nutil.compareFieldsById = function compareFieldsById(a, b) {\n return a.id - b.id;\n};\n\n/**\n * Decorator helper for types (TypeScript).\n * @param {Constructor} ctor Constructor function\n * @param {string} [typeName] Type name, defaults to the constructor's name\n * @returns {Type} Reflected type\n * @template T extends Message\n * @property {Root} root Decorators root\n */\nutil.decorateType = function decorateType(ctor, typeName) {\n\n /* istanbul ignore if */\n if (ctor.$type) {\n if (typeName && ctor.$type.name !== typeName) {\n util.decorateRoot.remove(ctor.$type);\n ctor.$type.name = typeName;\n util.decorateRoot.add(ctor.$type);\n }\n return ctor.$type;\n }\n\n /* istanbul ignore next */\n if (!Type)\n Type = require(31);\n\n var type = new Type(typeName || ctor.name);\n util.decorateRoot.add(type);\n type.ctor = ctor; // sets up .encode, .decode etc.\n Object.defineProperty(ctor, \"$type\", { value: type, enumerable: false });\n Object.defineProperty(ctor.prototype, \"$type\", { value: type, enumerable: false });\n return type;\n};\n\nvar decorateEnumIndex = 0;\n\n/**\n * Decorator helper for enums (TypeScript).\n * @param {Object} object Enum object\n * @returns {Enum} Reflected enum\n */\nutil.decorateEnum = function decorateEnum(object) {\n\n /* istanbul ignore if */\n if (object.$type)\n return object.$type;\n\n /* istanbul ignore next */\n if (!Enum)\n Enum = require(14);\n\n var enm = new Enum(\"Enum\" + decorateEnumIndex++, object);\n util.decorateRoot.add(enm);\n Object.defineProperty(object, \"$type\", { value: enm, enumerable: false });\n return enm;\n};\n\n\n/**\n * Sets the value of a property by property path. If a value already exists, it is turned to an array\n * @param {Object.} dst Destination object\n * @param {string} path dot '.' delimited path of the property to set\n * @param {Object} value the value to set\n * @returns {Object.} Destination object\n */\nutil.setProperty = function setProperty(dst, path, value) {\n function setProp(dst, path, value) {\n var part = path.shift();\n if (part === \"__proto__\" || part === \"prototype\") {\n return dst;\n }\n if (path.length > 0) {\n dst[part] = setProp(dst[part] || {}, path, value);\n } else {\n var prevValue = dst[part];\n if (prevValue)\n value = [].concat(prevValue).concat(value);\n dst[part] = value;\n }\n return dst;\n }\n\n if (typeof dst !== \"object\")\n throw TypeError(\"dst must be an object\");\n if (!path)\n throw TypeError(\"path must be specified\");\n\n path = path.split(\".\");\n return setProp(dst, path, value);\n};\n\n/**\n * Decorator root (TypeScript).\n * @name util.decorateRoot\n * @type {Root}\n * @readonly\n */\nObject.defineProperty(util, \"decorateRoot\", {\n get: function() {\n return roots[\"decorated\"] || (roots[\"decorated\"] = new (require(26))());\n }\n});\n","\"use strict\";\nmodule.exports = LongBits;\n\nvar util = require(35);\n\n/**\n * Constructs new long bits.\n * @classdesc Helper class for working with the low and high bits of a 64 bit value.\n * @memberof util\n * @constructor\n * @param {number} lo Low 32 bits, unsigned\n * @param {number} hi High 32 bits, unsigned\n */\nfunction LongBits(lo, hi) {\n\n // note that the casts below are theoretically unnecessary as of today, but older statically\n // generated converter code might still call the ctor with signed 32bits. kept for compat.\n\n /**\n * Low bits.\n * @type {number}\n */\n this.lo = lo >>> 0;\n\n /**\n * High bits.\n * @type {number}\n */\n this.hi = hi >>> 0;\n}\n\n/**\n * Zero bits.\n * @memberof util.LongBits\n * @type {util.LongBits}\n */\nvar zero = LongBits.zero = new LongBits(0, 0);\n\nzero.toNumber = function() { return 0; };\nzero.zzEncode = zero.zzDecode = function() { return this; };\nzero.length = function() { return 1; };\n\n/**\n * Zero hash.\n * @memberof util.LongBits\n * @type {string}\n */\nvar zeroHash = LongBits.zeroHash = \"\\0\\0\\0\\0\\0\\0\\0\\0\";\n\n/**\n * Constructs new long bits from the specified number.\n * @param {number} value Value\n * @returns {util.LongBits} Instance\n */\nLongBits.fromNumber = function fromNumber(value) {\n if (value === 0)\n return zero;\n var sign = value < 0;\n if (sign)\n value = -value;\n var lo = value >>> 0,\n hi = (value - lo) / 4294967296 >>> 0;\n if (sign) {\n hi = ~hi >>> 0;\n lo = ~lo >>> 0;\n if (++lo > 4294967295) {\n lo = 0;\n if (++hi > 4294967295)\n hi = 0;\n }\n }\n return new LongBits(lo, hi);\n};\n\n/**\n * Constructs new long bits from a number, long or string.\n * @param {Long|number|string} value Value\n * @returns {util.LongBits} Instance\n */\nLongBits.from = function from(value) {\n if (typeof value === \"number\")\n return LongBits.fromNumber(value);\n if (util.isString(value)) {\n /* istanbul ignore else */\n if (util.Long)\n value = util.Long.fromString(value);\n else\n return LongBits.fromNumber(parseInt(value, 10));\n }\n return value.low || value.high ? new LongBits(value.low >>> 0, value.high >>> 0) : zero;\n};\n\n/**\n * Converts this long bits to a possibly unsafe JavaScript number.\n * @param {boolean} [unsigned=false] Whether unsigned or not\n * @returns {number} Possibly unsafe number\n */\nLongBits.prototype.toNumber = function toNumber(unsigned) {\n if (!unsigned && this.hi >>> 31) {\n var lo = ~this.lo + 1 >>> 0,\n hi = ~this.hi >>> 0;\n if (!lo)\n hi = hi + 1 >>> 0;\n return -(lo + hi * 4294967296);\n }\n return this.lo + this.hi * 4294967296;\n};\n\n/**\n * Converts this long bits to a long.\n * @param {boolean} [unsigned=false] Whether unsigned or not\n * @returns {Long} Long\n */\nLongBits.prototype.toLong = function toLong(unsigned) {\n return util.Long\n ? new util.Long(this.lo | 0, this.hi | 0, Boolean(unsigned))\n /* istanbul ignore next */\n : { low: this.lo | 0, high: this.hi | 0, unsigned: Boolean(unsigned) };\n};\n\nvar charCodeAt = String.prototype.charCodeAt;\n\n/**\n * Constructs new long bits from the specified 8 characters long hash.\n * @param {string} hash Hash\n * @returns {util.LongBits} Bits\n */\nLongBits.fromHash = function fromHash(hash) {\n if (hash === zeroHash)\n return zero;\n return new LongBits(\n ( charCodeAt.call(hash, 0)\n | charCodeAt.call(hash, 1) << 8\n | charCodeAt.call(hash, 2) << 16\n | charCodeAt.call(hash, 3) << 24) >>> 0\n ,\n ( charCodeAt.call(hash, 4)\n | charCodeAt.call(hash, 5) << 8\n | charCodeAt.call(hash, 6) << 16\n | charCodeAt.call(hash, 7) << 24) >>> 0\n );\n};\n\n/**\n * Converts this long bits to a 8 characters long hash.\n * @returns {string} Hash\n */\nLongBits.prototype.toHash = function toHash() {\n return String.fromCharCode(\n this.lo & 255,\n this.lo >>> 8 & 255,\n this.lo >>> 16 & 255,\n this.lo >>> 24 ,\n this.hi & 255,\n this.hi >>> 8 & 255,\n this.hi >>> 16 & 255,\n this.hi >>> 24\n );\n};\n\n/**\n * Zig-zag encodes this long bits.\n * @returns {util.LongBits} `this`\n */\nLongBits.prototype.zzEncode = function zzEncode() {\n var mask = this.hi >> 31;\n this.hi = ((this.hi << 1 | this.lo >>> 31) ^ mask) >>> 0;\n this.lo = ( this.lo << 1 ^ mask) >>> 0;\n return this;\n};\n\n/**\n * Zig-zag decodes this long bits.\n * @returns {util.LongBits} `this`\n */\nLongBits.prototype.zzDecode = function zzDecode() {\n var mask = -(this.lo & 1);\n this.lo = ((this.lo >>> 1 | this.hi << 31) ^ mask) >>> 0;\n this.hi = ( this.hi >>> 1 ^ mask) >>> 0;\n return this;\n};\n\n/**\n * Calculates the length of this longbits when encoded as a varint.\n * @returns {number} Length\n */\nLongBits.prototype.length = function length() {\n var part0 = this.lo,\n part1 = (this.lo >>> 28 | this.hi << 4) >>> 0,\n part2 = this.hi >>> 24;\n return part2 === 0\n ? part1 === 0\n ? part0 < 16384\n ? part0 < 128 ? 1 : 2\n : part0 < 2097152 ? 3 : 4\n : part1 < 16384\n ? part1 < 128 ? 5 : 6\n : part1 < 2097152 ? 7 : 8\n : part2 < 128 ? 9 : 10;\n};\n","\"use strict\";\nvar util = exports;\n\n// used to return a Promise where callback is omitted\nutil.asPromise = require(1);\n\n// converts to / from base64 encoded strings\nutil.base64 = require(2);\n\n// base class of rpc.Service\nutil.EventEmitter = require(4);\n\n// float handling accross browsers\nutil.float = require(6);\n\n// requires modules optionally and hides the call from bundlers\nutil.inquire = require(7);\n\n// converts to / from utf8 encoded strings\nutil.utf8 = require(10);\n\n// provides a node-like buffer pool in the browser\nutil.pool = require(9);\n\n// utility to work with the low and high bits of a 64 bit value\nutil.LongBits = require(34);\n\n/**\n * Whether running within node or not.\n * @memberof util\n * @type {boolean}\n */\nutil.isNode = Boolean(typeof global !== \"undefined\"\n && global\n && global.process\n && global.process.versions\n && global.process.versions.node);\n\n/**\n * Global object reference.\n * @memberof util\n * @type {Object}\n */\nutil.global = util.isNode && global\n || typeof window !== \"undefined\" && window\n || typeof self !== \"undefined\" && self\n || this; // eslint-disable-line no-invalid-this\n\n/**\n * An immuable empty array.\n * @memberof util\n * @type {Array.<*>}\n * @const\n */\nutil.emptyArray = Object.freeze ? Object.freeze([]) : /* istanbul ignore next */ []; // used on prototypes\n\n/**\n * An immutable empty object.\n * @type {Object}\n * @const\n */\nutil.emptyObject = Object.freeze ? Object.freeze({}) : /* istanbul ignore next */ {}; // used on prototypes\n\n/**\n * Tests if the specified value is an integer.\n * @function\n * @param {*} value Value to test\n * @returns {boolean} `true` if the value is an integer\n */\nutil.isInteger = Number.isInteger || /* istanbul ignore next */ function isInteger(value) {\n return typeof value === \"number\" && isFinite(value) && Math.floor(value) === value;\n};\n\n/**\n * Tests if the specified value is a string.\n * @param {*} value Value to test\n * @returns {boolean} `true` if the value is a string\n */\nutil.isString = function isString(value) {\n return typeof value === \"string\" || value instanceof String;\n};\n\n/**\n * Tests if the specified value is a non-null object.\n * @param {*} value Value to test\n * @returns {boolean} `true` if the value is a non-null object\n */\nutil.isObject = function isObject(value) {\n return value && typeof value === \"object\";\n};\n\n/**\n * Checks if a property on a message is considered to be present.\n * This is an alias of {@link util.isSet}.\n * @function\n * @param {Object} obj Plain object or message instance\n * @param {string} prop Property name\n * @returns {boolean} `true` if considered to be present, otherwise `false`\n */\nutil.isset =\n\n/**\n * Checks if a property on a message is considered to be present.\n * @param {Object} obj Plain object or message instance\n * @param {string} prop Property name\n * @returns {boolean} `true` if considered to be present, otherwise `false`\n */\nutil.isSet = function isSet(obj, prop) {\n var value = obj[prop];\n if (value != null && obj.hasOwnProperty(prop)) // eslint-disable-line eqeqeq, no-prototype-builtins\n return typeof value !== \"object\" || (Array.isArray(value) ? value.length : Object.keys(value).length) > 0;\n return false;\n};\n\n/**\n * Any compatible Buffer instance.\n * This is a minimal stand-alone definition of a Buffer instance. The actual type is that exported by node's typings.\n * @interface Buffer\n * @extends Uint8Array\n */\n\n/**\n * Node's Buffer class if available.\n * @type {Constructor}\n */\nutil.Buffer = (function() {\n try {\n var Buffer = util.inquire(\"buffer\").Buffer;\n // refuse to use non-node buffers if not explicitly assigned (perf reasons):\n return Buffer.prototype.utf8Write ? Buffer : /* istanbul ignore next */ null;\n } catch (e) {\n /* istanbul ignore next */\n return null;\n }\n})();\n\n// Internal alias of or polyfull for Buffer.from.\nutil._Buffer_from = null;\n\n// Internal alias of or polyfill for Buffer.allocUnsafe.\nutil._Buffer_allocUnsafe = null;\n\n/**\n * Creates a new buffer of whatever type supported by the environment.\n * @param {number|number[]} [sizeOrArray=0] Buffer size or number array\n * @returns {Uint8Array|Buffer} Buffer\n */\nutil.newBuffer = function newBuffer(sizeOrArray) {\n /* istanbul ignore next */\n return typeof sizeOrArray === \"number\"\n ? util.Buffer\n ? util._Buffer_allocUnsafe(sizeOrArray)\n : new util.Array(sizeOrArray)\n : util.Buffer\n ? util._Buffer_from(sizeOrArray)\n : typeof Uint8Array === \"undefined\"\n ? sizeOrArray\n : new Uint8Array(sizeOrArray);\n};\n\n/**\n * Array implementation used in the browser. `Uint8Array` if supported, otherwise `Array`.\n * @type {Constructor}\n */\nutil.Array = typeof Uint8Array !== \"undefined\" ? Uint8Array /* istanbul ignore next */ : Array;\n\n/**\n * Any compatible Long instance.\n * This is a minimal stand-alone definition of a Long instance. The actual type is that exported by long.js.\n * @interface Long\n * @property {number} low Low bits\n * @property {number} high High bits\n * @property {boolean} unsigned Whether unsigned or not\n */\n\n/**\n * Long.js's Long class if available.\n * @type {Constructor}\n */\nutil.Long = /* istanbul ignore next */ util.global.dcodeIO && /* istanbul ignore next */ util.global.dcodeIO.Long\n || /* istanbul ignore next */ util.global.Long\n || util.inquire(\"long\");\n\n/**\n * Regular expression used to verify 2 bit (`bool`) map keys.\n * @type {RegExp}\n * @const\n */\nutil.key2Re = /^true|false|0|1$/;\n\n/**\n * Regular expression used to verify 32 bit (`int32` etc.) map keys.\n * @type {RegExp}\n * @const\n */\nutil.key32Re = /^-?(?:0|[1-9][0-9]*)$/;\n\n/**\n * Regular expression used to verify 64 bit (`int64` etc.) map keys.\n * @type {RegExp}\n * @const\n */\nutil.key64Re = /^(?:[\\\\x00-\\\\xff]{8}|-?(?:0|[1-9][0-9]*))$/;\n\n/**\n * Converts a number or long to an 8 characters long hash string.\n * @param {Long|number} value Value to convert\n * @returns {string} Hash\n */\nutil.longToHash = function longToHash(value) {\n return value\n ? util.LongBits.from(value).toHash()\n : util.LongBits.zeroHash;\n};\n\n/**\n * Converts an 8 characters long hash string to a long or number.\n * @param {string} hash Hash\n * @param {boolean} [unsigned=false] Whether unsigned or not\n * @returns {Long|number} Original value\n */\nutil.longFromHash = function longFromHash(hash, unsigned) {\n var bits = util.LongBits.fromHash(hash);\n if (util.Long)\n return util.Long.fromBits(bits.lo, bits.hi, unsigned);\n return bits.toNumber(Boolean(unsigned));\n};\n\n/**\n * Merges the properties of the source object into the destination object.\n * @memberof util\n * @param {Object.} dst Destination object\n * @param {Object.} src Source object\n * @param {boolean} [ifNotSet=false] Merges only if the key is not already set\n * @returns {Object.} Destination object\n */\nfunction merge(dst, src, ifNotSet) { // used by converters\n for (var keys = Object.keys(src), i = 0; i < keys.length; ++i)\n if (dst[keys[i]] === undefined || !ifNotSet)\n dst[keys[i]] = src[keys[i]];\n return dst;\n}\n\nutil.merge = merge;\n\n/**\n * Converts the first character of a string to lower case.\n * @param {string} str String to convert\n * @returns {string} Converted string\n */\nutil.lcFirst = function lcFirst(str) {\n return str.charAt(0).toLowerCase() + str.substring(1);\n};\n\n/**\n * Creates a custom error constructor.\n * @memberof util\n * @param {string} name Error name\n * @returns {Constructor} Custom error constructor\n */\nfunction newError(name) {\n\n function CustomError(message, properties) {\n\n if (!(this instanceof CustomError))\n return new CustomError(message, properties);\n\n // Error.call(this, message);\n // ^ just returns a new error instance because the ctor can be called as a function\n\n Object.defineProperty(this, \"message\", { get: function() { return message; } });\n\n /* istanbul ignore next */\n if (Error.captureStackTrace) // node\n Error.captureStackTrace(this, CustomError);\n else\n Object.defineProperty(this, \"stack\", { value: new Error().stack || \"\" });\n\n if (properties)\n merge(this, properties);\n }\n\n CustomError.prototype = Object.create(Error.prototype, {\n constructor: {\n value: CustomError,\n writable: true,\n enumerable: false,\n configurable: true,\n },\n name: {\n get: function get() { return name; },\n set: undefined,\n enumerable: false,\n // configurable: false would accurately preserve the behavior of\n // the original, but I'm guessing that was not intentional.\n // For an actual error subclass, this property would\n // be configurable.\n configurable: true,\n },\n toString: {\n value: function value() { return this.name + \": \" + this.message; },\n writable: true,\n enumerable: false,\n configurable: true,\n },\n });\n\n return CustomError;\n}\n\nutil.newError = newError;\n\n/**\n * Constructs a new protocol error.\n * @classdesc Error subclass indicating a protocol specifc error.\n * @memberof util\n * @extends Error\n * @template T extends Message\n * @constructor\n * @param {string} message Error message\n * @param {Object.} [properties] Additional properties\n * @example\n * try {\n * MyMessage.decode(someBuffer); // throws if required fields are missing\n * } catch (e) {\n * if (e instanceof ProtocolError && e.instance)\n * console.log(\"decoded so far: \" + JSON.stringify(e.instance));\n * }\n */\nutil.ProtocolError = newError(\"ProtocolError\");\n\n/**\n * So far decoded message instance.\n * @name util.ProtocolError#instance\n * @type {Message}\n */\n\n/**\n * A OneOf getter as returned by {@link util.oneOfGetter}.\n * @typedef OneOfGetter\n * @type {function}\n * @returns {string|undefined} Set field name, if any\n */\n\n/**\n * Builds a getter for a oneof's present field name.\n * @param {string[]} fieldNames Field names\n * @returns {OneOfGetter} Unbound getter\n */\nutil.oneOfGetter = function getOneOf(fieldNames) {\n var fieldMap = {};\n for (var i = 0; i < fieldNames.length; ++i)\n fieldMap[fieldNames[i]] = 1;\n\n /**\n * @returns {string|undefined} Set field name, if any\n * @this Object\n * @ignore\n */\n return function() { // eslint-disable-line consistent-return\n for (var keys = Object.keys(this), i = keys.length - 1; i > -1; --i)\n if (fieldMap[keys[i]] === 1 && this[keys[i]] !== undefined && this[keys[i]] !== null)\n return keys[i];\n };\n};\n\n/**\n * A OneOf setter as returned by {@link util.oneOfSetter}.\n * @typedef OneOfSetter\n * @type {function}\n * @param {string|undefined} value Field name\n * @returns {undefined}\n */\n\n/**\n * Builds a setter for a oneof's present field name.\n * @param {string[]} fieldNames Field names\n * @returns {OneOfSetter} Unbound setter\n */\nutil.oneOfSetter = function setOneOf(fieldNames) {\n\n /**\n * @param {string} name Field name\n * @returns {undefined}\n * @this Object\n * @ignore\n */\n return function(name) {\n for (var i = 0; i < fieldNames.length; ++i)\n if (fieldNames[i] !== name)\n delete this[fieldNames[i]];\n };\n};\n\n/**\n * Default conversion options used for {@link Message#toJSON} implementations.\n *\n * These options are close to proto3's JSON mapping with the exception that internal types like Any are handled just like messages. More precisely:\n *\n * - Longs become strings\n * - Enums become string keys\n * - Bytes become base64 encoded strings\n * - (Sub-)Messages become plain objects\n * - Maps become plain objects with all string keys\n * - Repeated fields become arrays\n * - NaN and Infinity for float and double fields become strings\n *\n * @type {IConversionOptions}\n * @see https://developers.google.com/protocol-buffers/docs/proto3?hl=en#json\n */\nutil.toJSONOptions = {\n longs: String,\n enums: String,\n bytes: String,\n json: true\n};\n\n// Sets up buffer utility according to the environment (called in index-minimal)\nutil._configure = function() {\n var Buffer = util.Buffer;\n /* istanbul ignore if */\n if (!Buffer) {\n util._Buffer_from = util._Buffer_allocUnsafe = null;\n return;\n }\n // because node 4.x buffers are incompatible & immutable\n // see: https://github.com/dcodeIO/protobuf.js/pull/665\n util._Buffer_from = Buffer.from !== Uint8Array.from && Buffer.from ||\n /* istanbul ignore next */\n function Buffer_from(value, encoding) {\n return new Buffer(value, encoding);\n };\n util._Buffer_allocUnsafe = Buffer.allocUnsafe ||\n /* istanbul ignore next */\n function Buffer_allocUnsafe(size) {\n return new Buffer(size);\n };\n};\n","\"use strict\";\nmodule.exports = verifier;\n\nvar Enum = require(14),\n util = require(33);\n\nfunction invalid(field, expected) {\n return field.name + \": \" + expected + (field.repeated && expected !== \"array\" ? \"[]\" : field.map && expected !== \"object\" ? \"{k:\"+field.keyType+\"}\" : \"\") + \" expected\";\n}\n\n/**\n * Generates a partial value verifier.\n * @param {Codegen} gen Codegen instance\n * @param {Field} field Reflected field\n * @param {number} fieldIndex Field index\n * @param {string} ref Variable reference\n * @returns {Codegen} Codegen instance\n * @ignore\n */\nfunction genVerifyValue(gen, field, fieldIndex, ref) {\n /* eslint-disable no-unexpected-multiline */\n if (field.resolvedType) {\n if (field.resolvedType instanceof Enum) { gen\n (\"switch(%s){\", ref)\n (\"default:\")\n (\"return%j\", invalid(field, \"enum value\"));\n for (var keys = Object.keys(field.resolvedType.values), j = 0; j < keys.length; ++j) gen\n (\"case %i:\", field.resolvedType.values[keys[j]]);\n gen\n (\"break\")\n (\"}\");\n } else {\n gen\n (\"{\")\n (\"var e=types[%i].verify(%s);\", fieldIndex, ref)\n (\"if(e)\")\n (\"return%j+e\", field.name + \".\")\n (\"}\");\n }\n } else {\n switch (field.type) {\n case \"int32\":\n case \"uint32\":\n case \"sint32\":\n case \"fixed32\":\n case \"sfixed32\": gen\n (\"if(!util.isInteger(%s))\", ref)\n (\"return%j\", invalid(field, \"integer\"));\n break;\n case \"int64\":\n case \"uint64\":\n case \"sint64\":\n case \"fixed64\":\n case \"sfixed64\": gen\n (\"if(!util.isInteger(%s)&&!(%s&&util.isInteger(%s.low)&&util.isInteger(%s.high)))\", ref, ref, ref, ref)\n (\"return%j\", invalid(field, \"integer|Long\"));\n break;\n case \"float\":\n case \"double\": gen\n (\"if(typeof %s!==\\\"number\\\")\", ref)\n (\"return%j\", invalid(field, \"number\"));\n break;\n case \"bool\": gen\n (\"if(typeof %s!==\\\"boolean\\\")\", ref)\n (\"return%j\", invalid(field, \"boolean\"));\n break;\n case \"string\": gen\n (\"if(!util.isString(%s))\", ref)\n (\"return%j\", invalid(field, \"string\"));\n break;\n case \"bytes\": gen\n (\"if(!(%s&&typeof %s.length===\\\"number\\\"||util.isString(%s)))\", ref, ref, ref)\n (\"return%j\", invalid(field, \"buffer\"));\n break;\n }\n }\n return gen;\n /* eslint-enable no-unexpected-multiline */\n}\n\n/**\n * Generates a partial key verifier.\n * @param {Codegen} gen Codegen instance\n * @param {Field} field Reflected field\n * @param {string} ref Variable reference\n * @returns {Codegen} Codegen instance\n * @ignore\n */\nfunction genVerifyKey(gen, field, ref) {\n /* eslint-disable no-unexpected-multiline */\n switch (field.keyType) {\n case \"int32\":\n case \"uint32\":\n case \"sint32\":\n case \"fixed32\":\n case \"sfixed32\": gen\n (\"if(!util.key32Re.test(%s))\", ref)\n (\"return%j\", invalid(field, \"integer key\"));\n break;\n case \"int64\":\n case \"uint64\":\n case \"sint64\":\n case \"fixed64\":\n case \"sfixed64\": gen\n (\"if(!util.key64Re.test(%s))\", ref) // see comment above: x is ok, d is not\n (\"return%j\", invalid(field, \"integer|Long key\"));\n break;\n case \"bool\": gen\n (\"if(!util.key2Re.test(%s))\", ref)\n (\"return%j\", invalid(field, \"boolean key\"));\n break;\n }\n return gen;\n /* eslint-enable no-unexpected-multiline */\n}\n\n/**\n * Generates a verifier specific to the specified message type.\n * @param {Type} mtype Message type\n * @returns {Codegen} Codegen instance\n */\nfunction verifier(mtype) {\n /* eslint-disable no-unexpected-multiline */\n\n var gen = util.codegen([\"m\"], mtype.name + \"$verify\")\n (\"if(typeof m!==\\\"object\\\"||m===null)\")\n (\"return%j\", \"object expected\");\n var oneofs = mtype.oneofsArray,\n seenFirstField = {};\n if (oneofs.length) gen\n (\"var p={}\");\n\n for (var i = 0; i < /* initializes */ mtype.fieldsArray.length; ++i) {\n var field = mtype._fieldsArray[i].resolve(),\n ref = \"m\" + util.safeProp(field.name);\n\n if (field.optional) gen\n (\"if(%s!=null&&m.hasOwnProperty(%j)){\", ref, field.name); // !== undefined && !== null\n\n // map fields\n if (field.map) { gen\n (\"if(!util.isObject(%s))\", ref)\n (\"return%j\", invalid(field, \"object\"))\n (\"var k=Object.keys(%s)\", ref)\n (\"for(var i=0;i}\n * @const\n */\nvar wrappers = exports;\n\nvar Message = require(19);\n\n/**\n * From object converter part of an {@link IWrapper}.\n * @typedef WrapperFromObjectConverter\n * @type {function}\n * @param {Object.} object Plain object\n * @returns {Message<{}>} Message instance\n * @this Type\n */\n\n/**\n * To object converter part of an {@link IWrapper}.\n * @typedef WrapperToObjectConverter\n * @type {function}\n * @param {Message<{}>} message Message instance\n * @param {IConversionOptions} [options] Conversion options\n * @returns {Object.} Plain object\n * @this Type\n */\n\n/**\n * Common type wrapper part of {@link wrappers}.\n * @interface IWrapper\n * @property {WrapperFromObjectConverter} [fromObject] From object converter\n * @property {WrapperToObjectConverter} [toObject] To object converter\n */\n\n// Custom wrapper for Any\nwrappers[\".google.protobuf.Any\"] = {\n\n fromObject: function(object) {\n\n // unwrap value type if mapped\n if (object && object[\"@type\"]) {\n // Only use fully qualified type name after the last '/'\n var name = object[\"@type\"].substring(object[\"@type\"].lastIndexOf(\"/\") + 1);\n var type = this.lookup(name);\n /* istanbul ignore else */\n if (type) {\n // type_url does not accept leading \".\"\n var type_url = object[\"@type\"].charAt(0) === \".\" ?\n object[\"@type\"].slice(1) : object[\"@type\"];\n // type_url prefix is optional, but path seperator is required\n if (type_url.indexOf(\"/\") === -1) {\n type_url = \"/\" + type_url;\n }\n return this.create({\n type_url: type_url,\n value: type.encode(type.fromObject(object)).finish()\n });\n }\n }\n\n return this.fromObject(object);\n },\n\n toObject: function(message, options) {\n\n // Default prefix\n var googleApi = \"type.googleapis.com/\";\n var prefix = \"\";\n var name = \"\";\n\n // decode value if requested and unmapped\n if (options && options.json && message.type_url && message.value) {\n // Only use fully qualified type name after the last '/'\n name = message.type_url.substring(message.type_url.lastIndexOf(\"/\") + 1);\n // Separate the prefix used\n prefix = message.type_url.substring(0, message.type_url.lastIndexOf(\"/\") + 1);\n var type = this.lookup(name);\n /* istanbul ignore else */\n if (type)\n message = type.decode(message.value);\n }\n\n // wrap value if unmapped\n if (!(message instanceof this.ctor) && message instanceof Message) {\n var object = message.$type.toObject(message, options);\n var messageName = message.$type.fullName[0] === \".\" ?\n message.$type.fullName.slice(1) : message.$type.fullName;\n // Default to type.googleapis.com prefix if no prefix is used\n if (prefix === \"\") {\n prefix = googleApi;\n }\n name = prefix + messageName;\n object[\"@type\"] = name;\n return object;\n }\n\n return this.toObject(message, options);\n }\n};\n","\"use strict\";\nmodule.exports = Writer;\n\nvar util = require(35);\n\nvar BufferWriter; // cyclic\n\nvar LongBits = util.LongBits,\n base64 = util.base64,\n utf8 = util.utf8;\n\n/**\n * Constructs a new writer operation instance.\n * @classdesc Scheduled writer operation.\n * @constructor\n * @param {function(*, Uint8Array, number)} fn Function to call\n * @param {number} len Value byte length\n * @param {*} val Value to write\n * @ignore\n */\nfunction Op(fn, len, val) {\n\n /**\n * Function to call.\n * @type {function(Uint8Array, number, *)}\n */\n this.fn = fn;\n\n /**\n * Value byte length.\n * @type {number}\n */\n this.len = len;\n\n /**\n * Next operation.\n * @type {Writer.Op|undefined}\n */\n this.next = undefined;\n\n /**\n * Value to write.\n * @type {*}\n */\n this.val = val; // type varies\n}\n\n/* istanbul ignore next */\nfunction noop() {} // eslint-disable-line no-empty-function\n\n/**\n * Constructs a new writer state instance.\n * @classdesc Copied writer state.\n * @memberof Writer\n * @constructor\n * @param {Writer} writer Writer to copy state from\n * @ignore\n */\nfunction State(writer) {\n\n /**\n * Current head.\n * @type {Writer.Op}\n */\n this.head = writer.head;\n\n /**\n * Current tail.\n * @type {Writer.Op}\n */\n this.tail = writer.tail;\n\n /**\n * Current buffer length.\n * @type {number}\n */\n this.len = writer.len;\n\n /**\n * Next state.\n * @type {State|null}\n */\n this.next = writer.states;\n}\n\n/**\n * Constructs a new writer instance.\n * @classdesc Wire format writer using `Uint8Array` if available, otherwise `Array`.\n * @constructor\n */\nfunction Writer() {\n\n /**\n * Current length.\n * @type {number}\n */\n this.len = 0;\n\n /**\n * Operations head.\n * @type {Object}\n */\n this.head = new Op(noop, 0, 0);\n\n /**\n * Operations tail\n * @type {Object}\n */\n this.tail = this.head;\n\n /**\n * Linked forked states.\n * @type {Object|null}\n */\n this.states = null;\n\n // When a value is written, the writer calculates its byte length and puts it into a linked\n // list of operations to perform when finish() is called. This both allows us to allocate\n // buffers of the exact required size and reduces the amount of work we have to do compared\n // to first calculating over objects and then encoding over objects. In our case, the encoding\n // part is just a linked list walk calling operations with already prepared values.\n}\n\nvar create = function create() {\n return util.Buffer\n ? function create_buffer_setup() {\n return (Writer.create = function create_buffer() {\n return new BufferWriter();\n })();\n }\n /* istanbul ignore next */\n : function create_array() {\n return new Writer();\n };\n};\n\n/**\n * Creates a new writer.\n * @function\n * @returns {BufferWriter|Writer} A {@link BufferWriter} when Buffers are supported, otherwise a {@link Writer}\n */\nWriter.create = create();\n\n/**\n * Allocates a buffer of the specified size.\n * @param {number} size Buffer size\n * @returns {Uint8Array} Buffer\n */\nWriter.alloc = function alloc(size) {\n return new util.Array(size);\n};\n\n// Use Uint8Array buffer pool in the browser, just like node does with buffers\n/* istanbul ignore else */\nif (util.Array !== Array)\n Writer.alloc = util.pool(Writer.alloc, util.Array.prototype.subarray);\n\n/**\n * Pushes a new operation to the queue.\n * @param {function(Uint8Array, number, *)} fn Function to call\n * @param {number} len Value byte length\n * @param {number} val Value to write\n * @returns {Writer} `this`\n * @private\n */\nWriter.prototype._push = function push(fn, len, val) {\n this.tail = this.tail.next = new Op(fn, len, val);\n this.len += len;\n return this;\n};\n\nfunction writeByte(val, buf, pos) {\n buf[pos] = val & 255;\n}\n\nfunction writeVarint32(val, buf, pos) {\n while (val > 127) {\n buf[pos++] = val & 127 | 128;\n val >>>= 7;\n }\n buf[pos] = val;\n}\n\n/**\n * Constructs a new varint writer operation instance.\n * @classdesc Scheduled varint writer operation.\n * @extends Op\n * @constructor\n * @param {number} len Value byte length\n * @param {number} val Value to write\n * @ignore\n */\nfunction VarintOp(len, val) {\n this.len = len;\n this.next = undefined;\n this.val = val;\n}\n\nVarintOp.prototype = Object.create(Op.prototype);\nVarintOp.prototype.fn = writeVarint32;\n\n/**\n * Writes an unsigned 32 bit value as a varint.\n * @param {number} value Value to write\n * @returns {Writer} `this`\n */\nWriter.prototype.uint32 = function write_uint32(value) {\n // here, the call to this.push has been inlined and a varint specific Op subclass is used.\n // uint32 is by far the most frequently used operation and benefits significantly from this.\n this.len += (this.tail = this.tail.next = new VarintOp(\n (value = value >>> 0)\n < 128 ? 1\n : value < 16384 ? 2\n : value < 2097152 ? 3\n : value < 268435456 ? 4\n : 5,\n value)).len;\n return this;\n};\n\n/**\n * Writes a signed 32 bit value as a varint.\n * @function\n * @param {number} value Value to write\n * @returns {Writer} `this`\n */\nWriter.prototype.int32 = function write_int32(value) {\n return value < 0\n ? this._push(writeVarint64, 10, LongBits.fromNumber(value)) // 10 bytes per spec\n : this.uint32(value);\n};\n\n/**\n * Writes a 32 bit value as a varint, zig-zag encoded.\n * @param {number} value Value to write\n * @returns {Writer} `this`\n */\nWriter.prototype.sint32 = function write_sint32(value) {\n return this.uint32((value << 1 ^ value >> 31) >>> 0);\n};\n\nfunction writeVarint64(val, buf, pos) {\n while (val.hi) {\n buf[pos++] = val.lo & 127 | 128;\n val.lo = (val.lo >>> 7 | val.hi << 25) >>> 0;\n val.hi >>>= 7;\n }\n while (val.lo > 127) {\n buf[pos++] = val.lo & 127 | 128;\n val.lo = val.lo >>> 7;\n }\n buf[pos++] = val.lo;\n}\n\n/**\n * Writes an unsigned 64 bit value as a varint.\n * @param {Long|number|string} value Value to write\n * @returns {Writer} `this`\n * @throws {TypeError} If `value` is a string and no long library is present.\n */\nWriter.prototype.uint64 = function write_uint64(value) {\n var bits = LongBits.from(value);\n return this._push(writeVarint64, bits.length(), bits);\n};\n\n/**\n * Writes a signed 64 bit value as a varint.\n * @function\n * @param {Long|number|string} value Value to write\n * @returns {Writer} `this`\n * @throws {TypeError} If `value` is a string and no long library is present.\n */\nWriter.prototype.int64 = Writer.prototype.uint64;\n\n/**\n * Writes a signed 64 bit value as a varint, zig-zag encoded.\n * @param {Long|number|string} value Value to write\n * @returns {Writer} `this`\n * @throws {TypeError} If `value` is a string and no long library is present.\n */\nWriter.prototype.sint64 = function write_sint64(value) {\n var bits = LongBits.from(value).zzEncode();\n return this._push(writeVarint64, bits.length(), bits);\n};\n\n/**\n * Writes a boolish value as a varint.\n * @param {boolean} value Value to write\n * @returns {Writer} `this`\n */\nWriter.prototype.bool = function write_bool(value) {\n return this._push(writeByte, 1, value ? 1 : 0);\n};\n\nfunction writeFixed32(val, buf, pos) {\n buf[pos ] = val & 255;\n buf[pos + 1] = val >>> 8 & 255;\n buf[pos + 2] = val >>> 16 & 255;\n buf[pos + 3] = val >>> 24;\n}\n\n/**\n * Writes an unsigned 32 bit value as fixed 32 bits.\n * @param {number} value Value to write\n * @returns {Writer} `this`\n */\nWriter.prototype.fixed32 = function write_fixed32(value) {\n return this._push(writeFixed32, 4, value >>> 0);\n};\n\n/**\n * Writes a signed 32 bit value as fixed 32 bits.\n * @function\n * @param {number} value Value to write\n * @returns {Writer} `this`\n */\nWriter.prototype.sfixed32 = Writer.prototype.fixed32;\n\n/**\n * Writes an unsigned 64 bit value as fixed 64 bits.\n * @param {Long|number|string} value Value to write\n * @returns {Writer} `this`\n * @throws {TypeError} If `value` is a string and no long library is present.\n */\nWriter.prototype.fixed64 = function write_fixed64(value) {\n var bits = LongBits.from(value);\n return this._push(writeFixed32, 4, bits.lo)._push(writeFixed32, 4, bits.hi);\n};\n\n/**\n * Writes a signed 64 bit value as fixed 64 bits.\n * @function\n * @param {Long|number|string} value Value to write\n * @returns {Writer} `this`\n * @throws {TypeError} If `value` is a string and no long library is present.\n */\nWriter.prototype.sfixed64 = Writer.prototype.fixed64;\n\n/**\n * Writes a float (32 bit).\n * @function\n * @param {number} value Value to write\n * @returns {Writer} `this`\n */\nWriter.prototype.float = function write_float(value) {\n return this._push(util.float.writeFloatLE, 4, value);\n};\n\n/**\n * Writes a double (64 bit float).\n * @function\n * @param {number} value Value to write\n * @returns {Writer} `this`\n */\nWriter.prototype.double = function write_double(value) {\n return this._push(util.float.writeDoubleLE, 8, value);\n};\n\nvar writeBytes = util.Array.prototype.set\n ? function writeBytes_set(val, buf, pos) {\n buf.set(val, pos); // also works for plain array values\n }\n /* istanbul ignore next */\n : function writeBytes_for(val, buf, pos) {\n for (var i = 0; i < val.length; ++i)\n buf[pos + i] = val[i];\n };\n\n/**\n * Writes a sequence of bytes.\n * @param {Uint8Array|string} value Buffer or base64 encoded string to write\n * @returns {Writer} `this`\n */\nWriter.prototype.bytes = function write_bytes(value) {\n var len = value.length >>> 0;\n if (!len)\n return this._push(writeByte, 1, 0);\n if (util.isString(value)) {\n var buf = Writer.alloc(len = base64.length(value));\n base64.decode(value, buf, 0);\n value = buf;\n }\n return this.uint32(len)._push(writeBytes, len, value);\n};\n\n/**\n * Writes a string.\n * @param {string} value Value to write\n * @returns {Writer} `this`\n */\nWriter.prototype.string = function write_string(value) {\n var len = utf8.length(value);\n return len\n ? this.uint32(len)._push(utf8.write, len, value)\n : this._push(writeByte, 1, 0);\n};\n\n/**\n * Forks this writer's state by pushing it to a stack.\n * Calling {@link Writer#reset|reset} or {@link Writer#ldelim|ldelim} resets the writer to the previous state.\n * @returns {Writer} `this`\n */\nWriter.prototype.fork = function fork() {\n this.states = new State(this);\n this.head = this.tail = new Op(noop, 0, 0);\n this.len = 0;\n return this;\n};\n\n/**\n * Resets this instance to the last state.\n * @returns {Writer} `this`\n */\nWriter.prototype.reset = function reset() {\n if (this.states) {\n this.head = this.states.head;\n this.tail = this.states.tail;\n this.len = this.states.len;\n this.states = this.states.next;\n } else {\n this.head = this.tail = new Op(noop, 0, 0);\n this.len = 0;\n }\n return this;\n};\n\n/**\n * Resets to the last state and appends the fork state's current write length as a varint followed by its operations.\n * @returns {Writer} `this`\n */\nWriter.prototype.ldelim = function ldelim() {\n var head = this.head,\n tail = this.tail,\n len = this.len;\n this.reset().uint32(len);\n if (len) {\n this.tail.next = head.next; // skip noop\n this.tail = tail;\n this.len += len;\n }\n return this;\n};\n\n/**\n * Finishes the write operation.\n * @returns {Uint8Array} Finished buffer\n */\nWriter.prototype.finish = function finish() {\n var head = this.head.next, // skip noop\n buf = this.constructor.alloc(this.len),\n pos = 0;\n while (head) {\n head.fn(head.val, buf, pos);\n pos += head.len;\n head = head.next;\n }\n // this.head = this.tail = null;\n return buf;\n};\n\nWriter._configure = function(BufferWriter_) {\n BufferWriter = BufferWriter_;\n Writer.create = create();\n BufferWriter._configure();\n};\n","\"use strict\";\nmodule.exports = BufferWriter;\n\n// extends Writer\nvar Writer = require(38);\n(BufferWriter.prototype = Object.create(Writer.prototype)).constructor = BufferWriter;\n\nvar util = require(35);\n\n/**\n * Constructs a new buffer writer instance.\n * @classdesc Wire format writer using node buffers.\n * @extends Writer\n * @constructor\n */\nfunction BufferWriter() {\n Writer.call(this);\n}\n\nBufferWriter._configure = function () {\n /**\n * Allocates a buffer of the specified size.\n * @function\n * @param {number} size Buffer size\n * @returns {Buffer} Buffer\n */\n BufferWriter.alloc = util._Buffer_allocUnsafe;\n\n BufferWriter.writeBytesBuffer = util.Buffer && util.Buffer.prototype instanceof Uint8Array && util.Buffer.prototype.set.name === \"set\"\n ? function writeBytesBuffer_set(val, buf, pos) {\n buf.set(val, pos); // faster than copy (requires node >= 4 where Buffers extend Uint8Array and set is properly inherited)\n // also works for plain array values\n }\n /* istanbul ignore next */\n : function writeBytesBuffer_copy(val, buf, pos) {\n if (val.copy) // Buffer values\n val.copy(buf, pos, 0, val.length);\n else for (var i = 0; i < val.length;) // plain array values\n buf[pos++] = val[i++];\n };\n};\n\n\n/**\n * @override\n */\nBufferWriter.prototype.bytes = function write_bytes_buffer(value) {\n if (util.isString(value))\n value = util._Buffer_from(value, \"base64\");\n var len = value.length >>> 0;\n this.uint32(len);\n if (len)\n this._push(BufferWriter.writeBytesBuffer, len, value);\n return this;\n};\n\nfunction writeStringBuffer(val, buf, pos) {\n if (val.length < 40) // plain js is faster for short strings (probably due to redundant assertions)\n util.utf8.write(val, buf, pos);\n else if (buf.utf8Write)\n buf.utf8Write(val, pos);\n else\n buf.write(val, pos);\n}\n\n/**\n * @override\n */\nBufferWriter.prototype.string = function write_string_buffer(value) {\n var len = util.Buffer.byteLength(value);\n this.uint32(len);\n if (len)\n this._push(writeStringBuffer, len, value);\n return this;\n};\n\n\n/**\n * Finishes the write operation.\n * @name BufferWriter#finish\n * @function\n * @returns {Buffer} Finished buffer\n */\n\nBufferWriter._configure();\n"],"sourceRoot":"."} \ No newline at end of file diff --git a/node_modules/protobufjs/dist/light/protobuf.min.js b/node_modules/protobufjs/dist/light/protobuf.min.js new file mode 100644 index 0000000..2980e55 --- /dev/null +++ b/node_modules/protobufjs/dist/light/protobuf.min.js @@ -0,0 +1,8 @@ +/*! + * protobuf.js v7.3.0 (c) 2016, daniel wirtz + * compiled fri, 10 may 2024 03:38:35 utc + * licensed under the bsd-3-clause license + * see: https://github.com/dcodeio/protobuf.js for details + */ +!function(g){"use strict";!function(r,e,t){var i=function t(i){var n=e[i];return n||r[i][0].call(n=e[i]={exports:{}},t,n,n.exports),n.exports}(t[0]);i.util.global.protobuf=i,"function"==typeof define&&define.amd&&define(["long"],function(t){return t&&t.isLong&&(i.util.Long=t,i.configure()),i}),"object"==typeof module&&module&&module.exports&&(module.exports=i)}({1:[function(t,i,n){i.exports=function(t,i){var n=Array(arguments.length-1),s=0,r=2,u=!0;for(;r>2],r=(3&h)<<4,o=1;break;case 1:s[u++]=f[r|h>>4],r=(15&h)<<2,o=2;break;case 2:s[u++]=f[r|h>>6],s[u++]=f[63&h],o=0}8191>4,r=o,s=2;break;case 2:i[n++]=(15&r)<<4|(60&o)>>2,r=o,s=3;break;case 3:i[n++]=(3&r)<<6|o,s=0}}if(1===s)throw Error(c);return n-e},n.test=function(t){return/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(t)}},{}],3:[function(t,i,n){function a(i,n){"string"==typeof i&&(n=i,i=g);var h=[];function f(t){if("string"!=typeof t){var i=c();if(a.verbose&&console.log("codegen: "+i),i="return "+i,t){for(var n=Object.keys(t),r=Array(n.length+1),e=Array(n.length),s=0;s>>0:i<11754943508222875e-54?(e<<31|Math.round(i/1401298464324817e-60))>>>0:(e<<31|127+(t=Math.floor(Math.log(i)/Math.LN2))<<23|8388607&Math.round(i*Math.pow(2,-t)*8388608))>>>0,n,r)}function n(t,i,n){t=t(i,n),i=2*(t>>31)+1,n=t>>>23&255,t&=8388607;return 255==n?t?NaN:1/0*i:0==n?1401298464324817e-60*i*t:i*Math.pow(2,n-150)*(8388608+t)}function r(t,i,n){o[0]=t,i[n]=h[0],i[n+1]=h[1],i[n+2]=h[2],i[n+3]=h[3]}function e(t,i,n){o[0]=t,i[n]=h[3],i[n+1]=h[2],i[n+2]=h[1],i[n+3]=h[0]}function s(t,i){return h[0]=t[i],h[1]=t[i+1],h[2]=t[i+2],h[3]=t[i+3],o[0]}function u(t,i){return h[3]=t[i],h[2]=t[i+1],h[1]=t[i+2],h[0]=t[i+3],o[0]}var o,h,f,c,a;function l(t,i,n,r,e,s){var u,o=r<0?1:0;0===(r=o?-r:r)?(t(0,e,s+i),t(0<1/r?0:2147483648,e,s+n)):isNaN(r)?(t(0,e,s+i),t(2146959360,e,s+n)):17976931348623157e292>>0,e,s+n)):r<22250738585072014e-324?(t((u=r/5e-324)>>>0,e,s+i),t((o<<31|u/4294967296)>>>0,e,s+n)):(t(4503599627370496*(u=r*Math.pow(2,-(r=1024===(r=Math.floor(Math.log(r)/Math.LN2))?1023:r)))>>>0,e,s+i),t((o<<31|r+1023<<20|1048576*u&1048575)>>>0,e,s+n))}function d(t,i,n,r,e){i=t(r,e+i),t=t(r,e+n),r=2*(t>>31)+1,e=t>>>20&2047,n=4294967296*(1048575&t)+i;return 2047==e?n?NaN:1/0*r:0==e?5e-324*r*n:r*Math.pow(2,e-1075)*(n+4503599627370496)}function v(t,i,n){f[0]=t,i[n]=c[0],i[n+1]=c[1],i[n+2]=c[2],i[n+3]=c[3],i[n+4]=c[4],i[n+5]=c[5],i[n+6]=c[6],i[n+7]=c[7]}function b(t,i,n){f[0]=t,i[n]=c[7],i[n+1]=c[6],i[n+2]=c[5],i[n+3]=c[4],i[n+4]=c[3],i[n+5]=c[2],i[n+6]=c[1],i[n+7]=c[0]}function p(t,i){return c[0]=t[i],c[1]=t[i+1],c[2]=t[i+2],c[3]=t[i+3],c[4]=t[i+4],c[5]=t[i+5],c[6]=t[i+6],c[7]=t[i+7],f[0]}function y(t,i){return c[7]=t[i],c[6]=t[i+1],c[5]=t[i+2],c[4]=t[i+3],c[3]=t[i+4],c[2]=t[i+5],c[1]=t[i+6],c[0]=t[i+7],f[0]}return"undefined"!=typeof Float32Array?(o=new Float32Array([-0]),h=new Uint8Array(o.buffer),a=128===h[3],t.writeFloatLE=a?r:e,t.writeFloatBE=a?e:r,t.readFloatLE=a?s:u,t.readFloatBE=a?u:s):(t.writeFloatLE=i.bind(null,m),t.writeFloatBE=i.bind(null,w),t.readFloatLE=n.bind(null,g),t.readFloatBE=n.bind(null,j)),"undefined"!=typeof Float64Array?(f=new Float64Array([-0]),c=new Uint8Array(f.buffer),a=128===c[7],t.writeDoubleLE=a?v:b,t.writeDoubleBE=a?b:v,t.readDoubleLE=a?p:y,t.readDoubleBE=a?y:p):(t.writeDoubleLE=l.bind(null,m,0,4),t.writeDoubleBE=l.bind(null,w,4,0),t.readDoubleLE=d.bind(null,g,0,4),t.readDoubleBE=d.bind(null,j,4,0)),t}function m(t,i,n){i[n]=255&t,i[n+1]=t>>>8&255,i[n+2]=t>>>16&255,i[n+3]=t>>>24}function w(t,i,n){i[n]=t>>>24,i[n+1]=t>>>16&255,i[n+2]=t>>>8&255,i[n+3]=255&t}function g(t,i){return(t[i]|t[i+1]<<8|t[i+2]<<16|t[i+3]<<24)>>>0}function j(t,i){return(t[i]<<24|t[i+1]<<16|t[i+2]<<8|t[i+3])>>>0}i.exports=r(r)},{}],7:[function(t,i,n){function r(t){try{var i=eval("require")(t);if(i&&(i.length||Object.keys(i).length))return i}catch(t){}return null}i.exports=r},{}],8:[function(t,i,n){var e=n.isAbsolute=function(t){return/^(?:\/|\w+:)/.test(t)},r=n.normalize=function(t){var i=(t=t.replace(/\\/g,"/").replace(/\/{2,}/g,"/")).split("/"),n=e(t),t="";n&&(t=i.shift()+"/");for(var r=0;r>>1,s=null,u=r;return function(t){if(t<1||e>10),s[u++]=56320+(1023&r)):s[u++]=(15&r)<<12|(63&t[i++])<<6|63&t[i++],8191>6|192:(55296==(64512&r)&&56320==(64512&(e=t.charCodeAt(u+1)))?(++u,i[n++]=(r=65536+((1023&r)<<10)+(1023&e))>>18|240,i[n++]=r>>12&63|128):i[n++]=r>>12|224,i[n++]=r>>6&63|128),i[n++]=63&r|128);return n-s}},{}],11:[function(t,i,n){var l=t(14),d=t(33);function u(t,i,n,r){var e=!1;if(i.resolvedType)if(i.resolvedType instanceof l){t("switch(d%s){",r);for(var s=i.resolvedType.values,u=Object.keys(s),o=0;o>>0",r,r);break;case"int32":case"sint32":case"sfixed32":t("m%s=d%s|0",r,r);break;case"uint64":h=!0;case"int64":case"sint64":case"fixed64":case"sfixed64":t("if(util.Long)")("(m%s=util.Long.fromValue(d%s)).unsigned=%j",r,r,h)('else if(typeof d%s==="string")',r)("m%s=parseInt(d%s,10)",r,r)('else if(typeof d%s==="number")',r)("m%s=d%s",r,r)('else if(typeof d%s==="object")',r)("m%s=new util.LongBits(d%s.low>>>0,d%s.high>>>0).toNumber(%s)",r,r,r,h?"true":"");break;case"bytes":t('if(typeof d%s==="string")',r)("util.base64.decode(d%s,m%s=util.newBuffer(util.base64.length(d%s)),0)",r,r,r)("else if(d%s.length >= 0)",r)("m%s=d%s",r,r);break;case"string":t("m%s=String(d%s)",r,r);break;case"bool":t("m%s=Boolean(d%s)",r,r)}}return t}function v(t,i,n,r){if(i.resolvedType)i.resolvedType instanceof l?t("d%s=o.enums===String?(types[%i].values[m%s]===undefined?m%s:types[%i].values[m%s]):m%s",r,n,r,r,n,r,r):t("d%s=types[%i].toObject(m%s,o)",r,n,r);else{var e=!1;switch(i.type){case"double":case"float":t("d%s=o.json&&!isFinite(m%s)?String(m%s):m%s",r,r,r,r);break;case"uint64":e=!0;case"int64":case"sint64":case"fixed64":case"sfixed64":t('if(typeof m%s==="number")',r)("d%s=o.longs===String?String(m%s):m%s",r,r,r)("else")("d%s=o.longs===String?util.Long.prototype.toString.call(m%s):o.longs===Number?new util.LongBits(m%s.low>>>0,m%s.high>>>0).toNumber(%s):m%s",r,r,r,r,e?"true":"",r);break;case"bytes":t("d%s=o.bytes===String?util.base64.encode(m%s,0,m%s.length):o.bytes===Array?Array.prototype.slice.call(m%s):m%s",r,r,r,r,r);break;default:t("d%s=m%s",r,r)}}return t}n.fromObject=function(t){var i=t.fieldsArray,n=d.codegen(["d"],t.name+"$fromObject")("if(d instanceof this.ctor)")("return d");if(!i.length)return n("return new this.ctor");n("var m=new this.ctor");for(var r=0;r>>3){");for(var n=0;n>>3){")("case 1: k=r.%s(); break",r.keyType)("case 2:"),h.basic[e]===g?i("value=types[%i].decode(r,r.uint32())",n):i("value=r.%s()",e),i("break")("default:")("r.skipType(tag2&7)")("break")("}")("}"),h.long[r.keyType]!==g?i('%s[typeof k==="object"?util.longToHash(k):k]=value',s):i("%s[k]=value",s)):r.repeated?(i("if(!(%s&&%s.length))",s,s)("%s=[]",s),h.packed[e]!==g&&i("if((t&7)===2){")("var c2=r.uint32()+r.pos")("while(r.pos>>0,8|c.mapKey[s.keyType],s.keyType),h===g?n("types[%i].encode(%s[ks[i]],w.uint32(18).fork()).ldelim().ldelim()",u,i):n(".uint32(%i).%s(%s[ks[i]]).ldelim()",16|h,o,i),n("}")("}")):s.repeated?(n("if(%s!=null&&%s.length){",i,i),s.packed&&c.packed[o]!==g?n("w.uint32(%i).fork()",(s.id<<3|2)>>>0)("for(var i=0;i<%s.length;++i)",i)("w.%s(%s[i])",o,i)("w.ldelim()"):(n("for(var i=0;i<%s.length;++i)",i),h===g?l(n,s,u,i+"[i]"):n("w.uint32(%i).%s(%s[i])",(s.id<<3|h)>>>0,o,i)),n("}")):(s.optional&&n("if(%s!=null&&Object.hasOwnProperty.call(m,%j))",i,s.name),h===g?l(n,s,u,i):n("w.uint32(%i).%s(%s)",(s.id<<3|h)>>>0,o,i))}return n("return w")};var f=t(14),c=t(32),a=t(33);function l(t,i,n,r){i.resolvedType.group?t("types[%i].encode(%s,w.uint32(%i)).uint32(%i)",n,r,(i.id<<3|3)>>>0,(i.id<<3|4)>>>0):t("types[%i].encode(%s,w.uint32(%i).fork()).ldelim()",n,r,(i.id<<3|2)>>>0)}},{14:14,32:32,33:33}],14:[function(t,i,n){i.exports=s;var h=t(22),r=(((s.prototype=Object.create(h.prototype)).constructor=s).className="Enum",t(21)),e=t(33);function s(t,i,n,r,e,s){if(h.call(this,t,n),i&&"object"!=typeof i)throw TypeError("values must be an object");if(this.valuesById={},this.values=Object.create(this.valuesById),this.comment=r,this.comments=e||{},this.valuesOptions=s,this.reserved=g,i)for(var u=Object.keys(i),o=0;oi)return!0;return!1},a.isReservedName=function(t,i){if(t)for(var n=0;n "+t.len)}function h(t){this.buf=t,this.pos=0,this.len=t.length}function f(){return e.Buffer?function(t){return(h.create=function(t){return e.Buffer.isBuffer(t)?new r(t):a(t)})(t)}:a}var c,a="undefined"!=typeof Uint8Array?function(t){if(t instanceof Uint8Array||Array.isArray(t))return new h(t);throw Error("illegal buffer")}:function(t){if(Array.isArray(t))return new h(t);throw Error("illegal buffer")};function l(){var t=new s(0,0),i=0;if(!(4=this.len)throw o(this);if(t.lo=(t.lo|(127&this.buf[this.pos])<<7*i)>>>0,this.buf[this.pos++]<128)return t}return t.lo=(t.lo|(127&this.buf[this.pos++])<<7*i)>>>0,t}for(;i<4;++i)if(t.lo=(t.lo|(127&this.buf[this.pos])<<7*i)>>>0,this.buf[this.pos++]<128)return t;if(t.lo=(t.lo|(127&this.buf[this.pos])<<28)>>>0,t.hi=(t.hi|(127&this.buf[this.pos])>>4)>>>0,this.buf[this.pos++]<128)return t;if(i=0,4>>0,this.buf[this.pos++]<128)return t}else for(;i<5;++i){if(this.pos>=this.len)throw o(this);if(t.hi=(t.hi|(127&this.buf[this.pos])<<7*i+3)>>>0,this.buf[this.pos++]<128)return t}throw Error("invalid varint encoding")}function d(t,i){return(t[i-4]|t[i-3]<<8|t[i-2]<<16|t[i-1]<<24)>>>0}function v(){if(this.pos+8>this.len)throw o(this,8);return new s(d(this.buf,this.pos+=4),d(this.buf,this.pos+=4))}h.create=f(),h.prototype.h=e.Array.prototype.subarray||e.Array.prototype.slice,h.prototype.uint32=(c=4294967295,function(){if(c=(127&this.buf[this.pos])>>>0,this.buf[this.pos++]<128||(c=(c|(127&this.buf[this.pos])<<7)>>>0,this.buf[this.pos++]<128||(c=(c|(127&this.buf[this.pos])<<14)>>>0,this.buf[this.pos++]<128||(c=(c|(127&this.buf[this.pos])<<21)>>>0,this.buf[this.pos++]<128||(c=(c|(15&this.buf[this.pos])<<28)>>>0,this.buf[this.pos++]<128||!((this.pos+=5)>this.len))))))return c;throw this.pos=this.len,o(this,10)}),h.prototype.int32=function(){return 0|this.uint32()},h.prototype.sint32=function(){var t=this.uint32();return t>>>1^-(1&t)|0},h.prototype.bool=function(){return 0!==this.uint32()},h.prototype.fixed32=function(){if(this.pos+4>this.len)throw o(this,4);return d(this.buf,this.pos+=4)},h.prototype.sfixed32=function(){if(this.pos+4>this.len)throw o(this,4);return 0|d(this.buf,this.pos+=4)},h.prototype.float=function(){if(this.pos+4>this.len)throw o(this,4);var t=e.float.readFloatLE(this.buf,this.pos);return this.pos+=4,t},h.prototype.double=function(){if(this.pos+8>this.len)throw o(this,4);var t=e.float.readDoubleLE(this.buf,this.pos);return this.pos+=8,t},h.prototype.bytes=function(){var t=this.uint32(),i=this.pos,n=this.pos+t;if(n>this.len)throw o(this,t);return this.pos+=t,Array.isArray(this.buf)?this.buf.slice(i,n):i===n?(t=e.Buffer)?t.alloc(0):new this.buf.constructor(0):this.h.call(this.buf,i,n)},h.prototype.string=function(){var t=this.bytes();return u.read(t,0,t.length)},h.prototype.skip=function(t){if("number"==typeof t){if(this.pos+t>this.len)throw o(this,t);this.pos+=t}else do{if(this.pos>=this.len)throw o(this)}while(128&this.buf[this.pos++]);return this},h.prototype.skipType=function(t){switch(t){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;4!=(t=7&this.uint32());)this.skipType(t);break;case 5:this.skip(4);break;default:throw Error("invalid wire type "+t+" at offset "+this.pos)}return this},h.r=function(t){r=t,h.create=f(),r.r();var i=e.Long?"toLong":"toNumber";e.merge(h.prototype,{int64:function(){return l.call(this)[i](!1)},uint64:function(){return l.call(this)[i](!0)},sint64:function(){return l.call(this).zzDecode()[i](!1)},fixed64:function(){return v.call(this)[i](!0)},sfixed64:function(){return v.call(this)[i](!1)}})}},{35:35}],25:[function(t,i,n){i.exports=s;var r=t(24),e=((s.prototype=Object.create(r.prototype)).constructor=s,t(35));function s(t){r.call(this,t)}s.r=function(){e.Buffer&&(s.prototype.h=e.Buffer.prototype.slice)},s.prototype.string=function(){var t=this.uint32();return this.buf.utf8Slice?this.buf.utf8Slice(this.pos,this.pos=Math.min(this.pos+t,this.len)):this.buf.toString("utf-8",this.pos,this.pos=Math.min(this.pos+t,this.len))},s.r()},{24:24,35:35}],26:[function(t,i,n){i.exports=h;var r,d,v,e=t(21),s=(((h.prototype=Object.create(e.prototype)).constructor=h).className="Root",t(15)),u=t(14),o=t(23),b=t(33);function h(t){e.call(this,"",t),this.deferred=[],this.files=[]}function p(){}h.fromJSON=function(t,i){return i=i||new h,t.options&&i.setOptions(t.options),i.addJSON(t.nested)},h.prototype.resolvePath=b.path.resolve,h.prototype.fetch=b.fetch,h.prototype.load=function t(i,s,e){"function"==typeof s&&(e=s,s=g);var u=this;if(!e)return b.asPromise(t,u,i,s);var o=e===p;function h(t,i){if(e){if(o)throw t;var n=e;e=null,n(t,i)}}function f(t){var i=t.lastIndexOf("google/protobuf/");if(-1>>0,this.hi=i>>>0}var s=e.zero=new e(0,0),u=(s.toNumber=function(){return 0},s.zzEncode=s.zzDecode=function(){return this},s.length=function(){return 1},e.zeroHash="\0\0\0\0\0\0\0\0",e.fromNumber=function(t){var i,n;return 0===t?s:(n=(t=(i=t<0)?-t:t)>>>0,t=(t-n)/4294967296>>>0,i&&(t=~t>>>0,n=~n>>>0,4294967295<++n&&(n=0,4294967295<++t&&(t=0))),new e(n,t))},e.from=function(t){if("number"==typeof t)return e.fromNumber(t);if(r.isString(t)){if(!r.Long)return e.fromNumber(parseInt(t,10));t=r.Long.fromString(t)}return t.low||t.high?new e(t.low>>>0,t.high>>>0):s},e.prototype.toNumber=function(t){var i;return!t&&this.hi>>>31?(t=1+~this.lo>>>0,i=~this.hi>>>0,-(t+4294967296*(i=t?i:i+1>>>0))):this.lo+4294967296*this.hi},e.prototype.toLong=function(t){return r.Long?new r.Long(0|this.lo,0|this.hi,!!t):{low:0|this.lo,high:0|this.hi,unsigned:!!t}},String.prototype.charCodeAt);e.fromHash=function(t){return"\0\0\0\0\0\0\0\0"===t?s:new e((u.call(t,0)|u.call(t,1)<<8|u.call(t,2)<<16|u.call(t,3)<<24)>>>0,(u.call(t,4)|u.call(t,5)<<8|u.call(t,6)<<16|u.call(t,7)<<24)>>>0)},e.prototype.toHash=function(){return String.fromCharCode(255&this.lo,this.lo>>>8&255,this.lo>>>16&255,this.lo>>>24,255&this.hi,this.hi>>>8&255,this.hi>>>16&255,this.hi>>>24)},e.prototype.zzEncode=function(){var t=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^t)>>>0,this.lo=(this.lo<<1^t)>>>0,this},e.prototype.zzDecode=function(){var t=-(1&this.lo);return this.lo=((this.lo>>>1|this.hi<<31)^t)>>>0,this.hi=(this.hi>>>1^t)>>>0,this},e.prototype.length=function(){var t=this.lo,i=(this.lo>>>28|this.hi<<4)>>>0,n=this.hi>>>24;return 0==n?0==i?t<16384?t<128?1:2:t<2097152?3:4:i<16384?i<128?5:6:i<2097152?7:8:n<128?9:10}},{35:35}],35:[function(t,i,n){var r=n;function e(t,i,n){for(var r=Object.keys(i),e=0;e>>7|t.hi<<25)>>>0,t.hi>>>=7;for(;127>>7;i[n++]=t.lo}function p(t,i,n){i[n]=255&t,i[n+1]=t>>>8&255,i[n+2]=t>>>16&255,i[n+3]=t>>>24}a.create=l(),a.alloc=function(t){return new e.Array(t)},e.Array!==Array&&(a.alloc=e.pool(a.alloc,e.Array.prototype.subarray)),a.prototype.p=function(t,i,n){return this.tail=this.tail.next=new h(t,i,n),this.len+=i,this},(v.prototype=Object.create(h.prototype)).fn=function(t,i,n){for(;127>>=7;i[n]=t},a.prototype.uint32=function(t){return this.len+=(this.tail=this.tail.next=new v((t>>>=0)<128?1:t<16384?2:t<2097152?3:t<268435456?4:5,t)).len,this},a.prototype.int32=function(t){return t<0?this.p(b,10,s.fromNumber(t)):this.uint32(t)},a.prototype.sint32=function(t){return this.uint32((t<<1^t>>31)>>>0)},a.prototype.int64=a.prototype.uint64=function(t){t=s.from(t);return this.p(b,t.length(),t)},a.prototype.sint64=function(t){t=s.from(t).zzEncode();return this.p(b,t.length(),t)},a.prototype.bool=function(t){return this.p(d,1,t?1:0)},a.prototype.sfixed32=a.prototype.fixed32=function(t){return this.p(p,4,t>>>0)},a.prototype.sfixed64=a.prototype.fixed64=function(t){t=s.from(t);return this.p(p,4,t.lo).p(p,4,t.hi)},a.prototype.float=function(t){return this.p(e.float.writeFloatLE,4,t)},a.prototype.double=function(t){return this.p(e.float.writeDoubleLE,8,t)};var y=e.Array.prototype.set?function(t,i,n){i.set(t,n)}:function(t,i,n){for(var r=0;r>>0;return n?(e.isString(t)&&(i=a.alloc(n=u.length(t)),u.decode(t,i,0),t=i),this.uint32(n).p(y,n,t)):this.p(d,1,0)},a.prototype.string=function(t){var i=o.length(t);return i?this.uint32(i).p(o.write,i,t):this.p(d,1,0)},a.prototype.fork=function(){return this.states=new c(this),this.head=this.tail=new h(f,0,0),this.len=0,this},a.prototype.reset=function(){return this.states?(this.head=this.states.head,this.tail=this.states.tail,this.len=this.states.len,this.states=this.states.next):(this.head=this.tail=new h(f,0,0),this.len=0),this},a.prototype.ldelim=function(){var t=this.head,i=this.tail,n=this.len;return this.reset().uint32(n),n&&(this.tail.next=t.next,this.tail=i,this.len+=n),this},a.prototype.finish=function(){for(var t=this.head.next,i=this.constructor.alloc(this.len),n=0;t;)t.fn(t.val,i,n),n+=t.len,t=t.next;return i},a.r=function(t){r=t,a.create=l(),r.r()}},{35:35}],39:[function(t,i,n){i.exports=s;var r=t(38),e=((s.prototype=Object.create(r.prototype)).constructor=s,t(35));function s(){r.call(this)}function u(t,i,n){t.length<40?e.utf8.write(t,i,n):i.utf8Write?i.utf8Write(t,n):i.write(t,n)}s.r=function(){s.alloc=e.b,s.writeBytesBuffer=e.Buffer&&e.Buffer.prototype instanceof Uint8Array&&"set"===e.Buffer.prototype.set.name?function(t,i,n){i.set(t,n)}:function(t,i,n){if(t.copy)t.copy(i,n,0,t.length);else for(var r=0;r>>0;return this.uint32(i),i&&this.p(s.writeBytesBuffer,i,t),this},s.prototype.string=function(t){var i=e.Buffer.byteLength(t);return this.uint32(i),i&&this.p(u,i,t),this},s.r()},{35:35,38:38}]},{},[16])}(); +//# sourceMappingURL=protobuf.min.js.map diff --git a/node_modules/protobufjs/dist/light/protobuf.min.js.map b/node_modules/protobufjs/dist/light/protobuf.min.js.map new file mode 100644 index 0000000..939a1d9 --- /dev/null +++ b/node_modules/protobufjs/dist/light/protobuf.min.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["lib/prelude.js","../node_modules/@protobufjs/aspromise/index.js","../node_modules/@protobufjs/base64/index.js","../node_modules/@protobufjs/codegen/index.js","../node_modules/@protobufjs/eventemitter/index.js","../node_modules/@protobufjs/fetch/index.js","../node_modules/@protobufjs/float/index.js","../node_modules/@protobufjs/inquire/index.js","../node_modules/@protobufjs/path/index.js","../node_modules/@protobufjs/pool/index.js","../node_modules/@protobufjs/utf8/index.js","../src/converter.js","../src/decoder.js","../src/encoder.js","../src/enum.js","../src/field.js","../src/index-light","../src/index-minimal.js","../src/mapfield.js","../src/message.js","../src/method.js","../src/namespace.js","../src/object.js","../src/oneof.js","../src/reader.js","../src/reader_buffer.js","../src/root.js","../src/roots.js","../src/rpc.js","../src/rpc/service.js","../src/service.js","../src/type.js","../src/types.js","../src/util.js","../src/util/longbits.js","../src/util/minimal.js","../src/verifier.js","../src/wrappers.js","../src/writer.js","../src/writer_buffer.js"],"names":["undefined","modules","cache","entries","protobuf","$require","name","$module","call","exports","util","global","define","amd","Long","isLong","configure","module","1","require","fn","ctx","params","Array","arguments","length","offset","index","pending","Promise","resolve","reject","err","apply","base64","string","p","n","Math","ceil","b64","s64","i","encode","buffer","start","end","t","parts","chunk","j","b","push","String","fromCharCode","slice","join","invalidEncoding","decode","c","charCodeAt","Error","test","codegen","functionParams","functionName","body","Codegen","formatStringOrScope","source","toString","verbose","console","log","scopeKeys","Object","keys","scopeParams","scopeValues","scopeOffset","Function","formatParams","formatOffset","replace","$0","$1","value","Number","floor","JSON","stringify","functionNameOverride","EventEmitter","this","_listeners","prototype","on","evt","off","listeners","splice","emit","args","fetch","asPromise","fs","filename","options","callback","xhr","readFile","contents","XMLHttpRequest","binary","onreadystatechange","readyState","status","response","responseText","Uint8Array","overrideMimeType","responseType","open","send","factory","writeFloat_ieee754","writeUint","val","buf","pos","sign","isNaN","round","exponent","LN2","pow","readFloat_ieee754","readUint","uint","mantissa","NaN","Infinity","writeFloat_f32_cpy","f32","f8b","writeFloat_f32_rev","readFloat_f32_cpy","readFloat_f32_rev","f64","le","writeDouble_ieee754","off0","off1","readDouble_ieee754","lo","hi","writeDouble_f64_cpy","writeDouble_f64_rev","readDouble_f64_cpy","readDouble_f64_rev","Float32Array","writeFloatLE","writeFloatBE","readFloatLE","readFloatBE","bind","writeUintLE","writeUintBE","readUintLE","readUintBE","Float64Array","writeDoubleLE","writeDoubleBE","readDoubleLE","readDoubleBE","inquire","moduleName","mod","eval","e","isAbsolute","path","normalize","split","absolute","prefix","shift","originPath","includePath","alreadyNormalized","alloc","size","SIZE","MAX","slab","utf8","len","read","write","c1","c2","Enum","genValuePartial_fromObject","gen","field","fieldIndex","prop","defaultAlreadyEmitted","resolvedType","values","typeDefault","repeated","fullName","isUnsigned","type","genValuePartial_toObject","converter","fromObject","mtype","fields","fieldsArray","safeProp","map","toObject","sort","compareFieldsById","repeatedFields","mapFields","normalFields","partOf","arrayDefault","valuesById","long","low","high","unsigned","toNumber","bytes","hasKs2","_fieldsArray","indexOf","filter","group","ref","id","types","defaults","keyType","basic","packed","rfield","required","wireType","mapKey","genTypePartial","optional","ReflectionObject","Namespace","create","constructor","className","comment","comments","valuesOptions","TypeError","reserved","fromJSON","json","enm","toJSON","toJSONOptions","keepComments","Boolean","add","isString","isInteger","isReservedId","isReservedName","allow_alias","remove","Field","Type","ruleRe","rule","extend","isObject","toLowerCase","message","defaultValue","extensionField","declaringField","_packed","defineProperty","get","getOption","setOption","ifNotSet","resolved","parent","lookupTypeOrEnum","proto3_optional","fromNumber","freeze","newBuffer","emptyObject","emptyArray","ctor","d","fieldId","fieldType","fieldRule","decorateType","decorateEnum","fieldName","default","_configure","Type_","build","load","root","Root","loadSync","encoder","decoder","verifier","OneOf","MapField","Service","Method","Message","wrappers","Writer","BufferWriter","Reader","BufferReader","rpc","roots","resolvedKeyType","fieldKeyType","fieldValueType","properties","$type","writer","encodeDelimited","reader","decodeDelimited","verify","object","requestType","requestStream","responseStream","parsedOptions","resolvedRequestType","resolvedResponseType","lookupType","arrayToJSON","array","obj","nested","_nestedArray","clearCache","namespace","addJSON","toArray","nestedArray","nestedJson","names","methods","getEnum","prev","setOptions","onAdd","onRemove","isArray","ptr","part","resolveAll","lookup","filterTypes","parentAlreadyChecked","found","lookupEnum","lookupService","Service_","Enum_","defineProperties","unshift","_handleAdd","_handleRemove","setParsedOption","propName","opt","newOpt","find","hasOwnProperty","newValue","setProperty","Root_","fieldNames","oneof","addFieldsToParent","oneofName","oneOfGetter","set","oneOfSetter","LongBits","indexOutOfRange","writeLength","RangeError","Buffer","isBuffer","create_array","readLongVarint","bits","readFixed32_end","readFixed64","_slice","subarray","uint32","int32","sint32","bool","fixed32","sfixed32","float","double","nativeBuffer","skip","skipType","BufferReader_","merge","int64","uint64","sint64","zzDecode","fixed64","sfixed64","utf8Slice","min","parse","common","deferred","files","SYNC","resolvePath","self","sync","finish","cb","getBundledFileName","idx","lastIndexOf","altname","substring","process","parsed","imports","weakImports","queued","weak","setTimeout","readFileSync","isNode","exposeRe","tryHandleExtension","sisterField","extendedType","parse_","common_","rpcImpl","requestDelimited","responseDelimited","rpcCall","method","requestCtor","responseCtor","request","endedByRPC","_methodsArray","service","inherited","methodsArray","rpcService","methodName","lcFirst","isReserved","m","q","s","oneofs","extensions","_fieldsById","_oneofsArray","_ctor","fieldsById","oneofsArray","generateConstructor","ctorProperties","setup","originalThis","wrapper","fork","ldelim","typeName","target","bake","o","safePropBackslashRe","key","safePropQuoteRe","camelCaseRe","ucFirst","str","toUpperCase","decorateEnumIndex","camelCase","a","decorateRoot","enumerable","dst","setProp","prevValue","concat","zero","zzEncode","zeroHash","from","parseInt","fromString","toLong","fromHash","hash","toHash","mask","part0","part1","part2","src","newError","CustomError","captureStackTrace","stack","writable","configurable","pool","versions","node","window","isFinite","isset","isSet","utf8Write","_Buffer_from","_Buffer_allocUnsafe","sizeOrArray","dcodeIO","key2Re","key32Re","key64Re","longToHash","longFromHash","fromBits","ProtocolError","fieldMap","longs","enums","encoding","allocUnsafe","seenFirstField","oneofProp","invalid","genVerifyValue","expected","type_url","messageName","Op","next","noop","State","head","tail","states","writeByte","VarintOp","writeVarint64","writeFixed32","_push","writeBytes","reset","BufferWriter_","writeStringBuffer","writeBytesBuffer","copy","byteLength"],"mappings":";;;;;;AAAA,CAAA,SAAAA,GAAA,aAAA,CAAA,SAAAC,EAAAC,EAAA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AA7G,EAAA+Y,OAAA1T,UAAAoT,IAAA7Y,KACA,SAAAyH,EAAAC,EAAAC,GACAD,EAAAmR,IAAApR,EAAAE,CAAA,CAEA,EAEA,SAAAF,EAAAC,EAAAC,GACA,GAAAF,EAAAid,KACAjd,EAAAid,KAAAhd,EAAAC,EAAA,EAAAF,EAAAtG,MAAA,OACA,IAAA,IAAAiB,EAAA,EAAAA,EAAAqF,EAAAtG,QACAuG,EAAAC,CAAA,IAAAF,EAAArF,CAAA,GACA,CACA,EAMAkS,EAAA7O,UAAA8I,MAAA,SAAAvJ,GAGA,IAAA8G,GADA9G,EADA5E,EAAAwQ,SAAA5L,CAAA,EACA5E,EAAA8hB,EAAAld,EAAA,QAAA,EACAA,GAAA7D,SAAA,EAIA,OAHAoE,KAAAqU,OAAA9N,CAAA,EACAA,GACAvG,KAAA6e,EAAA9P,EAAAmQ,iBAAA3Y,EAAA9G,CAAA,EACAO,IACA,EAcA+O,EAAA7O,UAAA5D,OAAA,SAAAmD,GACA,IAAA8G,EAAA1L,EAAA+Y,OAAAwL,WAAA3f,CAAA,EAIA,OAHAO,KAAAqU,OAAA9N,CAAA,EACAA,GACAvG,KAAA6e,EAAAI,EAAA1Y,EAAA9G,CAAA,EACAO,IACA,EAUA+O,EAAAjB,EAAA","file":"protobuf.min.js","sourcesContent":["(function prelude(modules, cache, entries) {\n\n // This is the prelude used to bundle protobuf.js for the browser. Wraps up the CommonJS\n // sources through a conflict-free require shim and is again wrapped within an iife that\n // provides a minification-friendly `undefined` var plus a global \"use strict\" directive\n // so that minification can remove the directives of each module.\n\n function $require(name) {\n var $module = cache[name];\n if (!$module)\n modules[name][0].call($module = cache[name] = { exports: {} }, $require, $module, $module.exports);\n return $module.exports;\n }\n\n var protobuf = $require(entries[0]);\n\n // Expose globally\n protobuf.util.global.protobuf = protobuf;\n\n // Be nice to AMD\n if (typeof define === \"function\" && define.amd)\n define([\"long\"], function(Long) {\n if (Long && Long.isLong) {\n protobuf.util.Long = Long;\n protobuf.configure();\n }\n return protobuf;\n });\n\n // Be nice to CommonJS\n if (typeof module === \"object\" && module && module.exports)\n module.exports = protobuf;\n\n})/* end of prelude */","\"use strict\";\r\nmodule.exports = asPromise;\r\n\r\n/**\r\n * Callback as used by {@link util.asPromise}.\r\n * @typedef asPromiseCallback\r\n * @type {function}\r\n * @param {Error|null} error Error, if any\r\n * @param {...*} params Additional arguments\r\n * @returns {undefined}\r\n */\r\n\r\n/**\r\n * Returns a promise from a node-style callback function.\r\n * @memberof util\r\n * @param {asPromiseCallback} fn Function to call\r\n * @param {*} ctx Function context\r\n * @param {...*} params Function arguments\r\n * @returns {Promise<*>} Promisified function\r\n */\r\nfunction asPromise(fn, ctx/*, varargs */) {\r\n var params = new Array(arguments.length - 1),\r\n offset = 0,\r\n index = 2,\r\n pending = true;\r\n while (index < arguments.length)\r\n params[offset++] = arguments[index++];\r\n return new Promise(function executor(resolve, reject) {\r\n params[offset] = function callback(err/*, varargs */) {\r\n if (pending) {\r\n pending = false;\r\n if (err)\r\n reject(err);\r\n else {\r\n var params = new Array(arguments.length - 1),\r\n offset = 0;\r\n while (offset < params.length)\r\n params[offset++] = arguments[offset];\r\n resolve.apply(null, params);\r\n }\r\n }\r\n };\r\n try {\r\n fn.apply(ctx || null, params);\r\n } catch (err) {\r\n if (pending) {\r\n pending = false;\r\n reject(err);\r\n }\r\n }\r\n });\r\n}\r\n","\"use strict\";\r\n\r\n/**\r\n * A minimal base64 implementation for number arrays.\r\n * @memberof util\r\n * @namespace\r\n */\r\nvar base64 = exports;\r\n\r\n/**\r\n * Calculates the byte length of a base64 encoded string.\r\n * @param {string} string Base64 encoded string\r\n * @returns {number} Byte length\r\n */\r\nbase64.length = function length(string) {\r\n var p = string.length;\r\n if (!p)\r\n return 0;\r\n var n = 0;\r\n while (--p % 4 > 1 && string.charAt(p) === \"=\")\r\n ++n;\r\n return Math.ceil(string.length * 3) / 4 - n;\r\n};\r\n\r\n// Base64 encoding table\r\nvar b64 = new Array(64);\r\n\r\n// Base64 decoding table\r\nvar s64 = new Array(123);\r\n\r\n// 65..90, 97..122, 48..57, 43, 47\r\nfor (var i = 0; i < 64;)\r\n s64[b64[i] = i < 26 ? i + 65 : i < 52 ? i + 71 : i < 62 ? i - 4 : i - 59 | 43] = i++;\r\n\r\n/**\r\n * Encodes a buffer to a base64 encoded string.\r\n * @param {Uint8Array} buffer Source buffer\r\n * @param {number} start Source start\r\n * @param {number} end Source end\r\n * @returns {string} Base64 encoded string\r\n */\r\nbase64.encode = function encode(buffer, start, end) {\r\n var parts = null,\r\n chunk = [];\r\n var i = 0, // output index\r\n j = 0, // goto index\r\n t; // temporary\r\n while (start < end) {\r\n var b = buffer[start++];\r\n switch (j) {\r\n case 0:\r\n chunk[i++] = b64[b >> 2];\r\n t = (b & 3) << 4;\r\n j = 1;\r\n break;\r\n case 1:\r\n chunk[i++] = b64[t | b >> 4];\r\n t = (b & 15) << 2;\r\n j = 2;\r\n break;\r\n case 2:\r\n chunk[i++] = b64[t | b >> 6];\r\n chunk[i++] = b64[b & 63];\r\n j = 0;\r\n break;\r\n }\r\n if (i > 8191) {\r\n (parts || (parts = [])).push(String.fromCharCode.apply(String, chunk));\r\n i = 0;\r\n }\r\n }\r\n if (j) {\r\n chunk[i++] = b64[t];\r\n chunk[i++] = 61;\r\n if (j === 1)\r\n chunk[i++] = 61;\r\n }\r\n if (parts) {\r\n if (i)\r\n parts.push(String.fromCharCode.apply(String, chunk.slice(0, i)));\r\n return parts.join(\"\");\r\n }\r\n return String.fromCharCode.apply(String, chunk.slice(0, i));\r\n};\r\n\r\nvar invalidEncoding = \"invalid encoding\";\r\n\r\n/**\r\n * Decodes a base64 encoded string to a buffer.\r\n * @param {string} string Source string\r\n * @param {Uint8Array} buffer Destination buffer\r\n * @param {number} offset Destination offset\r\n * @returns {number} Number of bytes written\r\n * @throws {Error} If encoding is invalid\r\n */\r\nbase64.decode = function decode(string, buffer, offset) {\r\n var start = offset;\r\n var j = 0, // goto index\r\n t; // temporary\r\n for (var i = 0; i < string.length;) {\r\n var c = string.charCodeAt(i++);\r\n if (c === 61 && j > 1)\r\n break;\r\n if ((c = s64[c]) === undefined)\r\n throw Error(invalidEncoding);\r\n switch (j) {\r\n case 0:\r\n t = c;\r\n j = 1;\r\n break;\r\n case 1:\r\n buffer[offset++] = t << 2 | (c & 48) >> 4;\r\n t = c;\r\n j = 2;\r\n break;\r\n case 2:\r\n buffer[offset++] = (t & 15) << 4 | (c & 60) >> 2;\r\n t = c;\r\n j = 3;\r\n break;\r\n case 3:\r\n buffer[offset++] = (t & 3) << 6 | c;\r\n j = 0;\r\n break;\r\n }\r\n }\r\n if (j === 1)\r\n throw Error(invalidEncoding);\r\n return offset - start;\r\n};\r\n\r\n/**\r\n * Tests if the specified string appears to be base64 encoded.\r\n * @param {string} string String to test\r\n * @returns {boolean} `true` if probably base64 encoded, otherwise false\r\n */\r\nbase64.test = function test(string) {\r\n return /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(string);\r\n};\r\n","\"use strict\";\r\nmodule.exports = codegen;\r\n\r\n/**\r\n * Begins generating a function.\r\n * @memberof util\r\n * @param {string[]} functionParams Function parameter names\r\n * @param {string} [functionName] Function name if not anonymous\r\n * @returns {Codegen} Appender that appends code to the function's body\r\n */\r\nfunction codegen(functionParams, functionName) {\r\n\r\n /* istanbul ignore if */\r\n if (typeof functionParams === \"string\") {\r\n functionName = functionParams;\r\n functionParams = undefined;\r\n }\r\n\r\n var body = [];\r\n\r\n /**\r\n * Appends code to the function's body or finishes generation.\r\n * @typedef Codegen\r\n * @type {function}\r\n * @param {string|Object.} [formatStringOrScope] Format string or, to finish the function, an object of additional scope variables, if any\r\n * @param {...*} [formatParams] Format parameters\r\n * @returns {Codegen|Function} Itself or the generated function if finished\r\n * @throws {Error} If format parameter counts do not match\r\n */\r\n\r\n function Codegen(formatStringOrScope) {\r\n // note that explicit array handling below makes this ~50% faster\r\n\r\n // finish the function\r\n if (typeof formatStringOrScope !== \"string\") {\r\n var source = toString();\r\n if (codegen.verbose)\r\n console.log(\"codegen: \" + source); // eslint-disable-line no-console\r\n source = \"return \" + source;\r\n if (formatStringOrScope) {\r\n var scopeKeys = Object.keys(formatStringOrScope),\r\n scopeParams = new Array(scopeKeys.length + 1),\r\n scopeValues = new Array(scopeKeys.length),\r\n scopeOffset = 0;\r\n while (scopeOffset < scopeKeys.length) {\r\n scopeParams[scopeOffset] = scopeKeys[scopeOffset];\r\n scopeValues[scopeOffset] = formatStringOrScope[scopeKeys[scopeOffset++]];\r\n }\r\n scopeParams[scopeOffset] = source;\r\n return Function.apply(null, scopeParams).apply(null, scopeValues); // eslint-disable-line no-new-func\r\n }\r\n return Function(source)(); // eslint-disable-line no-new-func\r\n }\r\n\r\n // otherwise append to body\r\n var formatParams = new Array(arguments.length - 1),\r\n formatOffset = 0;\r\n while (formatOffset < formatParams.length)\r\n formatParams[formatOffset] = arguments[++formatOffset];\r\n formatOffset = 0;\r\n formatStringOrScope = formatStringOrScope.replace(/%([%dfijs])/g, function replace($0, $1) {\r\n var value = formatParams[formatOffset++];\r\n switch ($1) {\r\n case \"d\": case \"f\": return String(Number(value));\r\n case \"i\": return String(Math.floor(value));\r\n case \"j\": return JSON.stringify(value);\r\n case \"s\": return String(value);\r\n }\r\n return \"%\";\r\n });\r\n if (formatOffset !== formatParams.length)\r\n throw Error(\"parameter count mismatch\");\r\n body.push(formatStringOrScope);\r\n return Codegen;\r\n }\r\n\r\n function toString(functionNameOverride) {\r\n return \"function \" + (functionNameOverride || functionName || \"\") + \"(\" + (functionParams && functionParams.join(\",\") || \"\") + \"){\\n \" + body.join(\"\\n \") + \"\\n}\";\r\n }\r\n\r\n Codegen.toString = toString;\r\n return Codegen;\r\n}\r\n\r\n/**\r\n * Begins generating a function.\r\n * @memberof util\r\n * @function codegen\r\n * @param {string} [functionName] Function name if not anonymous\r\n * @returns {Codegen} Appender that appends code to the function's body\r\n * @variation 2\r\n */\r\n\r\n/**\r\n * When set to `true`, codegen will log generated code to console. Useful for debugging.\r\n * @name util.codegen.verbose\r\n * @type {boolean}\r\n */\r\ncodegen.verbose = false;\r\n","\"use strict\";\r\nmodule.exports = EventEmitter;\r\n\r\n/**\r\n * Constructs a new event emitter instance.\r\n * @classdesc A minimal event emitter.\r\n * @memberof util\r\n * @constructor\r\n */\r\nfunction EventEmitter() {\r\n\r\n /**\r\n * Registered listeners.\r\n * @type {Object.}\r\n * @private\r\n */\r\n this._listeners = {};\r\n}\r\n\r\n/**\r\n * Registers an event listener.\r\n * @param {string} evt Event name\r\n * @param {function} fn Listener\r\n * @param {*} [ctx] Listener context\r\n * @returns {util.EventEmitter} `this`\r\n */\r\nEventEmitter.prototype.on = function on(evt, fn, ctx) {\r\n (this._listeners[evt] || (this._listeners[evt] = [])).push({\r\n fn : fn,\r\n ctx : ctx || this\r\n });\r\n return this;\r\n};\r\n\r\n/**\r\n * Removes an event listener or any matching listeners if arguments are omitted.\r\n * @param {string} [evt] Event name. Removes all listeners if omitted.\r\n * @param {function} [fn] Listener to remove. Removes all listeners of `evt` if omitted.\r\n * @returns {util.EventEmitter} `this`\r\n */\r\nEventEmitter.prototype.off = function off(evt, fn) {\r\n if (evt === undefined)\r\n this._listeners = {};\r\n else {\r\n if (fn === undefined)\r\n this._listeners[evt] = [];\r\n else {\r\n var listeners = this._listeners[evt];\r\n for (var i = 0; i < listeners.length;)\r\n if (listeners[i].fn === fn)\r\n listeners.splice(i, 1);\r\n else\r\n ++i;\r\n }\r\n }\r\n return this;\r\n};\r\n\r\n/**\r\n * Emits an event by calling its listeners with the specified arguments.\r\n * @param {string} evt Event name\r\n * @param {...*} args Arguments\r\n * @returns {util.EventEmitter} `this`\r\n */\r\nEventEmitter.prototype.emit = function emit(evt) {\r\n var listeners = this._listeners[evt];\r\n if (listeners) {\r\n var args = [],\r\n i = 1;\r\n for (; i < arguments.length;)\r\n args.push(arguments[i++]);\r\n for (i = 0; i < listeners.length;)\r\n listeners[i].fn.apply(listeners[i++].ctx, args);\r\n }\r\n return this;\r\n};\r\n","\"use strict\";\r\nmodule.exports = fetch;\r\n\r\nvar asPromise = require(1),\r\n inquire = require(7);\r\n\r\nvar fs = inquire(\"fs\");\r\n\r\n/**\r\n * Node-style callback as used by {@link util.fetch}.\r\n * @typedef FetchCallback\r\n * @type {function}\r\n * @param {?Error} error Error, if any, otherwise `null`\r\n * @param {string} [contents] File contents, if there hasn't been an error\r\n * @returns {undefined}\r\n */\r\n\r\n/**\r\n * Options as used by {@link util.fetch}.\r\n * @typedef FetchOptions\r\n * @type {Object}\r\n * @property {boolean} [binary=false] Whether expecting a binary response\r\n * @property {boolean} [xhr=false] If `true`, forces the use of XMLHttpRequest\r\n */\r\n\r\n/**\r\n * Fetches the contents of a file.\r\n * @memberof util\r\n * @param {string} filename File path or url\r\n * @param {FetchOptions} options Fetch options\r\n * @param {FetchCallback} callback Callback function\r\n * @returns {undefined}\r\n */\r\nfunction fetch(filename, options, callback) {\r\n if (typeof options === \"function\") {\r\n callback = options;\r\n options = {};\r\n } else if (!options)\r\n options = {};\r\n\r\n if (!callback)\r\n return asPromise(fetch, this, filename, options); // eslint-disable-line no-invalid-this\r\n\r\n // if a node-like filesystem is present, try it first but fall back to XHR if nothing is found.\r\n if (!options.xhr && fs && fs.readFile)\r\n return fs.readFile(filename, function fetchReadFileCallback(err, contents) {\r\n return err && typeof XMLHttpRequest !== \"undefined\"\r\n ? fetch.xhr(filename, options, callback)\r\n : err\r\n ? callback(err)\r\n : callback(null, options.binary ? contents : contents.toString(\"utf8\"));\r\n });\r\n\r\n // use the XHR version otherwise.\r\n return fetch.xhr(filename, options, callback);\r\n}\r\n\r\n/**\r\n * Fetches the contents of a file.\r\n * @name util.fetch\r\n * @function\r\n * @param {string} path File path or url\r\n * @param {FetchCallback} callback Callback function\r\n * @returns {undefined}\r\n * @variation 2\r\n */\r\n\r\n/**\r\n * Fetches the contents of a file.\r\n * @name util.fetch\r\n * @function\r\n * @param {string} path File path or url\r\n * @param {FetchOptions} [options] Fetch options\r\n * @returns {Promise} Promise\r\n * @variation 3\r\n */\r\n\r\n/**/\r\nfetch.xhr = function fetch_xhr(filename, options, callback) {\r\n var xhr = new XMLHttpRequest();\r\n xhr.onreadystatechange /* works everywhere */ = function fetchOnReadyStateChange() {\r\n\r\n if (xhr.readyState !== 4)\r\n return undefined;\r\n\r\n // local cors security errors return status 0 / empty string, too. afaik this cannot be\r\n // reliably distinguished from an actually empty file for security reasons. feel free\r\n // to send a pull request if you are aware of a solution.\r\n if (xhr.status !== 0 && xhr.status !== 200)\r\n return callback(Error(\"status \" + xhr.status));\r\n\r\n // if binary data is expected, make sure that some sort of array is returned, even if\r\n // ArrayBuffers are not supported. the binary string fallback, however, is unsafe.\r\n if (options.binary) {\r\n var buffer = xhr.response;\r\n if (!buffer) {\r\n buffer = [];\r\n for (var i = 0; i < xhr.responseText.length; ++i)\r\n buffer.push(xhr.responseText.charCodeAt(i) & 255);\r\n }\r\n return callback(null, typeof Uint8Array !== \"undefined\" ? new Uint8Array(buffer) : buffer);\r\n }\r\n return callback(null, xhr.responseText);\r\n };\r\n\r\n if (options.binary) {\r\n // ref: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Sending_and_Receiving_Binary_Data#Receiving_binary_data_in_older_browsers\r\n if (\"overrideMimeType\" in xhr)\r\n xhr.overrideMimeType(\"text/plain; charset=x-user-defined\");\r\n xhr.responseType = \"arraybuffer\";\r\n }\r\n\r\n xhr.open(\"GET\", filename);\r\n xhr.send();\r\n};\r\n","\"use strict\";\r\n\r\nmodule.exports = factory(factory);\r\n\r\n/**\r\n * Reads / writes floats / doubles from / to buffers.\r\n * @name util.float\r\n * @namespace\r\n */\r\n\r\n/**\r\n * Writes a 32 bit float to a buffer using little endian byte order.\r\n * @name util.float.writeFloatLE\r\n * @function\r\n * @param {number} val Value to write\r\n * @param {Uint8Array} buf Target buffer\r\n * @param {number} pos Target buffer offset\r\n * @returns {undefined}\r\n */\r\n\r\n/**\r\n * Writes a 32 bit float to a buffer using big endian byte order.\r\n * @name util.float.writeFloatBE\r\n * @function\r\n * @param {number} val Value to write\r\n * @param {Uint8Array} buf Target buffer\r\n * @param {number} pos Target buffer offset\r\n * @returns {undefined}\r\n */\r\n\r\n/**\r\n * Reads a 32 bit float from a buffer using little endian byte order.\r\n * @name util.float.readFloatLE\r\n * @function\r\n * @param {Uint8Array} buf Source buffer\r\n * @param {number} pos Source buffer offset\r\n * @returns {number} Value read\r\n */\r\n\r\n/**\r\n * Reads a 32 bit float from a buffer using big endian byte order.\r\n * @name util.float.readFloatBE\r\n * @function\r\n * @param {Uint8Array} buf Source buffer\r\n * @param {number} pos Source buffer offset\r\n * @returns {number} Value read\r\n */\r\n\r\n/**\r\n * Writes a 64 bit double to a buffer using little endian byte order.\r\n * @name util.float.writeDoubleLE\r\n * @function\r\n * @param {number} val Value to write\r\n * @param {Uint8Array} buf Target buffer\r\n * @param {number} pos Target buffer offset\r\n * @returns {undefined}\r\n */\r\n\r\n/**\r\n * Writes a 64 bit double to a buffer using big endian byte order.\r\n * @name util.float.writeDoubleBE\r\n * @function\r\n * @param {number} val Value to write\r\n * @param {Uint8Array} buf Target buffer\r\n * @param {number} pos Target buffer offset\r\n * @returns {undefined}\r\n */\r\n\r\n/**\r\n * Reads a 64 bit double from a buffer using little endian byte order.\r\n * @name util.float.readDoubleLE\r\n * @function\r\n * @param {Uint8Array} buf Source buffer\r\n * @param {number} pos Source buffer offset\r\n * @returns {number} Value read\r\n */\r\n\r\n/**\r\n * Reads a 64 bit double from a buffer using big endian byte order.\r\n * @name util.float.readDoubleBE\r\n * @function\r\n * @param {Uint8Array} buf Source buffer\r\n * @param {number} pos Source buffer offset\r\n * @returns {number} Value read\r\n */\r\n\r\n// Factory function for the purpose of node-based testing in modified global environments\r\nfunction factory(exports) {\r\n\r\n // float: typed array\r\n if (typeof Float32Array !== \"undefined\") (function() {\r\n\r\n var f32 = new Float32Array([ -0 ]),\r\n f8b = new Uint8Array(f32.buffer),\r\n le = f8b[3] === 128;\r\n\r\n function writeFloat_f32_cpy(val, buf, pos) {\r\n f32[0] = val;\r\n buf[pos ] = f8b[0];\r\n buf[pos + 1] = f8b[1];\r\n buf[pos + 2] = f8b[2];\r\n buf[pos + 3] = f8b[3];\r\n }\r\n\r\n function writeFloat_f32_rev(val, buf, pos) {\r\n f32[0] = val;\r\n buf[pos ] = f8b[3];\r\n buf[pos + 1] = f8b[2];\r\n buf[pos + 2] = f8b[1];\r\n buf[pos + 3] = f8b[0];\r\n }\r\n\r\n /* istanbul ignore next */\r\n exports.writeFloatLE = le ? writeFloat_f32_cpy : writeFloat_f32_rev;\r\n /* istanbul ignore next */\r\n exports.writeFloatBE = le ? writeFloat_f32_rev : writeFloat_f32_cpy;\r\n\r\n function readFloat_f32_cpy(buf, pos) {\r\n f8b[0] = buf[pos ];\r\n f8b[1] = buf[pos + 1];\r\n f8b[2] = buf[pos + 2];\r\n f8b[3] = buf[pos + 3];\r\n return f32[0];\r\n }\r\n\r\n function readFloat_f32_rev(buf, pos) {\r\n f8b[3] = buf[pos ];\r\n f8b[2] = buf[pos + 1];\r\n f8b[1] = buf[pos + 2];\r\n f8b[0] = buf[pos + 3];\r\n return f32[0];\r\n }\r\n\r\n /* istanbul ignore next */\r\n exports.readFloatLE = le ? readFloat_f32_cpy : readFloat_f32_rev;\r\n /* istanbul ignore next */\r\n exports.readFloatBE = le ? readFloat_f32_rev : readFloat_f32_cpy;\r\n\r\n // float: ieee754\r\n })(); else (function() {\r\n\r\n function writeFloat_ieee754(writeUint, val, buf, pos) {\r\n var sign = val < 0 ? 1 : 0;\r\n if (sign)\r\n val = -val;\r\n if (val === 0)\r\n writeUint(1 / val > 0 ? /* positive */ 0 : /* negative 0 */ 2147483648, buf, pos);\r\n else if (isNaN(val))\r\n writeUint(2143289344, buf, pos);\r\n else if (val > 3.4028234663852886e+38) // +-Infinity\r\n writeUint((sign << 31 | 2139095040) >>> 0, buf, pos);\r\n else if (val < 1.1754943508222875e-38) // denormal\r\n writeUint((sign << 31 | Math.round(val / 1.401298464324817e-45)) >>> 0, buf, pos);\r\n else {\r\n var exponent = Math.floor(Math.log(val) / Math.LN2),\r\n mantissa = Math.round(val * Math.pow(2, -exponent) * 8388608) & 8388607;\r\n writeUint((sign << 31 | exponent + 127 << 23 | mantissa) >>> 0, buf, pos);\r\n }\r\n }\r\n\r\n exports.writeFloatLE = writeFloat_ieee754.bind(null, writeUintLE);\r\n exports.writeFloatBE = writeFloat_ieee754.bind(null, writeUintBE);\r\n\r\n function readFloat_ieee754(readUint, buf, pos) {\r\n var uint = readUint(buf, pos),\r\n sign = (uint >> 31) * 2 + 1,\r\n exponent = uint >>> 23 & 255,\r\n mantissa = uint & 8388607;\r\n return exponent === 255\r\n ? mantissa\r\n ? NaN\r\n : sign * Infinity\r\n : exponent === 0 // denormal\r\n ? sign * 1.401298464324817e-45 * mantissa\r\n : sign * Math.pow(2, exponent - 150) * (mantissa + 8388608);\r\n }\r\n\r\n exports.readFloatLE = readFloat_ieee754.bind(null, readUintLE);\r\n exports.readFloatBE = readFloat_ieee754.bind(null, readUintBE);\r\n\r\n })();\r\n\r\n // double: typed array\r\n if (typeof Float64Array !== \"undefined\") (function() {\r\n\r\n var f64 = new Float64Array([-0]),\r\n f8b = new Uint8Array(f64.buffer),\r\n le = f8b[7] === 128;\r\n\r\n function writeDouble_f64_cpy(val, buf, pos) {\r\n f64[0] = val;\r\n buf[pos ] = f8b[0];\r\n buf[pos + 1] = f8b[1];\r\n buf[pos + 2] = f8b[2];\r\n buf[pos + 3] = f8b[3];\r\n buf[pos + 4] = f8b[4];\r\n buf[pos + 5] = f8b[5];\r\n buf[pos + 6] = f8b[6];\r\n buf[pos + 7] = f8b[7];\r\n }\r\n\r\n function writeDouble_f64_rev(val, buf, pos) {\r\n f64[0] = val;\r\n buf[pos ] = f8b[7];\r\n buf[pos + 1] = f8b[6];\r\n buf[pos + 2] = f8b[5];\r\n buf[pos + 3] = f8b[4];\r\n buf[pos + 4] = f8b[3];\r\n buf[pos + 5] = f8b[2];\r\n buf[pos + 6] = f8b[1];\r\n buf[pos + 7] = f8b[0];\r\n }\r\n\r\n /* istanbul ignore next */\r\n exports.writeDoubleLE = le ? writeDouble_f64_cpy : writeDouble_f64_rev;\r\n /* istanbul ignore next */\r\n exports.writeDoubleBE = le ? writeDouble_f64_rev : writeDouble_f64_cpy;\r\n\r\n function readDouble_f64_cpy(buf, pos) {\r\n f8b[0] = buf[pos ];\r\n f8b[1] = buf[pos + 1];\r\n f8b[2] = buf[pos + 2];\r\n f8b[3] = buf[pos + 3];\r\n f8b[4] = buf[pos + 4];\r\n f8b[5] = buf[pos + 5];\r\n f8b[6] = buf[pos + 6];\r\n f8b[7] = buf[pos + 7];\r\n return f64[0];\r\n }\r\n\r\n function readDouble_f64_rev(buf, pos) {\r\n f8b[7] = buf[pos ];\r\n f8b[6] = buf[pos + 1];\r\n f8b[5] = buf[pos + 2];\r\n f8b[4] = buf[pos + 3];\r\n f8b[3] = buf[pos + 4];\r\n f8b[2] = buf[pos + 5];\r\n f8b[1] = buf[pos + 6];\r\n f8b[0] = buf[pos + 7];\r\n return f64[0];\r\n }\r\n\r\n /* istanbul ignore next */\r\n exports.readDoubleLE = le ? readDouble_f64_cpy : readDouble_f64_rev;\r\n /* istanbul ignore next */\r\n exports.readDoubleBE = le ? readDouble_f64_rev : readDouble_f64_cpy;\r\n\r\n // double: ieee754\r\n })(); else (function() {\r\n\r\n function writeDouble_ieee754(writeUint, off0, off1, val, buf, pos) {\r\n var sign = val < 0 ? 1 : 0;\r\n if (sign)\r\n val = -val;\r\n if (val === 0) {\r\n writeUint(0, buf, pos + off0);\r\n writeUint(1 / val > 0 ? /* positive */ 0 : /* negative 0 */ 2147483648, buf, pos + off1);\r\n } else if (isNaN(val)) {\r\n writeUint(0, buf, pos + off0);\r\n writeUint(2146959360, buf, pos + off1);\r\n } else if (val > 1.7976931348623157e+308) { // +-Infinity\r\n writeUint(0, buf, pos + off0);\r\n writeUint((sign << 31 | 2146435072) >>> 0, buf, pos + off1);\r\n } else {\r\n var mantissa;\r\n if (val < 2.2250738585072014e-308) { // denormal\r\n mantissa = val / 5e-324;\r\n writeUint(mantissa >>> 0, buf, pos + off0);\r\n writeUint((sign << 31 | mantissa / 4294967296) >>> 0, buf, pos + off1);\r\n } else {\r\n var exponent = Math.floor(Math.log(val) / Math.LN2);\r\n if (exponent === 1024)\r\n exponent = 1023;\r\n mantissa = val * Math.pow(2, -exponent);\r\n writeUint(mantissa * 4503599627370496 >>> 0, buf, pos + off0);\r\n writeUint((sign << 31 | exponent + 1023 << 20 | mantissa * 1048576 & 1048575) >>> 0, buf, pos + off1);\r\n }\r\n }\r\n }\r\n\r\n exports.writeDoubleLE = writeDouble_ieee754.bind(null, writeUintLE, 0, 4);\r\n exports.writeDoubleBE = writeDouble_ieee754.bind(null, writeUintBE, 4, 0);\r\n\r\n function readDouble_ieee754(readUint, off0, off1, buf, pos) {\r\n var lo = readUint(buf, pos + off0),\r\n hi = readUint(buf, pos + off1);\r\n var sign = (hi >> 31) * 2 + 1,\r\n exponent = hi >>> 20 & 2047,\r\n mantissa = 4294967296 * (hi & 1048575) + lo;\r\n return exponent === 2047\r\n ? mantissa\r\n ? NaN\r\n : sign * Infinity\r\n : exponent === 0 // denormal\r\n ? sign * 5e-324 * mantissa\r\n : sign * Math.pow(2, exponent - 1075) * (mantissa + 4503599627370496);\r\n }\r\n\r\n exports.readDoubleLE = readDouble_ieee754.bind(null, readUintLE, 0, 4);\r\n exports.readDoubleBE = readDouble_ieee754.bind(null, readUintBE, 4, 0);\r\n\r\n })();\r\n\r\n return exports;\r\n}\r\n\r\n// uint helpers\r\n\r\nfunction writeUintLE(val, buf, pos) {\r\n buf[pos ] = val & 255;\r\n buf[pos + 1] = val >>> 8 & 255;\r\n buf[pos + 2] = val >>> 16 & 255;\r\n buf[pos + 3] = val >>> 24;\r\n}\r\n\r\nfunction writeUintBE(val, buf, pos) {\r\n buf[pos ] = val >>> 24;\r\n buf[pos + 1] = val >>> 16 & 255;\r\n buf[pos + 2] = val >>> 8 & 255;\r\n buf[pos + 3] = val & 255;\r\n}\r\n\r\nfunction readUintLE(buf, pos) {\r\n return (buf[pos ]\r\n | buf[pos + 1] << 8\r\n | buf[pos + 2] << 16\r\n | buf[pos + 3] << 24) >>> 0;\r\n}\r\n\r\nfunction readUintBE(buf, pos) {\r\n return (buf[pos ] << 24\r\n | buf[pos + 1] << 16\r\n | buf[pos + 2] << 8\r\n | buf[pos + 3]) >>> 0;\r\n}\r\n","\"use strict\";\r\nmodule.exports = inquire;\r\n\r\n/**\r\n * Requires a module only if available.\r\n * @memberof util\r\n * @param {string} moduleName Module to require\r\n * @returns {?Object} Required module if available and not empty, otherwise `null`\r\n */\r\nfunction inquire(moduleName) {\r\n try {\r\n var mod = eval(\"quire\".replace(/^/,\"re\"))(moduleName); // eslint-disable-line no-eval\r\n if (mod && (mod.length || Object.keys(mod).length))\r\n return mod;\r\n } catch (e) {} // eslint-disable-line no-empty\r\n return null;\r\n}\r\n","\"use strict\";\r\n\r\n/**\r\n * A minimal path module to resolve Unix, Windows and URL paths alike.\r\n * @memberof util\r\n * @namespace\r\n */\r\nvar path = exports;\r\n\r\nvar isAbsolute =\r\n/**\r\n * Tests if the specified path is absolute.\r\n * @param {string} path Path to test\r\n * @returns {boolean} `true` if path is absolute\r\n */\r\npath.isAbsolute = function isAbsolute(path) {\r\n return /^(?:\\/|\\w+:)/.test(path);\r\n};\r\n\r\nvar normalize =\r\n/**\r\n * Normalizes the specified path.\r\n * @param {string} path Path to normalize\r\n * @returns {string} Normalized path\r\n */\r\npath.normalize = function normalize(path) {\r\n path = path.replace(/\\\\/g, \"/\")\r\n .replace(/\\/{2,}/g, \"/\");\r\n var parts = path.split(\"/\"),\r\n absolute = isAbsolute(path),\r\n prefix = \"\";\r\n if (absolute)\r\n prefix = parts.shift() + \"/\";\r\n for (var i = 0; i < parts.length;) {\r\n if (parts[i] === \"..\") {\r\n if (i > 0 && parts[i - 1] !== \"..\")\r\n parts.splice(--i, 2);\r\n else if (absolute)\r\n parts.splice(i, 1);\r\n else\r\n ++i;\r\n } else if (parts[i] === \".\")\r\n parts.splice(i, 1);\r\n else\r\n ++i;\r\n }\r\n return prefix + parts.join(\"/\");\r\n};\r\n\r\n/**\r\n * Resolves the specified include path against the specified origin path.\r\n * @param {string} originPath Path to the origin file\r\n * @param {string} includePath Include path relative to origin path\r\n * @param {boolean} [alreadyNormalized=false] `true` if both paths are already known to be normalized\r\n * @returns {string} Path to the include file\r\n */\r\npath.resolve = function resolve(originPath, includePath, alreadyNormalized) {\r\n if (!alreadyNormalized)\r\n includePath = normalize(includePath);\r\n if (isAbsolute(includePath))\r\n return includePath;\r\n if (!alreadyNormalized)\r\n originPath = normalize(originPath);\r\n return (originPath = originPath.replace(/(?:\\/|^)[^/]+$/, \"\")).length ? normalize(originPath + \"/\" + includePath) : includePath;\r\n};\r\n","\"use strict\";\r\nmodule.exports = pool;\r\n\r\n/**\r\n * An allocator as used by {@link util.pool}.\r\n * @typedef PoolAllocator\r\n * @type {function}\r\n * @param {number} size Buffer size\r\n * @returns {Uint8Array} Buffer\r\n */\r\n\r\n/**\r\n * A slicer as used by {@link util.pool}.\r\n * @typedef PoolSlicer\r\n * @type {function}\r\n * @param {number} start Start offset\r\n * @param {number} end End offset\r\n * @returns {Uint8Array} Buffer slice\r\n * @this {Uint8Array}\r\n */\r\n\r\n/**\r\n * A general purpose buffer pool.\r\n * @memberof util\r\n * @function\r\n * @param {PoolAllocator} alloc Allocator\r\n * @param {PoolSlicer} slice Slicer\r\n * @param {number} [size=8192] Slab size\r\n * @returns {PoolAllocator} Pooled allocator\r\n */\r\nfunction pool(alloc, slice, size) {\r\n var SIZE = size || 8192;\r\n var MAX = SIZE >>> 1;\r\n var slab = null;\r\n var offset = SIZE;\r\n return function pool_alloc(size) {\r\n if (size < 1 || size > MAX)\r\n return alloc(size);\r\n if (offset + size > SIZE) {\r\n slab = alloc(SIZE);\r\n offset = 0;\r\n }\r\n var buf = slice.call(slab, offset, offset += size);\r\n if (offset & 7) // align to 32 bit\r\n offset = (offset | 7) + 1;\r\n return buf;\r\n };\r\n}\r\n","\"use strict\";\r\n\r\n/**\r\n * A minimal UTF8 implementation for number arrays.\r\n * @memberof util\r\n * @namespace\r\n */\r\nvar utf8 = exports;\r\n\r\n/**\r\n * Calculates the UTF8 byte length of a string.\r\n * @param {string} string String\r\n * @returns {number} Byte length\r\n */\r\nutf8.length = function utf8_length(string) {\r\n var len = 0,\r\n c = 0;\r\n for (var i = 0; i < string.length; ++i) {\r\n c = string.charCodeAt(i);\r\n if (c < 128)\r\n len += 1;\r\n else if (c < 2048)\r\n len += 2;\r\n else if ((c & 0xFC00) === 0xD800 && (string.charCodeAt(i + 1) & 0xFC00) === 0xDC00) {\r\n ++i;\r\n len += 4;\r\n } else\r\n len += 3;\r\n }\r\n return len;\r\n};\r\n\r\n/**\r\n * Reads UTF8 bytes as a string.\r\n * @param {Uint8Array} buffer Source buffer\r\n * @param {number} start Source start\r\n * @param {number} end Source end\r\n * @returns {string} String read\r\n */\r\nutf8.read = function utf8_read(buffer, start, end) {\r\n var len = end - start;\r\n if (len < 1)\r\n return \"\";\r\n var parts = null,\r\n chunk = [],\r\n i = 0, // char offset\r\n t; // temporary\r\n while (start < end) {\r\n t = buffer[start++];\r\n if (t < 128)\r\n chunk[i++] = t;\r\n else if (t > 191 && t < 224)\r\n chunk[i++] = (t & 31) << 6 | buffer[start++] & 63;\r\n else if (t > 239 && t < 365) {\r\n t = ((t & 7) << 18 | (buffer[start++] & 63) << 12 | (buffer[start++] & 63) << 6 | buffer[start++] & 63) - 0x10000;\r\n chunk[i++] = 0xD800 + (t >> 10);\r\n chunk[i++] = 0xDC00 + (t & 1023);\r\n } else\r\n chunk[i++] = (t & 15) << 12 | (buffer[start++] & 63) << 6 | buffer[start++] & 63;\r\n if (i > 8191) {\r\n (parts || (parts = [])).push(String.fromCharCode.apply(String, chunk));\r\n i = 0;\r\n }\r\n }\r\n if (parts) {\r\n if (i)\r\n parts.push(String.fromCharCode.apply(String, chunk.slice(0, i)));\r\n return parts.join(\"\");\r\n }\r\n return String.fromCharCode.apply(String, chunk.slice(0, i));\r\n};\r\n\r\n/**\r\n * Writes a string as UTF8 bytes.\r\n * @param {string} string Source string\r\n * @param {Uint8Array} buffer Destination buffer\r\n * @param {number} offset Destination offset\r\n * @returns {number} Bytes written\r\n */\r\nutf8.write = function utf8_write(string, buffer, offset) {\r\n var start = offset,\r\n c1, // character 1\r\n c2; // character 2\r\n for (var i = 0; i < string.length; ++i) {\r\n c1 = string.charCodeAt(i);\r\n if (c1 < 128) {\r\n buffer[offset++] = c1;\r\n } else if (c1 < 2048) {\r\n buffer[offset++] = c1 >> 6 | 192;\r\n buffer[offset++] = c1 & 63 | 128;\r\n } else if ((c1 & 0xFC00) === 0xD800 && ((c2 = string.charCodeAt(i + 1)) & 0xFC00) === 0xDC00) {\r\n c1 = 0x10000 + ((c1 & 0x03FF) << 10) + (c2 & 0x03FF);\r\n ++i;\r\n buffer[offset++] = c1 >> 18 | 240;\r\n buffer[offset++] = c1 >> 12 & 63 | 128;\r\n buffer[offset++] = c1 >> 6 & 63 | 128;\r\n buffer[offset++] = c1 & 63 | 128;\r\n } else {\r\n buffer[offset++] = c1 >> 12 | 224;\r\n buffer[offset++] = c1 >> 6 & 63 | 128;\r\n buffer[offset++] = c1 & 63 | 128;\r\n }\r\n }\r\n return offset - start;\r\n};\r\n","\"use strict\";\n/**\n * Runtime message from/to plain object converters.\n * @namespace\n */\nvar converter = exports;\n\nvar Enum = require(14),\n util = require(33);\n\n/**\n * Generates a partial value fromObject conveter.\n * @param {Codegen} gen Codegen instance\n * @param {Field} field Reflected field\n * @param {number} fieldIndex Field index\n * @param {string} prop Property reference\n * @returns {Codegen} Codegen instance\n * @ignore\n */\nfunction genValuePartial_fromObject(gen, field, fieldIndex, prop) {\n var defaultAlreadyEmitted = false;\n /* eslint-disable no-unexpected-multiline, block-scoped-var, no-redeclare */\n if (field.resolvedType) {\n if (field.resolvedType instanceof Enum) { gen\n (\"switch(d%s){\", prop);\n for (var values = field.resolvedType.values, keys = Object.keys(values), i = 0; i < keys.length; ++i) {\n // enum unknown values passthrough\n if (values[keys[i]] === field.typeDefault && !defaultAlreadyEmitted) { gen\n (\"default:\")\n (\"if(typeof(d%s)===\\\"number\\\"){m%s=d%s;break}\", prop, prop, prop);\n if (!field.repeated) gen // fallback to default value only for\n // arrays, to avoid leaving holes.\n (\"break\"); // for non-repeated fields, just ignore\n defaultAlreadyEmitted = true;\n }\n gen\n (\"case%j:\", keys[i])\n (\"case %i:\", values[keys[i]])\n (\"m%s=%j\", prop, values[keys[i]])\n (\"break\");\n } gen\n (\"}\");\n } else gen\n (\"if(typeof d%s!==\\\"object\\\")\", prop)\n (\"throw TypeError(%j)\", field.fullName + \": object expected\")\n (\"m%s=types[%i].fromObject(d%s)\", prop, fieldIndex, prop);\n } else {\n var isUnsigned = false;\n switch (field.type) {\n case \"double\":\n case \"float\": gen\n (\"m%s=Number(d%s)\", prop, prop); // also catches \"NaN\", \"Infinity\"\n break;\n case \"uint32\":\n case \"fixed32\": gen\n (\"m%s=d%s>>>0\", prop, prop);\n break;\n case \"int32\":\n case \"sint32\":\n case \"sfixed32\": gen\n (\"m%s=d%s|0\", prop, prop);\n break;\n case \"uint64\":\n isUnsigned = true;\n // eslint-disable-next-line no-fallthrough\n case \"int64\":\n case \"sint64\":\n case \"fixed64\":\n case \"sfixed64\": gen\n (\"if(util.Long)\")\n (\"(m%s=util.Long.fromValue(d%s)).unsigned=%j\", prop, prop, isUnsigned)\n (\"else if(typeof d%s===\\\"string\\\")\", prop)\n (\"m%s=parseInt(d%s,10)\", prop, prop)\n (\"else if(typeof d%s===\\\"number\\\")\", prop)\n (\"m%s=d%s\", prop, prop)\n (\"else if(typeof d%s===\\\"object\\\")\", prop)\n (\"m%s=new util.LongBits(d%s.low>>>0,d%s.high>>>0).toNumber(%s)\", prop, prop, prop, isUnsigned ? \"true\" : \"\");\n break;\n case \"bytes\": gen\n (\"if(typeof d%s===\\\"string\\\")\", prop)\n (\"util.base64.decode(d%s,m%s=util.newBuffer(util.base64.length(d%s)),0)\", prop, prop, prop)\n (\"else if(d%s.length >= 0)\", prop)\n (\"m%s=d%s\", prop, prop);\n break;\n case \"string\": gen\n (\"m%s=String(d%s)\", prop, prop);\n break;\n case \"bool\": gen\n (\"m%s=Boolean(d%s)\", prop, prop);\n break;\n /* default: gen\n (\"m%s=d%s\", prop, prop);\n break; */\n }\n }\n return gen;\n /* eslint-enable no-unexpected-multiline, block-scoped-var, no-redeclare */\n}\n\n/**\n * Generates a plain object to runtime message converter specific to the specified message type.\n * @param {Type} mtype Message type\n * @returns {Codegen} Codegen instance\n */\nconverter.fromObject = function fromObject(mtype) {\n /* eslint-disable no-unexpected-multiline, block-scoped-var, no-redeclare */\n var fields = mtype.fieldsArray;\n var gen = util.codegen([\"d\"], mtype.name + \"$fromObject\")\n (\"if(d instanceof this.ctor)\")\n (\"return d\");\n if (!fields.length) return gen\n (\"return new this.ctor\");\n gen\n (\"var m=new this.ctor\");\n for (var i = 0; i < fields.length; ++i) {\n var field = fields[i].resolve(),\n prop = util.safeProp(field.name);\n\n // Map fields\n if (field.map) { gen\n (\"if(d%s){\", prop)\n (\"if(typeof d%s!==\\\"object\\\")\", prop)\n (\"throw TypeError(%j)\", field.fullName + \": object expected\")\n (\"m%s={}\", prop)\n (\"for(var ks=Object.keys(d%s),i=0;i>>0,m%s.high>>>0).toNumber(%s):m%s\", prop, prop, prop, prop, isUnsigned ? \"true\": \"\", prop);\n break;\n case \"bytes\": gen\n (\"d%s=o.bytes===String?util.base64.encode(m%s,0,m%s.length):o.bytes===Array?Array.prototype.slice.call(m%s):m%s\", prop, prop, prop, prop, prop);\n break;\n default: gen\n (\"d%s=m%s\", prop, prop);\n break;\n }\n }\n return gen;\n /* eslint-enable no-unexpected-multiline, block-scoped-var, no-redeclare */\n}\n\n/**\n * Generates a runtime message to plain object converter specific to the specified message type.\n * @param {Type} mtype Message type\n * @returns {Codegen} Codegen instance\n */\nconverter.toObject = function toObject(mtype) {\n /* eslint-disable no-unexpected-multiline, block-scoped-var, no-redeclare */\n var fields = mtype.fieldsArray.slice().sort(util.compareFieldsById);\n if (!fields.length)\n return util.codegen()(\"return {}\");\n var gen = util.codegen([\"m\", \"o\"], mtype.name + \"$toObject\")\n (\"if(!o)\")\n (\"o={}\")\n (\"var d={}\");\n\n var repeatedFields = [],\n mapFields = [],\n normalFields = [],\n i = 0;\n for (; i < fields.length; ++i)\n if (!fields[i].partOf)\n ( fields[i].resolve().repeated ? repeatedFields\n : fields[i].map ? mapFields\n : normalFields).push(fields[i]);\n\n if (repeatedFields.length) { gen\n (\"if(o.arrays||o.defaults){\");\n for (i = 0; i < repeatedFields.length; ++i) gen\n (\"d%s=[]\", util.safeProp(repeatedFields[i].name));\n gen\n (\"}\");\n }\n\n if (mapFields.length) { gen\n (\"if(o.objects||o.defaults){\");\n for (i = 0; i < mapFields.length; ++i) gen\n (\"d%s={}\", util.safeProp(mapFields[i].name));\n gen\n (\"}\");\n }\n\n if (normalFields.length) { gen\n (\"if(o.defaults){\");\n for (i = 0; i < normalFields.length; ++i) {\n var field = normalFields[i],\n prop = util.safeProp(field.name);\n if (field.resolvedType instanceof Enum) gen\n (\"d%s=o.enums===String?%j:%j\", prop, field.resolvedType.valuesById[field.typeDefault], field.typeDefault);\n else if (field.long) gen\n (\"if(util.Long){\")\n (\"var n=new util.Long(%i,%i,%j)\", field.typeDefault.low, field.typeDefault.high, field.typeDefault.unsigned)\n (\"d%s=o.longs===String?n.toString():o.longs===Number?n.toNumber():n\", prop)\n (\"}else\")\n (\"d%s=o.longs===String?%j:%i\", prop, field.typeDefault.toString(), field.typeDefault.toNumber());\n else if (field.bytes) {\n var arrayDefault = \"[\" + Array.prototype.slice.call(field.typeDefault).join(\",\") + \"]\";\n gen\n (\"if(o.bytes===String)d%s=%j\", prop, String.fromCharCode.apply(String, field.typeDefault))\n (\"else{\")\n (\"d%s=%s\", prop, arrayDefault)\n (\"if(o.bytes!==Array)d%s=util.newBuffer(d%s)\", prop, prop)\n (\"}\");\n } else gen\n (\"d%s=%j\", prop, field.typeDefault); // also messages (=null)\n } gen\n (\"}\");\n }\n var hasKs2 = false;\n for (i = 0; i < fields.length; ++i) {\n var field = fields[i],\n index = mtype._fieldsArray.indexOf(field),\n prop = util.safeProp(field.name);\n if (field.map) {\n if (!hasKs2) { hasKs2 = true; gen\n (\"var ks2\");\n } gen\n (\"if(m%s&&(ks2=Object.keys(m%s)).length){\", prop, prop)\n (\"d%s={}\", prop)\n (\"for(var j=0;j>>3){\");\n\n var i = 0;\n for (; i < /* initializes */ mtype.fieldsArray.length; ++i) {\n var field = mtype._fieldsArray[i].resolve(),\n type = field.resolvedType instanceof Enum ? \"int32\" : field.type,\n ref = \"m\" + util.safeProp(field.name); gen\n (\"case %i: {\", field.id);\n\n // Map fields\n if (field.map) { gen\n (\"if(%s===util.emptyObject)\", ref)\n (\"%s={}\", ref)\n (\"var c2 = r.uint32()+r.pos\");\n\n if (types.defaults[field.keyType] !== undefined) gen\n (\"k=%j\", types.defaults[field.keyType]);\n else gen\n (\"k=null\");\n\n if (types.defaults[type] !== undefined) gen\n (\"value=%j\", types.defaults[type]);\n else gen\n (\"value=null\");\n\n gen\n (\"while(r.pos>>3){\")\n (\"case 1: k=r.%s(); break\", field.keyType)\n (\"case 2:\");\n\n if (types.basic[type] === undefined) gen\n (\"value=types[%i].decode(r,r.uint32())\", i); // can't be groups\n else gen\n (\"value=r.%s()\", type);\n\n gen\n (\"break\")\n (\"default:\")\n (\"r.skipType(tag2&7)\")\n (\"break\")\n (\"}\")\n (\"}\");\n\n if (types.long[field.keyType] !== undefined) gen\n (\"%s[typeof k===\\\"object\\\"?util.longToHash(k):k]=value\", ref);\n else gen\n (\"%s[k]=value\", ref);\n\n // Repeated fields\n } else if (field.repeated) { gen\n\n (\"if(!(%s&&%s.length))\", ref, ref)\n (\"%s=[]\", ref);\n\n // Packable (always check for forward and backward compatiblity)\n if (types.packed[type] !== undefined) gen\n (\"if((t&7)===2){\")\n (\"var c2=r.uint32()+r.pos\")\n (\"while(r.pos>> 0, (field.id << 3 | 4) >>> 0)\n : gen(\"types[%i].encode(%s,w.uint32(%i).fork()).ldelim()\", fieldIndex, ref, (field.id << 3 | 2) >>> 0);\n}\n\n/**\n * Generates an encoder specific to the specified message type.\n * @param {Type} mtype Message type\n * @returns {Codegen} Codegen instance\n */\nfunction encoder(mtype) {\n /* eslint-disable no-unexpected-multiline, block-scoped-var, no-redeclare */\n var gen = util.codegen([\"m\", \"w\"], mtype.name + \"$encode\")\n (\"if(!w)\")\n (\"w=Writer.create()\");\n\n var i, ref;\n\n // \"when a message is serialized its known fields should be written sequentially by field number\"\n var fields = /* initializes */ mtype.fieldsArray.slice().sort(util.compareFieldsById);\n\n for (var i = 0; i < fields.length; ++i) {\n var field = fields[i].resolve(),\n index = mtype._fieldsArray.indexOf(field),\n type = field.resolvedType instanceof Enum ? \"int32\" : field.type,\n wireType = types.basic[type];\n ref = \"m\" + util.safeProp(field.name);\n\n // Map fields\n if (field.map) {\n gen\n (\"if(%s!=null&&Object.hasOwnProperty.call(m,%j)){\", ref, field.name) // !== undefined && !== null\n (\"for(var ks=Object.keys(%s),i=0;i>> 0, 8 | types.mapKey[field.keyType], field.keyType);\n if (wireType === undefined) gen\n (\"types[%i].encode(%s[ks[i]],w.uint32(18).fork()).ldelim().ldelim()\", index, ref); // can't be groups\n else gen\n (\".uint32(%i).%s(%s[ks[i]]).ldelim()\", 16 | wireType, type, ref);\n gen\n (\"}\")\n (\"}\");\n\n // Repeated fields\n } else if (field.repeated) { gen\n (\"if(%s!=null&&%s.length){\", ref, ref); // !== undefined && !== null\n\n // Packed repeated\n if (field.packed && types.packed[type] !== undefined) { gen\n\n (\"w.uint32(%i).fork()\", (field.id << 3 | 2) >>> 0)\n (\"for(var i=0;i<%s.length;++i)\", ref)\n (\"w.%s(%s[i])\", type, ref)\n (\"w.ldelim()\");\n\n // Non-packed\n } else { gen\n\n (\"for(var i=0;i<%s.length;++i)\", ref);\n if (wireType === undefined)\n genTypePartial(gen, field, index, ref + \"[i]\");\n else gen\n (\"w.uint32(%i).%s(%s[i])\", (field.id << 3 | wireType) >>> 0, type, ref);\n\n } gen\n (\"}\");\n\n // Non-repeated\n } else {\n if (field.optional) gen\n (\"if(%s!=null&&Object.hasOwnProperty.call(m,%j))\", ref, field.name); // !== undefined && !== null\n\n if (wireType === undefined)\n genTypePartial(gen, field, index, ref);\n else gen\n (\"w.uint32(%i).%s(%s)\", (field.id << 3 | wireType) >>> 0, type, ref);\n\n }\n }\n\n return gen\n (\"return w\");\n /* eslint-enable no-unexpected-multiline, block-scoped-var, no-redeclare */\n}\n","\"use strict\";\nmodule.exports = Enum;\n\n// extends ReflectionObject\nvar ReflectionObject = require(22);\n((Enum.prototype = Object.create(ReflectionObject.prototype)).constructor = Enum).className = \"Enum\";\n\nvar Namespace = require(21),\n util = require(33);\n\n/**\n * Constructs a new enum instance.\n * @classdesc Reflected enum.\n * @extends ReflectionObject\n * @constructor\n * @param {string} name Unique name within its namespace\n * @param {Object.} [values] Enum values as an object, by name\n * @param {Object.} [options] Declared options\n * @param {string} [comment] The comment for this enum\n * @param {Object.} [comments] The value comments for this enum\n * @param {Object.>|undefined} [valuesOptions] The value options for this enum\n */\nfunction Enum(name, values, options, comment, comments, valuesOptions) {\n ReflectionObject.call(this, name, options);\n\n if (values && typeof values !== \"object\")\n throw TypeError(\"values must be an object\");\n\n /**\n * Enum values by id.\n * @type {Object.}\n */\n this.valuesById = {};\n\n /**\n * Enum values by name.\n * @type {Object.}\n */\n this.values = Object.create(this.valuesById); // toJSON, marker\n\n /**\n * Enum comment text.\n * @type {string|null}\n */\n this.comment = comment;\n\n /**\n * Value comment texts, if any.\n * @type {Object.}\n */\n this.comments = comments || {};\n\n /**\n * Values options, if any\n * @type {Object>|undefined}\n */\n this.valuesOptions = valuesOptions;\n\n /**\n * Reserved ranges, if any.\n * @type {Array.}\n */\n this.reserved = undefined; // toJSON\n\n // Note that values inherit valuesById on their prototype which makes them a TypeScript-\n // compatible enum. This is used by pbts to write actual enum definitions that work for\n // static and reflection code alike instead of emitting generic object definitions.\n\n if (values)\n for (var keys = Object.keys(values), i = 0; i < keys.length; ++i)\n if (typeof values[keys[i]] === \"number\") // use forward entries only\n this.valuesById[ this.values[keys[i]] = values[keys[i]] ] = keys[i];\n}\n\n/**\n * Enum descriptor.\n * @interface IEnum\n * @property {Object.} values Enum values\n * @property {Object.} [options] Enum options\n */\n\n/**\n * Constructs an enum from an enum descriptor.\n * @param {string} name Enum name\n * @param {IEnum} json Enum descriptor\n * @returns {Enum} Created enum\n * @throws {TypeError} If arguments are invalid\n */\nEnum.fromJSON = function fromJSON(name, json) {\n var enm = new Enum(name, json.values, json.options, json.comment, json.comments);\n enm.reserved = json.reserved;\n return enm;\n};\n\n/**\n * Converts this enum to an enum descriptor.\n * @param {IToJSONOptions} [toJSONOptions] JSON conversion options\n * @returns {IEnum} Enum descriptor\n */\nEnum.prototype.toJSON = function toJSON(toJSONOptions) {\n var keepComments = toJSONOptions ? Boolean(toJSONOptions.keepComments) : false;\n return util.toObject([\n \"options\" , this.options,\n \"valuesOptions\" , this.valuesOptions,\n \"values\" , this.values,\n \"reserved\" , this.reserved && this.reserved.length ? this.reserved : undefined,\n \"comment\" , keepComments ? this.comment : undefined,\n \"comments\" , keepComments ? this.comments : undefined\n ]);\n};\n\n/**\n * Adds a value to this enum.\n * @param {string} name Value name\n * @param {number} id Value id\n * @param {string} [comment] Comment, if any\n * @param {Object.|undefined} [options] Options, if any\n * @returns {Enum} `this`\n * @throws {TypeError} If arguments are invalid\n * @throws {Error} If there is already a value with this name or id\n */\nEnum.prototype.add = function add(name, id, comment, options) {\n // utilized by the parser but not by .fromJSON\n\n if (!util.isString(name))\n throw TypeError(\"name must be a string\");\n\n if (!util.isInteger(id))\n throw TypeError(\"id must be an integer\");\n\n if (this.values[name] !== undefined)\n throw Error(\"duplicate name '\" + name + \"' in \" + this);\n\n if (this.isReservedId(id))\n throw Error(\"id \" + id + \" is reserved in \" + this);\n\n if (this.isReservedName(name))\n throw Error(\"name '\" + name + \"' is reserved in \" + this);\n\n if (this.valuesById[id] !== undefined) {\n if (!(this.options && this.options.allow_alias))\n throw Error(\"duplicate id \" + id + \" in \" + this);\n this.values[name] = id;\n } else\n this.valuesById[this.values[name] = id] = name;\n\n if (options) {\n if (this.valuesOptions === undefined)\n this.valuesOptions = {};\n this.valuesOptions[name] = options || null;\n }\n\n this.comments[name] = comment || null;\n return this;\n};\n\n/**\n * Removes a value from this enum\n * @param {string} name Value name\n * @returns {Enum} `this`\n * @throws {TypeError} If arguments are invalid\n * @throws {Error} If `name` is not a name of this enum\n */\nEnum.prototype.remove = function remove(name) {\n\n if (!util.isString(name))\n throw TypeError(\"name must be a string\");\n\n var val = this.values[name];\n if (val == null)\n throw Error(\"name '\" + name + \"' does not exist in \" + this);\n\n delete this.valuesById[val];\n delete this.values[name];\n delete this.comments[name];\n if (this.valuesOptions)\n delete this.valuesOptions[name];\n\n return this;\n};\n\n/**\n * Tests if the specified id is reserved.\n * @param {number} id Id to test\n * @returns {boolean} `true` if reserved, otherwise `false`\n */\nEnum.prototype.isReservedId = function isReservedId(id) {\n return Namespace.isReservedId(this.reserved, id);\n};\n\n/**\n * Tests if the specified name is reserved.\n * @param {string} name Name to test\n * @returns {boolean} `true` if reserved, otherwise `false`\n */\nEnum.prototype.isReservedName = function isReservedName(name) {\n return Namespace.isReservedName(this.reserved, name);\n};\n","\"use strict\";\nmodule.exports = Field;\n\n// extends ReflectionObject\nvar ReflectionObject = require(22);\n((Field.prototype = Object.create(ReflectionObject.prototype)).constructor = Field).className = \"Field\";\n\nvar Enum = require(14),\n types = require(32),\n util = require(33);\n\nvar Type; // cyclic\n\nvar ruleRe = /^required|optional|repeated$/;\n\n/**\n * Constructs a new message field instance. Note that {@link MapField|map fields} have their own class.\n * @name Field\n * @classdesc Reflected message field.\n * @extends FieldBase\n * @constructor\n * @param {string} name Unique name within its namespace\n * @param {number} id Unique id within its namespace\n * @param {string} type Value type\n * @param {string|Object.} [rule=\"optional\"] Field rule\n * @param {string|Object.} [extend] Extended type if different from parent\n * @param {Object.} [options] Declared options\n */\n\n/**\n * Constructs a field from a field descriptor.\n * @param {string} name Field name\n * @param {IField} json Field descriptor\n * @returns {Field} Created field\n * @throws {TypeError} If arguments are invalid\n */\nField.fromJSON = function fromJSON(name, json) {\n return new Field(name, json.id, json.type, json.rule, json.extend, json.options, json.comment);\n};\n\n/**\n * Not an actual constructor. Use {@link Field} instead.\n * @classdesc Base class of all reflected message fields. This is not an actual class but here for the sake of having consistent type definitions.\n * @exports FieldBase\n * @extends ReflectionObject\n * @constructor\n * @param {string} name Unique name within its namespace\n * @param {number} id Unique id within its namespace\n * @param {string} type Value type\n * @param {string|Object.} [rule=\"optional\"] Field rule\n * @param {string|Object.} [extend] Extended type if different from parent\n * @param {Object.} [options] Declared options\n * @param {string} [comment] Comment associated with this field\n */\nfunction Field(name, id, type, rule, extend, options, comment) {\n\n if (util.isObject(rule)) {\n comment = extend;\n options = rule;\n rule = extend = undefined;\n } else if (util.isObject(extend)) {\n comment = options;\n options = extend;\n extend = undefined;\n }\n\n ReflectionObject.call(this, name, options);\n\n if (!util.isInteger(id) || id < 0)\n throw TypeError(\"id must be a non-negative integer\");\n\n if (!util.isString(type))\n throw TypeError(\"type must be a string\");\n\n if (rule !== undefined && !ruleRe.test(rule = rule.toString().toLowerCase()))\n throw TypeError(\"rule must be a string rule\");\n\n if (extend !== undefined && !util.isString(extend))\n throw TypeError(\"extend must be a string\");\n\n /**\n * Field rule, if any.\n * @type {string|undefined}\n */\n if (rule === \"proto3_optional\") {\n rule = \"optional\";\n }\n this.rule = rule && rule !== \"optional\" ? rule : undefined; // toJSON\n\n /**\n * Field type.\n * @type {string}\n */\n this.type = type; // toJSON\n\n /**\n * Unique field id.\n * @type {number}\n */\n this.id = id; // toJSON, marker\n\n /**\n * Extended type if different from parent.\n * @type {string|undefined}\n */\n this.extend = extend || undefined; // toJSON\n\n /**\n * Whether this field is required.\n * @type {boolean}\n */\n this.required = rule === \"required\";\n\n /**\n * Whether this field is optional.\n * @type {boolean}\n */\n this.optional = !this.required;\n\n /**\n * Whether this field is repeated.\n * @type {boolean}\n */\n this.repeated = rule === \"repeated\";\n\n /**\n * Whether this field is a map or not.\n * @type {boolean}\n */\n this.map = false;\n\n /**\n * Message this field belongs to.\n * @type {Type|null}\n */\n this.message = null;\n\n /**\n * OneOf this field belongs to, if any,\n * @type {OneOf|null}\n */\n this.partOf = null;\n\n /**\n * The field type's default value.\n * @type {*}\n */\n this.typeDefault = null;\n\n /**\n * The field's default value on prototypes.\n * @type {*}\n */\n this.defaultValue = null;\n\n /**\n * Whether this field's value should be treated as a long.\n * @type {boolean}\n */\n this.long = util.Long ? types.long[type] !== undefined : /* istanbul ignore next */ false;\n\n /**\n * Whether this field's value is a buffer.\n * @type {boolean}\n */\n this.bytes = type === \"bytes\";\n\n /**\n * Resolved type if not a basic type.\n * @type {Type|Enum|null}\n */\n this.resolvedType = null;\n\n /**\n * Sister-field within the extended type if a declaring extension field.\n * @type {Field|null}\n */\n this.extensionField = null;\n\n /**\n * Sister-field within the declaring namespace if an extended field.\n * @type {Field|null}\n */\n this.declaringField = null;\n\n /**\n * Internally remembers whether this field is packed.\n * @type {boolean|null}\n * @private\n */\n this._packed = null;\n\n /**\n * Comment for this field.\n * @type {string|null}\n */\n this.comment = comment;\n}\n\n/**\n * Determines whether this field is packed. Only relevant when repeated and working with proto2.\n * @name Field#packed\n * @type {boolean}\n * @readonly\n */\nObject.defineProperty(Field.prototype, \"packed\", {\n get: function() {\n // defaults to packed=true if not explicity set to false\n if (this._packed === null)\n this._packed = this.getOption(\"packed\") !== false;\n return this._packed;\n }\n});\n\n/**\n * @override\n */\nField.prototype.setOption = function setOption(name, value, ifNotSet) {\n if (name === \"packed\") // clear cached before setting\n this._packed = null;\n return ReflectionObject.prototype.setOption.call(this, name, value, ifNotSet);\n};\n\n/**\n * Field descriptor.\n * @interface IField\n * @property {string} [rule=\"optional\"] Field rule\n * @property {string} type Field type\n * @property {number} id Field id\n * @property {Object.} [options] Field options\n */\n\n/**\n * Extension field descriptor.\n * @interface IExtensionField\n * @extends IField\n * @property {string} extend Extended type\n */\n\n/**\n * Converts this field to a field descriptor.\n * @param {IToJSONOptions} [toJSONOptions] JSON conversion options\n * @returns {IField} Field descriptor\n */\nField.prototype.toJSON = function toJSON(toJSONOptions) {\n var keepComments = toJSONOptions ? Boolean(toJSONOptions.keepComments) : false;\n return util.toObject([\n \"rule\" , this.rule !== \"optional\" && this.rule || undefined,\n \"type\" , this.type,\n \"id\" , this.id,\n \"extend\" , this.extend,\n \"options\" , this.options,\n \"comment\" , keepComments ? this.comment : undefined\n ]);\n};\n\n/**\n * Resolves this field's type references.\n * @returns {Field} `this`\n * @throws {Error} If any reference cannot be resolved\n */\nField.prototype.resolve = function resolve() {\n\n if (this.resolved)\n return this;\n\n if ((this.typeDefault = types.defaults[this.type]) === undefined) { // if not a basic type, resolve it\n this.resolvedType = (this.declaringField ? this.declaringField.parent : this.parent).lookupTypeOrEnum(this.type);\n if (this.resolvedType instanceof Type)\n this.typeDefault = null;\n else // instanceof Enum\n this.typeDefault = this.resolvedType.values[Object.keys(this.resolvedType.values)[0]]; // first defined\n } else if (this.options && this.options.proto3_optional) {\n // proto3 scalar value marked optional; should default to null\n this.typeDefault = null;\n }\n\n // use explicitly set default value if present\n if (this.options && this.options[\"default\"] != null) {\n this.typeDefault = this.options[\"default\"];\n if (this.resolvedType instanceof Enum && typeof this.typeDefault === \"string\")\n this.typeDefault = this.resolvedType.values[this.typeDefault];\n }\n\n // remove unnecessary options\n if (this.options) {\n if (this.options.packed === true || this.options.packed !== undefined && this.resolvedType && !(this.resolvedType instanceof Enum))\n delete this.options.packed;\n if (!Object.keys(this.options).length)\n this.options = undefined;\n }\n\n // convert to internal data type if necesssary\n if (this.long) {\n this.typeDefault = util.Long.fromNumber(this.typeDefault, this.type.charAt(0) === \"u\");\n\n /* istanbul ignore else */\n if (Object.freeze)\n Object.freeze(this.typeDefault); // long instances are meant to be immutable anyway (i.e. use small int cache that even requires it)\n\n } else if (this.bytes && typeof this.typeDefault === \"string\") {\n var buf;\n if (util.base64.test(this.typeDefault))\n util.base64.decode(this.typeDefault, buf = util.newBuffer(util.base64.length(this.typeDefault)), 0);\n else\n util.utf8.write(this.typeDefault, buf = util.newBuffer(util.utf8.length(this.typeDefault)), 0);\n this.typeDefault = buf;\n }\n\n // take special care of maps and repeated fields\n if (this.map)\n this.defaultValue = util.emptyObject;\n else if (this.repeated)\n this.defaultValue = util.emptyArray;\n else\n this.defaultValue = this.typeDefault;\n\n // ensure proper value on prototype\n if (this.parent instanceof Type)\n this.parent.ctor.prototype[this.name] = this.defaultValue;\n\n return ReflectionObject.prototype.resolve.call(this);\n};\n\n/**\n * Decorator function as returned by {@link Field.d} and {@link MapField.d} (TypeScript).\n * @typedef FieldDecorator\n * @type {function}\n * @param {Object} prototype Target prototype\n * @param {string} fieldName Field name\n * @returns {undefined}\n */\n\n/**\n * Field decorator (TypeScript).\n * @name Field.d\n * @function\n * @param {number} fieldId Field id\n * @param {\"double\"|\"float\"|\"int32\"|\"uint32\"|\"sint32\"|\"fixed32\"|\"sfixed32\"|\"int64\"|\"uint64\"|\"sint64\"|\"fixed64\"|\"sfixed64\"|\"string\"|\"bool\"|\"bytes\"|Object} fieldType Field type\n * @param {\"optional\"|\"required\"|\"repeated\"} [fieldRule=\"optional\"] Field rule\n * @param {T} [defaultValue] Default value\n * @returns {FieldDecorator} Decorator function\n * @template T extends number | number[] | Long | Long[] | string | string[] | boolean | boolean[] | Uint8Array | Uint8Array[] | Buffer | Buffer[]\n */\nField.d = function decorateField(fieldId, fieldType, fieldRule, defaultValue) {\n\n // submessage: decorate the submessage and use its name as the type\n if (typeof fieldType === \"function\")\n fieldType = util.decorateType(fieldType).name;\n\n // enum reference: create a reflected copy of the enum and keep reuseing it\n else if (fieldType && typeof fieldType === \"object\")\n fieldType = util.decorateEnum(fieldType).name;\n\n return function fieldDecorator(prototype, fieldName) {\n util.decorateType(prototype.constructor)\n .add(new Field(fieldName, fieldId, fieldType, fieldRule, { \"default\": defaultValue }));\n };\n};\n\n/**\n * Field decorator (TypeScript).\n * @name Field.d\n * @function\n * @param {number} fieldId Field id\n * @param {Constructor|string} fieldType Field type\n * @param {\"optional\"|\"required\"|\"repeated\"} [fieldRule=\"optional\"] Field rule\n * @returns {FieldDecorator} Decorator function\n * @template T extends Message\n * @variation 2\n */\n// like Field.d but without a default value\n\n// Sets up cyclic dependencies (called in index-light)\nField._configure = function configure(Type_) {\n Type = Type_;\n};\n","\"use strict\";\nvar protobuf = module.exports = require(17);\n\nprotobuf.build = \"light\";\n\n/**\n * A node-style callback as used by {@link load} and {@link Root#load}.\n * @typedef LoadCallback\n * @type {function}\n * @param {Error|null} error Error, if any, otherwise `null`\n * @param {Root} [root] Root, if there hasn't been an error\n * @returns {undefined}\n */\n\n/**\n * Loads one or multiple .proto or preprocessed .json files into a common root namespace and calls the callback.\n * @param {string|string[]} filename One or multiple files to load\n * @param {Root} root Root namespace, defaults to create a new one if omitted.\n * @param {LoadCallback} callback Callback function\n * @returns {undefined}\n * @see {@link Root#load}\n */\nfunction load(filename, root, callback) {\n if (typeof root === \"function\") {\n callback = root;\n root = new protobuf.Root();\n } else if (!root)\n root = new protobuf.Root();\n return root.load(filename, callback);\n}\n\n/**\n * Loads one or multiple .proto or preprocessed .json files into a common root namespace and calls the callback.\n * @name load\n * @function\n * @param {string|string[]} filename One or multiple files to load\n * @param {LoadCallback} callback Callback function\n * @returns {undefined}\n * @see {@link Root#load}\n * @variation 2\n */\n// function load(filename:string, callback:LoadCallback):undefined\n\n/**\n * Loads one or multiple .proto or preprocessed .json files into a common root namespace and returns a promise.\n * @name load\n * @function\n * @param {string|string[]} filename One or multiple files to load\n * @param {Root} [root] Root namespace, defaults to create a new one if omitted.\n * @returns {Promise} Promise\n * @see {@link Root#load}\n * @variation 3\n */\n// function load(filename:string, [root:Root]):Promise\n\nprotobuf.load = load;\n\n/**\n * Synchronously loads one or multiple .proto or preprocessed .json files into a common root namespace (node only).\n * @param {string|string[]} filename One or multiple files to load\n * @param {Root} [root] Root namespace, defaults to create a new one if omitted.\n * @returns {Root} Root namespace\n * @throws {Error} If synchronous fetching is not supported (i.e. in browsers) or if a file's syntax is invalid\n * @see {@link Root#loadSync}\n */\nfunction loadSync(filename, root) {\n if (!root)\n root = new protobuf.Root();\n return root.loadSync(filename);\n}\n\nprotobuf.loadSync = loadSync;\n\n// Serialization\nprotobuf.encoder = require(13);\nprotobuf.decoder = require(12);\nprotobuf.verifier = require(36);\nprotobuf.converter = require(11);\n\n// Reflection\nprotobuf.ReflectionObject = require(22);\nprotobuf.Namespace = require(21);\nprotobuf.Root = require(26);\nprotobuf.Enum = require(14);\nprotobuf.Type = require(31);\nprotobuf.Field = require(15);\nprotobuf.OneOf = require(23);\nprotobuf.MapField = require(18);\nprotobuf.Service = require(30);\nprotobuf.Method = require(20);\n\n// Runtime\nprotobuf.Message = require(19);\nprotobuf.wrappers = require(37);\n\n// Utility\nprotobuf.types = require(32);\nprotobuf.util = require(33);\n\n// Set up possibly cyclic reflection dependencies\nprotobuf.ReflectionObject._configure(protobuf.Root);\nprotobuf.Namespace._configure(protobuf.Type, protobuf.Service, protobuf.Enum);\nprotobuf.Root._configure(protobuf.Type);\nprotobuf.Field._configure(protobuf.Type);\n","\"use strict\";\nvar protobuf = exports;\n\n/**\n * Build type, one of `\"full\"`, `\"light\"` or `\"minimal\"`.\n * @name build\n * @type {string}\n * @const\n */\nprotobuf.build = \"minimal\";\n\n// Serialization\nprotobuf.Writer = require(38);\nprotobuf.BufferWriter = require(39);\nprotobuf.Reader = require(24);\nprotobuf.BufferReader = require(25);\n\n// Utility\nprotobuf.util = require(35);\nprotobuf.rpc = require(28);\nprotobuf.roots = require(27);\nprotobuf.configure = configure;\n\n/* istanbul ignore next */\n/**\n * Reconfigures the library according to the environment.\n * @returns {undefined}\n */\nfunction configure() {\n protobuf.util._configure();\n protobuf.Writer._configure(protobuf.BufferWriter);\n protobuf.Reader._configure(protobuf.BufferReader);\n}\n\n// Set up buffer utility according to the environment\nconfigure();\n","\"use strict\";\nmodule.exports = MapField;\n\n// extends Field\nvar Field = require(15);\n((MapField.prototype = Object.create(Field.prototype)).constructor = MapField).className = \"MapField\";\n\nvar types = require(32),\n util = require(33);\n\n/**\n * Constructs a new map field instance.\n * @classdesc Reflected map field.\n * @extends FieldBase\n * @constructor\n * @param {string} name Unique name within its namespace\n * @param {number} id Unique id within its namespace\n * @param {string} keyType Key type\n * @param {string} type Value type\n * @param {Object.} [options] Declared options\n * @param {string} [comment] Comment associated with this field\n */\nfunction MapField(name, id, keyType, type, options, comment) {\n Field.call(this, name, id, type, undefined, undefined, options, comment);\n\n /* istanbul ignore if */\n if (!util.isString(keyType))\n throw TypeError(\"keyType must be a string\");\n\n /**\n * Key type.\n * @type {string}\n */\n this.keyType = keyType; // toJSON, marker\n\n /**\n * Resolved key type if not a basic type.\n * @type {ReflectionObject|null}\n */\n this.resolvedKeyType = null;\n\n // Overrides Field#map\n this.map = true;\n}\n\n/**\n * Map field descriptor.\n * @interface IMapField\n * @extends {IField}\n * @property {string} keyType Key type\n */\n\n/**\n * Extension map field descriptor.\n * @interface IExtensionMapField\n * @extends IMapField\n * @property {string} extend Extended type\n */\n\n/**\n * Constructs a map field from a map field descriptor.\n * @param {string} name Field name\n * @param {IMapField} json Map field descriptor\n * @returns {MapField} Created map field\n * @throws {TypeError} If arguments are invalid\n */\nMapField.fromJSON = function fromJSON(name, json) {\n return new MapField(name, json.id, json.keyType, json.type, json.options, json.comment);\n};\n\n/**\n * Converts this map field to a map field descriptor.\n * @param {IToJSONOptions} [toJSONOptions] JSON conversion options\n * @returns {IMapField} Map field descriptor\n */\nMapField.prototype.toJSON = function toJSON(toJSONOptions) {\n var keepComments = toJSONOptions ? Boolean(toJSONOptions.keepComments) : false;\n return util.toObject([\n \"keyType\" , this.keyType,\n \"type\" , this.type,\n \"id\" , this.id,\n \"extend\" , this.extend,\n \"options\" , this.options,\n \"comment\" , keepComments ? this.comment : undefined\n ]);\n};\n\n/**\n * @override\n */\nMapField.prototype.resolve = function resolve() {\n if (this.resolved)\n return this;\n\n // Besides a value type, map fields have a key type that may be \"any scalar type except for floating point types and bytes\"\n if (types.mapKey[this.keyType] === undefined)\n throw Error(\"invalid key type: \" + this.keyType);\n\n return Field.prototype.resolve.call(this);\n};\n\n/**\n * Map field decorator (TypeScript).\n * @name MapField.d\n * @function\n * @param {number} fieldId Field id\n * @param {\"int32\"|\"uint32\"|\"sint32\"|\"fixed32\"|\"sfixed32\"|\"int64\"|\"uint64\"|\"sint64\"|\"fixed64\"|\"sfixed64\"|\"bool\"|\"string\"} fieldKeyType Field key type\n * @param {\"double\"|\"float\"|\"int32\"|\"uint32\"|\"sint32\"|\"fixed32\"|\"sfixed32\"|\"int64\"|\"uint64\"|\"sint64\"|\"fixed64\"|\"sfixed64\"|\"bool\"|\"string\"|\"bytes\"|Object|Constructor<{}>} fieldValueType Field value type\n * @returns {FieldDecorator} Decorator function\n * @template T extends { [key: string]: number | Long | string | boolean | Uint8Array | Buffer | number[] | Message<{}> }\n */\nMapField.d = function decorateMapField(fieldId, fieldKeyType, fieldValueType) {\n\n // submessage value: decorate the submessage and use its name as the type\n if (typeof fieldValueType === \"function\")\n fieldValueType = util.decorateType(fieldValueType).name;\n\n // enum reference value: create a reflected copy of the enum and keep reuseing it\n else if (fieldValueType && typeof fieldValueType === \"object\")\n fieldValueType = util.decorateEnum(fieldValueType).name;\n\n return function mapFieldDecorator(prototype, fieldName) {\n util.decorateType(prototype.constructor)\n .add(new MapField(fieldName, fieldId, fieldKeyType, fieldValueType));\n };\n};\n","\"use strict\";\nmodule.exports = Message;\n\nvar util = require(35);\n\n/**\n * Constructs a new message instance.\n * @classdesc Abstract runtime message.\n * @constructor\n * @param {Properties} [properties] Properties to set\n * @template T extends object = object\n */\nfunction Message(properties) {\n // not used internally\n if (properties)\n for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i)\n this[keys[i]] = properties[keys[i]];\n}\n\n/**\n * Reference to the reflected type.\n * @name Message.$type\n * @type {Type}\n * @readonly\n */\n\n/**\n * Reference to the reflected type.\n * @name Message#$type\n * @type {Type}\n * @readonly\n */\n\n/*eslint-disable valid-jsdoc*/\n\n/**\n * Creates a new message of this type using the specified properties.\n * @param {Object.} [properties] Properties to set\n * @returns {Message} Message instance\n * @template T extends Message\n * @this Constructor\n */\nMessage.create = function create(properties) {\n return this.$type.create(properties);\n};\n\n/**\n * Encodes a message of this type.\n * @param {T|Object.} message Message to encode\n * @param {Writer} [writer] Writer to use\n * @returns {Writer} Writer\n * @template T extends Message\n * @this Constructor\n */\nMessage.encode = function encode(message, writer) {\n return this.$type.encode(message, writer);\n};\n\n/**\n * Encodes a message of this type preceeded by its length as a varint.\n * @param {T|Object.} message Message to encode\n * @param {Writer} [writer] Writer to use\n * @returns {Writer} Writer\n * @template T extends Message\n * @this Constructor\n */\nMessage.encodeDelimited = function encodeDelimited(message, writer) {\n return this.$type.encodeDelimited(message, writer);\n};\n\n/**\n * Decodes a message of this type.\n * @name Message.decode\n * @function\n * @param {Reader|Uint8Array} reader Reader or buffer to decode\n * @returns {T} Decoded message\n * @template T extends Message\n * @this Constructor\n */\nMessage.decode = function decode(reader) {\n return this.$type.decode(reader);\n};\n\n/**\n * Decodes a message of this type preceeded by its length as a varint.\n * @name Message.decodeDelimited\n * @function\n * @param {Reader|Uint8Array} reader Reader or buffer to decode\n * @returns {T} Decoded message\n * @template T extends Message\n * @this Constructor\n */\nMessage.decodeDelimited = function decodeDelimited(reader) {\n return this.$type.decodeDelimited(reader);\n};\n\n/**\n * Verifies a message of this type.\n * @name Message.verify\n * @function\n * @param {Object.} message Plain object to verify\n * @returns {string|null} `null` if valid, otherwise the reason why it is not\n */\nMessage.verify = function verify(message) {\n return this.$type.verify(message);\n};\n\n/**\n * Creates a new message of this type from a plain object. Also converts values to their respective internal types.\n * @param {Object.} object Plain object\n * @returns {T} Message instance\n * @template T extends Message\n * @this Constructor\n */\nMessage.fromObject = function fromObject(object) {\n return this.$type.fromObject(object);\n};\n\n/**\n * Creates a plain object from a message of this type. Also converts values to other types if specified.\n * @param {T} message Message instance\n * @param {IConversionOptions} [options] Conversion options\n * @returns {Object.} Plain object\n * @template T extends Message\n * @this Constructor\n */\nMessage.toObject = function toObject(message, options) {\n return this.$type.toObject(message, options);\n};\n\n/**\n * Converts this message to JSON.\n * @returns {Object.} JSON object\n */\nMessage.prototype.toJSON = function toJSON() {\n return this.$type.toObject(this, util.toJSONOptions);\n};\n\n/*eslint-enable valid-jsdoc*/","\"use strict\";\nmodule.exports = Method;\n\n// extends ReflectionObject\nvar ReflectionObject = require(22);\n((Method.prototype = Object.create(ReflectionObject.prototype)).constructor = Method).className = \"Method\";\n\nvar util = require(33);\n\n/**\n * Constructs a new service method instance.\n * @classdesc Reflected service method.\n * @extends ReflectionObject\n * @constructor\n * @param {string} name Method name\n * @param {string|undefined} type Method type, usually `\"rpc\"`\n * @param {string} requestType Request message type\n * @param {string} responseType Response message type\n * @param {boolean|Object.} [requestStream] Whether the request is streamed\n * @param {boolean|Object.} [responseStream] Whether the response is streamed\n * @param {Object.} [options] Declared options\n * @param {string} [comment] The comment for this method\n * @param {Object.} [parsedOptions] Declared options, properly parsed into an object\n */\nfunction Method(name, type, requestType, responseType, requestStream, responseStream, options, comment, parsedOptions) {\n\n /* istanbul ignore next */\n if (util.isObject(requestStream)) {\n options = requestStream;\n requestStream = responseStream = undefined;\n } else if (util.isObject(responseStream)) {\n options = responseStream;\n responseStream = undefined;\n }\n\n /* istanbul ignore if */\n if (!(type === undefined || util.isString(type)))\n throw TypeError(\"type must be a string\");\n\n /* istanbul ignore if */\n if (!util.isString(requestType))\n throw TypeError(\"requestType must be a string\");\n\n /* istanbul ignore if */\n if (!util.isString(responseType))\n throw TypeError(\"responseType must be a string\");\n\n ReflectionObject.call(this, name, options);\n\n /**\n * Method type.\n * @type {string}\n */\n this.type = type || \"rpc\"; // toJSON\n\n /**\n * Request type.\n * @type {string}\n */\n this.requestType = requestType; // toJSON, marker\n\n /**\n * Whether requests are streamed or not.\n * @type {boolean|undefined}\n */\n this.requestStream = requestStream ? true : undefined; // toJSON\n\n /**\n * Response type.\n * @type {string}\n */\n this.responseType = responseType; // toJSON\n\n /**\n * Whether responses are streamed or not.\n * @type {boolean|undefined}\n */\n this.responseStream = responseStream ? true : undefined; // toJSON\n\n /**\n * Resolved request type.\n * @type {Type|null}\n */\n this.resolvedRequestType = null;\n\n /**\n * Resolved response type.\n * @type {Type|null}\n */\n this.resolvedResponseType = null;\n\n /**\n * Comment for this method\n * @type {string|null}\n */\n this.comment = comment;\n\n /**\n * Options properly parsed into an object\n */\n this.parsedOptions = parsedOptions;\n}\n\n/**\n * Method descriptor.\n * @interface IMethod\n * @property {string} [type=\"rpc\"] Method type\n * @property {string} requestType Request type\n * @property {string} responseType Response type\n * @property {boolean} [requestStream=false] Whether requests are streamed\n * @property {boolean} [responseStream=false] Whether responses are streamed\n * @property {Object.} [options] Method options\n * @property {string} comment Method comments\n * @property {Object.} [parsedOptions] Method options properly parsed into an object\n */\n\n/**\n * Constructs a method from a method descriptor.\n * @param {string} name Method name\n * @param {IMethod} json Method descriptor\n * @returns {Method} Created method\n * @throws {TypeError} If arguments are invalid\n */\nMethod.fromJSON = function fromJSON(name, json) {\n return new Method(name, json.type, json.requestType, json.responseType, json.requestStream, json.responseStream, json.options, json.comment, json.parsedOptions);\n};\n\n/**\n * Converts this method to a method descriptor.\n * @param {IToJSONOptions} [toJSONOptions] JSON conversion options\n * @returns {IMethod} Method descriptor\n */\nMethod.prototype.toJSON = function toJSON(toJSONOptions) {\n var keepComments = toJSONOptions ? Boolean(toJSONOptions.keepComments) : false;\n return util.toObject([\n \"type\" , this.type !== \"rpc\" && /* istanbul ignore next */ this.type || undefined,\n \"requestType\" , this.requestType,\n \"requestStream\" , this.requestStream,\n \"responseType\" , this.responseType,\n \"responseStream\" , this.responseStream,\n \"options\" , this.options,\n \"comment\" , keepComments ? this.comment : undefined,\n \"parsedOptions\" , this.parsedOptions,\n ]);\n};\n\n/**\n * @override\n */\nMethod.prototype.resolve = function resolve() {\n\n /* istanbul ignore if */\n if (this.resolved)\n return this;\n\n this.resolvedRequestType = this.parent.lookupType(this.requestType);\n this.resolvedResponseType = this.parent.lookupType(this.responseType);\n\n return ReflectionObject.prototype.resolve.call(this);\n};\n","\"use strict\";\nmodule.exports = Namespace;\n\n// extends ReflectionObject\nvar ReflectionObject = require(22);\n((Namespace.prototype = Object.create(ReflectionObject.prototype)).constructor = Namespace).className = \"Namespace\";\n\nvar Field = require(15),\n util = require(33),\n OneOf = require(23);\n\nvar Type, // cyclic\n Service,\n Enum;\n\n/**\n * Constructs a new namespace instance.\n * @name Namespace\n * @classdesc Reflected namespace.\n * @extends NamespaceBase\n * @constructor\n * @param {string} name Namespace name\n * @param {Object.} [options] Declared options\n */\n\n/**\n * Constructs a namespace from JSON.\n * @memberof Namespace\n * @function\n * @param {string} name Namespace name\n * @param {Object.} json JSON object\n * @returns {Namespace} Created namespace\n * @throws {TypeError} If arguments are invalid\n */\nNamespace.fromJSON = function fromJSON(name, json) {\n return new Namespace(name, json.options).addJSON(json.nested);\n};\n\n/**\n * Converts an array of reflection objects to JSON.\n * @memberof Namespace\n * @param {ReflectionObject[]} array Object array\n * @param {IToJSONOptions} [toJSONOptions] JSON conversion options\n * @returns {Object.|undefined} JSON object or `undefined` when array is empty\n */\nfunction arrayToJSON(array, toJSONOptions) {\n if (!(array && array.length))\n return undefined;\n var obj = {};\n for (var i = 0; i < array.length; ++i)\n obj[array[i].name] = array[i].toJSON(toJSONOptions);\n return obj;\n}\n\nNamespace.arrayToJSON = arrayToJSON;\n\n/**\n * Tests if the specified id is reserved.\n * @param {Array.|undefined} reserved Array of reserved ranges and names\n * @param {number} id Id to test\n * @returns {boolean} `true` if reserved, otherwise `false`\n */\nNamespace.isReservedId = function isReservedId(reserved, id) {\n if (reserved)\n for (var i = 0; i < reserved.length; ++i)\n if (typeof reserved[i] !== \"string\" && reserved[i][0] <= id && reserved[i][1] > id)\n return true;\n return false;\n};\n\n/**\n * Tests if the specified name is reserved.\n * @param {Array.|undefined} reserved Array of reserved ranges and names\n * @param {string} name Name to test\n * @returns {boolean} `true` if reserved, otherwise `false`\n */\nNamespace.isReservedName = function isReservedName(reserved, name) {\n if (reserved)\n for (var i = 0; i < reserved.length; ++i)\n if (reserved[i] === name)\n return true;\n return false;\n};\n\n/**\n * Not an actual constructor. Use {@link Namespace} instead.\n * @classdesc Base class of all reflection objects containing nested objects. This is not an actual class but here for the sake of having consistent type definitions.\n * @exports NamespaceBase\n * @extends ReflectionObject\n * @abstract\n * @constructor\n * @param {string} name Namespace name\n * @param {Object.} [options] Declared options\n * @see {@link Namespace}\n */\nfunction Namespace(name, options) {\n ReflectionObject.call(this, name, options);\n\n /**\n * Nested objects by name.\n * @type {Object.|undefined}\n */\n this.nested = undefined; // toJSON\n\n /**\n * Cached nested objects as an array.\n * @type {ReflectionObject[]|null}\n * @private\n */\n this._nestedArray = null;\n}\n\nfunction clearCache(namespace) {\n namespace._nestedArray = null;\n return namespace;\n}\n\n/**\n * Nested objects of this namespace as an array for iteration.\n * @name NamespaceBase#nestedArray\n * @type {ReflectionObject[]}\n * @readonly\n */\nObject.defineProperty(Namespace.prototype, \"nestedArray\", {\n get: function() {\n return this._nestedArray || (this._nestedArray = util.toArray(this.nested));\n }\n});\n\n/**\n * Namespace descriptor.\n * @interface INamespace\n * @property {Object.} [options] Namespace options\n * @property {Object.} [nested] Nested object descriptors\n */\n\n/**\n * Any extension field descriptor.\n * @typedef AnyExtensionField\n * @type {IExtensionField|IExtensionMapField}\n */\n\n/**\n * Any nested object descriptor.\n * @typedef AnyNestedObject\n * @type {IEnum|IType|IService|AnyExtensionField|INamespace|IOneOf}\n */\n\n/**\n * Converts this namespace to a namespace descriptor.\n * @param {IToJSONOptions} [toJSONOptions] JSON conversion options\n * @returns {INamespace} Namespace descriptor\n */\nNamespace.prototype.toJSON = function toJSON(toJSONOptions) {\n return util.toObject([\n \"options\" , this.options,\n \"nested\" , arrayToJSON(this.nestedArray, toJSONOptions)\n ]);\n};\n\n/**\n * Adds nested objects to this namespace from nested object descriptors.\n * @param {Object.} nestedJson Any nested object descriptors\n * @returns {Namespace} `this`\n */\nNamespace.prototype.addJSON = function addJSON(nestedJson) {\n var ns = this;\n /* istanbul ignore else */\n if (nestedJson) {\n for (var names = Object.keys(nestedJson), i = 0, nested; i < names.length; ++i) {\n nested = nestedJson[names[i]];\n ns.add( // most to least likely\n ( nested.fields !== undefined\n ? Type.fromJSON\n : nested.values !== undefined\n ? Enum.fromJSON\n : nested.methods !== undefined\n ? Service.fromJSON\n : nested.id !== undefined\n ? Field.fromJSON\n : Namespace.fromJSON )(names[i], nested)\n );\n }\n }\n return this;\n};\n\n/**\n * Gets the nested object of the specified name.\n * @param {string} name Nested object name\n * @returns {ReflectionObject|null} The reflection object or `null` if it doesn't exist\n */\nNamespace.prototype.get = function get(name) {\n return this.nested && this.nested[name]\n || null;\n};\n\n/**\n * Gets the values of the nested {@link Enum|enum} of the specified name.\n * This methods differs from {@link Namespace#get|get} in that it returns an enum's values directly and throws instead of returning `null`.\n * @param {string} name Nested enum name\n * @returns {Object.} Enum values\n * @throws {Error} If there is no such enum\n */\nNamespace.prototype.getEnum = function getEnum(name) {\n if (this.nested && this.nested[name] instanceof Enum)\n return this.nested[name].values;\n throw Error(\"no such enum: \" + name);\n};\n\n/**\n * Adds a nested object to this namespace.\n * @param {ReflectionObject} object Nested object to add\n * @returns {Namespace} `this`\n * @throws {TypeError} If arguments are invalid\n * @throws {Error} If there is already a nested object with this name\n */\nNamespace.prototype.add = function add(object) {\n\n if (!(object instanceof Field && object.extend !== undefined || object instanceof Type || object instanceof OneOf || object instanceof Enum || object instanceof Service || object instanceof Namespace))\n throw TypeError(\"object must be a valid nested object\");\n\n if (!this.nested)\n this.nested = {};\n else {\n var prev = this.get(object.name);\n if (prev) {\n if (prev instanceof Namespace && object instanceof Namespace && !(prev instanceof Type || prev instanceof Service)) {\n // replace plain namespace but keep existing nested elements and options\n var nested = prev.nestedArray;\n for (var i = 0; i < nested.length; ++i)\n object.add(nested[i]);\n this.remove(prev);\n if (!this.nested)\n this.nested = {};\n object.setOptions(prev.options, true);\n\n } else\n throw Error(\"duplicate name '\" + object.name + \"' in \" + this);\n }\n }\n this.nested[object.name] = object;\n object.onAdd(this);\n return clearCache(this);\n};\n\n/**\n * Removes a nested object from this namespace.\n * @param {ReflectionObject} object Nested object to remove\n * @returns {Namespace} `this`\n * @throws {TypeError} If arguments are invalid\n * @throws {Error} If `object` is not a member of this namespace\n */\nNamespace.prototype.remove = function remove(object) {\n\n if (!(object instanceof ReflectionObject))\n throw TypeError(\"object must be a ReflectionObject\");\n if (object.parent !== this)\n throw Error(object + \" is not a member of \" + this);\n\n delete this.nested[object.name];\n if (!Object.keys(this.nested).length)\n this.nested = undefined;\n\n object.onRemove(this);\n return clearCache(this);\n};\n\n/**\n * Defines additial namespaces within this one if not yet existing.\n * @param {string|string[]} path Path to create\n * @param {*} [json] Nested types to create from JSON\n * @returns {Namespace} Pointer to the last namespace created or `this` if path is empty\n */\nNamespace.prototype.define = function define(path, json) {\n\n if (util.isString(path))\n path = path.split(\".\");\n else if (!Array.isArray(path))\n throw TypeError(\"illegal path\");\n if (path && path.length && path[0] === \"\")\n throw Error(\"path must be relative\");\n\n var ptr = this;\n while (path.length > 0) {\n var part = path.shift();\n if (ptr.nested && ptr.nested[part]) {\n ptr = ptr.nested[part];\n if (!(ptr instanceof Namespace))\n throw Error(\"path conflicts with non-namespace objects\");\n } else\n ptr.add(ptr = new Namespace(part));\n }\n if (json)\n ptr.addJSON(json);\n return ptr;\n};\n\n/**\n * Resolves this namespace's and all its nested objects' type references. Useful to validate a reflection tree, but comes at a cost.\n * @returns {Namespace} `this`\n */\nNamespace.prototype.resolveAll = function resolveAll() {\n var nested = this.nestedArray, i = 0;\n while (i < nested.length)\n if (nested[i] instanceof Namespace)\n nested[i++].resolveAll();\n else\n nested[i++].resolve();\n return this.resolve();\n};\n\n/**\n * Recursively looks up the reflection object matching the specified path in the scope of this namespace.\n * @param {string|string[]} path Path to look up\n * @param {*|Array.<*>} filterTypes Filter types, any combination of the constructors of `protobuf.Type`, `protobuf.Enum`, `protobuf.Service` etc.\n * @param {boolean} [parentAlreadyChecked=false] If known, whether the parent has already been checked\n * @returns {ReflectionObject|null} Looked up object or `null` if none could be found\n */\nNamespace.prototype.lookup = function lookup(path, filterTypes, parentAlreadyChecked) {\n\n /* istanbul ignore next */\n if (typeof filterTypes === \"boolean\") {\n parentAlreadyChecked = filterTypes;\n filterTypes = undefined;\n } else if (filterTypes && !Array.isArray(filterTypes))\n filterTypes = [ filterTypes ];\n\n if (util.isString(path) && path.length) {\n if (path === \".\")\n return this.root;\n path = path.split(\".\");\n } else if (!path.length)\n return this;\n\n // Start at root if path is absolute\n if (path[0] === \"\")\n return this.root.lookup(path.slice(1), filterTypes);\n\n // Test if the first part matches any nested object, and if so, traverse if path contains more\n var found = this.get(path[0]);\n if (found) {\n if (path.length === 1) {\n if (!filterTypes || filterTypes.indexOf(found.constructor) > -1)\n return found;\n } else if (found instanceof Namespace && (found = found.lookup(path.slice(1), filterTypes, true)))\n return found;\n\n // Otherwise try each nested namespace\n } else\n for (var i = 0; i < this.nestedArray.length; ++i)\n if (this._nestedArray[i] instanceof Namespace && (found = this._nestedArray[i].lookup(path, filterTypes, true)))\n return found;\n\n // If there hasn't been a match, try again at the parent\n if (this.parent === null || parentAlreadyChecked)\n return null;\n return this.parent.lookup(path, filterTypes);\n};\n\n/**\n * Looks up the reflection object at the specified path, relative to this namespace.\n * @name NamespaceBase#lookup\n * @function\n * @param {string|string[]} path Path to look up\n * @param {boolean} [parentAlreadyChecked=false] Whether the parent has already been checked\n * @returns {ReflectionObject|null} Looked up object or `null` if none could be found\n * @variation 2\n */\n// lookup(path: string, [parentAlreadyChecked: boolean])\n\n/**\n * Looks up the {@link Type|type} at the specified path, relative to this namespace.\n * Besides its signature, this methods differs from {@link Namespace#lookup|lookup} in that it throws instead of returning `null`.\n * @param {string|string[]} path Path to look up\n * @returns {Type} Looked up type\n * @throws {Error} If `path` does not point to a type\n */\nNamespace.prototype.lookupType = function lookupType(path) {\n var found = this.lookup(path, [ Type ]);\n if (!found)\n throw Error(\"no such type: \" + path);\n return found;\n};\n\n/**\n * Looks up the values of the {@link Enum|enum} at the specified path, relative to this namespace.\n * Besides its signature, this methods differs from {@link Namespace#lookup|lookup} in that it throws instead of returning `null`.\n * @param {string|string[]} path Path to look up\n * @returns {Enum} Looked up enum\n * @throws {Error} If `path` does not point to an enum\n */\nNamespace.prototype.lookupEnum = function lookupEnum(path) {\n var found = this.lookup(path, [ Enum ]);\n if (!found)\n throw Error(\"no such Enum '\" + path + \"' in \" + this);\n return found;\n};\n\n/**\n * Looks up the {@link Type|type} or {@link Enum|enum} at the specified path, relative to this namespace.\n * Besides its signature, this methods differs from {@link Namespace#lookup|lookup} in that it throws instead of returning `null`.\n * @param {string|string[]} path Path to look up\n * @returns {Type} Looked up type or enum\n * @throws {Error} If `path` does not point to a type or enum\n */\nNamespace.prototype.lookupTypeOrEnum = function lookupTypeOrEnum(path) {\n var found = this.lookup(path, [ Type, Enum ]);\n if (!found)\n throw Error(\"no such Type or Enum '\" + path + \"' in \" + this);\n return found;\n};\n\n/**\n * Looks up the {@link Service|service} at the specified path, relative to this namespace.\n * Besides its signature, this methods differs from {@link Namespace#lookup|lookup} in that it throws instead of returning `null`.\n * @param {string|string[]} path Path to look up\n * @returns {Service} Looked up service\n * @throws {Error} If `path` does not point to a service\n */\nNamespace.prototype.lookupService = function lookupService(path) {\n var found = this.lookup(path, [ Service ]);\n if (!found)\n throw Error(\"no such Service '\" + path + \"' in \" + this);\n return found;\n};\n\n// Sets up cyclic dependencies (called in index-light)\nNamespace._configure = function(Type_, Service_, Enum_) {\n Type = Type_;\n Service = Service_;\n Enum = Enum_;\n};\n","\"use strict\";\nmodule.exports = ReflectionObject;\n\nReflectionObject.className = \"ReflectionObject\";\n\nvar util = require(33);\n\nvar Root; // cyclic\n\n/**\n * Constructs a new reflection object instance.\n * @classdesc Base class of all reflection objects.\n * @constructor\n * @param {string} name Object name\n * @param {Object.} [options] Declared options\n * @abstract\n */\nfunction ReflectionObject(name, options) {\n\n if (!util.isString(name))\n throw TypeError(\"name must be a string\");\n\n if (options && !util.isObject(options))\n throw TypeError(\"options must be an object\");\n\n /**\n * Options.\n * @type {Object.|undefined}\n */\n this.options = options; // toJSON\n\n /**\n * Parsed Options.\n * @type {Array.>|undefined}\n */\n this.parsedOptions = null;\n\n /**\n * Unique name within its namespace.\n * @type {string}\n */\n this.name = name;\n\n /**\n * Parent namespace.\n * @type {Namespace|null}\n */\n this.parent = null;\n\n /**\n * Whether already resolved or not.\n * @type {boolean}\n */\n this.resolved = false;\n\n /**\n * Comment text, if any.\n * @type {string|null}\n */\n this.comment = null;\n\n /**\n * Defining file name.\n * @type {string|null}\n */\n this.filename = null;\n}\n\nObject.defineProperties(ReflectionObject.prototype, {\n\n /**\n * Reference to the root namespace.\n * @name ReflectionObject#root\n * @type {Root}\n * @readonly\n */\n root: {\n get: function() {\n var ptr = this;\n while (ptr.parent !== null)\n ptr = ptr.parent;\n return ptr;\n }\n },\n\n /**\n * Full name including leading dot.\n * @name ReflectionObject#fullName\n * @type {string}\n * @readonly\n */\n fullName: {\n get: function() {\n var path = [ this.name ],\n ptr = this.parent;\n while (ptr) {\n path.unshift(ptr.name);\n ptr = ptr.parent;\n }\n return path.join(\".\");\n }\n }\n});\n\n/**\n * Converts this reflection object to its descriptor representation.\n * @returns {Object.} Descriptor\n * @abstract\n */\nReflectionObject.prototype.toJSON = /* istanbul ignore next */ function toJSON() {\n throw Error(); // not implemented, shouldn't happen\n};\n\n/**\n * Called when this object is added to a parent.\n * @param {ReflectionObject} parent Parent added to\n * @returns {undefined}\n */\nReflectionObject.prototype.onAdd = function onAdd(parent) {\n if (this.parent && this.parent !== parent)\n this.parent.remove(this);\n this.parent = parent;\n this.resolved = false;\n var root = parent.root;\n if (root instanceof Root)\n root._handleAdd(this);\n};\n\n/**\n * Called when this object is removed from a parent.\n * @param {ReflectionObject} parent Parent removed from\n * @returns {undefined}\n */\nReflectionObject.prototype.onRemove = function onRemove(parent) {\n var root = parent.root;\n if (root instanceof Root)\n root._handleRemove(this);\n this.parent = null;\n this.resolved = false;\n};\n\n/**\n * Resolves this objects type references.\n * @returns {ReflectionObject} `this`\n */\nReflectionObject.prototype.resolve = function resolve() {\n if (this.resolved)\n return this;\n if (this.root instanceof Root)\n this.resolved = true; // only if part of a root\n return this;\n};\n\n/**\n * Gets an option value.\n * @param {string} name Option name\n * @returns {*} Option value or `undefined` if not set\n */\nReflectionObject.prototype.getOption = function getOption(name) {\n if (this.options)\n return this.options[name];\n return undefined;\n};\n\n/**\n * Sets an option.\n * @param {string} name Option name\n * @param {*} value Option value\n * @param {boolean} [ifNotSet] Sets the option only if it isn't currently set\n * @returns {ReflectionObject} `this`\n */\nReflectionObject.prototype.setOption = function setOption(name, value, ifNotSet) {\n if (!ifNotSet || !this.options || this.options[name] === undefined)\n (this.options || (this.options = {}))[name] = value;\n return this;\n};\n\n/**\n * Sets a parsed option.\n * @param {string} name parsed Option name\n * @param {*} value Option value\n * @param {string} propName dot '.' delimited full path of property within the option to set. if undefined\\empty, will add a new option with that value\n * @returns {ReflectionObject} `this`\n */\nReflectionObject.prototype.setParsedOption = function setParsedOption(name, value, propName) {\n if (!this.parsedOptions) {\n this.parsedOptions = [];\n }\n var parsedOptions = this.parsedOptions;\n if (propName) {\n // If setting a sub property of an option then try to merge it\n // with an existing option\n var opt = parsedOptions.find(function (opt) {\n return Object.prototype.hasOwnProperty.call(opt, name);\n });\n if (opt) {\n // If we found an existing option - just merge the property value\n var newValue = opt[name];\n util.setProperty(newValue, propName, value);\n } else {\n // otherwise, create a new option, set it's property and add it to the list\n opt = {};\n opt[name] = util.setProperty({}, propName, value);\n parsedOptions.push(opt);\n }\n } else {\n // Always create a new option when setting the value of the option itself\n var newOpt = {};\n newOpt[name] = value;\n parsedOptions.push(newOpt);\n }\n return this;\n};\n\n/**\n * Sets multiple options.\n * @param {Object.} options Options to set\n * @param {boolean} [ifNotSet] Sets an option only if it isn't currently set\n * @returns {ReflectionObject} `this`\n */\nReflectionObject.prototype.setOptions = function setOptions(options, ifNotSet) {\n if (options)\n for (var keys = Object.keys(options), i = 0; i < keys.length; ++i)\n this.setOption(keys[i], options[keys[i]], ifNotSet);\n return this;\n};\n\n/**\n * Converts this instance to its string representation.\n * @returns {string} Class name[, space, full name]\n */\nReflectionObject.prototype.toString = function toString() {\n var className = this.constructor.className,\n fullName = this.fullName;\n if (fullName.length)\n return className + \" \" + fullName;\n return className;\n};\n\n// Sets up cyclic dependencies (called in index-light)\nReflectionObject._configure = function(Root_) {\n Root = Root_;\n};\n","\"use strict\";\nmodule.exports = OneOf;\n\n// extends ReflectionObject\nvar ReflectionObject = require(22);\n((OneOf.prototype = Object.create(ReflectionObject.prototype)).constructor = OneOf).className = \"OneOf\";\n\nvar Field = require(15),\n util = require(33);\n\n/**\n * Constructs a new oneof instance.\n * @classdesc Reflected oneof.\n * @extends ReflectionObject\n * @constructor\n * @param {string} name Oneof name\n * @param {string[]|Object.} [fieldNames] Field names\n * @param {Object.} [options] Declared options\n * @param {string} [comment] Comment associated with this field\n */\nfunction OneOf(name, fieldNames, options, comment) {\n if (!Array.isArray(fieldNames)) {\n options = fieldNames;\n fieldNames = undefined;\n }\n ReflectionObject.call(this, name, options);\n\n /* istanbul ignore if */\n if (!(fieldNames === undefined || Array.isArray(fieldNames)))\n throw TypeError(\"fieldNames must be an Array\");\n\n /**\n * Field names that belong to this oneof.\n * @type {string[]}\n */\n this.oneof = fieldNames || []; // toJSON, marker\n\n /**\n * Fields that belong to this oneof as an array for iteration.\n * @type {Field[]}\n * @readonly\n */\n this.fieldsArray = []; // declared readonly for conformance, possibly not yet added to parent\n\n /**\n * Comment for this field.\n * @type {string|null}\n */\n this.comment = comment;\n}\n\n/**\n * Oneof descriptor.\n * @interface IOneOf\n * @property {Array.} oneof Oneof field names\n * @property {Object.} [options] Oneof options\n */\n\n/**\n * Constructs a oneof from a oneof descriptor.\n * @param {string} name Oneof name\n * @param {IOneOf} json Oneof descriptor\n * @returns {OneOf} Created oneof\n * @throws {TypeError} If arguments are invalid\n */\nOneOf.fromJSON = function fromJSON(name, json) {\n return new OneOf(name, json.oneof, json.options, json.comment);\n};\n\n/**\n * Converts this oneof to a oneof descriptor.\n * @param {IToJSONOptions} [toJSONOptions] JSON conversion options\n * @returns {IOneOf} Oneof descriptor\n */\nOneOf.prototype.toJSON = function toJSON(toJSONOptions) {\n var keepComments = toJSONOptions ? Boolean(toJSONOptions.keepComments) : false;\n return util.toObject([\n \"options\" , this.options,\n \"oneof\" , this.oneof,\n \"comment\" , keepComments ? this.comment : undefined\n ]);\n};\n\n/**\n * Adds the fields of the specified oneof to the parent if not already done so.\n * @param {OneOf} oneof The oneof\n * @returns {undefined}\n * @inner\n * @ignore\n */\nfunction addFieldsToParent(oneof) {\n if (oneof.parent)\n for (var i = 0; i < oneof.fieldsArray.length; ++i)\n if (!oneof.fieldsArray[i].parent)\n oneof.parent.add(oneof.fieldsArray[i]);\n}\n\n/**\n * Adds a field to this oneof and removes it from its current parent, if any.\n * @param {Field} field Field to add\n * @returns {OneOf} `this`\n */\nOneOf.prototype.add = function add(field) {\n\n /* istanbul ignore if */\n if (!(field instanceof Field))\n throw TypeError(\"field must be a Field\");\n\n if (field.parent && field.parent !== this.parent)\n field.parent.remove(field);\n this.oneof.push(field.name);\n this.fieldsArray.push(field);\n field.partOf = this; // field.parent remains null\n addFieldsToParent(this);\n return this;\n};\n\n/**\n * Removes a field from this oneof and puts it back to the oneof's parent.\n * @param {Field} field Field to remove\n * @returns {OneOf} `this`\n */\nOneOf.prototype.remove = function remove(field) {\n\n /* istanbul ignore if */\n if (!(field instanceof Field))\n throw TypeError(\"field must be a Field\");\n\n var index = this.fieldsArray.indexOf(field);\n\n /* istanbul ignore if */\n if (index < 0)\n throw Error(field + \" is not a member of \" + this);\n\n this.fieldsArray.splice(index, 1);\n index = this.oneof.indexOf(field.name);\n\n /* istanbul ignore else */\n if (index > -1) // theoretical\n this.oneof.splice(index, 1);\n\n field.partOf = null;\n return this;\n};\n\n/**\n * @override\n */\nOneOf.prototype.onAdd = function onAdd(parent) {\n ReflectionObject.prototype.onAdd.call(this, parent);\n var self = this;\n // Collect present fields\n for (var i = 0; i < this.oneof.length; ++i) {\n var field = parent.get(this.oneof[i]);\n if (field && !field.partOf) {\n field.partOf = self;\n self.fieldsArray.push(field);\n }\n }\n // Add not yet present fields\n addFieldsToParent(this);\n};\n\n/**\n * @override\n */\nOneOf.prototype.onRemove = function onRemove(parent) {\n for (var i = 0, field; i < this.fieldsArray.length; ++i)\n if ((field = this.fieldsArray[i]).parent)\n field.parent.remove(field);\n ReflectionObject.prototype.onRemove.call(this, parent);\n};\n\n/**\n * Decorator function as returned by {@link OneOf.d} (TypeScript).\n * @typedef OneOfDecorator\n * @type {function}\n * @param {Object} prototype Target prototype\n * @param {string} oneofName OneOf name\n * @returns {undefined}\n */\n\n/**\n * OneOf decorator (TypeScript).\n * @function\n * @param {...string} fieldNames Field names\n * @returns {OneOfDecorator} Decorator function\n * @template T extends string\n */\nOneOf.d = function decorateOneOf() {\n var fieldNames = new Array(arguments.length),\n index = 0;\n while (index < arguments.length)\n fieldNames[index] = arguments[index++];\n return function oneOfDecorator(prototype, oneofName) {\n util.decorateType(prototype.constructor)\n .add(new OneOf(oneofName, fieldNames));\n Object.defineProperty(prototype, oneofName, {\n get: util.oneOfGetter(fieldNames),\n set: util.oneOfSetter(fieldNames)\n });\n };\n};\n","\"use strict\";\nmodule.exports = Reader;\n\nvar util = require(35);\n\nvar BufferReader; // cyclic\n\nvar LongBits = util.LongBits,\n utf8 = util.utf8;\n\n/* istanbul ignore next */\nfunction indexOutOfRange(reader, writeLength) {\n return RangeError(\"index out of range: \" + reader.pos + \" + \" + (writeLength || 1) + \" > \" + reader.len);\n}\n\n/**\n * Constructs a new reader instance using the specified buffer.\n * @classdesc Wire format reader using `Uint8Array` if available, otherwise `Array`.\n * @constructor\n * @param {Uint8Array} buffer Buffer to read from\n */\nfunction Reader(buffer) {\n\n /**\n * Read buffer.\n * @type {Uint8Array}\n */\n this.buf = buffer;\n\n /**\n * Read buffer position.\n * @type {number}\n */\n this.pos = 0;\n\n /**\n * Read buffer length.\n * @type {number}\n */\n this.len = buffer.length;\n}\n\nvar create_array = typeof Uint8Array !== \"undefined\"\n ? function create_typed_array(buffer) {\n if (buffer instanceof Uint8Array || Array.isArray(buffer))\n return new Reader(buffer);\n throw Error(\"illegal buffer\");\n }\n /* istanbul ignore next */\n : function create_array(buffer) {\n if (Array.isArray(buffer))\n return new Reader(buffer);\n throw Error(\"illegal buffer\");\n };\n\nvar create = function create() {\n return util.Buffer\n ? function create_buffer_setup(buffer) {\n return (Reader.create = function create_buffer(buffer) {\n return util.Buffer.isBuffer(buffer)\n ? new BufferReader(buffer)\n /* istanbul ignore next */\n : create_array(buffer);\n })(buffer);\n }\n /* istanbul ignore next */\n : create_array;\n};\n\n/**\n * Creates a new reader using the specified buffer.\n * @function\n * @param {Uint8Array|Buffer} buffer Buffer to read from\n * @returns {Reader|BufferReader} A {@link BufferReader} if `buffer` is a Buffer, otherwise a {@link Reader}\n * @throws {Error} If `buffer` is not a valid buffer\n */\nReader.create = create();\n\nReader.prototype._slice = util.Array.prototype.subarray || /* istanbul ignore next */ util.Array.prototype.slice;\n\n/**\n * Reads a varint as an unsigned 32 bit value.\n * @function\n * @returns {number} Value read\n */\nReader.prototype.uint32 = (function read_uint32_setup() {\n var value = 4294967295; // optimizer type-hint, tends to deopt otherwise (?!)\n return function read_uint32() {\n value = ( this.buf[this.pos] & 127 ) >>> 0; if (this.buf[this.pos++] < 128) return value;\n value = (value | (this.buf[this.pos] & 127) << 7) >>> 0; if (this.buf[this.pos++] < 128) return value;\n value = (value | (this.buf[this.pos] & 127) << 14) >>> 0; if (this.buf[this.pos++] < 128) return value;\n value = (value | (this.buf[this.pos] & 127) << 21) >>> 0; if (this.buf[this.pos++] < 128) return value;\n value = (value | (this.buf[this.pos] & 15) << 28) >>> 0; if (this.buf[this.pos++] < 128) return value;\n\n /* istanbul ignore if */\n if ((this.pos += 5) > this.len) {\n this.pos = this.len;\n throw indexOutOfRange(this, 10);\n }\n return value;\n };\n})();\n\n/**\n * Reads a varint as a signed 32 bit value.\n * @returns {number} Value read\n */\nReader.prototype.int32 = function read_int32() {\n return this.uint32() | 0;\n};\n\n/**\n * Reads a zig-zag encoded varint as a signed 32 bit value.\n * @returns {number} Value read\n */\nReader.prototype.sint32 = function read_sint32() {\n var value = this.uint32();\n return value >>> 1 ^ -(value & 1) | 0;\n};\n\n/* eslint-disable no-invalid-this */\n\nfunction readLongVarint() {\n // tends to deopt with local vars for octet etc.\n var bits = new LongBits(0, 0);\n var i = 0;\n if (this.len - this.pos > 4) { // fast route (lo)\n for (; i < 4; ++i) {\n // 1st..4th\n bits.lo = (bits.lo | (this.buf[this.pos] & 127) << i * 7) >>> 0;\n if (this.buf[this.pos++] < 128)\n return bits;\n }\n // 5th\n bits.lo = (bits.lo | (this.buf[this.pos] & 127) << 28) >>> 0;\n bits.hi = (bits.hi | (this.buf[this.pos] & 127) >> 4) >>> 0;\n if (this.buf[this.pos++] < 128)\n return bits;\n i = 0;\n } else {\n for (; i < 3; ++i) {\n /* istanbul ignore if */\n if (this.pos >= this.len)\n throw indexOutOfRange(this);\n // 1st..3th\n bits.lo = (bits.lo | (this.buf[this.pos] & 127) << i * 7) >>> 0;\n if (this.buf[this.pos++] < 128)\n return bits;\n }\n // 4th\n bits.lo = (bits.lo | (this.buf[this.pos++] & 127) << i * 7) >>> 0;\n return bits;\n }\n if (this.len - this.pos > 4) { // fast route (hi)\n for (; i < 5; ++i) {\n // 6th..10th\n bits.hi = (bits.hi | (this.buf[this.pos] & 127) << i * 7 + 3) >>> 0;\n if (this.buf[this.pos++] < 128)\n return bits;\n }\n } else {\n for (; i < 5; ++i) {\n /* istanbul ignore if */\n if (this.pos >= this.len)\n throw indexOutOfRange(this);\n // 6th..10th\n bits.hi = (bits.hi | (this.buf[this.pos] & 127) << i * 7 + 3) >>> 0;\n if (this.buf[this.pos++] < 128)\n return bits;\n }\n }\n /* istanbul ignore next */\n throw Error(\"invalid varint encoding\");\n}\n\n/* eslint-enable no-invalid-this */\n\n/**\n * Reads a varint as a signed 64 bit value.\n * @name Reader#int64\n * @function\n * @returns {Long} Value read\n */\n\n/**\n * Reads a varint as an unsigned 64 bit value.\n * @name Reader#uint64\n * @function\n * @returns {Long} Value read\n */\n\n/**\n * Reads a zig-zag encoded varint as a signed 64 bit value.\n * @name Reader#sint64\n * @function\n * @returns {Long} Value read\n */\n\n/**\n * Reads a varint as a boolean.\n * @returns {boolean} Value read\n */\nReader.prototype.bool = function read_bool() {\n return this.uint32() !== 0;\n};\n\nfunction readFixed32_end(buf, end) { // note that this uses `end`, not `pos`\n return (buf[end - 4]\n | buf[end - 3] << 8\n | buf[end - 2] << 16\n | buf[end - 1] << 24) >>> 0;\n}\n\n/**\n * Reads fixed 32 bits as an unsigned 32 bit integer.\n * @returns {number} Value read\n */\nReader.prototype.fixed32 = function read_fixed32() {\n\n /* istanbul ignore if */\n if (this.pos + 4 > this.len)\n throw indexOutOfRange(this, 4);\n\n return readFixed32_end(this.buf, this.pos += 4);\n};\n\n/**\n * Reads fixed 32 bits as a signed 32 bit integer.\n * @returns {number} Value read\n */\nReader.prototype.sfixed32 = function read_sfixed32() {\n\n /* istanbul ignore if */\n if (this.pos + 4 > this.len)\n throw indexOutOfRange(this, 4);\n\n return readFixed32_end(this.buf, this.pos += 4) | 0;\n};\n\n/* eslint-disable no-invalid-this */\n\nfunction readFixed64(/* this: Reader */) {\n\n /* istanbul ignore if */\n if (this.pos + 8 > this.len)\n throw indexOutOfRange(this, 8);\n\n return new LongBits(readFixed32_end(this.buf, this.pos += 4), readFixed32_end(this.buf, this.pos += 4));\n}\n\n/* eslint-enable no-invalid-this */\n\n/**\n * Reads fixed 64 bits.\n * @name Reader#fixed64\n * @function\n * @returns {Long} Value read\n */\n\n/**\n * Reads zig-zag encoded fixed 64 bits.\n * @name Reader#sfixed64\n * @function\n * @returns {Long} Value read\n */\n\n/**\n * Reads a float (32 bit) as a number.\n * @function\n * @returns {number} Value read\n */\nReader.prototype.float = function read_float() {\n\n /* istanbul ignore if */\n if (this.pos + 4 > this.len)\n throw indexOutOfRange(this, 4);\n\n var value = util.float.readFloatLE(this.buf, this.pos);\n this.pos += 4;\n return value;\n};\n\n/**\n * Reads a double (64 bit float) as a number.\n * @function\n * @returns {number} Value read\n */\nReader.prototype.double = function read_double() {\n\n /* istanbul ignore if */\n if (this.pos + 8 > this.len)\n throw indexOutOfRange(this, 4);\n\n var value = util.float.readDoubleLE(this.buf, this.pos);\n this.pos += 8;\n return value;\n};\n\n/**\n * Reads a sequence of bytes preceeded by its length as a varint.\n * @returns {Uint8Array} Value read\n */\nReader.prototype.bytes = function read_bytes() {\n var length = this.uint32(),\n start = this.pos,\n end = this.pos + length;\n\n /* istanbul ignore if */\n if (end > this.len)\n throw indexOutOfRange(this, length);\n\n this.pos += length;\n if (Array.isArray(this.buf)) // plain array\n return this.buf.slice(start, end);\n\n if (start === end) { // fix for IE 10/Win8 and others' subarray returning array of size 1\n var nativeBuffer = util.Buffer;\n return nativeBuffer\n ? nativeBuffer.alloc(0)\n : new this.buf.constructor(0);\n }\n return this._slice.call(this.buf, start, end);\n};\n\n/**\n * Reads a string preceeded by its byte length as a varint.\n * @returns {string} Value read\n */\nReader.prototype.string = function read_string() {\n var bytes = this.bytes();\n return utf8.read(bytes, 0, bytes.length);\n};\n\n/**\n * Skips the specified number of bytes if specified, otherwise skips a varint.\n * @param {number} [length] Length if known, otherwise a varint is assumed\n * @returns {Reader} `this`\n */\nReader.prototype.skip = function skip(length) {\n if (typeof length === \"number\") {\n /* istanbul ignore if */\n if (this.pos + length > this.len)\n throw indexOutOfRange(this, length);\n this.pos += length;\n } else {\n do {\n /* istanbul ignore if */\n if (this.pos >= this.len)\n throw indexOutOfRange(this);\n } while (this.buf[this.pos++] & 128);\n }\n return this;\n};\n\n/**\n * Skips the next element of the specified wire type.\n * @param {number} wireType Wire type received\n * @returns {Reader} `this`\n */\nReader.prototype.skipType = function(wireType) {\n switch (wireType) {\n case 0:\n this.skip();\n break;\n case 1:\n this.skip(8);\n break;\n case 2:\n this.skip(this.uint32());\n break;\n case 3:\n while ((wireType = this.uint32() & 7) !== 4) {\n this.skipType(wireType);\n }\n break;\n case 5:\n this.skip(4);\n break;\n\n /* istanbul ignore next */\n default:\n throw Error(\"invalid wire type \" + wireType + \" at offset \" + this.pos);\n }\n return this;\n};\n\nReader._configure = function(BufferReader_) {\n BufferReader = BufferReader_;\n Reader.create = create();\n BufferReader._configure();\n\n var fn = util.Long ? \"toLong\" : /* istanbul ignore next */ \"toNumber\";\n util.merge(Reader.prototype, {\n\n int64: function read_int64() {\n return readLongVarint.call(this)[fn](false);\n },\n\n uint64: function read_uint64() {\n return readLongVarint.call(this)[fn](true);\n },\n\n sint64: function read_sint64() {\n return readLongVarint.call(this).zzDecode()[fn](false);\n },\n\n fixed64: function read_fixed64() {\n return readFixed64.call(this)[fn](true);\n },\n\n sfixed64: function read_sfixed64() {\n return readFixed64.call(this)[fn](false);\n }\n\n });\n};\n","\"use strict\";\nmodule.exports = BufferReader;\n\n// extends Reader\nvar Reader = require(24);\n(BufferReader.prototype = Object.create(Reader.prototype)).constructor = BufferReader;\n\nvar util = require(35);\n\n/**\n * Constructs a new buffer reader instance.\n * @classdesc Wire format reader using node buffers.\n * @extends Reader\n * @constructor\n * @param {Buffer} buffer Buffer to read from\n */\nfunction BufferReader(buffer) {\n Reader.call(this, buffer);\n\n /**\n * Read buffer.\n * @name BufferReader#buf\n * @type {Buffer}\n */\n}\n\nBufferReader._configure = function () {\n /* istanbul ignore else */\n if (util.Buffer)\n BufferReader.prototype._slice = util.Buffer.prototype.slice;\n};\n\n\n/**\n * @override\n */\nBufferReader.prototype.string = function read_string_buffer() {\n var len = this.uint32(); // modifies pos\n return this.buf.utf8Slice\n ? this.buf.utf8Slice(this.pos, this.pos = Math.min(this.pos + len, this.len))\n : this.buf.toString(\"utf-8\", this.pos, this.pos = Math.min(this.pos + len, this.len));\n};\n\n/**\n * Reads a sequence of bytes preceeded by its length as a varint.\n * @name BufferReader#bytes\n * @function\n * @returns {Buffer} Value read\n */\n\nBufferReader._configure();\n","\"use strict\";\nmodule.exports = Root;\n\n// extends Namespace\nvar Namespace = require(21);\n((Root.prototype = Object.create(Namespace.prototype)).constructor = Root).className = \"Root\";\n\nvar Field = require(15),\n Enum = require(14),\n OneOf = require(23),\n util = require(33);\n\nvar Type, // cyclic\n parse, // might be excluded\n common; // \"\n\n/**\n * Constructs a new root namespace instance.\n * @classdesc Root namespace wrapping all types, enums, services, sub-namespaces etc. that belong together.\n * @extends NamespaceBase\n * @constructor\n * @param {Object.} [options] Top level options\n */\nfunction Root(options) {\n Namespace.call(this, \"\", options);\n\n /**\n * Deferred extension fields.\n * @type {Field[]}\n */\n this.deferred = [];\n\n /**\n * Resolved file names of loaded files.\n * @type {string[]}\n */\n this.files = [];\n}\n\n/**\n * Loads a namespace descriptor into a root namespace.\n * @param {INamespace} json Nameespace descriptor\n * @param {Root} [root] Root namespace, defaults to create a new one if omitted\n * @returns {Root} Root namespace\n */\nRoot.fromJSON = function fromJSON(json, root) {\n if (!root)\n root = new Root();\n if (json.options)\n root.setOptions(json.options);\n return root.addJSON(json.nested);\n};\n\n/**\n * Resolves the path of an imported file, relative to the importing origin.\n * This method exists so you can override it with your own logic in case your imports are scattered over multiple directories.\n * @function\n * @param {string} origin The file name of the importing file\n * @param {string} target The file name being imported\n * @returns {string|null} Resolved path to `target` or `null` to skip the file\n */\nRoot.prototype.resolvePath = util.path.resolve;\n\n/**\n * Fetch content from file path or url\n * This method exists so you can override it with your own logic.\n * @function\n * @param {string} path File path or url\n * @param {FetchCallback} callback Callback function\n * @returns {undefined}\n */\nRoot.prototype.fetch = util.fetch;\n\n// A symbol-like function to safely signal synchronous loading\n/* istanbul ignore next */\nfunction SYNC() {} // eslint-disable-line no-empty-function\n\n/**\n * Loads one or multiple .proto or preprocessed .json files into this root namespace and calls the callback.\n * @param {string|string[]} filename Names of one or multiple files to load\n * @param {IParseOptions} options Parse options\n * @param {LoadCallback} callback Callback function\n * @returns {undefined}\n */\nRoot.prototype.load = function load(filename, options, callback) {\n if (typeof options === \"function\") {\n callback = options;\n options = undefined;\n }\n var self = this;\n if (!callback)\n return util.asPromise(load, self, filename, options);\n\n var sync = callback === SYNC; // undocumented\n\n // Finishes loading by calling the callback (exactly once)\n function finish(err, root) {\n /* istanbul ignore if */\n if (!callback)\n return;\n if (sync)\n throw err;\n var cb = callback;\n callback = null;\n cb(err, root);\n }\n\n // Bundled definition existence checking\n function getBundledFileName(filename) {\n var idx = filename.lastIndexOf(\"google/protobuf/\");\n if (idx > -1) {\n var altname = filename.substring(idx);\n if (altname in common) return altname;\n }\n return null;\n }\n\n // Processes a single file\n function process(filename, source) {\n try {\n if (util.isString(source) && source.charAt(0) === \"{\")\n source = JSON.parse(source);\n if (!util.isString(source))\n self.setOptions(source.options).addJSON(source.nested);\n else {\n parse.filename = filename;\n var parsed = parse(source, self, options),\n resolved,\n i = 0;\n if (parsed.imports)\n for (; i < parsed.imports.length; ++i)\n if (resolved = getBundledFileName(parsed.imports[i]) || self.resolvePath(filename, parsed.imports[i]))\n fetch(resolved);\n if (parsed.weakImports)\n for (i = 0; i < parsed.weakImports.length; ++i)\n if (resolved = getBundledFileName(parsed.weakImports[i]) || self.resolvePath(filename, parsed.weakImports[i]))\n fetch(resolved, true);\n }\n } catch (err) {\n finish(err);\n }\n if (!sync && !queued)\n finish(null, self); // only once anyway\n }\n\n // Fetches a single file\n function fetch(filename, weak) {\n filename = getBundledFileName(filename) || filename;\n\n // Skip if already loaded / attempted\n if (self.files.indexOf(filename) > -1)\n return;\n self.files.push(filename);\n\n // Shortcut bundled definitions\n if (filename in common) {\n if (sync)\n process(filename, common[filename]);\n else {\n ++queued;\n setTimeout(function() {\n --queued;\n process(filename, common[filename]);\n });\n }\n return;\n }\n\n // Otherwise fetch from disk or network\n if (sync) {\n var source;\n try {\n source = util.fs.readFileSync(filename).toString(\"utf8\");\n } catch (err) {\n if (!weak)\n finish(err);\n return;\n }\n process(filename, source);\n } else {\n ++queued;\n self.fetch(filename, function(err, source) {\n --queued;\n /* istanbul ignore if */\n if (!callback)\n return; // terminated meanwhile\n if (err) {\n /* istanbul ignore else */\n if (!weak)\n finish(err);\n else if (!queued) // can't be covered reliably\n finish(null, self);\n return;\n }\n process(filename, source);\n });\n }\n }\n var queued = 0;\n\n // Assembling the root namespace doesn't require working type\n // references anymore, so we can load everything in parallel\n if (util.isString(filename))\n filename = [ filename ];\n for (var i = 0, resolved; i < filename.length; ++i)\n if (resolved = self.resolvePath(\"\", filename[i]))\n fetch(resolved);\n\n if (sync)\n return self;\n if (!queued)\n finish(null, self);\n return undefined;\n};\n// function load(filename:string, options:IParseOptions, callback:LoadCallback):undefined\n\n/**\n * Loads one or multiple .proto or preprocessed .json files into this root namespace and calls the callback.\n * @function Root#load\n * @param {string|string[]} filename Names of one or multiple files to load\n * @param {LoadCallback} callback Callback function\n * @returns {undefined}\n * @variation 2\n */\n// function load(filename:string, callback:LoadCallback):undefined\n\n/**\n * Loads one or multiple .proto or preprocessed .json files into this root namespace and returns a promise.\n * @function Root#load\n * @param {string|string[]} filename Names of one or multiple files to load\n * @param {IParseOptions} [options] Parse options. Defaults to {@link parse.defaults} when omitted.\n * @returns {Promise} Promise\n * @variation 3\n */\n// function load(filename:string, [options:IParseOptions]):Promise\n\n/**\n * Synchronously loads one or multiple .proto or preprocessed .json files into this root namespace (node only).\n * @function Root#loadSync\n * @param {string|string[]} filename Names of one or multiple files to load\n * @param {IParseOptions} [options] Parse options. Defaults to {@link parse.defaults} when omitted.\n * @returns {Root} Root namespace\n * @throws {Error} If synchronous fetching is not supported (i.e. in browsers) or if a file's syntax is invalid\n */\nRoot.prototype.loadSync = function loadSync(filename, options) {\n if (!util.isNode)\n throw Error(\"not supported\");\n return this.load(filename, options, SYNC);\n};\n\n/**\n * @override\n */\nRoot.prototype.resolveAll = function resolveAll() {\n if (this.deferred.length)\n throw Error(\"unresolvable extensions: \" + this.deferred.map(function(field) {\n return \"'extend \" + field.extend + \"' in \" + field.parent.fullName;\n }).join(\", \"));\n return Namespace.prototype.resolveAll.call(this);\n};\n\n// only uppercased (and thus conflict-free) children are exposed, see below\nvar exposeRe = /^[A-Z]/;\n\n/**\n * Handles a deferred declaring extension field by creating a sister field to represent it within its extended type.\n * @param {Root} root Root instance\n * @param {Field} field Declaring extension field witin the declaring type\n * @returns {boolean} `true` if successfully added to the extended type, `false` otherwise\n * @inner\n * @ignore\n */\nfunction tryHandleExtension(root, field) {\n var extendedType = field.parent.lookup(field.extend);\n if (extendedType) {\n var sisterField = new Field(field.fullName, field.id, field.type, field.rule, undefined, field.options);\n //do not allow to extend same field twice to prevent the error\n if (extendedType.get(sisterField.name)) {\n return true;\n }\n sisterField.declaringField = field;\n field.extensionField = sisterField;\n extendedType.add(sisterField);\n return true;\n }\n return false;\n}\n\n/**\n * Called when any object is added to this root or its sub-namespaces.\n * @param {ReflectionObject} object Object added\n * @returns {undefined}\n * @private\n */\nRoot.prototype._handleAdd = function _handleAdd(object) {\n if (object instanceof Field) {\n\n if (/* an extension field (implies not part of a oneof) */ object.extend !== undefined && /* not already handled */ !object.extensionField)\n if (!tryHandleExtension(this, object))\n this.deferred.push(object);\n\n } else if (object instanceof Enum) {\n\n if (exposeRe.test(object.name))\n object.parent[object.name] = object.values; // expose enum values as property of its parent\n\n } else if (!(object instanceof OneOf)) /* everything else is a namespace */ {\n\n if (object instanceof Type) // Try to handle any deferred extensions\n for (var i = 0; i < this.deferred.length;)\n if (tryHandleExtension(this, this.deferred[i]))\n this.deferred.splice(i, 1);\n else\n ++i;\n for (var j = 0; j < /* initializes */ object.nestedArray.length; ++j) // recurse into the namespace\n this._handleAdd(object._nestedArray[j]);\n if (exposeRe.test(object.name))\n object.parent[object.name] = object; // expose namespace as property of its parent\n }\n\n // The above also adds uppercased (and thus conflict-free) nested types, services and enums as\n // properties of namespaces just like static code does. This allows using a .d.ts generated for\n // a static module with reflection-based solutions where the condition is met.\n};\n\n/**\n * Called when any object is removed from this root or its sub-namespaces.\n * @param {ReflectionObject} object Object removed\n * @returns {undefined}\n * @private\n */\nRoot.prototype._handleRemove = function _handleRemove(object) {\n if (object instanceof Field) {\n\n if (/* an extension field */ object.extend !== undefined) {\n if (/* already handled */ object.extensionField) { // remove its sister field\n object.extensionField.parent.remove(object.extensionField);\n object.extensionField = null;\n } else { // cancel the extension\n var index = this.deferred.indexOf(object);\n /* istanbul ignore else */\n if (index > -1)\n this.deferred.splice(index, 1);\n }\n }\n\n } else if (object instanceof Enum) {\n\n if (exposeRe.test(object.name))\n delete object.parent[object.name]; // unexpose enum values\n\n } else if (object instanceof Namespace) {\n\n for (var i = 0; i < /* initializes */ object.nestedArray.length; ++i) // recurse into the namespace\n this._handleRemove(object._nestedArray[i]);\n\n if (exposeRe.test(object.name))\n delete object.parent[object.name]; // unexpose namespaces\n\n }\n};\n\n// Sets up cyclic dependencies (called in index-light)\nRoot._configure = function(Type_, parse_, common_) {\n Type = Type_;\n parse = parse_;\n common = common_;\n};\n","\"use strict\";\nmodule.exports = {};\n\n/**\n * Named roots.\n * This is where pbjs stores generated structures (the option `-r, --root` specifies a name).\n * Can also be used manually to make roots available across modules.\n * @name roots\n * @type {Object.}\n * @example\n * // pbjs -r myroot -o compiled.js ...\n *\n * // in another module:\n * require(\"./compiled.js\");\n *\n * // in any subsequent module:\n * var root = protobuf.roots[\"myroot\"];\n */\n","\"use strict\";\n\n/**\n * Streaming RPC helpers.\n * @namespace\n */\nvar rpc = exports;\n\n/**\n * RPC implementation passed to {@link Service#create} performing a service request on network level, i.e. by utilizing http requests or websockets.\n * @typedef RPCImpl\n * @type {function}\n * @param {Method|rpc.ServiceMethod,Message<{}>>} method Reflected or static method being called\n * @param {Uint8Array} requestData Request data\n * @param {RPCImplCallback} callback Callback function\n * @returns {undefined}\n * @example\n * function rpcImpl(method, requestData, callback) {\n * if (protobuf.util.lcFirst(method.name) !== \"myMethod\") // compatible with static code\n * throw Error(\"no such method\");\n * asynchronouslyObtainAResponse(requestData, function(err, responseData) {\n * callback(err, responseData);\n * });\n * }\n */\n\n/**\n * Node-style callback as used by {@link RPCImpl}.\n * @typedef RPCImplCallback\n * @type {function}\n * @param {Error|null} error Error, if any, otherwise `null`\n * @param {Uint8Array|null} [response] Response data or `null` to signal end of stream, if there hasn't been an error\n * @returns {undefined}\n */\n\nrpc.Service = require(29);\n","\"use strict\";\nmodule.exports = Service;\n\nvar util = require(35);\n\n// Extends EventEmitter\n(Service.prototype = Object.create(util.EventEmitter.prototype)).constructor = Service;\n\n/**\n * A service method callback as used by {@link rpc.ServiceMethod|ServiceMethod}.\n *\n * Differs from {@link RPCImplCallback} in that it is an actual callback of a service method which may not return `response = null`.\n * @typedef rpc.ServiceMethodCallback\n * @template TRes extends Message\n * @type {function}\n * @param {Error|null} error Error, if any\n * @param {TRes} [response] Response message\n * @returns {undefined}\n */\n\n/**\n * A service method part of a {@link rpc.Service} as created by {@link Service.create}.\n * @typedef rpc.ServiceMethod\n * @template TReq extends Message\n * @template TRes extends Message\n * @type {function}\n * @param {TReq|Properties} request Request message or plain object\n * @param {rpc.ServiceMethodCallback} [callback] Node-style callback called with the error, if any, and the response message\n * @returns {Promise>} Promise if `callback` has been omitted, otherwise `undefined`\n */\n\n/**\n * Constructs a new RPC service instance.\n * @classdesc An RPC service as returned by {@link Service#create}.\n * @exports rpc.Service\n * @extends util.EventEmitter\n * @constructor\n * @param {RPCImpl} rpcImpl RPC implementation\n * @param {boolean} [requestDelimited=false] Whether requests are length-delimited\n * @param {boolean} [responseDelimited=false] Whether responses are length-delimited\n */\nfunction Service(rpcImpl, requestDelimited, responseDelimited) {\n\n if (typeof rpcImpl !== \"function\")\n throw TypeError(\"rpcImpl must be a function\");\n\n util.EventEmitter.call(this);\n\n /**\n * RPC implementation. Becomes `null` once the service is ended.\n * @type {RPCImpl|null}\n */\n this.rpcImpl = rpcImpl;\n\n /**\n * Whether requests are length-delimited.\n * @type {boolean}\n */\n this.requestDelimited = Boolean(requestDelimited);\n\n /**\n * Whether responses are length-delimited.\n * @type {boolean}\n */\n this.responseDelimited = Boolean(responseDelimited);\n}\n\n/**\n * Calls a service method through {@link rpc.Service#rpcImpl|rpcImpl}.\n * @param {Method|rpc.ServiceMethod} method Reflected or static method\n * @param {Constructor} requestCtor Request constructor\n * @param {Constructor} responseCtor Response constructor\n * @param {TReq|Properties} request Request message or plain object\n * @param {rpc.ServiceMethodCallback} callback Service callback\n * @returns {undefined}\n * @template TReq extends Message\n * @template TRes extends Message\n */\nService.prototype.rpcCall = function rpcCall(method, requestCtor, responseCtor, request, callback) {\n\n if (!request)\n throw TypeError(\"request must be specified\");\n\n var self = this;\n if (!callback)\n return util.asPromise(rpcCall, self, method, requestCtor, responseCtor, request);\n\n if (!self.rpcImpl) {\n setTimeout(function() { callback(Error(\"already ended\")); }, 0);\n return undefined;\n }\n\n try {\n return self.rpcImpl(\n method,\n requestCtor[self.requestDelimited ? \"encodeDelimited\" : \"encode\"](request).finish(),\n function rpcCallback(err, response) {\n\n if (err) {\n self.emit(\"error\", err, method);\n return callback(err);\n }\n\n if (response === null) {\n self.end(/* endedByRPC */ true);\n return undefined;\n }\n\n if (!(response instanceof responseCtor)) {\n try {\n response = responseCtor[self.responseDelimited ? \"decodeDelimited\" : \"decode\"](response);\n } catch (err) {\n self.emit(\"error\", err, method);\n return callback(err);\n }\n }\n\n self.emit(\"data\", response, method);\n return callback(null, response);\n }\n );\n } catch (err) {\n self.emit(\"error\", err, method);\n setTimeout(function() { callback(err); }, 0);\n return undefined;\n }\n};\n\n/**\n * Ends this service and emits the `end` event.\n * @param {boolean} [endedByRPC=false] Whether the service has been ended by the RPC implementation.\n * @returns {rpc.Service} `this`\n */\nService.prototype.end = function end(endedByRPC) {\n if (this.rpcImpl) {\n if (!endedByRPC) // signal end to rpcImpl\n this.rpcImpl(null, null, null);\n this.rpcImpl = null;\n this.emit(\"end\").off();\n }\n return this;\n};\n","\"use strict\";\nmodule.exports = Service;\n\n// extends Namespace\nvar Namespace = require(21);\n((Service.prototype = Object.create(Namespace.prototype)).constructor = Service).className = \"Service\";\n\nvar Method = require(20),\n util = require(33),\n rpc = require(28);\n\n/**\n * Constructs a new service instance.\n * @classdesc Reflected service.\n * @extends NamespaceBase\n * @constructor\n * @param {string} name Service name\n * @param {Object.} [options] Service options\n * @throws {TypeError} If arguments are invalid\n */\nfunction Service(name, options) {\n Namespace.call(this, name, options);\n\n /**\n * Service methods.\n * @type {Object.}\n */\n this.methods = {}; // toJSON, marker\n\n /**\n * Cached methods as an array.\n * @type {Method[]|null}\n * @private\n */\n this._methodsArray = null;\n}\n\n/**\n * Service descriptor.\n * @interface IService\n * @extends INamespace\n * @property {Object.} methods Method descriptors\n */\n\n/**\n * Constructs a service from a service descriptor.\n * @param {string} name Service name\n * @param {IService} json Service descriptor\n * @returns {Service} Created service\n * @throws {TypeError} If arguments are invalid\n */\nService.fromJSON = function fromJSON(name, json) {\n var service = new Service(name, json.options);\n /* istanbul ignore else */\n if (json.methods)\n for (var names = Object.keys(json.methods), i = 0; i < names.length; ++i)\n service.add(Method.fromJSON(names[i], json.methods[names[i]]));\n if (json.nested)\n service.addJSON(json.nested);\n service.comment = json.comment;\n return service;\n};\n\n/**\n * Converts this service to a service descriptor.\n * @param {IToJSONOptions} [toJSONOptions] JSON conversion options\n * @returns {IService} Service descriptor\n */\nService.prototype.toJSON = function toJSON(toJSONOptions) {\n var inherited = Namespace.prototype.toJSON.call(this, toJSONOptions);\n var keepComments = toJSONOptions ? Boolean(toJSONOptions.keepComments) : false;\n return util.toObject([\n \"options\" , inherited && inherited.options || undefined,\n \"methods\" , Namespace.arrayToJSON(this.methodsArray, toJSONOptions) || /* istanbul ignore next */ {},\n \"nested\" , inherited && inherited.nested || undefined,\n \"comment\" , keepComments ? this.comment : undefined\n ]);\n};\n\n/**\n * Methods of this service as an array for iteration.\n * @name Service#methodsArray\n * @type {Method[]}\n * @readonly\n */\nObject.defineProperty(Service.prototype, \"methodsArray\", {\n get: function() {\n return this._methodsArray || (this._methodsArray = util.toArray(this.methods));\n }\n});\n\nfunction clearCache(service) {\n service._methodsArray = null;\n return service;\n}\n\n/**\n * @override\n */\nService.prototype.get = function get(name) {\n return this.methods[name]\n || Namespace.prototype.get.call(this, name);\n};\n\n/**\n * @override\n */\nService.prototype.resolveAll = function resolveAll() {\n var methods = this.methodsArray;\n for (var i = 0; i < methods.length; ++i)\n methods[i].resolve();\n return Namespace.prototype.resolve.call(this);\n};\n\n/**\n * @override\n */\nService.prototype.add = function add(object) {\n\n /* istanbul ignore if */\n if (this.get(object.name))\n throw Error(\"duplicate name '\" + object.name + \"' in \" + this);\n\n if (object instanceof Method) {\n this.methods[object.name] = object;\n object.parent = this;\n return clearCache(this);\n }\n return Namespace.prototype.add.call(this, object);\n};\n\n/**\n * @override\n */\nService.prototype.remove = function remove(object) {\n if (object instanceof Method) {\n\n /* istanbul ignore if */\n if (this.methods[object.name] !== object)\n throw Error(object + \" is not a member of \" + this);\n\n delete this.methods[object.name];\n object.parent = null;\n return clearCache(this);\n }\n return Namespace.prototype.remove.call(this, object);\n};\n\n/**\n * Creates a runtime service using the specified rpc implementation.\n * @param {RPCImpl} rpcImpl RPC implementation\n * @param {boolean} [requestDelimited=false] Whether requests are length-delimited\n * @param {boolean} [responseDelimited=false] Whether responses are length-delimited\n * @returns {rpc.Service} RPC service. Useful where requests and/or responses are streamed.\n */\nService.prototype.create = function create(rpcImpl, requestDelimited, responseDelimited) {\n var rpcService = new rpc.Service(rpcImpl, requestDelimited, responseDelimited);\n for (var i = 0, method; i < /* initializes */ this.methodsArray.length; ++i) {\n var methodName = util.lcFirst((method = this._methodsArray[i]).resolve().name).replace(/[^$\\w_]/g, \"\");\n rpcService[methodName] = util.codegen([\"r\",\"c\"], util.isReserved(methodName) ? methodName + \"_\" : methodName)(\"return this.rpcCall(m,q,s,r,c)\")({\n m: method,\n q: method.resolvedRequestType.ctor,\n s: method.resolvedResponseType.ctor\n });\n }\n return rpcService;\n};\n","\"use strict\";\nmodule.exports = Type;\n\n// extends Namespace\nvar Namespace = require(21);\n((Type.prototype = Object.create(Namespace.prototype)).constructor = Type).className = \"Type\";\n\nvar Enum = require(14),\n OneOf = require(23),\n Field = require(15),\n MapField = require(18),\n Service = require(30),\n Message = require(19),\n Reader = require(24),\n Writer = require(38),\n util = require(33),\n encoder = require(13),\n decoder = require(12),\n verifier = require(36),\n converter = require(11),\n wrappers = require(37);\n\n/**\n * Constructs a new reflected message type instance.\n * @classdesc Reflected message type.\n * @extends NamespaceBase\n * @constructor\n * @param {string} name Message name\n * @param {Object.} [options] Declared options\n */\nfunction Type(name, options) {\n Namespace.call(this, name, options);\n\n /**\n * Message fields.\n * @type {Object.}\n */\n this.fields = {}; // toJSON, marker\n\n /**\n * Oneofs declared within this namespace, if any.\n * @type {Object.}\n */\n this.oneofs = undefined; // toJSON\n\n /**\n * Extension ranges, if any.\n * @type {number[][]}\n */\n this.extensions = undefined; // toJSON\n\n /**\n * Reserved ranges, if any.\n * @type {Array.}\n */\n this.reserved = undefined; // toJSON\n\n /*?\n * Whether this type is a legacy group.\n * @type {boolean|undefined}\n */\n this.group = undefined; // toJSON\n\n /**\n * Cached fields by id.\n * @type {Object.|null}\n * @private\n */\n this._fieldsById = null;\n\n /**\n * Cached fields as an array.\n * @type {Field[]|null}\n * @private\n */\n this._fieldsArray = null;\n\n /**\n * Cached oneofs as an array.\n * @type {OneOf[]|null}\n * @private\n */\n this._oneofsArray = null;\n\n /**\n * Cached constructor.\n * @type {Constructor<{}>}\n * @private\n */\n this._ctor = null;\n}\n\nObject.defineProperties(Type.prototype, {\n\n /**\n * Message fields by id.\n * @name Type#fieldsById\n * @type {Object.}\n * @readonly\n */\n fieldsById: {\n get: function() {\n\n /* istanbul ignore if */\n if (this._fieldsById)\n return this._fieldsById;\n\n this._fieldsById = {};\n for (var names = Object.keys(this.fields), i = 0; i < names.length; ++i) {\n var field = this.fields[names[i]],\n id = field.id;\n\n /* istanbul ignore if */\n if (this._fieldsById[id])\n throw Error(\"duplicate id \" + id + \" in \" + this);\n\n this._fieldsById[id] = field;\n }\n return this._fieldsById;\n }\n },\n\n /**\n * Fields of this message as an array for iteration.\n * @name Type#fieldsArray\n * @type {Field[]}\n * @readonly\n */\n fieldsArray: {\n get: function() {\n return this._fieldsArray || (this._fieldsArray = util.toArray(this.fields));\n }\n },\n\n /**\n * Oneofs of this message as an array for iteration.\n * @name Type#oneofsArray\n * @type {OneOf[]}\n * @readonly\n */\n oneofsArray: {\n get: function() {\n return this._oneofsArray || (this._oneofsArray = util.toArray(this.oneofs));\n }\n },\n\n /**\n * The registered constructor, if any registered, otherwise a generic constructor.\n * Assigning a function replaces the internal constructor. If the function does not extend {@link Message} yet, its prototype will be setup accordingly and static methods will be populated. If it already extends {@link Message}, it will just replace the internal constructor.\n * @name Type#ctor\n * @type {Constructor<{}>}\n */\n ctor: {\n get: function() {\n return this._ctor || (this.ctor = Type.generateConstructor(this)());\n },\n set: function(ctor) {\n\n // Ensure proper prototype\n var prototype = ctor.prototype;\n if (!(prototype instanceof Message)) {\n (ctor.prototype = new Message()).constructor = ctor;\n util.merge(ctor.prototype, prototype);\n }\n\n // Classes and messages reference their reflected type\n ctor.$type = ctor.prototype.$type = this;\n\n // Mix in static methods\n util.merge(ctor, Message, true);\n\n this._ctor = ctor;\n\n // Messages have non-enumerable default values on their prototype\n var i = 0;\n for (; i < /* initializes */ this.fieldsArray.length; ++i)\n this._fieldsArray[i].resolve(); // ensures a proper value\n\n // Messages have non-enumerable getters and setters for each virtual oneof field\n var ctorProperties = {};\n for (i = 0; i < /* initializes */ this.oneofsArray.length; ++i)\n ctorProperties[this._oneofsArray[i].resolve().name] = {\n get: util.oneOfGetter(this._oneofsArray[i].oneof),\n set: util.oneOfSetter(this._oneofsArray[i].oneof)\n };\n if (i)\n Object.defineProperties(ctor.prototype, ctorProperties);\n }\n }\n});\n\n/**\n * Generates a constructor function for the specified type.\n * @param {Type} mtype Message type\n * @returns {Codegen} Codegen instance\n */\nType.generateConstructor = function generateConstructor(mtype) {\n /* eslint-disable no-unexpected-multiline */\n var gen = util.codegen([\"p\"], mtype.name);\n // explicitly initialize mutable object/array fields so that these aren't just inherited from the prototype\n for (var i = 0, field; i < mtype.fieldsArray.length; ++i)\n if ((field = mtype._fieldsArray[i]).map) gen\n (\"this%s={}\", util.safeProp(field.name));\n else if (field.repeated) gen\n (\"this%s=[]\", util.safeProp(field.name));\n return gen\n (\"if(p)for(var ks=Object.keys(p),i=0;i} [oneofs] Oneof descriptors\n * @property {Object.} fields Field descriptors\n * @property {number[][]} [extensions] Extension ranges\n * @property {number[][]} [reserved] Reserved ranges\n * @property {boolean} [group=false] Whether a legacy group or not\n */\n\n/**\n * Creates a message type from a message type descriptor.\n * @param {string} name Message name\n * @param {IType} json Message type descriptor\n * @returns {Type} Created message type\n */\nType.fromJSON = function fromJSON(name, json) {\n var type = new Type(name, json.options);\n type.extensions = json.extensions;\n type.reserved = json.reserved;\n var names = Object.keys(json.fields),\n i = 0;\n for (; i < names.length; ++i)\n type.add(\n ( typeof json.fields[names[i]].keyType !== \"undefined\"\n ? MapField.fromJSON\n : Field.fromJSON )(names[i], json.fields[names[i]])\n );\n if (json.oneofs)\n for (names = Object.keys(json.oneofs), i = 0; i < names.length; ++i)\n type.add(OneOf.fromJSON(names[i], json.oneofs[names[i]]));\n if (json.nested)\n for (names = Object.keys(json.nested), i = 0; i < names.length; ++i) {\n var nested = json.nested[names[i]];\n type.add( // most to least likely\n ( nested.id !== undefined\n ? Field.fromJSON\n : nested.fields !== undefined\n ? Type.fromJSON\n : nested.values !== undefined\n ? Enum.fromJSON\n : nested.methods !== undefined\n ? Service.fromJSON\n : Namespace.fromJSON )(names[i], nested)\n );\n }\n if (json.extensions && json.extensions.length)\n type.extensions = json.extensions;\n if (json.reserved && json.reserved.length)\n type.reserved = json.reserved;\n if (json.group)\n type.group = true;\n if (json.comment)\n type.comment = json.comment;\n return type;\n};\n\n/**\n * Converts this message type to a message type descriptor.\n * @param {IToJSONOptions} [toJSONOptions] JSON conversion options\n * @returns {IType} Message type descriptor\n */\nType.prototype.toJSON = function toJSON(toJSONOptions) {\n var inherited = Namespace.prototype.toJSON.call(this, toJSONOptions);\n var keepComments = toJSONOptions ? Boolean(toJSONOptions.keepComments) : false;\n return util.toObject([\n \"options\" , inherited && inherited.options || undefined,\n \"oneofs\" , Namespace.arrayToJSON(this.oneofsArray, toJSONOptions),\n \"fields\" , Namespace.arrayToJSON(this.fieldsArray.filter(function(obj) { return !obj.declaringField; }), toJSONOptions) || {},\n \"extensions\" , this.extensions && this.extensions.length ? this.extensions : undefined,\n \"reserved\" , this.reserved && this.reserved.length ? this.reserved : undefined,\n \"group\" , this.group || undefined,\n \"nested\" , inherited && inherited.nested || undefined,\n \"comment\" , keepComments ? this.comment : undefined\n ]);\n};\n\n/**\n * @override\n */\nType.prototype.resolveAll = function resolveAll() {\n var fields = this.fieldsArray, i = 0;\n while (i < fields.length)\n fields[i++].resolve();\n var oneofs = this.oneofsArray; i = 0;\n while (i < oneofs.length)\n oneofs[i++].resolve();\n return Namespace.prototype.resolveAll.call(this);\n};\n\n/**\n * @override\n */\nType.prototype.get = function get(name) {\n return this.fields[name]\n || this.oneofs && this.oneofs[name]\n || this.nested && this.nested[name]\n || null;\n};\n\n/**\n * Adds a nested object to this type.\n * @param {ReflectionObject} object Nested object to add\n * @returns {Type} `this`\n * @throws {TypeError} If arguments are invalid\n * @throws {Error} If there is already a nested object with this name or, if a field, when there is already a field with this id\n */\nType.prototype.add = function add(object) {\n\n if (this.get(object.name))\n throw Error(\"duplicate name '\" + object.name + \"' in \" + this);\n\n if (object instanceof Field && object.extend === undefined) {\n // NOTE: Extension fields aren't actual fields on the declaring type, but nested objects.\n // The root object takes care of adding distinct sister-fields to the respective extended\n // type instead.\n\n // avoids calling the getter if not absolutely necessary because it's called quite frequently\n if (this._fieldsById ? /* istanbul ignore next */ this._fieldsById[object.id] : this.fieldsById[object.id])\n throw Error(\"duplicate id \" + object.id + \" in \" + this);\n if (this.isReservedId(object.id))\n throw Error(\"id \" + object.id + \" is reserved in \" + this);\n if (this.isReservedName(object.name))\n throw Error(\"name '\" + object.name + \"' is reserved in \" + this);\n\n if (object.parent)\n object.parent.remove(object);\n this.fields[object.name] = object;\n object.message = this;\n object.onAdd(this);\n return clearCache(this);\n }\n if (object instanceof OneOf) {\n if (!this.oneofs)\n this.oneofs = {};\n this.oneofs[object.name] = object;\n object.onAdd(this);\n return clearCache(this);\n }\n return Namespace.prototype.add.call(this, object);\n};\n\n/**\n * Removes a nested object from this type.\n * @param {ReflectionObject} object Nested object to remove\n * @returns {Type} `this`\n * @throws {TypeError} If arguments are invalid\n * @throws {Error} If `object` is not a member of this type\n */\nType.prototype.remove = function remove(object) {\n if (object instanceof Field && object.extend === undefined) {\n // See Type#add for the reason why extension fields are excluded here.\n\n /* istanbul ignore if */\n if (!this.fields || this.fields[object.name] !== object)\n throw Error(object + \" is not a member of \" + this);\n\n delete this.fields[object.name];\n object.parent = null;\n object.onRemove(this);\n return clearCache(this);\n }\n if (object instanceof OneOf) {\n\n /* istanbul ignore if */\n if (!this.oneofs || this.oneofs[object.name] !== object)\n throw Error(object + \" is not a member of \" + this);\n\n delete this.oneofs[object.name];\n object.parent = null;\n object.onRemove(this);\n return clearCache(this);\n }\n return Namespace.prototype.remove.call(this, object);\n};\n\n/**\n * Tests if the specified id is reserved.\n * @param {number} id Id to test\n * @returns {boolean} `true` if reserved, otherwise `false`\n */\nType.prototype.isReservedId = function isReservedId(id) {\n return Namespace.isReservedId(this.reserved, id);\n};\n\n/**\n * Tests if the specified name is reserved.\n * @param {string} name Name to test\n * @returns {boolean} `true` if reserved, otherwise `false`\n */\nType.prototype.isReservedName = function isReservedName(name) {\n return Namespace.isReservedName(this.reserved, name);\n};\n\n/**\n * Creates a new message of this type using the specified properties.\n * @param {Object.} [properties] Properties to set\n * @returns {Message<{}>} Message instance\n */\nType.prototype.create = function create(properties) {\n return new this.ctor(properties);\n};\n\n/**\n * Sets up {@link Type#encode|encode}, {@link Type#decode|decode} and {@link Type#verify|verify}.\n * @returns {Type} `this`\n */\nType.prototype.setup = function setup() {\n // Sets up everything at once so that the prototype chain does not have to be re-evaluated\n // multiple times (V8, soft-deopt prototype-check).\n\n var fullName = this.fullName,\n types = [];\n for (var i = 0; i < /* initializes */ this.fieldsArray.length; ++i)\n types.push(this._fieldsArray[i].resolve().resolvedType);\n\n // Replace setup methods with type-specific generated functions\n this.encode = encoder(this)({\n Writer : Writer,\n types : types,\n util : util\n });\n this.decode = decoder(this)({\n Reader : Reader,\n types : types,\n util : util\n });\n this.verify = verifier(this)({\n types : types,\n util : util\n });\n this.fromObject = converter.fromObject(this)({\n types : types,\n util : util\n });\n this.toObject = converter.toObject(this)({\n types : types,\n util : util\n });\n\n // Inject custom wrappers for common types\n var wrapper = wrappers[fullName];\n if (wrapper) {\n var originalThis = Object.create(this);\n // if (wrapper.fromObject) {\n originalThis.fromObject = this.fromObject;\n this.fromObject = wrapper.fromObject.bind(originalThis);\n // }\n // if (wrapper.toObject) {\n originalThis.toObject = this.toObject;\n this.toObject = wrapper.toObject.bind(originalThis);\n // }\n }\n\n return this;\n};\n\n/**\n * Encodes a message of this type. Does not implicitly {@link Type#verify|verify} messages.\n * @param {Message<{}>|Object.} message Message instance or plain object\n * @param {Writer} [writer] Writer to encode to\n * @returns {Writer} writer\n */\nType.prototype.encode = function encode_setup(message, writer) {\n return this.setup().encode(message, writer); // overrides this method\n};\n\n/**\n * Encodes a message of this type preceeded by its byte length as a varint. Does not implicitly {@link Type#verify|verify} messages.\n * @param {Message<{}>|Object.} message Message instance or plain object\n * @param {Writer} [writer] Writer to encode to\n * @returns {Writer} writer\n */\nType.prototype.encodeDelimited = function encodeDelimited(message, writer) {\n return this.encode(message, writer && writer.len ? writer.fork() : writer).ldelim();\n};\n\n/**\n * Decodes a message of this type.\n * @param {Reader|Uint8Array} reader Reader or buffer to decode from\n * @param {number} [length] Length of the message, if known beforehand\n * @returns {Message<{}>} Decoded message\n * @throws {Error} If the payload is not a reader or valid buffer\n * @throws {util.ProtocolError<{}>} If required fields are missing\n */\nType.prototype.decode = function decode_setup(reader, length) {\n return this.setup().decode(reader, length); // overrides this method\n};\n\n/**\n * Decodes a message of this type preceeded by its byte length as a varint.\n * @param {Reader|Uint8Array} reader Reader or buffer to decode from\n * @returns {Message<{}>} Decoded message\n * @throws {Error} If the payload is not a reader or valid buffer\n * @throws {util.ProtocolError} If required fields are missing\n */\nType.prototype.decodeDelimited = function decodeDelimited(reader) {\n if (!(reader instanceof Reader))\n reader = Reader.create(reader);\n return this.decode(reader, reader.uint32());\n};\n\n/**\n * Verifies that field values are valid and that required fields are present.\n * @param {Object.} message Plain object to verify\n * @returns {null|string} `null` if valid, otherwise the reason why it is not\n */\nType.prototype.verify = function verify_setup(message) {\n return this.setup().verify(message); // overrides this method\n};\n\n/**\n * Creates a new message of this type from a plain object. Also converts values to their respective internal types.\n * @param {Object.} object Plain object to convert\n * @returns {Message<{}>} Message instance\n */\nType.prototype.fromObject = function fromObject(object) {\n return this.setup().fromObject(object);\n};\n\n/**\n * Conversion options as used by {@link Type#toObject} and {@link Message.toObject}.\n * @interface IConversionOptions\n * @property {Function} [longs] Long conversion type.\n * Valid values are `String` and `Number` (the global types).\n * Defaults to copy the present value, which is a possibly unsafe number without and a {@link Long} with a long library.\n * @property {Function} [enums] Enum value conversion type.\n * Only valid value is `String` (the global type).\n * Defaults to copy the present value, which is the numeric id.\n * @property {Function} [bytes] Bytes value conversion type.\n * Valid values are `Array` and (a base64 encoded) `String` (the global types).\n * Defaults to copy the present value, which usually is a Buffer under node and an Uint8Array in the browser.\n * @property {boolean} [defaults=false] Also sets default values on the resulting object\n * @property {boolean} [arrays=false] Sets empty arrays for missing repeated fields even if `defaults=false`\n * @property {boolean} [objects=false] Sets empty objects for missing map fields even if `defaults=false`\n * @property {boolean} [oneofs=false] Includes virtual oneof properties set to the present field's name, if any\n * @property {boolean} [json=false] Performs additional JSON compatibility conversions, i.e. NaN and Infinity to strings\n */\n\n/**\n * Creates a plain object from a message of this type. Also converts values to other types if specified.\n * @param {Message<{}>} message Message instance\n * @param {IConversionOptions} [options] Conversion options\n * @returns {Object.} Plain object\n */\nType.prototype.toObject = function toObject(message, options) {\n return this.setup().toObject(message, options);\n};\n\n/**\n * Decorator function as returned by {@link Type.d} (TypeScript).\n * @typedef TypeDecorator\n * @type {function}\n * @param {Constructor} target Target constructor\n * @returns {undefined}\n * @template T extends Message\n */\n\n/**\n * Type decorator (TypeScript).\n * @param {string} [typeName] Type name, defaults to the constructor's name\n * @returns {TypeDecorator} Decorator function\n * @template T extends Message\n */\nType.d = function decorateType(typeName) {\n return function typeDecorator(target) {\n util.decorateType(target, typeName);\n };\n};\n","\"use strict\";\n\n/**\n * Common type constants.\n * @namespace\n */\nvar types = exports;\n\nvar util = require(33);\n\nvar s = [\n \"double\", // 0\n \"float\", // 1\n \"int32\", // 2\n \"uint32\", // 3\n \"sint32\", // 4\n \"fixed32\", // 5\n \"sfixed32\", // 6\n \"int64\", // 7\n \"uint64\", // 8\n \"sint64\", // 9\n \"fixed64\", // 10\n \"sfixed64\", // 11\n \"bool\", // 12\n \"string\", // 13\n \"bytes\" // 14\n];\n\nfunction bake(values, offset) {\n var i = 0, o = {};\n offset |= 0;\n while (i < values.length) o[s[i + offset]] = values[i++];\n return o;\n}\n\n/**\n * Basic type wire types.\n * @type {Object.}\n * @const\n * @property {number} double=1 Fixed64 wire type\n * @property {number} float=5 Fixed32 wire type\n * @property {number} int32=0 Varint wire type\n * @property {number} uint32=0 Varint wire type\n * @property {number} sint32=0 Varint wire type\n * @property {number} fixed32=5 Fixed32 wire type\n * @property {number} sfixed32=5 Fixed32 wire type\n * @property {number} int64=0 Varint wire type\n * @property {number} uint64=0 Varint wire type\n * @property {number} sint64=0 Varint wire type\n * @property {number} fixed64=1 Fixed64 wire type\n * @property {number} sfixed64=1 Fixed64 wire type\n * @property {number} bool=0 Varint wire type\n * @property {number} string=2 Ldelim wire type\n * @property {number} bytes=2 Ldelim wire type\n */\ntypes.basic = bake([\n /* double */ 1,\n /* float */ 5,\n /* int32 */ 0,\n /* uint32 */ 0,\n /* sint32 */ 0,\n /* fixed32 */ 5,\n /* sfixed32 */ 5,\n /* int64 */ 0,\n /* uint64 */ 0,\n /* sint64 */ 0,\n /* fixed64 */ 1,\n /* sfixed64 */ 1,\n /* bool */ 0,\n /* string */ 2,\n /* bytes */ 2\n]);\n\n/**\n * Basic type defaults.\n * @type {Object.}\n * @const\n * @property {number} double=0 Double default\n * @property {number} float=0 Float default\n * @property {number} int32=0 Int32 default\n * @property {number} uint32=0 Uint32 default\n * @property {number} sint32=0 Sint32 default\n * @property {number} fixed32=0 Fixed32 default\n * @property {number} sfixed32=0 Sfixed32 default\n * @property {number} int64=0 Int64 default\n * @property {number} uint64=0 Uint64 default\n * @property {number} sint64=0 Sint32 default\n * @property {number} fixed64=0 Fixed64 default\n * @property {number} sfixed64=0 Sfixed64 default\n * @property {boolean} bool=false Bool default\n * @property {string} string=\"\" String default\n * @property {Array.} bytes=Array(0) Bytes default\n * @property {null} message=null Message default\n */\ntypes.defaults = bake([\n /* double */ 0,\n /* float */ 0,\n /* int32 */ 0,\n /* uint32 */ 0,\n /* sint32 */ 0,\n /* fixed32 */ 0,\n /* sfixed32 */ 0,\n /* int64 */ 0,\n /* uint64 */ 0,\n /* sint64 */ 0,\n /* fixed64 */ 0,\n /* sfixed64 */ 0,\n /* bool */ false,\n /* string */ \"\",\n /* bytes */ util.emptyArray,\n /* message */ null\n]);\n\n/**\n * Basic long type wire types.\n * @type {Object.}\n * @const\n * @property {number} int64=0 Varint wire type\n * @property {number} uint64=0 Varint wire type\n * @property {number} sint64=0 Varint wire type\n * @property {number} fixed64=1 Fixed64 wire type\n * @property {number} sfixed64=1 Fixed64 wire type\n */\ntypes.long = bake([\n /* int64 */ 0,\n /* uint64 */ 0,\n /* sint64 */ 0,\n /* fixed64 */ 1,\n /* sfixed64 */ 1\n], 7);\n\n/**\n * Allowed types for map keys with their associated wire type.\n * @type {Object.}\n * @const\n * @property {number} int32=0 Varint wire type\n * @property {number} uint32=0 Varint wire type\n * @property {number} sint32=0 Varint wire type\n * @property {number} fixed32=5 Fixed32 wire type\n * @property {number} sfixed32=5 Fixed32 wire type\n * @property {number} int64=0 Varint wire type\n * @property {number} uint64=0 Varint wire type\n * @property {number} sint64=0 Varint wire type\n * @property {number} fixed64=1 Fixed64 wire type\n * @property {number} sfixed64=1 Fixed64 wire type\n * @property {number} bool=0 Varint wire type\n * @property {number} string=2 Ldelim wire type\n */\ntypes.mapKey = bake([\n /* int32 */ 0,\n /* uint32 */ 0,\n /* sint32 */ 0,\n /* fixed32 */ 5,\n /* sfixed32 */ 5,\n /* int64 */ 0,\n /* uint64 */ 0,\n /* sint64 */ 0,\n /* fixed64 */ 1,\n /* sfixed64 */ 1,\n /* bool */ 0,\n /* string */ 2\n], 2);\n\n/**\n * Allowed types for packed repeated fields with their associated wire type.\n * @type {Object.}\n * @const\n * @property {number} double=1 Fixed64 wire type\n * @property {number} float=5 Fixed32 wire type\n * @property {number} int32=0 Varint wire type\n * @property {number} uint32=0 Varint wire type\n * @property {number} sint32=0 Varint wire type\n * @property {number} fixed32=5 Fixed32 wire type\n * @property {number} sfixed32=5 Fixed32 wire type\n * @property {number} int64=0 Varint wire type\n * @property {number} uint64=0 Varint wire type\n * @property {number} sint64=0 Varint wire type\n * @property {number} fixed64=1 Fixed64 wire type\n * @property {number} sfixed64=1 Fixed64 wire type\n * @property {number} bool=0 Varint wire type\n */\ntypes.packed = bake([\n /* double */ 1,\n /* float */ 5,\n /* int32 */ 0,\n /* uint32 */ 0,\n /* sint32 */ 0,\n /* fixed32 */ 5,\n /* sfixed32 */ 5,\n /* int64 */ 0,\n /* uint64 */ 0,\n /* sint64 */ 0,\n /* fixed64 */ 1,\n /* sfixed64 */ 1,\n /* bool */ 0\n]);\n","\"use strict\";\n\n/**\n * Various utility functions.\n * @namespace\n */\nvar util = module.exports = require(35);\n\nvar roots = require(27);\n\nvar Type, // cyclic\n Enum;\n\nutil.codegen = require(3);\nutil.fetch = require(5);\nutil.path = require(8);\n\n/**\n * Node's fs module if available.\n * @type {Object.}\n */\nutil.fs = util.inquire(\"fs\");\n\n/**\n * Converts an object's values to an array.\n * @param {Object.} object Object to convert\n * @returns {Array.<*>} Converted array\n */\nutil.toArray = function toArray(object) {\n if (object) {\n var keys = Object.keys(object),\n array = new Array(keys.length),\n index = 0;\n while (index < keys.length)\n array[index] = object[keys[index++]];\n return array;\n }\n return [];\n};\n\n/**\n * Converts an array of keys immediately followed by their respective value to an object, omitting undefined values.\n * @param {Array.<*>} array Array to convert\n * @returns {Object.} Converted object\n */\nutil.toObject = function toObject(array) {\n var object = {},\n index = 0;\n while (index < array.length) {\n var key = array[index++],\n val = array[index++];\n if (val !== undefined)\n object[key] = val;\n }\n return object;\n};\n\nvar safePropBackslashRe = /\\\\/g,\n safePropQuoteRe = /\"/g;\n\n/**\n * Tests whether the specified name is a reserved word in JS.\n * @param {string} name Name to test\n * @returns {boolean} `true` if reserved, otherwise `false`\n */\nutil.isReserved = function isReserved(name) {\n return /^(?:do|if|in|for|let|new|try|var|case|else|enum|eval|false|null|this|true|void|with|break|catch|class|const|super|throw|while|yield|delete|export|import|public|return|static|switch|typeof|default|extends|finally|package|private|continue|debugger|function|arguments|interface|protected|implements|instanceof)$/.test(name);\n};\n\n/**\n * Returns a safe property accessor for the specified property name.\n * @param {string} prop Property name\n * @returns {string} Safe accessor\n */\nutil.safeProp = function safeProp(prop) {\n if (!/^[$\\w_]+$/.test(prop) || util.isReserved(prop))\n return \"[\\\"\" + prop.replace(safePropBackslashRe, \"\\\\\\\\\").replace(safePropQuoteRe, \"\\\\\\\"\") + \"\\\"]\";\n return \".\" + prop;\n};\n\n/**\n * Converts the first character of a string to upper case.\n * @param {string} str String to convert\n * @returns {string} Converted string\n */\nutil.ucFirst = function ucFirst(str) {\n return str.charAt(0).toUpperCase() + str.substring(1);\n};\n\nvar camelCaseRe = /_([a-z])/g;\n\n/**\n * Converts a string to camel case.\n * @param {string} str String to convert\n * @returns {string} Converted string\n */\nutil.camelCase = function camelCase(str) {\n return str.substring(0, 1)\n + str.substring(1)\n .replace(camelCaseRe, function($0, $1) { return $1.toUpperCase(); });\n};\n\n/**\n * Compares reflected fields by id.\n * @param {Field} a First field\n * @param {Field} b Second field\n * @returns {number} Comparison value\n */\nutil.compareFieldsById = function compareFieldsById(a, b) {\n return a.id - b.id;\n};\n\n/**\n * Decorator helper for types (TypeScript).\n * @param {Constructor} ctor Constructor function\n * @param {string} [typeName] Type name, defaults to the constructor's name\n * @returns {Type} Reflected type\n * @template T extends Message\n * @property {Root} root Decorators root\n */\nutil.decorateType = function decorateType(ctor, typeName) {\n\n /* istanbul ignore if */\n if (ctor.$type) {\n if (typeName && ctor.$type.name !== typeName) {\n util.decorateRoot.remove(ctor.$type);\n ctor.$type.name = typeName;\n util.decorateRoot.add(ctor.$type);\n }\n return ctor.$type;\n }\n\n /* istanbul ignore next */\n if (!Type)\n Type = require(31);\n\n var type = new Type(typeName || ctor.name);\n util.decorateRoot.add(type);\n type.ctor = ctor; // sets up .encode, .decode etc.\n Object.defineProperty(ctor, \"$type\", { value: type, enumerable: false });\n Object.defineProperty(ctor.prototype, \"$type\", { value: type, enumerable: false });\n return type;\n};\n\nvar decorateEnumIndex = 0;\n\n/**\n * Decorator helper for enums (TypeScript).\n * @param {Object} object Enum object\n * @returns {Enum} Reflected enum\n */\nutil.decorateEnum = function decorateEnum(object) {\n\n /* istanbul ignore if */\n if (object.$type)\n return object.$type;\n\n /* istanbul ignore next */\n if (!Enum)\n Enum = require(14);\n\n var enm = new Enum(\"Enum\" + decorateEnumIndex++, object);\n util.decorateRoot.add(enm);\n Object.defineProperty(object, \"$type\", { value: enm, enumerable: false });\n return enm;\n};\n\n\n/**\n * Sets the value of a property by property path. If a value already exists, it is turned to an array\n * @param {Object.} dst Destination object\n * @param {string} path dot '.' delimited path of the property to set\n * @param {Object} value the value to set\n * @returns {Object.} Destination object\n */\nutil.setProperty = function setProperty(dst, path, value) {\n function setProp(dst, path, value) {\n var part = path.shift();\n if (part === \"__proto__\" || part === \"prototype\") {\n return dst;\n }\n if (path.length > 0) {\n dst[part] = setProp(dst[part] || {}, path, value);\n } else {\n var prevValue = dst[part];\n if (prevValue)\n value = [].concat(prevValue).concat(value);\n dst[part] = value;\n }\n return dst;\n }\n\n if (typeof dst !== \"object\")\n throw TypeError(\"dst must be an object\");\n if (!path)\n throw TypeError(\"path must be specified\");\n\n path = path.split(\".\");\n return setProp(dst, path, value);\n};\n\n/**\n * Decorator root (TypeScript).\n * @name util.decorateRoot\n * @type {Root}\n * @readonly\n */\nObject.defineProperty(util, \"decorateRoot\", {\n get: function() {\n return roots[\"decorated\"] || (roots[\"decorated\"] = new (require(26))());\n }\n});\n","\"use strict\";\nmodule.exports = LongBits;\n\nvar util = require(35);\n\n/**\n * Constructs new long bits.\n * @classdesc Helper class for working with the low and high bits of a 64 bit value.\n * @memberof util\n * @constructor\n * @param {number} lo Low 32 bits, unsigned\n * @param {number} hi High 32 bits, unsigned\n */\nfunction LongBits(lo, hi) {\n\n // note that the casts below are theoretically unnecessary as of today, but older statically\n // generated converter code might still call the ctor with signed 32bits. kept for compat.\n\n /**\n * Low bits.\n * @type {number}\n */\n this.lo = lo >>> 0;\n\n /**\n * High bits.\n * @type {number}\n */\n this.hi = hi >>> 0;\n}\n\n/**\n * Zero bits.\n * @memberof util.LongBits\n * @type {util.LongBits}\n */\nvar zero = LongBits.zero = new LongBits(0, 0);\n\nzero.toNumber = function() { return 0; };\nzero.zzEncode = zero.zzDecode = function() { return this; };\nzero.length = function() { return 1; };\n\n/**\n * Zero hash.\n * @memberof util.LongBits\n * @type {string}\n */\nvar zeroHash = LongBits.zeroHash = \"\\0\\0\\0\\0\\0\\0\\0\\0\";\n\n/**\n * Constructs new long bits from the specified number.\n * @param {number} value Value\n * @returns {util.LongBits} Instance\n */\nLongBits.fromNumber = function fromNumber(value) {\n if (value === 0)\n return zero;\n var sign = value < 0;\n if (sign)\n value = -value;\n var lo = value >>> 0,\n hi = (value - lo) / 4294967296 >>> 0;\n if (sign) {\n hi = ~hi >>> 0;\n lo = ~lo >>> 0;\n if (++lo > 4294967295) {\n lo = 0;\n if (++hi > 4294967295)\n hi = 0;\n }\n }\n return new LongBits(lo, hi);\n};\n\n/**\n * Constructs new long bits from a number, long or string.\n * @param {Long|number|string} value Value\n * @returns {util.LongBits} Instance\n */\nLongBits.from = function from(value) {\n if (typeof value === \"number\")\n return LongBits.fromNumber(value);\n if (util.isString(value)) {\n /* istanbul ignore else */\n if (util.Long)\n value = util.Long.fromString(value);\n else\n return LongBits.fromNumber(parseInt(value, 10));\n }\n return value.low || value.high ? new LongBits(value.low >>> 0, value.high >>> 0) : zero;\n};\n\n/**\n * Converts this long bits to a possibly unsafe JavaScript number.\n * @param {boolean} [unsigned=false] Whether unsigned or not\n * @returns {number} Possibly unsafe number\n */\nLongBits.prototype.toNumber = function toNumber(unsigned) {\n if (!unsigned && this.hi >>> 31) {\n var lo = ~this.lo + 1 >>> 0,\n hi = ~this.hi >>> 0;\n if (!lo)\n hi = hi + 1 >>> 0;\n return -(lo + hi * 4294967296);\n }\n return this.lo + this.hi * 4294967296;\n};\n\n/**\n * Converts this long bits to a long.\n * @param {boolean} [unsigned=false] Whether unsigned or not\n * @returns {Long} Long\n */\nLongBits.prototype.toLong = function toLong(unsigned) {\n return util.Long\n ? new util.Long(this.lo | 0, this.hi | 0, Boolean(unsigned))\n /* istanbul ignore next */\n : { low: this.lo | 0, high: this.hi | 0, unsigned: Boolean(unsigned) };\n};\n\nvar charCodeAt = String.prototype.charCodeAt;\n\n/**\n * Constructs new long bits from the specified 8 characters long hash.\n * @param {string} hash Hash\n * @returns {util.LongBits} Bits\n */\nLongBits.fromHash = function fromHash(hash) {\n if (hash === zeroHash)\n return zero;\n return new LongBits(\n ( charCodeAt.call(hash, 0)\n | charCodeAt.call(hash, 1) << 8\n | charCodeAt.call(hash, 2) << 16\n | charCodeAt.call(hash, 3) << 24) >>> 0\n ,\n ( charCodeAt.call(hash, 4)\n | charCodeAt.call(hash, 5) << 8\n | charCodeAt.call(hash, 6) << 16\n | charCodeAt.call(hash, 7) << 24) >>> 0\n );\n};\n\n/**\n * Converts this long bits to a 8 characters long hash.\n * @returns {string} Hash\n */\nLongBits.prototype.toHash = function toHash() {\n return String.fromCharCode(\n this.lo & 255,\n this.lo >>> 8 & 255,\n this.lo >>> 16 & 255,\n this.lo >>> 24 ,\n this.hi & 255,\n this.hi >>> 8 & 255,\n this.hi >>> 16 & 255,\n this.hi >>> 24\n );\n};\n\n/**\n * Zig-zag encodes this long bits.\n * @returns {util.LongBits} `this`\n */\nLongBits.prototype.zzEncode = function zzEncode() {\n var mask = this.hi >> 31;\n this.hi = ((this.hi << 1 | this.lo >>> 31) ^ mask) >>> 0;\n this.lo = ( this.lo << 1 ^ mask) >>> 0;\n return this;\n};\n\n/**\n * Zig-zag decodes this long bits.\n * @returns {util.LongBits} `this`\n */\nLongBits.prototype.zzDecode = function zzDecode() {\n var mask = -(this.lo & 1);\n this.lo = ((this.lo >>> 1 | this.hi << 31) ^ mask) >>> 0;\n this.hi = ( this.hi >>> 1 ^ mask) >>> 0;\n return this;\n};\n\n/**\n * Calculates the length of this longbits when encoded as a varint.\n * @returns {number} Length\n */\nLongBits.prototype.length = function length() {\n var part0 = this.lo,\n part1 = (this.lo >>> 28 | this.hi << 4) >>> 0,\n part2 = this.hi >>> 24;\n return part2 === 0\n ? part1 === 0\n ? part0 < 16384\n ? part0 < 128 ? 1 : 2\n : part0 < 2097152 ? 3 : 4\n : part1 < 16384\n ? part1 < 128 ? 5 : 6\n : part1 < 2097152 ? 7 : 8\n : part2 < 128 ? 9 : 10;\n};\n","\"use strict\";\nvar util = exports;\n\n// used to return a Promise where callback is omitted\nutil.asPromise = require(1);\n\n// converts to / from base64 encoded strings\nutil.base64 = require(2);\n\n// base class of rpc.Service\nutil.EventEmitter = require(4);\n\n// float handling accross browsers\nutil.float = require(6);\n\n// requires modules optionally and hides the call from bundlers\nutil.inquire = require(7);\n\n// converts to / from utf8 encoded strings\nutil.utf8 = require(10);\n\n// provides a node-like buffer pool in the browser\nutil.pool = require(9);\n\n// utility to work with the low and high bits of a 64 bit value\nutil.LongBits = require(34);\n\n/**\n * Whether running within node or not.\n * @memberof util\n * @type {boolean}\n */\nutil.isNode = Boolean(typeof global !== \"undefined\"\n && global\n && global.process\n && global.process.versions\n && global.process.versions.node);\n\n/**\n * Global object reference.\n * @memberof util\n * @type {Object}\n */\nutil.global = util.isNode && global\n || typeof window !== \"undefined\" && window\n || typeof self !== \"undefined\" && self\n || this; // eslint-disable-line no-invalid-this\n\n/**\n * An immuable empty array.\n * @memberof util\n * @type {Array.<*>}\n * @const\n */\nutil.emptyArray = Object.freeze ? Object.freeze([]) : /* istanbul ignore next */ []; // used on prototypes\n\n/**\n * An immutable empty object.\n * @type {Object}\n * @const\n */\nutil.emptyObject = Object.freeze ? Object.freeze({}) : /* istanbul ignore next */ {}; // used on prototypes\n\n/**\n * Tests if the specified value is an integer.\n * @function\n * @param {*} value Value to test\n * @returns {boolean} `true` if the value is an integer\n */\nutil.isInteger = Number.isInteger || /* istanbul ignore next */ function isInteger(value) {\n return typeof value === \"number\" && isFinite(value) && Math.floor(value) === value;\n};\n\n/**\n * Tests if the specified value is a string.\n * @param {*} value Value to test\n * @returns {boolean} `true` if the value is a string\n */\nutil.isString = function isString(value) {\n return typeof value === \"string\" || value instanceof String;\n};\n\n/**\n * Tests if the specified value is a non-null object.\n * @param {*} value Value to test\n * @returns {boolean} `true` if the value is a non-null object\n */\nutil.isObject = function isObject(value) {\n return value && typeof value === \"object\";\n};\n\n/**\n * Checks if a property on a message is considered to be present.\n * This is an alias of {@link util.isSet}.\n * @function\n * @param {Object} obj Plain object or message instance\n * @param {string} prop Property name\n * @returns {boolean} `true` if considered to be present, otherwise `false`\n */\nutil.isset =\n\n/**\n * Checks if a property on a message is considered to be present.\n * @param {Object} obj Plain object or message instance\n * @param {string} prop Property name\n * @returns {boolean} `true` if considered to be present, otherwise `false`\n */\nutil.isSet = function isSet(obj, prop) {\n var value = obj[prop];\n if (value != null && obj.hasOwnProperty(prop)) // eslint-disable-line eqeqeq, no-prototype-builtins\n return typeof value !== \"object\" || (Array.isArray(value) ? value.length : Object.keys(value).length) > 0;\n return false;\n};\n\n/**\n * Any compatible Buffer instance.\n * This is a minimal stand-alone definition of a Buffer instance. The actual type is that exported by node's typings.\n * @interface Buffer\n * @extends Uint8Array\n */\n\n/**\n * Node's Buffer class if available.\n * @type {Constructor}\n */\nutil.Buffer = (function() {\n try {\n var Buffer = util.inquire(\"buffer\").Buffer;\n // refuse to use non-node buffers if not explicitly assigned (perf reasons):\n return Buffer.prototype.utf8Write ? Buffer : /* istanbul ignore next */ null;\n } catch (e) {\n /* istanbul ignore next */\n return null;\n }\n})();\n\n// Internal alias of or polyfull for Buffer.from.\nutil._Buffer_from = null;\n\n// Internal alias of or polyfill for Buffer.allocUnsafe.\nutil._Buffer_allocUnsafe = null;\n\n/**\n * Creates a new buffer of whatever type supported by the environment.\n * @param {number|number[]} [sizeOrArray=0] Buffer size or number array\n * @returns {Uint8Array|Buffer} Buffer\n */\nutil.newBuffer = function newBuffer(sizeOrArray) {\n /* istanbul ignore next */\n return typeof sizeOrArray === \"number\"\n ? util.Buffer\n ? util._Buffer_allocUnsafe(sizeOrArray)\n : new util.Array(sizeOrArray)\n : util.Buffer\n ? util._Buffer_from(sizeOrArray)\n : typeof Uint8Array === \"undefined\"\n ? sizeOrArray\n : new Uint8Array(sizeOrArray);\n};\n\n/**\n * Array implementation used in the browser. `Uint8Array` if supported, otherwise `Array`.\n * @type {Constructor}\n */\nutil.Array = typeof Uint8Array !== \"undefined\" ? Uint8Array /* istanbul ignore next */ : Array;\n\n/**\n * Any compatible Long instance.\n * This is a minimal stand-alone definition of a Long instance. The actual type is that exported by long.js.\n * @interface Long\n * @property {number} low Low bits\n * @property {number} high High bits\n * @property {boolean} unsigned Whether unsigned or not\n */\n\n/**\n * Long.js's Long class if available.\n * @type {Constructor}\n */\nutil.Long = /* istanbul ignore next */ util.global.dcodeIO && /* istanbul ignore next */ util.global.dcodeIO.Long\n || /* istanbul ignore next */ util.global.Long\n || util.inquire(\"long\");\n\n/**\n * Regular expression used to verify 2 bit (`bool`) map keys.\n * @type {RegExp}\n * @const\n */\nutil.key2Re = /^true|false|0|1$/;\n\n/**\n * Regular expression used to verify 32 bit (`int32` etc.) map keys.\n * @type {RegExp}\n * @const\n */\nutil.key32Re = /^-?(?:0|[1-9][0-9]*)$/;\n\n/**\n * Regular expression used to verify 64 bit (`int64` etc.) map keys.\n * @type {RegExp}\n * @const\n */\nutil.key64Re = /^(?:[\\\\x00-\\\\xff]{8}|-?(?:0|[1-9][0-9]*))$/;\n\n/**\n * Converts a number or long to an 8 characters long hash string.\n * @param {Long|number} value Value to convert\n * @returns {string} Hash\n */\nutil.longToHash = function longToHash(value) {\n return value\n ? util.LongBits.from(value).toHash()\n : util.LongBits.zeroHash;\n};\n\n/**\n * Converts an 8 characters long hash string to a long or number.\n * @param {string} hash Hash\n * @param {boolean} [unsigned=false] Whether unsigned or not\n * @returns {Long|number} Original value\n */\nutil.longFromHash = function longFromHash(hash, unsigned) {\n var bits = util.LongBits.fromHash(hash);\n if (util.Long)\n return util.Long.fromBits(bits.lo, bits.hi, unsigned);\n return bits.toNumber(Boolean(unsigned));\n};\n\n/**\n * Merges the properties of the source object into the destination object.\n * @memberof util\n * @param {Object.} dst Destination object\n * @param {Object.} src Source object\n * @param {boolean} [ifNotSet=false] Merges only if the key is not already set\n * @returns {Object.} Destination object\n */\nfunction merge(dst, src, ifNotSet) { // used by converters\n for (var keys = Object.keys(src), i = 0; i < keys.length; ++i)\n if (dst[keys[i]] === undefined || !ifNotSet)\n dst[keys[i]] = src[keys[i]];\n return dst;\n}\n\nutil.merge = merge;\n\n/**\n * Converts the first character of a string to lower case.\n * @param {string} str String to convert\n * @returns {string} Converted string\n */\nutil.lcFirst = function lcFirst(str) {\n return str.charAt(0).toLowerCase() + str.substring(1);\n};\n\n/**\n * Creates a custom error constructor.\n * @memberof util\n * @param {string} name Error name\n * @returns {Constructor} Custom error constructor\n */\nfunction newError(name) {\n\n function CustomError(message, properties) {\n\n if (!(this instanceof CustomError))\n return new CustomError(message, properties);\n\n // Error.call(this, message);\n // ^ just returns a new error instance because the ctor can be called as a function\n\n Object.defineProperty(this, \"message\", { get: function() { return message; } });\n\n /* istanbul ignore next */\n if (Error.captureStackTrace) // node\n Error.captureStackTrace(this, CustomError);\n else\n Object.defineProperty(this, \"stack\", { value: new Error().stack || \"\" });\n\n if (properties)\n merge(this, properties);\n }\n\n CustomError.prototype = Object.create(Error.prototype, {\n constructor: {\n value: CustomError,\n writable: true,\n enumerable: false,\n configurable: true,\n },\n name: {\n get: function get() { return name; },\n set: undefined,\n enumerable: false,\n // configurable: false would accurately preserve the behavior of\n // the original, but I'm guessing that was not intentional.\n // For an actual error subclass, this property would\n // be configurable.\n configurable: true,\n },\n toString: {\n value: function value() { return this.name + \": \" + this.message; },\n writable: true,\n enumerable: false,\n configurable: true,\n },\n });\n\n return CustomError;\n}\n\nutil.newError = newError;\n\n/**\n * Constructs a new protocol error.\n * @classdesc Error subclass indicating a protocol specifc error.\n * @memberof util\n * @extends Error\n * @template T extends Message\n * @constructor\n * @param {string} message Error message\n * @param {Object.} [properties] Additional properties\n * @example\n * try {\n * MyMessage.decode(someBuffer); // throws if required fields are missing\n * } catch (e) {\n * if (e instanceof ProtocolError && e.instance)\n * console.log(\"decoded so far: \" + JSON.stringify(e.instance));\n * }\n */\nutil.ProtocolError = newError(\"ProtocolError\");\n\n/**\n * So far decoded message instance.\n * @name util.ProtocolError#instance\n * @type {Message}\n */\n\n/**\n * A OneOf getter as returned by {@link util.oneOfGetter}.\n * @typedef OneOfGetter\n * @type {function}\n * @returns {string|undefined} Set field name, if any\n */\n\n/**\n * Builds a getter for a oneof's present field name.\n * @param {string[]} fieldNames Field names\n * @returns {OneOfGetter} Unbound getter\n */\nutil.oneOfGetter = function getOneOf(fieldNames) {\n var fieldMap = {};\n for (var i = 0; i < fieldNames.length; ++i)\n fieldMap[fieldNames[i]] = 1;\n\n /**\n * @returns {string|undefined} Set field name, if any\n * @this Object\n * @ignore\n */\n return function() { // eslint-disable-line consistent-return\n for (var keys = Object.keys(this), i = keys.length - 1; i > -1; --i)\n if (fieldMap[keys[i]] === 1 && this[keys[i]] !== undefined && this[keys[i]] !== null)\n return keys[i];\n };\n};\n\n/**\n * A OneOf setter as returned by {@link util.oneOfSetter}.\n * @typedef OneOfSetter\n * @type {function}\n * @param {string|undefined} value Field name\n * @returns {undefined}\n */\n\n/**\n * Builds a setter for a oneof's present field name.\n * @param {string[]} fieldNames Field names\n * @returns {OneOfSetter} Unbound setter\n */\nutil.oneOfSetter = function setOneOf(fieldNames) {\n\n /**\n * @param {string} name Field name\n * @returns {undefined}\n * @this Object\n * @ignore\n */\n return function(name) {\n for (var i = 0; i < fieldNames.length; ++i)\n if (fieldNames[i] !== name)\n delete this[fieldNames[i]];\n };\n};\n\n/**\n * Default conversion options used for {@link Message#toJSON} implementations.\n *\n * These options are close to proto3's JSON mapping with the exception that internal types like Any are handled just like messages. More precisely:\n *\n * - Longs become strings\n * - Enums become string keys\n * - Bytes become base64 encoded strings\n * - (Sub-)Messages become plain objects\n * - Maps become plain objects with all string keys\n * - Repeated fields become arrays\n * - NaN and Infinity for float and double fields become strings\n *\n * @type {IConversionOptions}\n * @see https://developers.google.com/protocol-buffers/docs/proto3?hl=en#json\n */\nutil.toJSONOptions = {\n longs: String,\n enums: String,\n bytes: String,\n json: true\n};\n\n// Sets up buffer utility according to the environment (called in index-minimal)\nutil._configure = function() {\n var Buffer = util.Buffer;\n /* istanbul ignore if */\n if (!Buffer) {\n util._Buffer_from = util._Buffer_allocUnsafe = null;\n return;\n }\n // because node 4.x buffers are incompatible & immutable\n // see: https://github.com/dcodeIO/protobuf.js/pull/665\n util._Buffer_from = Buffer.from !== Uint8Array.from && Buffer.from ||\n /* istanbul ignore next */\n function Buffer_from(value, encoding) {\n return new Buffer(value, encoding);\n };\n util._Buffer_allocUnsafe = Buffer.allocUnsafe ||\n /* istanbul ignore next */\n function Buffer_allocUnsafe(size) {\n return new Buffer(size);\n };\n};\n","\"use strict\";\nmodule.exports = verifier;\n\nvar Enum = require(14),\n util = require(33);\n\nfunction invalid(field, expected) {\n return field.name + \": \" + expected + (field.repeated && expected !== \"array\" ? \"[]\" : field.map && expected !== \"object\" ? \"{k:\"+field.keyType+\"}\" : \"\") + \" expected\";\n}\n\n/**\n * Generates a partial value verifier.\n * @param {Codegen} gen Codegen instance\n * @param {Field} field Reflected field\n * @param {number} fieldIndex Field index\n * @param {string} ref Variable reference\n * @returns {Codegen} Codegen instance\n * @ignore\n */\nfunction genVerifyValue(gen, field, fieldIndex, ref) {\n /* eslint-disable no-unexpected-multiline */\n if (field.resolvedType) {\n if (field.resolvedType instanceof Enum) { gen\n (\"switch(%s){\", ref)\n (\"default:\")\n (\"return%j\", invalid(field, \"enum value\"));\n for (var keys = Object.keys(field.resolvedType.values), j = 0; j < keys.length; ++j) gen\n (\"case %i:\", field.resolvedType.values[keys[j]]);\n gen\n (\"break\")\n (\"}\");\n } else {\n gen\n (\"{\")\n (\"var e=types[%i].verify(%s);\", fieldIndex, ref)\n (\"if(e)\")\n (\"return%j+e\", field.name + \".\")\n (\"}\");\n }\n } else {\n switch (field.type) {\n case \"int32\":\n case \"uint32\":\n case \"sint32\":\n case \"fixed32\":\n case \"sfixed32\": gen\n (\"if(!util.isInteger(%s))\", ref)\n (\"return%j\", invalid(field, \"integer\"));\n break;\n case \"int64\":\n case \"uint64\":\n case \"sint64\":\n case \"fixed64\":\n case \"sfixed64\": gen\n (\"if(!util.isInteger(%s)&&!(%s&&util.isInteger(%s.low)&&util.isInteger(%s.high)))\", ref, ref, ref, ref)\n (\"return%j\", invalid(field, \"integer|Long\"));\n break;\n case \"float\":\n case \"double\": gen\n (\"if(typeof %s!==\\\"number\\\")\", ref)\n (\"return%j\", invalid(field, \"number\"));\n break;\n case \"bool\": gen\n (\"if(typeof %s!==\\\"boolean\\\")\", ref)\n (\"return%j\", invalid(field, \"boolean\"));\n break;\n case \"string\": gen\n (\"if(!util.isString(%s))\", ref)\n (\"return%j\", invalid(field, \"string\"));\n break;\n case \"bytes\": gen\n (\"if(!(%s&&typeof %s.length===\\\"number\\\"||util.isString(%s)))\", ref, ref, ref)\n (\"return%j\", invalid(field, \"buffer\"));\n break;\n }\n }\n return gen;\n /* eslint-enable no-unexpected-multiline */\n}\n\n/**\n * Generates a partial key verifier.\n * @param {Codegen} gen Codegen instance\n * @param {Field} field Reflected field\n * @param {string} ref Variable reference\n * @returns {Codegen} Codegen instance\n * @ignore\n */\nfunction genVerifyKey(gen, field, ref) {\n /* eslint-disable no-unexpected-multiline */\n switch (field.keyType) {\n case \"int32\":\n case \"uint32\":\n case \"sint32\":\n case \"fixed32\":\n case \"sfixed32\": gen\n (\"if(!util.key32Re.test(%s))\", ref)\n (\"return%j\", invalid(field, \"integer key\"));\n break;\n case \"int64\":\n case \"uint64\":\n case \"sint64\":\n case \"fixed64\":\n case \"sfixed64\": gen\n (\"if(!util.key64Re.test(%s))\", ref) // see comment above: x is ok, d is not\n (\"return%j\", invalid(field, \"integer|Long key\"));\n break;\n case \"bool\": gen\n (\"if(!util.key2Re.test(%s))\", ref)\n (\"return%j\", invalid(field, \"boolean key\"));\n break;\n }\n return gen;\n /* eslint-enable no-unexpected-multiline */\n}\n\n/**\n * Generates a verifier specific to the specified message type.\n * @param {Type} mtype Message type\n * @returns {Codegen} Codegen instance\n */\nfunction verifier(mtype) {\n /* eslint-disable no-unexpected-multiline */\n\n var gen = util.codegen([\"m\"], mtype.name + \"$verify\")\n (\"if(typeof m!==\\\"object\\\"||m===null)\")\n (\"return%j\", \"object expected\");\n var oneofs = mtype.oneofsArray,\n seenFirstField = {};\n if (oneofs.length) gen\n (\"var p={}\");\n\n for (var i = 0; i < /* initializes */ mtype.fieldsArray.length; ++i) {\n var field = mtype._fieldsArray[i].resolve(),\n ref = \"m\" + util.safeProp(field.name);\n\n if (field.optional) gen\n (\"if(%s!=null&&m.hasOwnProperty(%j)){\", ref, field.name); // !== undefined && !== null\n\n // map fields\n if (field.map) { gen\n (\"if(!util.isObject(%s))\", ref)\n (\"return%j\", invalid(field, \"object\"))\n (\"var k=Object.keys(%s)\", ref)\n (\"for(var i=0;i}\n * @const\n */\nvar wrappers = exports;\n\nvar Message = require(19);\n\n/**\n * From object converter part of an {@link IWrapper}.\n * @typedef WrapperFromObjectConverter\n * @type {function}\n * @param {Object.} object Plain object\n * @returns {Message<{}>} Message instance\n * @this Type\n */\n\n/**\n * To object converter part of an {@link IWrapper}.\n * @typedef WrapperToObjectConverter\n * @type {function}\n * @param {Message<{}>} message Message instance\n * @param {IConversionOptions} [options] Conversion options\n * @returns {Object.} Plain object\n * @this Type\n */\n\n/**\n * Common type wrapper part of {@link wrappers}.\n * @interface IWrapper\n * @property {WrapperFromObjectConverter} [fromObject] From object converter\n * @property {WrapperToObjectConverter} [toObject] To object converter\n */\n\n// Custom wrapper for Any\nwrappers[\".google.protobuf.Any\"] = {\n\n fromObject: function(object) {\n\n // unwrap value type if mapped\n if (object && object[\"@type\"]) {\n // Only use fully qualified type name after the last '/'\n var name = object[\"@type\"].substring(object[\"@type\"].lastIndexOf(\"/\") + 1);\n var type = this.lookup(name);\n /* istanbul ignore else */\n if (type) {\n // type_url does not accept leading \".\"\n var type_url = object[\"@type\"].charAt(0) === \".\" ?\n object[\"@type\"].slice(1) : object[\"@type\"];\n // type_url prefix is optional, but path seperator is required\n if (type_url.indexOf(\"/\") === -1) {\n type_url = \"/\" + type_url;\n }\n return this.create({\n type_url: type_url,\n value: type.encode(type.fromObject(object)).finish()\n });\n }\n }\n\n return this.fromObject(object);\n },\n\n toObject: function(message, options) {\n\n // Default prefix\n var googleApi = \"type.googleapis.com/\";\n var prefix = \"\";\n var name = \"\";\n\n // decode value if requested and unmapped\n if (options && options.json && message.type_url && message.value) {\n // Only use fully qualified type name after the last '/'\n name = message.type_url.substring(message.type_url.lastIndexOf(\"/\") + 1);\n // Separate the prefix used\n prefix = message.type_url.substring(0, message.type_url.lastIndexOf(\"/\") + 1);\n var type = this.lookup(name);\n /* istanbul ignore else */\n if (type)\n message = type.decode(message.value);\n }\n\n // wrap value if unmapped\n if (!(message instanceof this.ctor) && message instanceof Message) {\n var object = message.$type.toObject(message, options);\n var messageName = message.$type.fullName[0] === \".\" ?\n message.$type.fullName.slice(1) : message.$type.fullName;\n // Default to type.googleapis.com prefix if no prefix is used\n if (prefix === \"\") {\n prefix = googleApi;\n }\n name = prefix + messageName;\n object[\"@type\"] = name;\n return object;\n }\n\n return this.toObject(message, options);\n }\n};\n","\"use strict\";\nmodule.exports = Writer;\n\nvar util = require(35);\n\nvar BufferWriter; // cyclic\n\nvar LongBits = util.LongBits,\n base64 = util.base64,\n utf8 = util.utf8;\n\n/**\n * Constructs a new writer operation instance.\n * @classdesc Scheduled writer operation.\n * @constructor\n * @param {function(*, Uint8Array, number)} fn Function to call\n * @param {number} len Value byte length\n * @param {*} val Value to write\n * @ignore\n */\nfunction Op(fn, len, val) {\n\n /**\n * Function to call.\n * @type {function(Uint8Array, number, *)}\n */\n this.fn = fn;\n\n /**\n * Value byte length.\n * @type {number}\n */\n this.len = len;\n\n /**\n * Next operation.\n * @type {Writer.Op|undefined}\n */\n this.next = undefined;\n\n /**\n * Value to write.\n * @type {*}\n */\n this.val = val; // type varies\n}\n\n/* istanbul ignore next */\nfunction noop() {} // eslint-disable-line no-empty-function\n\n/**\n * Constructs a new writer state instance.\n * @classdesc Copied writer state.\n * @memberof Writer\n * @constructor\n * @param {Writer} writer Writer to copy state from\n * @ignore\n */\nfunction State(writer) {\n\n /**\n * Current head.\n * @type {Writer.Op}\n */\n this.head = writer.head;\n\n /**\n * Current tail.\n * @type {Writer.Op}\n */\n this.tail = writer.tail;\n\n /**\n * Current buffer length.\n * @type {number}\n */\n this.len = writer.len;\n\n /**\n * Next state.\n * @type {State|null}\n */\n this.next = writer.states;\n}\n\n/**\n * Constructs a new writer instance.\n * @classdesc Wire format writer using `Uint8Array` if available, otherwise `Array`.\n * @constructor\n */\nfunction Writer() {\n\n /**\n * Current length.\n * @type {number}\n */\n this.len = 0;\n\n /**\n * Operations head.\n * @type {Object}\n */\n this.head = new Op(noop, 0, 0);\n\n /**\n * Operations tail\n * @type {Object}\n */\n this.tail = this.head;\n\n /**\n * Linked forked states.\n * @type {Object|null}\n */\n this.states = null;\n\n // When a value is written, the writer calculates its byte length and puts it into a linked\n // list of operations to perform when finish() is called. This both allows us to allocate\n // buffers of the exact required size and reduces the amount of work we have to do compared\n // to first calculating over objects and then encoding over objects. In our case, the encoding\n // part is just a linked list walk calling operations with already prepared values.\n}\n\nvar create = function create() {\n return util.Buffer\n ? function create_buffer_setup() {\n return (Writer.create = function create_buffer() {\n return new BufferWriter();\n })();\n }\n /* istanbul ignore next */\n : function create_array() {\n return new Writer();\n };\n};\n\n/**\n * Creates a new writer.\n * @function\n * @returns {BufferWriter|Writer} A {@link BufferWriter} when Buffers are supported, otherwise a {@link Writer}\n */\nWriter.create = create();\n\n/**\n * Allocates a buffer of the specified size.\n * @param {number} size Buffer size\n * @returns {Uint8Array} Buffer\n */\nWriter.alloc = function alloc(size) {\n return new util.Array(size);\n};\n\n// Use Uint8Array buffer pool in the browser, just like node does with buffers\n/* istanbul ignore else */\nif (util.Array !== Array)\n Writer.alloc = util.pool(Writer.alloc, util.Array.prototype.subarray);\n\n/**\n * Pushes a new operation to the queue.\n * @param {function(Uint8Array, number, *)} fn Function to call\n * @param {number} len Value byte length\n * @param {number} val Value to write\n * @returns {Writer} `this`\n * @private\n */\nWriter.prototype._push = function push(fn, len, val) {\n this.tail = this.tail.next = new Op(fn, len, val);\n this.len += len;\n return this;\n};\n\nfunction writeByte(val, buf, pos) {\n buf[pos] = val & 255;\n}\n\nfunction writeVarint32(val, buf, pos) {\n while (val > 127) {\n buf[pos++] = val & 127 | 128;\n val >>>= 7;\n }\n buf[pos] = val;\n}\n\n/**\n * Constructs a new varint writer operation instance.\n * @classdesc Scheduled varint writer operation.\n * @extends Op\n * @constructor\n * @param {number} len Value byte length\n * @param {number} val Value to write\n * @ignore\n */\nfunction VarintOp(len, val) {\n this.len = len;\n this.next = undefined;\n this.val = val;\n}\n\nVarintOp.prototype = Object.create(Op.prototype);\nVarintOp.prototype.fn = writeVarint32;\n\n/**\n * Writes an unsigned 32 bit value as a varint.\n * @param {number} value Value to write\n * @returns {Writer} `this`\n */\nWriter.prototype.uint32 = function write_uint32(value) {\n // here, the call to this.push has been inlined and a varint specific Op subclass is used.\n // uint32 is by far the most frequently used operation and benefits significantly from this.\n this.len += (this.tail = this.tail.next = new VarintOp(\n (value = value >>> 0)\n < 128 ? 1\n : value < 16384 ? 2\n : value < 2097152 ? 3\n : value < 268435456 ? 4\n : 5,\n value)).len;\n return this;\n};\n\n/**\n * Writes a signed 32 bit value as a varint.\n * @function\n * @param {number} value Value to write\n * @returns {Writer} `this`\n */\nWriter.prototype.int32 = function write_int32(value) {\n return value < 0\n ? this._push(writeVarint64, 10, LongBits.fromNumber(value)) // 10 bytes per spec\n : this.uint32(value);\n};\n\n/**\n * Writes a 32 bit value as a varint, zig-zag encoded.\n * @param {number} value Value to write\n * @returns {Writer} `this`\n */\nWriter.prototype.sint32 = function write_sint32(value) {\n return this.uint32((value << 1 ^ value >> 31) >>> 0);\n};\n\nfunction writeVarint64(val, buf, pos) {\n while (val.hi) {\n buf[pos++] = val.lo & 127 | 128;\n val.lo = (val.lo >>> 7 | val.hi << 25) >>> 0;\n val.hi >>>= 7;\n }\n while (val.lo > 127) {\n buf[pos++] = val.lo & 127 | 128;\n val.lo = val.lo >>> 7;\n }\n buf[pos++] = val.lo;\n}\n\n/**\n * Writes an unsigned 64 bit value as a varint.\n * @param {Long|number|string} value Value to write\n * @returns {Writer} `this`\n * @throws {TypeError} If `value` is a string and no long library is present.\n */\nWriter.prototype.uint64 = function write_uint64(value) {\n var bits = LongBits.from(value);\n return this._push(writeVarint64, bits.length(), bits);\n};\n\n/**\n * Writes a signed 64 bit value as a varint.\n * @function\n * @param {Long|number|string} value Value to write\n * @returns {Writer} `this`\n * @throws {TypeError} If `value` is a string and no long library is present.\n */\nWriter.prototype.int64 = Writer.prototype.uint64;\n\n/**\n * Writes a signed 64 bit value as a varint, zig-zag encoded.\n * @param {Long|number|string} value Value to write\n * @returns {Writer} `this`\n * @throws {TypeError} If `value` is a string and no long library is present.\n */\nWriter.prototype.sint64 = function write_sint64(value) {\n var bits = LongBits.from(value).zzEncode();\n return this._push(writeVarint64, bits.length(), bits);\n};\n\n/**\n * Writes a boolish value as a varint.\n * @param {boolean} value Value to write\n * @returns {Writer} `this`\n */\nWriter.prototype.bool = function write_bool(value) {\n return this._push(writeByte, 1, value ? 1 : 0);\n};\n\nfunction writeFixed32(val, buf, pos) {\n buf[pos ] = val & 255;\n buf[pos + 1] = val >>> 8 & 255;\n buf[pos + 2] = val >>> 16 & 255;\n buf[pos + 3] = val >>> 24;\n}\n\n/**\n * Writes an unsigned 32 bit value as fixed 32 bits.\n * @param {number} value Value to write\n * @returns {Writer} `this`\n */\nWriter.prototype.fixed32 = function write_fixed32(value) {\n return this._push(writeFixed32, 4, value >>> 0);\n};\n\n/**\n * Writes a signed 32 bit value as fixed 32 bits.\n * @function\n * @param {number} value Value to write\n * @returns {Writer} `this`\n */\nWriter.prototype.sfixed32 = Writer.prototype.fixed32;\n\n/**\n * Writes an unsigned 64 bit value as fixed 64 bits.\n * @param {Long|number|string} value Value to write\n * @returns {Writer} `this`\n * @throws {TypeError} If `value` is a string and no long library is present.\n */\nWriter.prototype.fixed64 = function write_fixed64(value) {\n var bits = LongBits.from(value);\n return this._push(writeFixed32, 4, bits.lo)._push(writeFixed32, 4, bits.hi);\n};\n\n/**\n * Writes a signed 64 bit value as fixed 64 bits.\n * @function\n * @param {Long|number|string} value Value to write\n * @returns {Writer} `this`\n * @throws {TypeError} If `value` is a string and no long library is present.\n */\nWriter.prototype.sfixed64 = Writer.prototype.fixed64;\n\n/**\n * Writes a float (32 bit).\n * @function\n * @param {number} value Value to write\n * @returns {Writer} `this`\n */\nWriter.prototype.float = function write_float(value) {\n return this._push(util.float.writeFloatLE, 4, value);\n};\n\n/**\n * Writes a double (64 bit float).\n * @function\n * @param {number} value Value to write\n * @returns {Writer} `this`\n */\nWriter.prototype.double = function write_double(value) {\n return this._push(util.float.writeDoubleLE, 8, value);\n};\n\nvar writeBytes = util.Array.prototype.set\n ? function writeBytes_set(val, buf, pos) {\n buf.set(val, pos); // also works for plain array values\n }\n /* istanbul ignore next */\n : function writeBytes_for(val, buf, pos) {\n for (var i = 0; i < val.length; ++i)\n buf[pos + i] = val[i];\n };\n\n/**\n * Writes a sequence of bytes.\n * @param {Uint8Array|string} value Buffer or base64 encoded string to write\n * @returns {Writer} `this`\n */\nWriter.prototype.bytes = function write_bytes(value) {\n var len = value.length >>> 0;\n if (!len)\n return this._push(writeByte, 1, 0);\n if (util.isString(value)) {\n var buf = Writer.alloc(len = base64.length(value));\n base64.decode(value, buf, 0);\n value = buf;\n }\n return this.uint32(len)._push(writeBytes, len, value);\n};\n\n/**\n * Writes a string.\n * @param {string} value Value to write\n * @returns {Writer} `this`\n */\nWriter.prototype.string = function write_string(value) {\n var len = utf8.length(value);\n return len\n ? this.uint32(len)._push(utf8.write, len, value)\n : this._push(writeByte, 1, 0);\n};\n\n/**\n * Forks this writer's state by pushing it to a stack.\n * Calling {@link Writer#reset|reset} or {@link Writer#ldelim|ldelim} resets the writer to the previous state.\n * @returns {Writer} `this`\n */\nWriter.prototype.fork = function fork() {\n this.states = new State(this);\n this.head = this.tail = new Op(noop, 0, 0);\n this.len = 0;\n return this;\n};\n\n/**\n * Resets this instance to the last state.\n * @returns {Writer} `this`\n */\nWriter.prototype.reset = function reset() {\n if (this.states) {\n this.head = this.states.head;\n this.tail = this.states.tail;\n this.len = this.states.len;\n this.states = this.states.next;\n } else {\n this.head = this.tail = new Op(noop, 0, 0);\n this.len = 0;\n }\n return this;\n};\n\n/**\n * Resets to the last state and appends the fork state's current write length as a varint followed by its operations.\n * @returns {Writer} `this`\n */\nWriter.prototype.ldelim = function ldelim() {\n var head = this.head,\n tail = this.tail,\n len = this.len;\n this.reset().uint32(len);\n if (len) {\n this.tail.next = head.next; // skip noop\n this.tail = tail;\n this.len += len;\n }\n return this;\n};\n\n/**\n * Finishes the write operation.\n * @returns {Uint8Array} Finished buffer\n */\nWriter.prototype.finish = function finish() {\n var head = this.head.next, // skip noop\n buf = this.constructor.alloc(this.len),\n pos = 0;\n while (head) {\n head.fn(head.val, buf, pos);\n pos += head.len;\n head = head.next;\n }\n // this.head = this.tail = null;\n return buf;\n};\n\nWriter._configure = function(BufferWriter_) {\n BufferWriter = BufferWriter_;\n Writer.create = create();\n BufferWriter._configure();\n};\n","\"use strict\";\nmodule.exports = BufferWriter;\n\n// extends Writer\nvar Writer = require(38);\n(BufferWriter.prototype = Object.create(Writer.prototype)).constructor = BufferWriter;\n\nvar util = require(35);\n\n/**\n * Constructs a new buffer writer instance.\n * @classdesc Wire format writer using node buffers.\n * @extends Writer\n * @constructor\n */\nfunction BufferWriter() {\n Writer.call(this);\n}\n\nBufferWriter._configure = function () {\n /**\n * Allocates a buffer of the specified size.\n * @function\n * @param {number} size Buffer size\n * @returns {Buffer} Buffer\n */\n BufferWriter.alloc = util._Buffer_allocUnsafe;\n\n BufferWriter.writeBytesBuffer = util.Buffer && util.Buffer.prototype instanceof Uint8Array && util.Buffer.prototype.set.name === \"set\"\n ? function writeBytesBuffer_set(val, buf, pos) {\n buf.set(val, pos); // faster than copy (requires node >= 4 where Buffers extend Uint8Array and set is properly inherited)\n // also works for plain array values\n }\n /* istanbul ignore next */\n : function writeBytesBuffer_copy(val, buf, pos) {\n if (val.copy) // Buffer values\n val.copy(buf, pos, 0, val.length);\n else for (var i = 0; i < val.length;) // plain array values\n buf[pos++] = val[i++];\n };\n};\n\n\n/**\n * @override\n */\nBufferWriter.prototype.bytes = function write_bytes_buffer(value) {\n if (util.isString(value))\n value = util._Buffer_from(value, \"base64\");\n var len = value.length >>> 0;\n this.uint32(len);\n if (len)\n this._push(BufferWriter.writeBytesBuffer, len, value);\n return this;\n};\n\nfunction writeStringBuffer(val, buf, pos) {\n if (val.length < 40) // plain js is faster for short strings (probably due to redundant assertions)\n util.utf8.write(val, buf, pos);\n else if (buf.utf8Write)\n buf.utf8Write(val, pos);\n else\n buf.write(val, pos);\n}\n\n/**\n * @override\n */\nBufferWriter.prototype.string = function write_string_buffer(value) {\n var len = util.Buffer.byteLength(value);\n this.uint32(len);\n if (len)\n this._push(writeStringBuffer, len, value);\n return this;\n};\n\n\n/**\n * Finishes the write operation.\n * @name BufferWriter#finish\n * @function\n * @returns {Buffer} Finished buffer\n */\n\nBufferWriter._configure();\n"],"sourceRoot":"."} \ No newline at end of file diff --git a/node_modules/protobufjs/dist/minimal/protobuf.js b/node_modules/protobufjs/dist/minimal/protobuf.js new file mode 100644 index 0000000..dbcc1d3 --- /dev/null +++ b/node_modules/protobufjs/dist/minimal/protobuf.js @@ -0,0 +1,2736 @@ +/*! + * protobuf.js v7.3.0 (c) 2016, daniel wirtz + * compiled fri, 10 may 2024 03:38:34 utc + * licensed under the bsd-3-clause license + * see: https://github.com/dcodeio/protobuf.js for details + */ +(function(undefined){"use strict";(function prelude(modules, cache, entries) { + + // This is the prelude used to bundle protobuf.js for the browser. Wraps up the CommonJS + // sources through a conflict-free require shim and is again wrapped within an iife that + // provides a minification-friendly `undefined` var plus a global "use strict" directive + // so that minification can remove the directives of each module. + + function $require(name) { + var $module = cache[name]; + if (!$module) + modules[name][0].call($module = cache[name] = { exports: {} }, $require, $module, $module.exports); + return $module.exports; + } + + var protobuf = $require(entries[0]); + + // Expose globally + protobuf.util.global.protobuf = protobuf; + + // Be nice to AMD + if (typeof define === "function" && define.amd) + define(["long"], function(Long) { + if (Long && Long.isLong) { + protobuf.util.Long = Long; + protobuf.configure(); + } + return protobuf; + }); + + // Be nice to CommonJS + if (typeof module === "object" && module && module.exports) + module.exports = protobuf; + +})/* end of prelude */({1:[function(require,module,exports){ +"use strict"; +module.exports = asPromise; + +/** + * Callback as used by {@link util.asPromise}. + * @typedef asPromiseCallback + * @type {function} + * @param {Error|null} error Error, if any + * @param {...*} params Additional arguments + * @returns {undefined} + */ + +/** + * Returns a promise from a node-style callback function. + * @memberof util + * @param {asPromiseCallback} fn Function to call + * @param {*} ctx Function context + * @param {...*} params Function arguments + * @returns {Promise<*>} Promisified function + */ +function asPromise(fn, ctx/*, varargs */) { + var params = new Array(arguments.length - 1), + offset = 0, + index = 2, + pending = true; + while (index < arguments.length) + params[offset++] = arguments[index++]; + return new Promise(function executor(resolve, reject) { + params[offset] = function callback(err/*, varargs */) { + if (pending) { + pending = false; + if (err) + reject(err); + else { + var params = new Array(arguments.length - 1), + offset = 0; + while (offset < params.length) + params[offset++] = arguments[offset]; + resolve.apply(null, params); + } + } + }; + try { + fn.apply(ctx || null, params); + } catch (err) { + if (pending) { + pending = false; + reject(err); + } + } + }); +} + +},{}],2:[function(require,module,exports){ +"use strict"; + +/** + * A minimal base64 implementation for number arrays. + * @memberof util + * @namespace + */ +var base64 = exports; + +/** + * Calculates the byte length of a base64 encoded string. + * @param {string} string Base64 encoded string + * @returns {number} Byte length + */ +base64.length = function length(string) { + var p = string.length; + if (!p) + return 0; + var n = 0; + while (--p % 4 > 1 && string.charAt(p) === "=") + ++n; + return Math.ceil(string.length * 3) / 4 - n; +}; + +// Base64 encoding table +var b64 = new Array(64); + +// Base64 decoding table +var s64 = new Array(123); + +// 65..90, 97..122, 48..57, 43, 47 +for (var i = 0; i < 64;) + s64[b64[i] = i < 26 ? i + 65 : i < 52 ? i + 71 : i < 62 ? i - 4 : i - 59 | 43] = i++; + +/** + * Encodes a buffer to a base64 encoded string. + * @param {Uint8Array} buffer Source buffer + * @param {number} start Source start + * @param {number} end Source end + * @returns {string} Base64 encoded string + */ +base64.encode = function encode(buffer, start, end) { + var parts = null, + chunk = []; + var i = 0, // output index + j = 0, // goto index + t; // temporary + while (start < end) { + var b = buffer[start++]; + switch (j) { + case 0: + chunk[i++] = b64[b >> 2]; + t = (b & 3) << 4; + j = 1; + break; + case 1: + chunk[i++] = b64[t | b >> 4]; + t = (b & 15) << 2; + j = 2; + break; + case 2: + chunk[i++] = b64[t | b >> 6]; + chunk[i++] = b64[b & 63]; + j = 0; + break; + } + if (i > 8191) { + (parts || (parts = [])).push(String.fromCharCode.apply(String, chunk)); + i = 0; + } + } + if (j) { + chunk[i++] = b64[t]; + chunk[i++] = 61; + if (j === 1) + chunk[i++] = 61; + } + if (parts) { + if (i) + parts.push(String.fromCharCode.apply(String, chunk.slice(0, i))); + return parts.join(""); + } + return String.fromCharCode.apply(String, chunk.slice(0, i)); +}; + +var invalidEncoding = "invalid encoding"; + +/** + * Decodes a base64 encoded string to a buffer. + * @param {string} string Source string + * @param {Uint8Array} buffer Destination buffer + * @param {number} offset Destination offset + * @returns {number} Number of bytes written + * @throws {Error} If encoding is invalid + */ +base64.decode = function decode(string, buffer, offset) { + var start = offset; + var j = 0, // goto index + t; // temporary + for (var i = 0; i < string.length;) { + var c = string.charCodeAt(i++); + if (c === 61 && j > 1) + break; + if ((c = s64[c]) === undefined) + throw Error(invalidEncoding); + switch (j) { + case 0: + t = c; + j = 1; + break; + case 1: + buffer[offset++] = t << 2 | (c & 48) >> 4; + t = c; + j = 2; + break; + case 2: + buffer[offset++] = (t & 15) << 4 | (c & 60) >> 2; + t = c; + j = 3; + break; + case 3: + buffer[offset++] = (t & 3) << 6 | c; + j = 0; + break; + } + } + if (j === 1) + throw Error(invalidEncoding); + return offset - start; +}; + +/** + * Tests if the specified string appears to be base64 encoded. + * @param {string} string String to test + * @returns {boolean} `true` if probably base64 encoded, otherwise false + */ +base64.test = function test(string) { + return /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(string); +}; + +},{}],3:[function(require,module,exports){ +"use strict"; +module.exports = EventEmitter; + +/** + * Constructs a new event emitter instance. + * @classdesc A minimal event emitter. + * @memberof util + * @constructor + */ +function EventEmitter() { + + /** + * Registered listeners. + * @type {Object.} + * @private + */ + this._listeners = {}; +} + +/** + * Registers an event listener. + * @param {string} evt Event name + * @param {function} fn Listener + * @param {*} [ctx] Listener context + * @returns {util.EventEmitter} `this` + */ +EventEmitter.prototype.on = function on(evt, fn, ctx) { + (this._listeners[evt] || (this._listeners[evt] = [])).push({ + fn : fn, + ctx : ctx || this + }); + return this; +}; + +/** + * Removes an event listener or any matching listeners if arguments are omitted. + * @param {string} [evt] Event name. Removes all listeners if omitted. + * @param {function} [fn] Listener to remove. Removes all listeners of `evt` if omitted. + * @returns {util.EventEmitter} `this` + */ +EventEmitter.prototype.off = function off(evt, fn) { + if (evt === undefined) + this._listeners = {}; + else { + if (fn === undefined) + this._listeners[evt] = []; + else { + var listeners = this._listeners[evt]; + for (var i = 0; i < listeners.length;) + if (listeners[i].fn === fn) + listeners.splice(i, 1); + else + ++i; + } + } + return this; +}; + +/** + * Emits an event by calling its listeners with the specified arguments. + * @param {string} evt Event name + * @param {...*} args Arguments + * @returns {util.EventEmitter} `this` + */ +EventEmitter.prototype.emit = function emit(evt) { + var listeners = this._listeners[evt]; + if (listeners) { + var args = [], + i = 1; + for (; i < arguments.length;) + args.push(arguments[i++]); + for (i = 0; i < listeners.length;) + listeners[i].fn.apply(listeners[i++].ctx, args); + } + return this; +}; + +},{}],4:[function(require,module,exports){ +"use strict"; + +module.exports = factory(factory); + +/** + * Reads / writes floats / doubles from / to buffers. + * @name util.float + * @namespace + */ + +/** + * Writes a 32 bit float to a buffer using little endian byte order. + * @name util.float.writeFloatLE + * @function + * @param {number} val Value to write + * @param {Uint8Array} buf Target buffer + * @param {number} pos Target buffer offset + * @returns {undefined} + */ + +/** + * Writes a 32 bit float to a buffer using big endian byte order. + * @name util.float.writeFloatBE + * @function + * @param {number} val Value to write + * @param {Uint8Array} buf Target buffer + * @param {number} pos Target buffer offset + * @returns {undefined} + */ + +/** + * Reads a 32 bit float from a buffer using little endian byte order. + * @name util.float.readFloatLE + * @function + * @param {Uint8Array} buf Source buffer + * @param {number} pos Source buffer offset + * @returns {number} Value read + */ + +/** + * Reads a 32 bit float from a buffer using big endian byte order. + * @name util.float.readFloatBE + * @function + * @param {Uint8Array} buf Source buffer + * @param {number} pos Source buffer offset + * @returns {number} Value read + */ + +/** + * Writes a 64 bit double to a buffer using little endian byte order. + * @name util.float.writeDoubleLE + * @function + * @param {number} val Value to write + * @param {Uint8Array} buf Target buffer + * @param {number} pos Target buffer offset + * @returns {undefined} + */ + +/** + * Writes a 64 bit double to a buffer using big endian byte order. + * @name util.float.writeDoubleBE + * @function + * @param {number} val Value to write + * @param {Uint8Array} buf Target buffer + * @param {number} pos Target buffer offset + * @returns {undefined} + */ + +/** + * Reads a 64 bit double from a buffer using little endian byte order. + * @name util.float.readDoubleLE + * @function + * @param {Uint8Array} buf Source buffer + * @param {number} pos Source buffer offset + * @returns {number} Value read + */ + +/** + * Reads a 64 bit double from a buffer using big endian byte order. + * @name util.float.readDoubleBE + * @function + * @param {Uint8Array} buf Source buffer + * @param {number} pos Source buffer offset + * @returns {number} Value read + */ + +// Factory function for the purpose of node-based testing in modified global environments +function factory(exports) { + + // float: typed array + if (typeof Float32Array !== "undefined") (function() { + + var f32 = new Float32Array([ -0 ]), + f8b = new Uint8Array(f32.buffer), + le = f8b[3] === 128; + + function writeFloat_f32_cpy(val, buf, pos) { + f32[0] = val; + buf[pos ] = f8b[0]; + buf[pos + 1] = f8b[1]; + buf[pos + 2] = f8b[2]; + buf[pos + 3] = f8b[3]; + } + + function writeFloat_f32_rev(val, buf, pos) { + f32[0] = val; + buf[pos ] = f8b[3]; + buf[pos + 1] = f8b[2]; + buf[pos + 2] = f8b[1]; + buf[pos + 3] = f8b[0]; + } + + /* istanbul ignore next */ + exports.writeFloatLE = le ? writeFloat_f32_cpy : writeFloat_f32_rev; + /* istanbul ignore next */ + exports.writeFloatBE = le ? writeFloat_f32_rev : writeFloat_f32_cpy; + + function readFloat_f32_cpy(buf, pos) { + f8b[0] = buf[pos ]; + f8b[1] = buf[pos + 1]; + f8b[2] = buf[pos + 2]; + f8b[3] = buf[pos + 3]; + return f32[0]; + } + + function readFloat_f32_rev(buf, pos) { + f8b[3] = buf[pos ]; + f8b[2] = buf[pos + 1]; + f8b[1] = buf[pos + 2]; + f8b[0] = buf[pos + 3]; + return f32[0]; + } + + /* istanbul ignore next */ + exports.readFloatLE = le ? readFloat_f32_cpy : readFloat_f32_rev; + /* istanbul ignore next */ + exports.readFloatBE = le ? readFloat_f32_rev : readFloat_f32_cpy; + + // float: ieee754 + })(); else (function() { + + function writeFloat_ieee754(writeUint, val, buf, pos) { + var sign = val < 0 ? 1 : 0; + if (sign) + val = -val; + if (val === 0) + writeUint(1 / val > 0 ? /* positive */ 0 : /* negative 0 */ 2147483648, buf, pos); + else if (isNaN(val)) + writeUint(2143289344, buf, pos); + else if (val > 3.4028234663852886e+38) // +-Infinity + writeUint((sign << 31 | 2139095040) >>> 0, buf, pos); + else if (val < 1.1754943508222875e-38) // denormal + writeUint((sign << 31 | Math.round(val / 1.401298464324817e-45)) >>> 0, buf, pos); + else { + var exponent = Math.floor(Math.log(val) / Math.LN2), + mantissa = Math.round(val * Math.pow(2, -exponent) * 8388608) & 8388607; + writeUint((sign << 31 | exponent + 127 << 23 | mantissa) >>> 0, buf, pos); + } + } + + exports.writeFloatLE = writeFloat_ieee754.bind(null, writeUintLE); + exports.writeFloatBE = writeFloat_ieee754.bind(null, writeUintBE); + + function readFloat_ieee754(readUint, buf, pos) { + var uint = readUint(buf, pos), + sign = (uint >> 31) * 2 + 1, + exponent = uint >>> 23 & 255, + mantissa = uint & 8388607; + return exponent === 255 + ? mantissa + ? NaN + : sign * Infinity + : exponent === 0 // denormal + ? sign * 1.401298464324817e-45 * mantissa + : sign * Math.pow(2, exponent - 150) * (mantissa + 8388608); + } + + exports.readFloatLE = readFloat_ieee754.bind(null, readUintLE); + exports.readFloatBE = readFloat_ieee754.bind(null, readUintBE); + + })(); + + // double: typed array + if (typeof Float64Array !== "undefined") (function() { + + var f64 = new Float64Array([-0]), + f8b = new Uint8Array(f64.buffer), + le = f8b[7] === 128; + + function writeDouble_f64_cpy(val, buf, pos) { + f64[0] = val; + buf[pos ] = f8b[0]; + buf[pos + 1] = f8b[1]; + buf[pos + 2] = f8b[2]; + buf[pos + 3] = f8b[3]; + buf[pos + 4] = f8b[4]; + buf[pos + 5] = f8b[5]; + buf[pos + 6] = f8b[6]; + buf[pos + 7] = f8b[7]; + } + + function writeDouble_f64_rev(val, buf, pos) { + f64[0] = val; + buf[pos ] = f8b[7]; + buf[pos + 1] = f8b[6]; + buf[pos + 2] = f8b[5]; + buf[pos + 3] = f8b[4]; + buf[pos + 4] = f8b[3]; + buf[pos + 5] = f8b[2]; + buf[pos + 6] = f8b[1]; + buf[pos + 7] = f8b[0]; + } + + /* istanbul ignore next */ + exports.writeDoubleLE = le ? writeDouble_f64_cpy : writeDouble_f64_rev; + /* istanbul ignore next */ + exports.writeDoubleBE = le ? writeDouble_f64_rev : writeDouble_f64_cpy; + + function readDouble_f64_cpy(buf, pos) { + f8b[0] = buf[pos ]; + f8b[1] = buf[pos + 1]; + f8b[2] = buf[pos + 2]; + f8b[3] = buf[pos + 3]; + f8b[4] = buf[pos + 4]; + f8b[5] = buf[pos + 5]; + f8b[6] = buf[pos + 6]; + f8b[7] = buf[pos + 7]; + return f64[0]; + } + + function readDouble_f64_rev(buf, pos) { + f8b[7] = buf[pos ]; + f8b[6] = buf[pos + 1]; + f8b[5] = buf[pos + 2]; + f8b[4] = buf[pos + 3]; + f8b[3] = buf[pos + 4]; + f8b[2] = buf[pos + 5]; + f8b[1] = buf[pos + 6]; + f8b[0] = buf[pos + 7]; + return f64[0]; + } + + /* istanbul ignore next */ + exports.readDoubleLE = le ? readDouble_f64_cpy : readDouble_f64_rev; + /* istanbul ignore next */ + exports.readDoubleBE = le ? readDouble_f64_rev : readDouble_f64_cpy; + + // double: ieee754 + })(); else (function() { + + function writeDouble_ieee754(writeUint, off0, off1, val, buf, pos) { + var sign = val < 0 ? 1 : 0; + if (sign) + val = -val; + if (val === 0) { + writeUint(0, buf, pos + off0); + writeUint(1 / val > 0 ? /* positive */ 0 : /* negative 0 */ 2147483648, buf, pos + off1); + } else if (isNaN(val)) { + writeUint(0, buf, pos + off0); + writeUint(2146959360, buf, pos + off1); + } else if (val > 1.7976931348623157e+308) { // +-Infinity + writeUint(0, buf, pos + off0); + writeUint((sign << 31 | 2146435072) >>> 0, buf, pos + off1); + } else { + var mantissa; + if (val < 2.2250738585072014e-308) { // denormal + mantissa = val / 5e-324; + writeUint(mantissa >>> 0, buf, pos + off0); + writeUint((sign << 31 | mantissa / 4294967296) >>> 0, buf, pos + off1); + } else { + var exponent = Math.floor(Math.log(val) / Math.LN2); + if (exponent === 1024) + exponent = 1023; + mantissa = val * Math.pow(2, -exponent); + writeUint(mantissa * 4503599627370496 >>> 0, buf, pos + off0); + writeUint((sign << 31 | exponent + 1023 << 20 | mantissa * 1048576 & 1048575) >>> 0, buf, pos + off1); + } + } + } + + exports.writeDoubleLE = writeDouble_ieee754.bind(null, writeUintLE, 0, 4); + exports.writeDoubleBE = writeDouble_ieee754.bind(null, writeUintBE, 4, 0); + + function readDouble_ieee754(readUint, off0, off1, buf, pos) { + var lo = readUint(buf, pos + off0), + hi = readUint(buf, pos + off1); + var sign = (hi >> 31) * 2 + 1, + exponent = hi >>> 20 & 2047, + mantissa = 4294967296 * (hi & 1048575) + lo; + return exponent === 2047 + ? mantissa + ? NaN + : sign * Infinity + : exponent === 0 // denormal + ? sign * 5e-324 * mantissa + : sign * Math.pow(2, exponent - 1075) * (mantissa + 4503599627370496); + } + + exports.readDoubleLE = readDouble_ieee754.bind(null, readUintLE, 0, 4); + exports.readDoubleBE = readDouble_ieee754.bind(null, readUintBE, 4, 0); + + })(); + + return exports; +} + +// uint helpers + +function writeUintLE(val, buf, pos) { + buf[pos ] = val & 255; + buf[pos + 1] = val >>> 8 & 255; + buf[pos + 2] = val >>> 16 & 255; + buf[pos + 3] = val >>> 24; +} + +function writeUintBE(val, buf, pos) { + buf[pos ] = val >>> 24; + buf[pos + 1] = val >>> 16 & 255; + buf[pos + 2] = val >>> 8 & 255; + buf[pos + 3] = val & 255; +} + +function readUintLE(buf, pos) { + return (buf[pos ] + | buf[pos + 1] << 8 + | buf[pos + 2] << 16 + | buf[pos + 3] << 24) >>> 0; +} + +function readUintBE(buf, pos) { + return (buf[pos ] << 24 + | buf[pos + 1] << 16 + | buf[pos + 2] << 8 + | buf[pos + 3]) >>> 0; +} + +},{}],5:[function(require,module,exports){ +"use strict"; +module.exports = inquire; + +/** + * Requires a module only if available. + * @memberof util + * @param {string} moduleName Module to require + * @returns {?Object} Required module if available and not empty, otherwise `null` + */ +function inquire(moduleName) { + try { + var mod = eval("quire".replace(/^/,"re"))(moduleName); // eslint-disable-line no-eval + if (mod && (mod.length || Object.keys(mod).length)) + return mod; + } catch (e) {} // eslint-disable-line no-empty + return null; +} + +},{}],6:[function(require,module,exports){ +"use strict"; +module.exports = pool; + +/** + * An allocator as used by {@link util.pool}. + * @typedef PoolAllocator + * @type {function} + * @param {number} size Buffer size + * @returns {Uint8Array} Buffer + */ + +/** + * A slicer as used by {@link util.pool}. + * @typedef PoolSlicer + * @type {function} + * @param {number} start Start offset + * @param {number} end End offset + * @returns {Uint8Array} Buffer slice + * @this {Uint8Array} + */ + +/** + * A general purpose buffer pool. + * @memberof util + * @function + * @param {PoolAllocator} alloc Allocator + * @param {PoolSlicer} slice Slicer + * @param {number} [size=8192] Slab size + * @returns {PoolAllocator} Pooled allocator + */ +function pool(alloc, slice, size) { + var SIZE = size || 8192; + var MAX = SIZE >>> 1; + var slab = null; + var offset = SIZE; + return function pool_alloc(size) { + if (size < 1 || size > MAX) + return alloc(size); + if (offset + size > SIZE) { + slab = alloc(SIZE); + offset = 0; + } + var buf = slice.call(slab, offset, offset += size); + if (offset & 7) // align to 32 bit + offset = (offset | 7) + 1; + return buf; + }; +} + +},{}],7:[function(require,module,exports){ +"use strict"; + +/** + * A minimal UTF8 implementation for number arrays. + * @memberof util + * @namespace + */ +var utf8 = exports; + +/** + * Calculates the UTF8 byte length of a string. + * @param {string} string String + * @returns {number} Byte length + */ +utf8.length = function utf8_length(string) { + var len = 0, + c = 0; + for (var i = 0; i < string.length; ++i) { + c = string.charCodeAt(i); + if (c < 128) + len += 1; + else if (c < 2048) + len += 2; + else if ((c & 0xFC00) === 0xD800 && (string.charCodeAt(i + 1) & 0xFC00) === 0xDC00) { + ++i; + len += 4; + } else + len += 3; + } + return len; +}; + +/** + * Reads UTF8 bytes as a string. + * @param {Uint8Array} buffer Source buffer + * @param {number} start Source start + * @param {number} end Source end + * @returns {string} String read + */ +utf8.read = function utf8_read(buffer, start, end) { + var len = end - start; + if (len < 1) + return ""; + var parts = null, + chunk = [], + i = 0, // char offset + t; // temporary + while (start < end) { + t = buffer[start++]; + if (t < 128) + chunk[i++] = t; + else if (t > 191 && t < 224) + chunk[i++] = (t & 31) << 6 | buffer[start++] & 63; + else if (t > 239 && t < 365) { + t = ((t & 7) << 18 | (buffer[start++] & 63) << 12 | (buffer[start++] & 63) << 6 | buffer[start++] & 63) - 0x10000; + chunk[i++] = 0xD800 + (t >> 10); + chunk[i++] = 0xDC00 + (t & 1023); + } else + chunk[i++] = (t & 15) << 12 | (buffer[start++] & 63) << 6 | buffer[start++] & 63; + if (i > 8191) { + (parts || (parts = [])).push(String.fromCharCode.apply(String, chunk)); + i = 0; + } + } + if (parts) { + if (i) + parts.push(String.fromCharCode.apply(String, chunk.slice(0, i))); + return parts.join(""); + } + return String.fromCharCode.apply(String, chunk.slice(0, i)); +}; + +/** + * Writes a string as UTF8 bytes. + * @param {string} string Source string + * @param {Uint8Array} buffer Destination buffer + * @param {number} offset Destination offset + * @returns {number} Bytes written + */ +utf8.write = function utf8_write(string, buffer, offset) { + var start = offset, + c1, // character 1 + c2; // character 2 + for (var i = 0; i < string.length; ++i) { + c1 = string.charCodeAt(i); + if (c1 < 128) { + buffer[offset++] = c1; + } else if (c1 < 2048) { + buffer[offset++] = c1 >> 6 | 192; + buffer[offset++] = c1 & 63 | 128; + } else if ((c1 & 0xFC00) === 0xD800 && ((c2 = string.charCodeAt(i + 1)) & 0xFC00) === 0xDC00) { + c1 = 0x10000 + ((c1 & 0x03FF) << 10) + (c2 & 0x03FF); + ++i; + buffer[offset++] = c1 >> 18 | 240; + buffer[offset++] = c1 >> 12 & 63 | 128; + buffer[offset++] = c1 >> 6 & 63 | 128; + buffer[offset++] = c1 & 63 | 128; + } else { + buffer[offset++] = c1 >> 12 | 224; + buffer[offset++] = c1 >> 6 & 63 | 128; + buffer[offset++] = c1 & 63 | 128; + } + } + return offset - start; +}; + +},{}],8:[function(require,module,exports){ +"use strict"; +var protobuf = exports; + +/** + * Build type, one of `"full"`, `"light"` or `"minimal"`. + * @name build + * @type {string} + * @const + */ +protobuf.build = "minimal"; + +// Serialization +protobuf.Writer = require(16); +protobuf.BufferWriter = require(17); +protobuf.Reader = require(9); +protobuf.BufferReader = require(10); + +// Utility +protobuf.util = require(15); +protobuf.rpc = require(12); +protobuf.roots = require(11); +protobuf.configure = configure; + +/* istanbul ignore next */ +/** + * Reconfigures the library according to the environment. + * @returns {undefined} + */ +function configure() { + protobuf.util._configure(); + protobuf.Writer._configure(protobuf.BufferWriter); + protobuf.Reader._configure(protobuf.BufferReader); +} + +// Set up buffer utility according to the environment +configure(); + +},{"10":10,"11":11,"12":12,"15":15,"16":16,"17":17,"9":9}],9:[function(require,module,exports){ +"use strict"; +module.exports = Reader; + +var util = require(15); + +var BufferReader; // cyclic + +var LongBits = util.LongBits, + utf8 = util.utf8; + +/* istanbul ignore next */ +function indexOutOfRange(reader, writeLength) { + return RangeError("index out of range: " + reader.pos + " + " + (writeLength || 1) + " > " + reader.len); +} + +/** + * Constructs a new reader instance using the specified buffer. + * @classdesc Wire format reader using `Uint8Array` if available, otherwise `Array`. + * @constructor + * @param {Uint8Array} buffer Buffer to read from + */ +function Reader(buffer) { + + /** + * Read buffer. + * @type {Uint8Array} + */ + this.buf = buffer; + + /** + * Read buffer position. + * @type {number} + */ + this.pos = 0; + + /** + * Read buffer length. + * @type {number} + */ + this.len = buffer.length; +} + +var create_array = typeof Uint8Array !== "undefined" + ? function create_typed_array(buffer) { + if (buffer instanceof Uint8Array || Array.isArray(buffer)) + return new Reader(buffer); + throw Error("illegal buffer"); + } + /* istanbul ignore next */ + : function create_array(buffer) { + if (Array.isArray(buffer)) + return new Reader(buffer); + throw Error("illegal buffer"); + }; + +var create = function create() { + return util.Buffer + ? function create_buffer_setup(buffer) { + return (Reader.create = function create_buffer(buffer) { + return util.Buffer.isBuffer(buffer) + ? new BufferReader(buffer) + /* istanbul ignore next */ + : create_array(buffer); + })(buffer); + } + /* istanbul ignore next */ + : create_array; +}; + +/** + * Creates a new reader using the specified buffer. + * @function + * @param {Uint8Array|Buffer} buffer Buffer to read from + * @returns {Reader|BufferReader} A {@link BufferReader} if `buffer` is a Buffer, otherwise a {@link Reader} + * @throws {Error} If `buffer` is not a valid buffer + */ +Reader.create = create(); + +Reader.prototype._slice = util.Array.prototype.subarray || /* istanbul ignore next */ util.Array.prototype.slice; + +/** + * Reads a varint as an unsigned 32 bit value. + * @function + * @returns {number} Value read + */ +Reader.prototype.uint32 = (function read_uint32_setup() { + var value = 4294967295; // optimizer type-hint, tends to deopt otherwise (?!) + return function read_uint32() { + value = ( this.buf[this.pos] & 127 ) >>> 0; if (this.buf[this.pos++] < 128) return value; + value = (value | (this.buf[this.pos] & 127) << 7) >>> 0; if (this.buf[this.pos++] < 128) return value; + value = (value | (this.buf[this.pos] & 127) << 14) >>> 0; if (this.buf[this.pos++] < 128) return value; + value = (value | (this.buf[this.pos] & 127) << 21) >>> 0; if (this.buf[this.pos++] < 128) return value; + value = (value | (this.buf[this.pos] & 15) << 28) >>> 0; if (this.buf[this.pos++] < 128) return value; + + /* istanbul ignore if */ + if ((this.pos += 5) > this.len) { + this.pos = this.len; + throw indexOutOfRange(this, 10); + } + return value; + }; +})(); + +/** + * Reads a varint as a signed 32 bit value. + * @returns {number} Value read + */ +Reader.prototype.int32 = function read_int32() { + return this.uint32() | 0; +}; + +/** + * Reads a zig-zag encoded varint as a signed 32 bit value. + * @returns {number} Value read + */ +Reader.prototype.sint32 = function read_sint32() { + var value = this.uint32(); + return value >>> 1 ^ -(value & 1) | 0; +}; + +/* eslint-disable no-invalid-this */ + +function readLongVarint() { + // tends to deopt with local vars for octet etc. + var bits = new LongBits(0, 0); + var i = 0; + if (this.len - this.pos > 4) { // fast route (lo) + for (; i < 4; ++i) { + // 1st..4th + bits.lo = (bits.lo | (this.buf[this.pos] & 127) << i * 7) >>> 0; + if (this.buf[this.pos++] < 128) + return bits; + } + // 5th + bits.lo = (bits.lo | (this.buf[this.pos] & 127) << 28) >>> 0; + bits.hi = (bits.hi | (this.buf[this.pos] & 127) >> 4) >>> 0; + if (this.buf[this.pos++] < 128) + return bits; + i = 0; + } else { + for (; i < 3; ++i) { + /* istanbul ignore if */ + if (this.pos >= this.len) + throw indexOutOfRange(this); + // 1st..3th + bits.lo = (bits.lo | (this.buf[this.pos] & 127) << i * 7) >>> 0; + if (this.buf[this.pos++] < 128) + return bits; + } + // 4th + bits.lo = (bits.lo | (this.buf[this.pos++] & 127) << i * 7) >>> 0; + return bits; + } + if (this.len - this.pos > 4) { // fast route (hi) + for (; i < 5; ++i) { + // 6th..10th + bits.hi = (bits.hi | (this.buf[this.pos] & 127) << i * 7 + 3) >>> 0; + if (this.buf[this.pos++] < 128) + return bits; + } + } else { + for (; i < 5; ++i) { + /* istanbul ignore if */ + if (this.pos >= this.len) + throw indexOutOfRange(this); + // 6th..10th + bits.hi = (bits.hi | (this.buf[this.pos] & 127) << i * 7 + 3) >>> 0; + if (this.buf[this.pos++] < 128) + return bits; + } + } + /* istanbul ignore next */ + throw Error("invalid varint encoding"); +} + +/* eslint-enable no-invalid-this */ + +/** + * Reads a varint as a signed 64 bit value. + * @name Reader#int64 + * @function + * @returns {Long} Value read + */ + +/** + * Reads a varint as an unsigned 64 bit value. + * @name Reader#uint64 + * @function + * @returns {Long} Value read + */ + +/** + * Reads a zig-zag encoded varint as a signed 64 bit value. + * @name Reader#sint64 + * @function + * @returns {Long} Value read + */ + +/** + * Reads a varint as a boolean. + * @returns {boolean} Value read + */ +Reader.prototype.bool = function read_bool() { + return this.uint32() !== 0; +}; + +function readFixed32_end(buf, end) { // note that this uses `end`, not `pos` + return (buf[end - 4] + | buf[end - 3] << 8 + | buf[end - 2] << 16 + | buf[end - 1] << 24) >>> 0; +} + +/** + * Reads fixed 32 bits as an unsigned 32 bit integer. + * @returns {number} Value read + */ +Reader.prototype.fixed32 = function read_fixed32() { + + /* istanbul ignore if */ + if (this.pos + 4 > this.len) + throw indexOutOfRange(this, 4); + + return readFixed32_end(this.buf, this.pos += 4); +}; + +/** + * Reads fixed 32 bits as a signed 32 bit integer. + * @returns {number} Value read + */ +Reader.prototype.sfixed32 = function read_sfixed32() { + + /* istanbul ignore if */ + if (this.pos + 4 > this.len) + throw indexOutOfRange(this, 4); + + return readFixed32_end(this.buf, this.pos += 4) | 0; +}; + +/* eslint-disable no-invalid-this */ + +function readFixed64(/* this: Reader */) { + + /* istanbul ignore if */ + if (this.pos + 8 > this.len) + throw indexOutOfRange(this, 8); + + return new LongBits(readFixed32_end(this.buf, this.pos += 4), readFixed32_end(this.buf, this.pos += 4)); +} + +/* eslint-enable no-invalid-this */ + +/** + * Reads fixed 64 bits. + * @name Reader#fixed64 + * @function + * @returns {Long} Value read + */ + +/** + * Reads zig-zag encoded fixed 64 bits. + * @name Reader#sfixed64 + * @function + * @returns {Long} Value read + */ + +/** + * Reads a float (32 bit) as a number. + * @function + * @returns {number} Value read + */ +Reader.prototype.float = function read_float() { + + /* istanbul ignore if */ + if (this.pos + 4 > this.len) + throw indexOutOfRange(this, 4); + + var value = util.float.readFloatLE(this.buf, this.pos); + this.pos += 4; + return value; +}; + +/** + * Reads a double (64 bit float) as a number. + * @function + * @returns {number} Value read + */ +Reader.prototype.double = function read_double() { + + /* istanbul ignore if */ + if (this.pos + 8 > this.len) + throw indexOutOfRange(this, 4); + + var value = util.float.readDoubleLE(this.buf, this.pos); + this.pos += 8; + return value; +}; + +/** + * Reads a sequence of bytes preceeded by its length as a varint. + * @returns {Uint8Array} Value read + */ +Reader.prototype.bytes = function read_bytes() { + var length = this.uint32(), + start = this.pos, + end = this.pos + length; + + /* istanbul ignore if */ + if (end > this.len) + throw indexOutOfRange(this, length); + + this.pos += length; + if (Array.isArray(this.buf)) // plain array + return this.buf.slice(start, end); + + if (start === end) { // fix for IE 10/Win8 and others' subarray returning array of size 1 + var nativeBuffer = util.Buffer; + return nativeBuffer + ? nativeBuffer.alloc(0) + : new this.buf.constructor(0); + } + return this._slice.call(this.buf, start, end); +}; + +/** + * Reads a string preceeded by its byte length as a varint. + * @returns {string} Value read + */ +Reader.prototype.string = function read_string() { + var bytes = this.bytes(); + return utf8.read(bytes, 0, bytes.length); +}; + +/** + * Skips the specified number of bytes if specified, otherwise skips a varint. + * @param {number} [length] Length if known, otherwise a varint is assumed + * @returns {Reader} `this` + */ +Reader.prototype.skip = function skip(length) { + if (typeof length === "number") { + /* istanbul ignore if */ + if (this.pos + length > this.len) + throw indexOutOfRange(this, length); + this.pos += length; + } else { + do { + /* istanbul ignore if */ + if (this.pos >= this.len) + throw indexOutOfRange(this); + } while (this.buf[this.pos++] & 128); + } + return this; +}; + +/** + * Skips the next element of the specified wire type. + * @param {number} wireType Wire type received + * @returns {Reader} `this` + */ +Reader.prototype.skipType = function(wireType) { + switch (wireType) { + case 0: + this.skip(); + break; + case 1: + this.skip(8); + break; + case 2: + this.skip(this.uint32()); + break; + case 3: + while ((wireType = this.uint32() & 7) !== 4) { + this.skipType(wireType); + } + break; + case 5: + this.skip(4); + break; + + /* istanbul ignore next */ + default: + throw Error("invalid wire type " + wireType + " at offset " + this.pos); + } + return this; +}; + +Reader._configure = function(BufferReader_) { + BufferReader = BufferReader_; + Reader.create = create(); + BufferReader._configure(); + + var fn = util.Long ? "toLong" : /* istanbul ignore next */ "toNumber"; + util.merge(Reader.prototype, { + + int64: function read_int64() { + return readLongVarint.call(this)[fn](false); + }, + + uint64: function read_uint64() { + return readLongVarint.call(this)[fn](true); + }, + + sint64: function read_sint64() { + return readLongVarint.call(this).zzDecode()[fn](false); + }, + + fixed64: function read_fixed64() { + return readFixed64.call(this)[fn](true); + }, + + sfixed64: function read_sfixed64() { + return readFixed64.call(this)[fn](false); + } + + }); +}; + +},{"15":15}],10:[function(require,module,exports){ +"use strict"; +module.exports = BufferReader; + +// extends Reader +var Reader = require(9); +(BufferReader.prototype = Object.create(Reader.prototype)).constructor = BufferReader; + +var util = require(15); + +/** + * Constructs a new buffer reader instance. + * @classdesc Wire format reader using node buffers. + * @extends Reader + * @constructor + * @param {Buffer} buffer Buffer to read from + */ +function BufferReader(buffer) { + Reader.call(this, buffer); + + /** + * Read buffer. + * @name BufferReader#buf + * @type {Buffer} + */ +} + +BufferReader._configure = function () { + /* istanbul ignore else */ + if (util.Buffer) + BufferReader.prototype._slice = util.Buffer.prototype.slice; +}; + + +/** + * @override + */ +BufferReader.prototype.string = function read_string_buffer() { + var len = this.uint32(); // modifies pos + return this.buf.utf8Slice + ? this.buf.utf8Slice(this.pos, this.pos = Math.min(this.pos + len, this.len)) + : this.buf.toString("utf-8", this.pos, this.pos = Math.min(this.pos + len, this.len)); +}; + +/** + * Reads a sequence of bytes preceeded by its length as a varint. + * @name BufferReader#bytes + * @function + * @returns {Buffer} Value read + */ + +BufferReader._configure(); + +},{"15":15,"9":9}],11:[function(require,module,exports){ +"use strict"; +module.exports = {}; + +/** + * Named roots. + * This is where pbjs stores generated structures (the option `-r, --root` specifies a name). + * Can also be used manually to make roots available across modules. + * @name roots + * @type {Object.} + * @example + * // pbjs -r myroot -o compiled.js ... + * + * // in another module: + * require("./compiled.js"); + * + * // in any subsequent module: + * var root = protobuf.roots["myroot"]; + */ + +},{}],12:[function(require,module,exports){ +"use strict"; + +/** + * Streaming RPC helpers. + * @namespace + */ +var rpc = exports; + +/** + * RPC implementation passed to {@link Service#create} performing a service request on network level, i.e. by utilizing http requests or websockets. + * @typedef RPCImpl + * @type {function} + * @param {Method|rpc.ServiceMethod,Message<{}>>} method Reflected or static method being called + * @param {Uint8Array} requestData Request data + * @param {RPCImplCallback} callback Callback function + * @returns {undefined} + * @example + * function rpcImpl(method, requestData, callback) { + * if (protobuf.util.lcFirst(method.name) !== "myMethod") // compatible with static code + * throw Error("no such method"); + * asynchronouslyObtainAResponse(requestData, function(err, responseData) { + * callback(err, responseData); + * }); + * } + */ + +/** + * Node-style callback as used by {@link RPCImpl}. + * @typedef RPCImplCallback + * @type {function} + * @param {Error|null} error Error, if any, otherwise `null` + * @param {Uint8Array|null} [response] Response data or `null` to signal end of stream, if there hasn't been an error + * @returns {undefined} + */ + +rpc.Service = require(13); + +},{"13":13}],13:[function(require,module,exports){ +"use strict"; +module.exports = Service; + +var util = require(15); + +// Extends EventEmitter +(Service.prototype = Object.create(util.EventEmitter.prototype)).constructor = Service; + +/** + * A service method callback as used by {@link rpc.ServiceMethod|ServiceMethod}. + * + * Differs from {@link RPCImplCallback} in that it is an actual callback of a service method which may not return `response = null`. + * @typedef rpc.ServiceMethodCallback + * @template TRes extends Message + * @type {function} + * @param {Error|null} error Error, if any + * @param {TRes} [response] Response message + * @returns {undefined} + */ + +/** + * A service method part of a {@link rpc.Service} as created by {@link Service.create}. + * @typedef rpc.ServiceMethod + * @template TReq extends Message + * @template TRes extends Message + * @type {function} + * @param {TReq|Properties} request Request message or plain object + * @param {rpc.ServiceMethodCallback} [callback] Node-style callback called with the error, if any, and the response message + * @returns {Promise>} Promise if `callback` has been omitted, otherwise `undefined` + */ + +/** + * Constructs a new RPC service instance. + * @classdesc An RPC service as returned by {@link Service#create}. + * @exports rpc.Service + * @extends util.EventEmitter + * @constructor + * @param {RPCImpl} rpcImpl RPC implementation + * @param {boolean} [requestDelimited=false] Whether requests are length-delimited + * @param {boolean} [responseDelimited=false] Whether responses are length-delimited + */ +function Service(rpcImpl, requestDelimited, responseDelimited) { + + if (typeof rpcImpl !== "function") + throw TypeError("rpcImpl must be a function"); + + util.EventEmitter.call(this); + + /** + * RPC implementation. Becomes `null` once the service is ended. + * @type {RPCImpl|null} + */ + this.rpcImpl = rpcImpl; + + /** + * Whether requests are length-delimited. + * @type {boolean} + */ + this.requestDelimited = Boolean(requestDelimited); + + /** + * Whether responses are length-delimited. + * @type {boolean} + */ + this.responseDelimited = Boolean(responseDelimited); +} + +/** + * Calls a service method through {@link rpc.Service#rpcImpl|rpcImpl}. + * @param {Method|rpc.ServiceMethod} method Reflected or static method + * @param {Constructor} requestCtor Request constructor + * @param {Constructor} responseCtor Response constructor + * @param {TReq|Properties} request Request message or plain object + * @param {rpc.ServiceMethodCallback} callback Service callback + * @returns {undefined} + * @template TReq extends Message + * @template TRes extends Message + */ +Service.prototype.rpcCall = function rpcCall(method, requestCtor, responseCtor, request, callback) { + + if (!request) + throw TypeError("request must be specified"); + + var self = this; + if (!callback) + return util.asPromise(rpcCall, self, method, requestCtor, responseCtor, request); + + if (!self.rpcImpl) { + setTimeout(function() { callback(Error("already ended")); }, 0); + return undefined; + } + + try { + return self.rpcImpl( + method, + requestCtor[self.requestDelimited ? "encodeDelimited" : "encode"](request).finish(), + function rpcCallback(err, response) { + + if (err) { + self.emit("error", err, method); + return callback(err); + } + + if (response === null) { + self.end(/* endedByRPC */ true); + return undefined; + } + + if (!(response instanceof responseCtor)) { + try { + response = responseCtor[self.responseDelimited ? "decodeDelimited" : "decode"](response); + } catch (err) { + self.emit("error", err, method); + return callback(err); + } + } + + self.emit("data", response, method); + return callback(null, response); + } + ); + } catch (err) { + self.emit("error", err, method); + setTimeout(function() { callback(err); }, 0); + return undefined; + } +}; + +/** + * Ends this service and emits the `end` event. + * @param {boolean} [endedByRPC=false] Whether the service has been ended by the RPC implementation. + * @returns {rpc.Service} `this` + */ +Service.prototype.end = function end(endedByRPC) { + if (this.rpcImpl) { + if (!endedByRPC) // signal end to rpcImpl + this.rpcImpl(null, null, null); + this.rpcImpl = null; + this.emit("end").off(); + } + return this; +}; + +},{"15":15}],14:[function(require,module,exports){ +"use strict"; +module.exports = LongBits; + +var util = require(15); + +/** + * Constructs new long bits. + * @classdesc Helper class for working with the low and high bits of a 64 bit value. + * @memberof util + * @constructor + * @param {number} lo Low 32 bits, unsigned + * @param {number} hi High 32 bits, unsigned + */ +function LongBits(lo, hi) { + + // note that the casts below are theoretically unnecessary as of today, but older statically + // generated converter code might still call the ctor with signed 32bits. kept for compat. + + /** + * Low bits. + * @type {number} + */ + this.lo = lo >>> 0; + + /** + * High bits. + * @type {number} + */ + this.hi = hi >>> 0; +} + +/** + * Zero bits. + * @memberof util.LongBits + * @type {util.LongBits} + */ +var zero = LongBits.zero = new LongBits(0, 0); + +zero.toNumber = function() { return 0; }; +zero.zzEncode = zero.zzDecode = function() { return this; }; +zero.length = function() { return 1; }; + +/** + * Zero hash. + * @memberof util.LongBits + * @type {string} + */ +var zeroHash = LongBits.zeroHash = "\0\0\0\0\0\0\0\0"; + +/** + * Constructs new long bits from the specified number. + * @param {number} value Value + * @returns {util.LongBits} Instance + */ +LongBits.fromNumber = function fromNumber(value) { + if (value === 0) + return zero; + var sign = value < 0; + if (sign) + value = -value; + var lo = value >>> 0, + hi = (value - lo) / 4294967296 >>> 0; + if (sign) { + hi = ~hi >>> 0; + lo = ~lo >>> 0; + if (++lo > 4294967295) { + lo = 0; + if (++hi > 4294967295) + hi = 0; + } + } + return new LongBits(lo, hi); +}; + +/** + * Constructs new long bits from a number, long or string. + * @param {Long|number|string} value Value + * @returns {util.LongBits} Instance + */ +LongBits.from = function from(value) { + if (typeof value === "number") + return LongBits.fromNumber(value); + if (util.isString(value)) { + /* istanbul ignore else */ + if (util.Long) + value = util.Long.fromString(value); + else + return LongBits.fromNumber(parseInt(value, 10)); + } + return value.low || value.high ? new LongBits(value.low >>> 0, value.high >>> 0) : zero; +}; + +/** + * Converts this long bits to a possibly unsafe JavaScript number. + * @param {boolean} [unsigned=false] Whether unsigned or not + * @returns {number} Possibly unsafe number + */ +LongBits.prototype.toNumber = function toNumber(unsigned) { + if (!unsigned && this.hi >>> 31) { + var lo = ~this.lo + 1 >>> 0, + hi = ~this.hi >>> 0; + if (!lo) + hi = hi + 1 >>> 0; + return -(lo + hi * 4294967296); + } + return this.lo + this.hi * 4294967296; +}; + +/** + * Converts this long bits to a long. + * @param {boolean} [unsigned=false] Whether unsigned or not + * @returns {Long} Long + */ +LongBits.prototype.toLong = function toLong(unsigned) { + return util.Long + ? new util.Long(this.lo | 0, this.hi | 0, Boolean(unsigned)) + /* istanbul ignore next */ + : { low: this.lo | 0, high: this.hi | 0, unsigned: Boolean(unsigned) }; +}; + +var charCodeAt = String.prototype.charCodeAt; + +/** + * Constructs new long bits from the specified 8 characters long hash. + * @param {string} hash Hash + * @returns {util.LongBits} Bits + */ +LongBits.fromHash = function fromHash(hash) { + if (hash === zeroHash) + return zero; + return new LongBits( + ( charCodeAt.call(hash, 0) + | charCodeAt.call(hash, 1) << 8 + | charCodeAt.call(hash, 2) << 16 + | charCodeAt.call(hash, 3) << 24) >>> 0 + , + ( charCodeAt.call(hash, 4) + | charCodeAt.call(hash, 5) << 8 + | charCodeAt.call(hash, 6) << 16 + | charCodeAt.call(hash, 7) << 24) >>> 0 + ); +}; + +/** + * Converts this long bits to a 8 characters long hash. + * @returns {string} Hash + */ +LongBits.prototype.toHash = function toHash() { + return String.fromCharCode( + this.lo & 255, + this.lo >>> 8 & 255, + this.lo >>> 16 & 255, + this.lo >>> 24 , + this.hi & 255, + this.hi >>> 8 & 255, + this.hi >>> 16 & 255, + this.hi >>> 24 + ); +}; + +/** + * Zig-zag encodes this long bits. + * @returns {util.LongBits} `this` + */ +LongBits.prototype.zzEncode = function zzEncode() { + var mask = this.hi >> 31; + this.hi = ((this.hi << 1 | this.lo >>> 31) ^ mask) >>> 0; + this.lo = ( this.lo << 1 ^ mask) >>> 0; + return this; +}; + +/** + * Zig-zag decodes this long bits. + * @returns {util.LongBits} `this` + */ +LongBits.prototype.zzDecode = function zzDecode() { + var mask = -(this.lo & 1); + this.lo = ((this.lo >>> 1 | this.hi << 31) ^ mask) >>> 0; + this.hi = ( this.hi >>> 1 ^ mask) >>> 0; + return this; +}; + +/** + * Calculates the length of this longbits when encoded as a varint. + * @returns {number} Length + */ +LongBits.prototype.length = function length() { + var part0 = this.lo, + part1 = (this.lo >>> 28 | this.hi << 4) >>> 0, + part2 = this.hi >>> 24; + return part2 === 0 + ? part1 === 0 + ? part0 < 16384 + ? part0 < 128 ? 1 : 2 + : part0 < 2097152 ? 3 : 4 + : part1 < 16384 + ? part1 < 128 ? 5 : 6 + : part1 < 2097152 ? 7 : 8 + : part2 < 128 ? 9 : 10; +}; + +},{"15":15}],15:[function(require,module,exports){ +"use strict"; +var util = exports; + +// used to return a Promise where callback is omitted +util.asPromise = require(1); + +// converts to / from base64 encoded strings +util.base64 = require(2); + +// base class of rpc.Service +util.EventEmitter = require(3); + +// float handling accross browsers +util.float = require(4); + +// requires modules optionally and hides the call from bundlers +util.inquire = require(5); + +// converts to / from utf8 encoded strings +util.utf8 = require(7); + +// provides a node-like buffer pool in the browser +util.pool = require(6); + +// utility to work with the low and high bits of a 64 bit value +util.LongBits = require(14); + +/** + * Whether running within node or not. + * @memberof util + * @type {boolean} + */ +util.isNode = Boolean(typeof global !== "undefined" + && global + && global.process + && global.process.versions + && global.process.versions.node); + +/** + * Global object reference. + * @memberof util + * @type {Object} + */ +util.global = util.isNode && global + || typeof window !== "undefined" && window + || typeof self !== "undefined" && self + || this; // eslint-disable-line no-invalid-this + +/** + * An immuable empty array. + * @memberof util + * @type {Array.<*>} + * @const + */ +util.emptyArray = Object.freeze ? Object.freeze([]) : /* istanbul ignore next */ []; // used on prototypes + +/** + * An immutable empty object. + * @type {Object} + * @const + */ +util.emptyObject = Object.freeze ? Object.freeze({}) : /* istanbul ignore next */ {}; // used on prototypes + +/** + * Tests if the specified value is an integer. + * @function + * @param {*} value Value to test + * @returns {boolean} `true` if the value is an integer + */ +util.isInteger = Number.isInteger || /* istanbul ignore next */ function isInteger(value) { + return typeof value === "number" && isFinite(value) && Math.floor(value) === value; +}; + +/** + * Tests if the specified value is a string. + * @param {*} value Value to test + * @returns {boolean} `true` if the value is a string + */ +util.isString = function isString(value) { + return typeof value === "string" || value instanceof String; +}; + +/** + * Tests if the specified value is a non-null object. + * @param {*} value Value to test + * @returns {boolean} `true` if the value is a non-null object + */ +util.isObject = function isObject(value) { + return value && typeof value === "object"; +}; + +/** + * Checks if a property on a message is considered to be present. + * This is an alias of {@link util.isSet}. + * @function + * @param {Object} obj Plain object or message instance + * @param {string} prop Property name + * @returns {boolean} `true` if considered to be present, otherwise `false` + */ +util.isset = + +/** + * Checks if a property on a message is considered to be present. + * @param {Object} obj Plain object or message instance + * @param {string} prop Property name + * @returns {boolean} `true` if considered to be present, otherwise `false` + */ +util.isSet = function isSet(obj, prop) { + var value = obj[prop]; + if (value != null && obj.hasOwnProperty(prop)) // eslint-disable-line eqeqeq, no-prototype-builtins + return typeof value !== "object" || (Array.isArray(value) ? value.length : Object.keys(value).length) > 0; + return false; +}; + +/** + * Any compatible Buffer instance. + * This is a minimal stand-alone definition of a Buffer instance. The actual type is that exported by node's typings. + * @interface Buffer + * @extends Uint8Array + */ + +/** + * Node's Buffer class if available. + * @type {Constructor} + */ +util.Buffer = (function() { + try { + var Buffer = util.inquire("buffer").Buffer; + // refuse to use non-node buffers if not explicitly assigned (perf reasons): + return Buffer.prototype.utf8Write ? Buffer : /* istanbul ignore next */ null; + } catch (e) { + /* istanbul ignore next */ + return null; + } +})(); + +// Internal alias of or polyfull for Buffer.from. +util._Buffer_from = null; + +// Internal alias of or polyfill for Buffer.allocUnsafe. +util._Buffer_allocUnsafe = null; + +/** + * Creates a new buffer of whatever type supported by the environment. + * @param {number|number[]} [sizeOrArray=0] Buffer size or number array + * @returns {Uint8Array|Buffer} Buffer + */ +util.newBuffer = function newBuffer(sizeOrArray) { + /* istanbul ignore next */ + return typeof sizeOrArray === "number" + ? util.Buffer + ? util._Buffer_allocUnsafe(sizeOrArray) + : new util.Array(sizeOrArray) + : util.Buffer + ? util._Buffer_from(sizeOrArray) + : typeof Uint8Array === "undefined" + ? sizeOrArray + : new Uint8Array(sizeOrArray); +}; + +/** + * Array implementation used in the browser. `Uint8Array` if supported, otherwise `Array`. + * @type {Constructor} + */ +util.Array = typeof Uint8Array !== "undefined" ? Uint8Array /* istanbul ignore next */ : Array; + +/** + * Any compatible Long instance. + * This is a minimal stand-alone definition of a Long instance. The actual type is that exported by long.js. + * @interface Long + * @property {number} low Low bits + * @property {number} high High bits + * @property {boolean} unsigned Whether unsigned or not + */ + +/** + * Long.js's Long class if available. + * @type {Constructor} + */ +util.Long = /* istanbul ignore next */ util.global.dcodeIO && /* istanbul ignore next */ util.global.dcodeIO.Long + || /* istanbul ignore next */ util.global.Long + || util.inquire("long"); + +/** + * Regular expression used to verify 2 bit (`bool`) map keys. + * @type {RegExp} + * @const + */ +util.key2Re = /^true|false|0|1$/; + +/** + * Regular expression used to verify 32 bit (`int32` etc.) map keys. + * @type {RegExp} + * @const + */ +util.key32Re = /^-?(?:0|[1-9][0-9]*)$/; + +/** + * Regular expression used to verify 64 bit (`int64` etc.) map keys. + * @type {RegExp} + * @const + */ +util.key64Re = /^(?:[\\x00-\\xff]{8}|-?(?:0|[1-9][0-9]*))$/; + +/** + * Converts a number or long to an 8 characters long hash string. + * @param {Long|number} value Value to convert + * @returns {string} Hash + */ +util.longToHash = function longToHash(value) { + return value + ? util.LongBits.from(value).toHash() + : util.LongBits.zeroHash; +}; + +/** + * Converts an 8 characters long hash string to a long or number. + * @param {string} hash Hash + * @param {boolean} [unsigned=false] Whether unsigned or not + * @returns {Long|number} Original value + */ +util.longFromHash = function longFromHash(hash, unsigned) { + var bits = util.LongBits.fromHash(hash); + if (util.Long) + return util.Long.fromBits(bits.lo, bits.hi, unsigned); + return bits.toNumber(Boolean(unsigned)); +}; + +/** + * Merges the properties of the source object into the destination object. + * @memberof util + * @param {Object.} dst Destination object + * @param {Object.} src Source object + * @param {boolean} [ifNotSet=false] Merges only if the key is not already set + * @returns {Object.} Destination object + */ +function merge(dst, src, ifNotSet) { // used by converters + for (var keys = Object.keys(src), i = 0; i < keys.length; ++i) + if (dst[keys[i]] === undefined || !ifNotSet) + dst[keys[i]] = src[keys[i]]; + return dst; +} + +util.merge = merge; + +/** + * Converts the first character of a string to lower case. + * @param {string} str String to convert + * @returns {string} Converted string + */ +util.lcFirst = function lcFirst(str) { + return str.charAt(0).toLowerCase() + str.substring(1); +}; + +/** + * Creates a custom error constructor. + * @memberof util + * @param {string} name Error name + * @returns {Constructor} Custom error constructor + */ +function newError(name) { + + function CustomError(message, properties) { + + if (!(this instanceof CustomError)) + return new CustomError(message, properties); + + // Error.call(this, message); + // ^ just returns a new error instance because the ctor can be called as a function + + Object.defineProperty(this, "message", { get: function() { return message; } }); + + /* istanbul ignore next */ + if (Error.captureStackTrace) // node + Error.captureStackTrace(this, CustomError); + else + Object.defineProperty(this, "stack", { value: new Error().stack || "" }); + + if (properties) + merge(this, properties); + } + + CustomError.prototype = Object.create(Error.prototype, { + constructor: { + value: CustomError, + writable: true, + enumerable: false, + configurable: true, + }, + name: { + get: function get() { return name; }, + set: undefined, + enumerable: false, + // configurable: false would accurately preserve the behavior of + // the original, but I'm guessing that was not intentional. + // For an actual error subclass, this property would + // be configurable. + configurable: true, + }, + toString: { + value: function value() { return this.name + ": " + this.message; }, + writable: true, + enumerable: false, + configurable: true, + }, + }); + + return CustomError; +} + +util.newError = newError; + +/** + * Constructs a new protocol error. + * @classdesc Error subclass indicating a protocol specifc error. + * @memberof util + * @extends Error + * @template T extends Message + * @constructor + * @param {string} message Error message + * @param {Object.} [properties] Additional properties + * @example + * try { + * MyMessage.decode(someBuffer); // throws if required fields are missing + * } catch (e) { + * if (e instanceof ProtocolError && e.instance) + * console.log("decoded so far: " + JSON.stringify(e.instance)); + * } + */ +util.ProtocolError = newError("ProtocolError"); + +/** + * So far decoded message instance. + * @name util.ProtocolError#instance + * @type {Message} + */ + +/** + * A OneOf getter as returned by {@link util.oneOfGetter}. + * @typedef OneOfGetter + * @type {function} + * @returns {string|undefined} Set field name, if any + */ + +/** + * Builds a getter for a oneof's present field name. + * @param {string[]} fieldNames Field names + * @returns {OneOfGetter} Unbound getter + */ +util.oneOfGetter = function getOneOf(fieldNames) { + var fieldMap = {}; + for (var i = 0; i < fieldNames.length; ++i) + fieldMap[fieldNames[i]] = 1; + + /** + * @returns {string|undefined} Set field name, if any + * @this Object + * @ignore + */ + return function() { // eslint-disable-line consistent-return + for (var keys = Object.keys(this), i = keys.length - 1; i > -1; --i) + if (fieldMap[keys[i]] === 1 && this[keys[i]] !== undefined && this[keys[i]] !== null) + return keys[i]; + }; +}; + +/** + * A OneOf setter as returned by {@link util.oneOfSetter}. + * @typedef OneOfSetter + * @type {function} + * @param {string|undefined} value Field name + * @returns {undefined} + */ + +/** + * Builds a setter for a oneof's present field name. + * @param {string[]} fieldNames Field names + * @returns {OneOfSetter} Unbound setter + */ +util.oneOfSetter = function setOneOf(fieldNames) { + + /** + * @param {string} name Field name + * @returns {undefined} + * @this Object + * @ignore + */ + return function(name) { + for (var i = 0; i < fieldNames.length; ++i) + if (fieldNames[i] !== name) + delete this[fieldNames[i]]; + }; +}; + +/** + * Default conversion options used for {@link Message#toJSON} implementations. + * + * These options are close to proto3's JSON mapping with the exception that internal types like Any are handled just like messages. More precisely: + * + * - Longs become strings + * - Enums become string keys + * - Bytes become base64 encoded strings + * - (Sub-)Messages become plain objects + * - Maps become plain objects with all string keys + * - Repeated fields become arrays + * - NaN and Infinity for float and double fields become strings + * + * @type {IConversionOptions} + * @see https://developers.google.com/protocol-buffers/docs/proto3?hl=en#json + */ +util.toJSONOptions = { + longs: String, + enums: String, + bytes: String, + json: true +}; + +// Sets up buffer utility according to the environment (called in index-minimal) +util._configure = function() { + var Buffer = util.Buffer; + /* istanbul ignore if */ + if (!Buffer) { + util._Buffer_from = util._Buffer_allocUnsafe = null; + return; + } + // because node 4.x buffers are incompatible & immutable + // see: https://github.com/dcodeIO/protobuf.js/pull/665 + util._Buffer_from = Buffer.from !== Uint8Array.from && Buffer.from || + /* istanbul ignore next */ + function Buffer_from(value, encoding) { + return new Buffer(value, encoding); + }; + util._Buffer_allocUnsafe = Buffer.allocUnsafe || + /* istanbul ignore next */ + function Buffer_allocUnsafe(size) { + return new Buffer(size); + }; +}; + +},{"1":1,"14":14,"2":2,"3":3,"4":4,"5":5,"6":6,"7":7}],16:[function(require,module,exports){ +"use strict"; +module.exports = Writer; + +var util = require(15); + +var BufferWriter; // cyclic + +var LongBits = util.LongBits, + base64 = util.base64, + utf8 = util.utf8; + +/** + * Constructs a new writer operation instance. + * @classdesc Scheduled writer operation. + * @constructor + * @param {function(*, Uint8Array, number)} fn Function to call + * @param {number} len Value byte length + * @param {*} val Value to write + * @ignore + */ +function Op(fn, len, val) { + + /** + * Function to call. + * @type {function(Uint8Array, number, *)} + */ + this.fn = fn; + + /** + * Value byte length. + * @type {number} + */ + this.len = len; + + /** + * Next operation. + * @type {Writer.Op|undefined} + */ + this.next = undefined; + + /** + * Value to write. + * @type {*} + */ + this.val = val; // type varies +} + +/* istanbul ignore next */ +function noop() {} // eslint-disable-line no-empty-function + +/** + * Constructs a new writer state instance. + * @classdesc Copied writer state. + * @memberof Writer + * @constructor + * @param {Writer} writer Writer to copy state from + * @ignore + */ +function State(writer) { + + /** + * Current head. + * @type {Writer.Op} + */ + this.head = writer.head; + + /** + * Current tail. + * @type {Writer.Op} + */ + this.tail = writer.tail; + + /** + * Current buffer length. + * @type {number} + */ + this.len = writer.len; + + /** + * Next state. + * @type {State|null} + */ + this.next = writer.states; +} + +/** + * Constructs a new writer instance. + * @classdesc Wire format writer using `Uint8Array` if available, otherwise `Array`. + * @constructor + */ +function Writer() { + + /** + * Current length. + * @type {number} + */ + this.len = 0; + + /** + * Operations head. + * @type {Object} + */ + this.head = new Op(noop, 0, 0); + + /** + * Operations tail + * @type {Object} + */ + this.tail = this.head; + + /** + * Linked forked states. + * @type {Object|null} + */ + this.states = null; + + // When a value is written, the writer calculates its byte length and puts it into a linked + // list of operations to perform when finish() is called. This both allows us to allocate + // buffers of the exact required size and reduces the amount of work we have to do compared + // to first calculating over objects and then encoding over objects. In our case, the encoding + // part is just a linked list walk calling operations with already prepared values. +} + +var create = function create() { + return util.Buffer + ? function create_buffer_setup() { + return (Writer.create = function create_buffer() { + return new BufferWriter(); + })(); + } + /* istanbul ignore next */ + : function create_array() { + return new Writer(); + }; +}; + +/** + * Creates a new writer. + * @function + * @returns {BufferWriter|Writer} A {@link BufferWriter} when Buffers are supported, otherwise a {@link Writer} + */ +Writer.create = create(); + +/** + * Allocates a buffer of the specified size. + * @param {number} size Buffer size + * @returns {Uint8Array} Buffer + */ +Writer.alloc = function alloc(size) { + return new util.Array(size); +}; + +// Use Uint8Array buffer pool in the browser, just like node does with buffers +/* istanbul ignore else */ +if (util.Array !== Array) + Writer.alloc = util.pool(Writer.alloc, util.Array.prototype.subarray); + +/** + * Pushes a new operation to the queue. + * @param {function(Uint8Array, number, *)} fn Function to call + * @param {number} len Value byte length + * @param {number} val Value to write + * @returns {Writer} `this` + * @private + */ +Writer.prototype._push = function push(fn, len, val) { + this.tail = this.tail.next = new Op(fn, len, val); + this.len += len; + return this; +}; + +function writeByte(val, buf, pos) { + buf[pos] = val & 255; +} + +function writeVarint32(val, buf, pos) { + while (val > 127) { + buf[pos++] = val & 127 | 128; + val >>>= 7; + } + buf[pos] = val; +} + +/** + * Constructs a new varint writer operation instance. + * @classdesc Scheduled varint writer operation. + * @extends Op + * @constructor + * @param {number} len Value byte length + * @param {number} val Value to write + * @ignore + */ +function VarintOp(len, val) { + this.len = len; + this.next = undefined; + this.val = val; +} + +VarintOp.prototype = Object.create(Op.prototype); +VarintOp.prototype.fn = writeVarint32; + +/** + * Writes an unsigned 32 bit value as a varint. + * @param {number} value Value to write + * @returns {Writer} `this` + */ +Writer.prototype.uint32 = function write_uint32(value) { + // here, the call to this.push has been inlined and a varint specific Op subclass is used. + // uint32 is by far the most frequently used operation and benefits significantly from this. + this.len += (this.tail = this.tail.next = new VarintOp( + (value = value >>> 0) + < 128 ? 1 + : value < 16384 ? 2 + : value < 2097152 ? 3 + : value < 268435456 ? 4 + : 5, + value)).len; + return this; +}; + +/** + * Writes a signed 32 bit value as a varint. + * @function + * @param {number} value Value to write + * @returns {Writer} `this` + */ +Writer.prototype.int32 = function write_int32(value) { + return value < 0 + ? this._push(writeVarint64, 10, LongBits.fromNumber(value)) // 10 bytes per spec + : this.uint32(value); +}; + +/** + * Writes a 32 bit value as a varint, zig-zag encoded. + * @param {number} value Value to write + * @returns {Writer} `this` + */ +Writer.prototype.sint32 = function write_sint32(value) { + return this.uint32((value << 1 ^ value >> 31) >>> 0); +}; + +function writeVarint64(val, buf, pos) { + while (val.hi) { + buf[pos++] = val.lo & 127 | 128; + val.lo = (val.lo >>> 7 | val.hi << 25) >>> 0; + val.hi >>>= 7; + } + while (val.lo > 127) { + buf[pos++] = val.lo & 127 | 128; + val.lo = val.lo >>> 7; + } + buf[pos++] = val.lo; +} + +/** + * Writes an unsigned 64 bit value as a varint. + * @param {Long|number|string} value Value to write + * @returns {Writer} `this` + * @throws {TypeError} If `value` is a string and no long library is present. + */ +Writer.prototype.uint64 = function write_uint64(value) { + var bits = LongBits.from(value); + return this._push(writeVarint64, bits.length(), bits); +}; + +/** + * Writes a signed 64 bit value as a varint. + * @function + * @param {Long|number|string} value Value to write + * @returns {Writer} `this` + * @throws {TypeError} If `value` is a string and no long library is present. + */ +Writer.prototype.int64 = Writer.prototype.uint64; + +/** + * Writes a signed 64 bit value as a varint, zig-zag encoded. + * @param {Long|number|string} value Value to write + * @returns {Writer} `this` + * @throws {TypeError} If `value` is a string and no long library is present. + */ +Writer.prototype.sint64 = function write_sint64(value) { + var bits = LongBits.from(value).zzEncode(); + return this._push(writeVarint64, bits.length(), bits); +}; + +/** + * Writes a boolish value as a varint. + * @param {boolean} value Value to write + * @returns {Writer} `this` + */ +Writer.prototype.bool = function write_bool(value) { + return this._push(writeByte, 1, value ? 1 : 0); +}; + +function writeFixed32(val, buf, pos) { + buf[pos ] = val & 255; + buf[pos + 1] = val >>> 8 & 255; + buf[pos + 2] = val >>> 16 & 255; + buf[pos + 3] = val >>> 24; +} + +/** + * Writes an unsigned 32 bit value as fixed 32 bits. + * @param {number} value Value to write + * @returns {Writer} `this` + */ +Writer.prototype.fixed32 = function write_fixed32(value) { + return this._push(writeFixed32, 4, value >>> 0); +}; + +/** + * Writes a signed 32 bit value as fixed 32 bits. + * @function + * @param {number} value Value to write + * @returns {Writer} `this` + */ +Writer.prototype.sfixed32 = Writer.prototype.fixed32; + +/** + * Writes an unsigned 64 bit value as fixed 64 bits. + * @param {Long|number|string} value Value to write + * @returns {Writer} `this` + * @throws {TypeError} If `value` is a string and no long library is present. + */ +Writer.prototype.fixed64 = function write_fixed64(value) { + var bits = LongBits.from(value); + return this._push(writeFixed32, 4, bits.lo)._push(writeFixed32, 4, bits.hi); +}; + +/** + * Writes a signed 64 bit value as fixed 64 bits. + * @function + * @param {Long|number|string} value Value to write + * @returns {Writer} `this` + * @throws {TypeError} If `value` is a string and no long library is present. + */ +Writer.prototype.sfixed64 = Writer.prototype.fixed64; + +/** + * Writes a float (32 bit). + * @function + * @param {number} value Value to write + * @returns {Writer} `this` + */ +Writer.prototype.float = function write_float(value) { + return this._push(util.float.writeFloatLE, 4, value); +}; + +/** + * Writes a double (64 bit float). + * @function + * @param {number} value Value to write + * @returns {Writer} `this` + */ +Writer.prototype.double = function write_double(value) { + return this._push(util.float.writeDoubleLE, 8, value); +}; + +var writeBytes = util.Array.prototype.set + ? function writeBytes_set(val, buf, pos) { + buf.set(val, pos); // also works for plain array values + } + /* istanbul ignore next */ + : function writeBytes_for(val, buf, pos) { + for (var i = 0; i < val.length; ++i) + buf[pos + i] = val[i]; + }; + +/** + * Writes a sequence of bytes. + * @param {Uint8Array|string} value Buffer or base64 encoded string to write + * @returns {Writer} `this` + */ +Writer.prototype.bytes = function write_bytes(value) { + var len = value.length >>> 0; + if (!len) + return this._push(writeByte, 1, 0); + if (util.isString(value)) { + var buf = Writer.alloc(len = base64.length(value)); + base64.decode(value, buf, 0); + value = buf; + } + return this.uint32(len)._push(writeBytes, len, value); +}; + +/** + * Writes a string. + * @param {string} value Value to write + * @returns {Writer} `this` + */ +Writer.prototype.string = function write_string(value) { + var len = utf8.length(value); + return len + ? this.uint32(len)._push(utf8.write, len, value) + : this._push(writeByte, 1, 0); +}; + +/** + * Forks this writer's state by pushing it to a stack. + * Calling {@link Writer#reset|reset} or {@link Writer#ldelim|ldelim} resets the writer to the previous state. + * @returns {Writer} `this` + */ +Writer.prototype.fork = function fork() { + this.states = new State(this); + this.head = this.tail = new Op(noop, 0, 0); + this.len = 0; + return this; +}; + +/** + * Resets this instance to the last state. + * @returns {Writer} `this` + */ +Writer.prototype.reset = function reset() { + if (this.states) { + this.head = this.states.head; + this.tail = this.states.tail; + this.len = this.states.len; + this.states = this.states.next; + } else { + this.head = this.tail = new Op(noop, 0, 0); + this.len = 0; + } + return this; +}; + +/** + * Resets to the last state and appends the fork state's current write length as a varint followed by its operations. + * @returns {Writer} `this` + */ +Writer.prototype.ldelim = function ldelim() { + var head = this.head, + tail = this.tail, + len = this.len; + this.reset().uint32(len); + if (len) { + this.tail.next = head.next; // skip noop + this.tail = tail; + this.len += len; + } + return this; +}; + +/** + * Finishes the write operation. + * @returns {Uint8Array} Finished buffer + */ +Writer.prototype.finish = function finish() { + var head = this.head.next, // skip noop + buf = this.constructor.alloc(this.len), + pos = 0; + while (head) { + head.fn(head.val, buf, pos); + pos += head.len; + head = head.next; + } + // this.head = this.tail = null; + return buf; +}; + +Writer._configure = function(BufferWriter_) { + BufferWriter = BufferWriter_; + Writer.create = create(); + BufferWriter._configure(); +}; + +},{"15":15}],17:[function(require,module,exports){ +"use strict"; +module.exports = BufferWriter; + +// extends Writer +var Writer = require(16); +(BufferWriter.prototype = Object.create(Writer.prototype)).constructor = BufferWriter; + +var util = require(15); + +/** + * Constructs a new buffer writer instance. + * @classdesc Wire format writer using node buffers. + * @extends Writer + * @constructor + */ +function BufferWriter() { + Writer.call(this); +} + +BufferWriter._configure = function () { + /** + * Allocates a buffer of the specified size. + * @function + * @param {number} size Buffer size + * @returns {Buffer} Buffer + */ + BufferWriter.alloc = util._Buffer_allocUnsafe; + + BufferWriter.writeBytesBuffer = util.Buffer && util.Buffer.prototype instanceof Uint8Array && util.Buffer.prototype.set.name === "set" + ? function writeBytesBuffer_set(val, buf, pos) { + buf.set(val, pos); // faster than copy (requires node >= 4 where Buffers extend Uint8Array and set is properly inherited) + // also works for plain array values + } + /* istanbul ignore next */ + : function writeBytesBuffer_copy(val, buf, pos) { + if (val.copy) // Buffer values + val.copy(buf, pos, 0, val.length); + else for (var i = 0; i < val.length;) // plain array values + buf[pos++] = val[i++]; + }; +}; + + +/** + * @override + */ +BufferWriter.prototype.bytes = function write_bytes_buffer(value) { + if (util.isString(value)) + value = util._Buffer_from(value, "base64"); + var len = value.length >>> 0; + this.uint32(len); + if (len) + this._push(BufferWriter.writeBytesBuffer, len, value); + return this; +}; + +function writeStringBuffer(val, buf, pos) { + if (val.length < 40) // plain js is faster for short strings (probably due to redundant assertions) + util.utf8.write(val, buf, pos); + else if (buf.utf8Write) + buf.utf8Write(val, pos); + else + buf.write(val, pos); +} + +/** + * @override + */ +BufferWriter.prototype.string = function write_string_buffer(value) { + var len = util.Buffer.byteLength(value); + this.uint32(len); + if (len) + this._push(writeStringBuffer, len, value); + return this; +}; + + +/** + * Finishes the write operation. + * @name BufferWriter#finish + * @function + * @returns {Buffer} Finished buffer + */ + +BufferWriter._configure(); + +},{"15":15,"16":16}]},{},[8]) + +})(); +//# sourceMappingURL=protobuf.js.map diff --git a/node_modules/protobufjs/dist/minimal/protobuf.js.map b/node_modules/protobufjs/dist/minimal/protobuf.js.map new file mode 100644 index 0000000..e9dfbe7 --- /dev/null +++ b/node_modules/protobufjs/dist/minimal/protobuf.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["lib/prelude.js","../node_modules/@protobufjs/aspromise/index.js","../node_modules/@protobufjs/base64/index.js","../node_modules/@protobufjs/eventemitter/index.js","../node_modules/@protobufjs/float/index.js","../node_modules/@protobufjs/inquire/index.js","../node_modules/@protobufjs/pool/index.js","../node_modules/@protobufjs/utf8/index.js","../src/index-minimal","../src/reader.js","../src/reader_buffer.js","../src/roots.js","../src/rpc.js","../src/rpc/service.js","../src/util/longbits.js","../src/util/minimal.js","../src/writer.js","../src/writer_buffer.js"],"names":[],"mappings":";;;;;;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;ACjCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACpDA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC3IA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC5EA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC/UA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACjBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AChDA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACzGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACpCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AChaA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACnDA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AClBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACpCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC9IA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACxMA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACtbA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACjdA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA","file":"protobuf.js","sourcesContent":["(function prelude(modules, cache, entries) {\n\n // This is the prelude used to bundle protobuf.js for the browser. Wraps up the CommonJS\n // sources through a conflict-free require shim and is again wrapped within an iife that\n // provides a minification-friendly `undefined` var plus a global \"use strict\" directive\n // so that minification can remove the directives of each module.\n\n function $require(name) {\n var $module = cache[name];\n if (!$module)\n modules[name][0].call($module = cache[name] = { exports: {} }, $require, $module, $module.exports);\n return $module.exports;\n }\n\n var protobuf = $require(entries[0]);\n\n // Expose globally\n protobuf.util.global.protobuf = protobuf;\n\n // Be nice to AMD\n if (typeof define === \"function\" && define.amd)\n define([\"long\"], function(Long) {\n if (Long && Long.isLong) {\n protobuf.util.Long = Long;\n protobuf.configure();\n }\n return protobuf;\n });\n\n // Be nice to CommonJS\n if (typeof module === \"object\" && module && module.exports)\n module.exports = protobuf;\n\n})/* end of prelude */","\"use strict\";\r\nmodule.exports = asPromise;\r\n\r\n/**\r\n * Callback as used by {@link util.asPromise}.\r\n * @typedef asPromiseCallback\r\n * @type {function}\r\n * @param {Error|null} error Error, if any\r\n * @param {...*} params Additional arguments\r\n * @returns {undefined}\r\n */\r\n\r\n/**\r\n * Returns a promise from a node-style callback function.\r\n * @memberof util\r\n * @param {asPromiseCallback} fn Function to call\r\n * @param {*} ctx Function context\r\n * @param {...*} params Function arguments\r\n * @returns {Promise<*>} Promisified function\r\n */\r\nfunction asPromise(fn, ctx/*, varargs */) {\r\n var params = new Array(arguments.length - 1),\r\n offset = 0,\r\n index = 2,\r\n pending = true;\r\n while (index < arguments.length)\r\n params[offset++] = arguments[index++];\r\n return new Promise(function executor(resolve, reject) {\r\n params[offset] = function callback(err/*, varargs */) {\r\n if (pending) {\r\n pending = false;\r\n if (err)\r\n reject(err);\r\n else {\r\n var params = new Array(arguments.length - 1),\r\n offset = 0;\r\n while (offset < params.length)\r\n params[offset++] = arguments[offset];\r\n resolve.apply(null, params);\r\n }\r\n }\r\n };\r\n try {\r\n fn.apply(ctx || null, params);\r\n } catch (err) {\r\n if (pending) {\r\n pending = false;\r\n reject(err);\r\n }\r\n }\r\n });\r\n}\r\n","\"use strict\";\r\n\r\n/**\r\n * A minimal base64 implementation for number arrays.\r\n * @memberof util\r\n * @namespace\r\n */\r\nvar base64 = exports;\r\n\r\n/**\r\n * Calculates the byte length of a base64 encoded string.\r\n * @param {string} string Base64 encoded string\r\n * @returns {number} Byte length\r\n */\r\nbase64.length = function length(string) {\r\n var p = string.length;\r\n if (!p)\r\n return 0;\r\n var n = 0;\r\n while (--p % 4 > 1 && string.charAt(p) === \"=\")\r\n ++n;\r\n return Math.ceil(string.length * 3) / 4 - n;\r\n};\r\n\r\n// Base64 encoding table\r\nvar b64 = new Array(64);\r\n\r\n// Base64 decoding table\r\nvar s64 = new Array(123);\r\n\r\n// 65..90, 97..122, 48..57, 43, 47\r\nfor (var i = 0; i < 64;)\r\n s64[b64[i] = i < 26 ? i + 65 : i < 52 ? i + 71 : i < 62 ? i - 4 : i - 59 | 43] = i++;\r\n\r\n/**\r\n * Encodes a buffer to a base64 encoded string.\r\n * @param {Uint8Array} buffer Source buffer\r\n * @param {number} start Source start\r\n * @param {number} end Source end\r\n * @returns {string} Base64 encoded string\r\n */\r\nbase64.encode = function encode(buffer, start, end) {\r\n var parts = null,\r\n chunk = [];\r\n var i = 0, // output index\r\n j = 0, // goto index\r\n t; // temporary\r\n while (start < end) {\r\n var b = buffer[start++];\r\n switch (j) {\r\n case 0:\r\n chunk[i++] = b64[b >> 2];\r\n t = (b & 3) << 4;\r\n j = 1;\r\n break;\r\n case 1:\r\n chunk[i++] = b64[t | b >> 4];\r\n t = (b & 15) << 2;\r\n j = 2;\r\n break;\r\n case 2:\r\n chunk[i++] = b64[t | b >> 6];\r\n chunk[i++] = b64[b & 63];\r\n j = 0;\r\n break;\r\n }\r\n if (i > 8191) {\r\n (parts || (parts = [])).push(String.fromCharCode.apply(String, chunk));\r\n i = 0;\r\n }\r\n }\r\n if (j) {\r\n chunk[i++] = b64[t];\r\n chunk[i++] = 61;\r\n if (j === 1)\r\n chunk[i++] = 61;\r\n }\r\n if (parts) {\r\n if (i)\r\n parts.push(String.fromCharCode.apply(String, chunk.slice(0, i)));\r\n return parts.join(\"\");\r\n }\r\n return String.fromCharCode.apply(String, chunk.slice(0, i));\r\n};\r\n\r\nvar invalidEncoding = \"invalid encoding\";\r\n\r\n/**\r\n * Decodes a base64 encoded string to a buffer.\r\n * @param {string} string Source string\r\n * @param {Uint8Array} buffer Destination buffer\r\n * @param {number} offset Destination offset\r\n * @returns {number} Number of bytes written\r\n * @throws {Error} If encoding is invalid\r\n */\r\nbase64.decode = function decode(string, buffer, offset) {\r\n var start = offset;\r\n var j = 0, // goto index\r\n t; // temporary\r\n for (var i = 0; i < string.length;) {\r\n var c = string.charCodeAt(i++);\r\n if (c === 61 && j > 1)\r\n break;\r\n if ((c = s64[c]) === undefined)\r\n throw Error(invalidEncoding);\r\n switch (j) {\r\n case 0:\r\n t = c;\r\n j = 1;\r\n break;\r\n case 1:\r\n buffer[offset++] = t << 2 | (c & 48) >> 4;\r\n t = c;\r\n j = 2;\r\n break;\r\n case 2:\r\n buffer[offset++] = (t & 15) << 4 | (c & 60) >> 2;\r\n t = c;\r\n j = 3;\r\n break;\r\n case 3:\r\n buffer[offset++] = (t & 3) << 6 | c;\r\n j = 0;\r\n break;\r\n }\r\n }\r\n if (j === 1)\r\n throw Error(invalidEncoding);\r\n return offset - start;\r\n};\r\n\r\n/**\r\n * Tests if the specified string appears to be base64 encoded.\r\n * @param {string} string String to test\r\n * @returns {boolean} `true` if probably base64 encoded, otherwise false\r\n */\r\nbase64.test = function test(string) {\r\n return /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(string);\r\n};\r\n","\"use strict\";\r\nmodule.exports = EventEmitter;\r\n\r\n/**\r\n * Constructs a new event emitter instance.\r\n * @classdesc A minimal event emitter.\r\n * @memberof util\r\n * @constructor\r\n */\r\nfunction EventEmitter() {\r\n\r\n /**\r\n * Registered listeners.\r\n * @type {Object.}\r\n * @private\r\n */\r\n this._listeners = {};\r\n}\r\n\r\n/**\r\n * Registers an event listener.\r\n * @param {string} evt Event name\r\n * @param {function} fn Listener\r\n * @param {*} [ctx] Listener context\r\n * @returns {util.EventEmitter} `this`\r\n */\r\nEventEmitter.prototype.on = function on(evt, fn, ctx) {\r\n (this._listeners[evt] || (this._listeners[evt] = [])).push({\r\n fn : fn,\r\n ctx : ctx || this\r\n });\r\n return this;\r\n};\r\n\r\n/**\r\n * Removes an event listener or any matching listeners if arguments are omitted.\r\n * @param {string} [evt] Event name. Removes all listeners if omitted.\r\n * @param {function} [fn] Listener to remove. Removes all listeners of `evt` if omitted.\r\n * @returns {util.EventEmitter} `this`\r\n */\r\nEventEmitter.prototype.off = function off(evt, fn) {\r\n if (evt === undefined)\r\n this._listeners = {};\r\n else {\r\n if (fn === undefined)\r\n this._listeners[evt] = [];\r\n else {\r\n var listeners = this._listeners[evt];\r\n for (var i = 0; i < listeners.length;)\r\n if (listeners[i].fn === fn)\r\n listeners.splice(i, 1);\r\n else\r\n ++i;\r\n }\r\n }\r\n return this;\r\n};\r\n\r\n/**\r\n * Emits an event by calling its listeners with the specified arguments.\r\n * @param {string} evt Event name\r\n * @param {...*} args Arguments\r\n * @returns {util.EventEmitter} `this`\r\n */\r\nEventEmitter.prototype.emit = function emit(evt) {\r\n var listeners = this._listeners[evt];\r\n if (listeners) {\r\n var args = [],\r\n i = 1;\r\n for (; i < arguments.length;)\r\n args.push(arguments[i++]);\r\n for (i = 0; i < listeners.length;)\r\n listeners[i].fn.apply(listeners[i++].ctx, args);\r\n }\r\n return this;\r\n};\r\n","\"use strict\";\r\n\r\nmodule.exports = factory(factory);\r\n\r\n/**\r\n * Reads / writes floats / doubles from / to buffers.\r\n * @name util.float\r\n * @namespace\r\n */\r\n\r\n/**\r\n * Writes a 32 bit float to a buffer using little endian byte order.\r\n * @name util.float.writeFloatLE\r\n * @function\r\n * @param {number} val Value to write\r\n * @param {Uint8Array} buf Target buffer\r\n * @param {number} pos Target buffer offset\r\n * @returns {undefined}\r\n */\r\n\r\n/**\r\n * Writes a 32 bit float to a buffer using big endian byte order.\r\n * @name util.float.writeFloatBE\r\n * @function\r\n * @param {number} val Value to write\r\n * @param {Uint8Array} buf Target buffer\r\n * @param {number} pos Target buffer offset\r\n * @returns {undefined}\r\n */\r\n\r\n/**\r\n * Reads a 32 bit float from a buffer using little endian byte order.\r\n * @name util.float.readFloatLE\r\n * @function\r\n * @param {Uint8Array} buf Source buffer\r\n * @param {number} pos Source buffer offset\r\n * @returns {number} Value read\r\n */\r\n\r\n/**\r\n * Reads a 32 bit float from a buffer using big endian byte order.\r\n * @name util.float.readFloatBE\r\n * @function\r\n * @param {Uint8Array} buf Source buffer\r\n * @param {number} pos Source buffer offset\r\n * @returns {number} Value read\r\n */\r\n\r\n/**\r\n * Writes a 64 bit double to a buffer using little endian byte order.\r\n * @name util.float.writeDoubleLE\r\n * @function\r\n * @param {number} val Value to write\r\n * @param {Uint8Array} buf Target buffer\r\n * @param {number} pos Target buffer offset\r\n * @returns {undefined}\r\n */\r\n\r\n/**\r\n * Writes a 64 bit double to a buffer using big endian byte order.\r\n * @name util.float.writeDoubleBE\r\n * @function\r\n * @param {number} val Value to write\r\n * @param {Uint8Array} buf Target buffer\r\n * @param {number} pos Target buffer offset\r\n * @returns {undefined}\r\n */\r\n\r\n/**\r\n * Reads a 64 bit double from a buffer using little endian byte order.\r\n * @name util.float.readDoubleLE\r\n * @function\r\n * @param {Uint8Array} buf Source buffer\r\n * @param {number} pos Source buffer offset\r\n * @returns {number} Value read\r\n */\r\n\r\n/**\r\n * Reads a 64 bit double from a buffer using big endian byte order.\r\n * @name util.float.readDoubleBE\r\n * @function\r\n * @param {Uint8Array} buf Source buffer\r\n * @param {number} pos Source buffer offset\r\n * @returns {number} Value read\r\n */\r\n\r\n// Factory function for the purpose of node-based testing in modified global environments\r\nfunction factory(exports) {\r\n\r\n // float: typed array\r\n if (typeof Float32Array !== \"undefined\") (function() {\r\n\r\n var f32 = new Float32Array([ -0 ]),\r\n f8b = new Uint8Array(f32.buffer),\r\n le = f8b[3] === 128;\r\n\r\n function writeFloat_f32_cpy(val, buf, pos) {\r\n f32[0] = val;\r\n buf[pos ] = f8b[0];\r\n buf[pos + 1] = f8b[1];\r\n buf[pos + 2] = f8b[2];\r\n buf[pos + 3] = f8b[3];\r\n }\r\n\r\n function writeFloat_f32_rev(val, buf, pos) {\r\n f32[0] = val;\r\n buf[pos ] = f8b[3];\r\n buf[pos + 1] = f8b[2];\r\n buf[pos + 2] = f8b[1];\r\n buf[pos + 3] = f8b[0];\r\n }\r\n\r\n /* istanbul ignore next */\r\n exports.writeFloatLE = le ? writeFloat_f32_cpy : writeFloat_f32_rev;\r\n /* istanbul ignore next */\r\n exports.writeFloatBE = le ? writeFloat_f32_rev : writeFloat_f32_cpy;\r\n\r\n function readFloat_f32_cpy(buf, pos) {\r\n f8b[0] = buf[pos ];\r\n f8b[1] = buf[pos + 1];\r\n f8b[2] = buf[pos + 2];\r\n f8b[3] = buf[pos + 3];\r\n return f32[0];\r\n }\r\n\r\n function readFloat_f32_rev(buf, pos) {\r\n f8b[3] = buf[pos ];\r\n f8b[2] = buf[pos + 1];\r\n f8b[1] = buf[pos + 2];\r\n f8b[0] = buf[pos + 3];\r\n return f32[0];\r\n }\r\n\r\n /* istanbul ignore next */\r\n exports.readFloatLE = le ? readFloat_f32_cpy : readFloat_f32_rev;\r\n /* istanbul ignore next */\r\n exports.readFloatBE = le ? readFloat_f32_rev : readFloat_f32_cpy;\r\n\r\n // float: ieee754\r\n })(); else (function() {\r\n\r\n function writeFloat_ieee754(writeUint, val, buf, pos) {\r\n var sign = val < 0 ? 1 : 0;\r\n if (sign)\r\n val = -val;\r\n if (val === 0)\r\n writeUint(1 / val > 0 ? /* positive */ 0 : /* negative 0 */ 2147483648, buf, pos);\r\n else if (isNaN(val))\r\n writeUint(2143289344, buf, pos);\r\n else if (val > 3.4028234663852886e+38) // +-Infinity\r\n writeUint((sign << 31 | 2139095040) >>> 0, buf, pos);\r\n else if (val < 1.1754943508222875e-38) // denormal\r\n writeUint((sign << 31 | Math.round(val / 1.401298464324817e-45)) >>> 0, buf, pos);\r\n else {\r\n var exponent = Math.floor(Math.log(val) / Math.LN2),\r\n mantissa = Math.round(val * Math.pow(2, -exponent) * 8388608) & 8388607;\r\n writeUint((sign << 31 | exponent + 127 << 23 | mantissa) >>> 0, buf, pos);\r\n }\r\n }\r\n\r\n exports.writeFloatLE = writeFloat_ieee754.bind(null, writeUintLE);\r\n exports.writeFloatBE = writeFloat_ieee754.bind(null, writeUintBE);\r\n\r\n function readFloat_ieee754(readUint, buf, pos) {\r\n var uint = readUint(buf, pos),\r\n sign = (uint >> 31) * 2 + 1,\r\n exponent = uint >>> 23 & 255,\r\n mantissa = uint & 8388607;\r\n return exponent === 255\r\n ? mantissa\r\n ? NaN\r\n : sign * Infinity\r\n : exponent === 0 // denormal\r\n ? sign * 1.401298464324817e-45 * mantissa\r\n : sign * Math.pow(2, exponent - 150) * (mantissa + 8388608);\r\n }\r\n\r\n exports.readFloatLE = readFloat_ieee754.bind(null, readUintLE);\r\n exports.readFloatBE = readFloat_ieee754.bind(null, readUintBE);\r\n\r\n })();\r\n\r\n // double: typed array\r\n if (typeof Float64Array !== \"undefined\") (function() {\r\n\r\n var f64 = new Float64Array([-0]),\r\n f8b = new Uint8Array(f64.buffer),\r\n le = f8b[7] === 128;\r\n\r\n function writeDouble_f64_cpy(val, buf, pos) {\r\n f64[0] = val;\r\n buf[pos ] = f8b[0];\r\n buf[pos + 1] = f8b[1];\r\n buf[pos + 2] = f8b[2];\r\n buf[pos + 3] = f8b[3];\r\n buf[pos + 4] = f8b[4];\r\n buf[pos + 5] = f8b[5];\r\n buf[pos + 6] = f8b[6];\r\n buf[pos + 7] = f8b[7];\r\n }\r\n\r\n function writeDouble_f64_rev(val, buf, pos) {\r\n f64[0] = val;\r\n buf[pos ] = f8b[7];\r\n buf[pos + 1] = f8b[6];\r\n buf[pos + 2] = f8b[5];\r\n buf[pos + 3] = f8b[4];\r\n buf[pos + 4] = f8b[3];\r\n buf[pos + 5] = f8b[2];\r\n buf[pos + 6] = f8b[1];\r\n buf[pos + 7] = f8b[0];\r\n }\r\n\r\n /* istanbul ignore next */\r\n exports.writeDoubleLE = le ? writeDouble_f64_cpy : writeDouble_f64_rev;\r\n /* istanbul ignore next */\r\n exports.writeDoubleBE = le ? writeDouble_f64_rev : writeDouble_f64_cpy;\r\n\r\n function readDouble_f64_cpy(buf, pos) {\r\n f8b[0] = buf[pos ];\r\n f8b[1] = buf[pos + 1];\r\n f8b[2] = buf[pos + 2];\r\n f8b[3] = buf[pos + 3];\r\n f8b[4] = buf[pos + 4];\r\n f8b[5] = buf[pos + 5];\r\n f8b[6] = buf[pos + 6];\r\n f8b[7] = buf[pos + 7];\r\n return f64[0];\r\n }\r\n\r\n function readDouble_f64_rev(buf, pos) {\r\n f8b[7] = buf[pos ];\r\n f8b[6] = buf[pos + 1];\r\n f8b[5] = buf[pos + 2];\r\n f8b[4] = buf[pos + 3];\r\n f8b[3] = buf[pos + 4];\r\n f8b[2] = buf[pos + 5];\r\n f8b[1] = buf[pos + 6];\r\n f8b[0] = buf[pos + 7];\r\n return f64[0];\r\n }\r\n\r\n /* istanbul ignore next */\r\n exports.readDoubleLE = le ? readDouble_f64_cpy : readDouble_f64_rev;\r\n /* istanbul ignore next */\r\n exports.readDoubleBE = le ? readDouble_f64_rev : readDouble_f64_cpy;\r\n\r\n // double: ieee754\r\n })(); else (function() {\r\n\r\n function writeDouble_ieee754(writeUint, off0, off1, val, buf, pos) {\r\n var sign = val < 0 ? 1 : 0;\r\n if (sign)\r\n val = -val;\r\n if (val === 0) {\r\n writeUint(0, buf, pos + off0);\r\n writeUint(1 / val > 0 ? /* positive */ 0 : /* negative 0 */ 2147483648, buf, pos + off1);\r\n } else if (isNaN(val)) {\r\n writeUint(0, buf, pos + off0);\r\n writeUint(2146959360, buf, pos + off1);\r\n } else if (val > 1.7976931348623157e+308) { // +-Infinity\r\n writeUint(0, buf, pos + off0);\r\n writeUint((sign << 31 | 2146435072) >>> 0, buf, pos + off1);\r\n } else {\r\n var mantissa;\r\n if (val < 2.2250738585072014e-308) { // denormal\r\n mantissa = val / 5e-324;\r\n writeUint(mantissa >>> 0, buf, pos + off0);\r\n writeUint((sign << 31 | mantissa / 4294967296) >>> 0, buf, pos + off1);\r\n } else {\r\n var exponent = Math.floor(Math.log(val) / Math.LN2);\r\n if (exponent === 1024)\r\n exponent = 1023;\r\n mantissa = val * Math.pow(2, -exponent);\r\n writeUint(mantissa * 4503599627370496 >>> 0, buf, pos + off0);\r\n writeUint((sign << 31 | exponent + 1023 << 20 | mantissa * 1048576 & 1048575) >>> 0, buf, pos + off1);\r\n }\r\n }\r\n }\r\n\r\n exports.writeDoubleLE = writeDouble_ieee754.bind(null, writeUintLE, 0, 4);\r\n exports.writeDoubleBE = writeDouble_ieee754.bind(null, writeUintBE, 4, 0);\r\n\r\n function readDouble_ieee754(readUint, off0, off1, buf, pos) {\r\n var lo = readUint(buf, pos + off0),\r\n hi = readUint(buf, pos + off1);\r\n var sign = (hi >> 31) * 2 + 1,\r\n exponent = hi >>> 20 & 2047,\r\n mantissa = 4294967296 * (hi & 1048575) + lo;\r\n return exponent === 2047\r\n ? mantissa\r\n ? NaN\r\n : sign * Infinity\r\n : exponent === 0 // denormal\r\n ? sign * 5e-324 * mantissa\r\n : sign * Math.pow(2, exponent - 1075) * (mantissa + 4503599627370496);\r\n }\r\n\r\n exports.readDoubleLE = readDouble_ieee754.bind(null, readUintLE, 0, 4);\r\n exports.readDoubleBE = readDouble_ieee754.bind(null, readUintBE, 4, 0);\r\n\r\n })();\r\n\r\n return exports;\r\n}\r\n\r\n// uint helpers\r\n\r\nfunction writeUintLE(val, buf, pos) {\r\n buf[pos ] = val & 255;\r\n buf[pos + 1] = val >>> 8 & 255;\r\n buf[pos + 2] = val >>> 16 & 255;\r\n buf[pos + 3] = val >>> 24;\r\n}\r\n\r\nfunction writeUintBE(val, buf, pos) {\r\n buf[pos ] = val >>> 24;\r\n buf[pos + 1] = val >>> 16 & 255;\r\n buf[pos + 2] = val >>> 8 & 255;\r\n buf[pos + 3] = val & 255;\r\n}\r\n\r\nfunction readUintLE(buf, pos) {\r\n return (buf[pos ]\r\n | buf[pos + 1] << 8\r\n | buf[pos + 2] << 16\r\n | buf[pos + 3] << 24) >>> 0;\r\n}\r\n\r\nfunction readUintBE(buf, pos) {\r\n return (buf[pos ] << 24\r\n | buf[pos + 1] << 16\r\n | buf[pos + 2] << 8\r\n | buf[pos + 3]) >>> 0;\r\n}\r\n","\"use strict\";\r\nmodule.exports = inquire;\r\n\r\n/**\r\n * Requires a module only if available.\r\n * @memberof util\r\n * @param {string} moduleName Module to require\r\n * @returns {?Object} Required module if available and not empty, otherwise `null`\r\n */\r\nfunction inquire(moduleName) {\r\n try {\r\n var mod = eval(\"quire\".replace(/^/,\"re\"))(moduleName); // eslint-disable-line no-eval\r\n if (mod && (mod.length || Object.keys(mod).length))\r\n return mod;\r\n } catch (e) {} // eslint-disable-line no-empty\r\n return null;\r\n}\r\n","\"use strict\";\r\nmodule.exports = pool;\r\n\r\n/**\r\n * An allocator as used by {@link util.pool}.\r\n * @typedef PoolAllocator\r\n * @type {function}\r\n * @param {number} size Buffer size\r\n * @returns {Uint8Array} Buffer\r\n */\r\n\r\n/**\r\n * A slicer as used by {@link util.pool}.\r\n * @typedef PoolSlicer\r\n * @type {function}\r\n * @param {number} start Start offset\r\n * @param {number} end End offset\r\n * @returns {Uint8Array} Buffer slice\r\n * @this {Uint8Array}\r\n */\r\n\r\n/**\r\n * A general purpose buffer pool.\r\n * @memberof util\r\n * @function\r\n * @param {PoolAllocator} alloc Allocator\r\n * @param {PoolSlicer} slice Slicer\r\n * @param {number} [size=8192] Slab size\r\n * @returns {PoolAllocator} Pooled allocator\r\n */\r\nfunction pool(alloc, slice, size) {\r\n var SIZE = size || 8192;\r\n var MAX = SIZE >>> 1;\r\n var slab = null;\r\n var offset = SIZE;\r\n return function pool_alloc(size) {\r\n if (size < 1 || size > MAX)\r\n return alloc(size);\r\n if (offset + size > SIZE) {\r\n slab = alloc(SIZE);\r\n offset = 0;\r\n }\r\n var buf = slice.call(slab, offset, offset += size);\r\n if (offset & 7) // align to 32 bit\r\n offset = (offset | 7) + 1;\r\n return buf;\r\n };\r\n}\r\n","\"use strict\";\r\n\r\n/**\r\n * A minimal UTF8 implementation for number arrays.\r\n * @memberof util\r\n * @namespace\r\n */\r\nvar utf8 = exports;\r\n\r\n/**\r\n * Calculates the UTF8 byte length of a string.\r\n * @param {string} string String\r\n * @returns {number} Byte length\r\n */\r\nutf8.length = function utf8_length(string) {\r\n var len = 0,\r\n c = 0;\r\n for (var i = 0; i < string.length; ++i) {\r\n c = string.charCodeAt(i);\r\n if (c < 128)\r\n len += 1;\r\n else if (c < 2048)\r\n len += 2;\r\n else if ((c & 0xFC00) === 0xD800 && (string.charCodeAt(i + 1) & 0xFC00) === 0xDC00) {\r\n ++i;\r\n len += 4;\r\n } else\r\n len += 3;\r\n }\r\n return len;\r\n};\r\n\r\n/**\r\n * Reads UTF8 bytes as a string.\r\n * @param {Uint8Array} buffer Source buffer\r\n * @param {number} start Source start\r\n * @param {number} end Source end\r\n * @returns {string} String read\r\n */\r\nutf8.read = function utf8_read(buffer, start, end) {\r\n var len = end - start;\r\n if (len < 1)\r\n return \"\";\r\n var parts = null,\r\n chunk = [],\r\n i = 0, // char offset\r\n t; // temporary\r\n while (start < end) {\r\n t = buffer[start++];\r\n if (t < 128)\r\n chunk[i++] = t;\r\n else if (t > 191 && t < 224)\r\n chunk[i++] = (t & 31) << 6 | buffer[start++] & 63;\r\n else if (t > 239 && t < 365) {\r\n t = ((t & 7) << 18 | (buffer[start++] & 63) << 12 | (buffer[start++] & 63) << 6 | buffer[start++] & 63) - 0x10000;\r\n chunk[i++] = 0xD800 + (t >> 10);\r\n chunk[i++] = 0xDC00 + (t & 1023);\r\n } else\r\n chunk[i++] = (t & 15) << 12 | (buffer[start++] & 63) << 6 | buffer[start++] & 63;\r\n if (i > 8191) {\r\n (parts || (parts = [])).push(String.fromCharCode.apply(String, chunk));\r\n i = 0;\r\n }\r\n }\r\n if (parts) {\r\n if (i)\r\n parts.push(String.fromCharCode.apply(String, chunk.slice(0, i)));\r\n return parts.join(\"\");\r\n }\r\n return String.fromCharCode.apply(String, chunk.slice(0, i));\r\n};\r\n\r\n/**\r\n * Writes a string as UTF8 bytes.\r\n * @param {string} string Source string\r\n * @param {Uint8Array} buffer Destination buffer\r\n * @param {number} offset Destination offset\r\n * @returns {number} Bytes written\r\n */\r\nutf8.write = function utf8_write(string, buffer, offset) {\r\n var start = offset,\r\n c1, // character 1\r\n c2; // character 2\r\n for (var i = 0; i < string.length; ++i) {\r\n c1 = string.charCodeAt(i);\r\n if (c1 < 128) {\r\n buffer[offset++] = c1;\r\n } else if (c1 < 2048) {\r\n buffer[offset++] = c1 >> 6 | 192;\r\n buffer[offset++] = c1 & 63 | 128;\r\n } else if ((c1 & 0xFC00) === 0xD800 && ((c2 = string.charCodeAt(i + 1)) & 0xFC00) === 0xDC00) {\r\n c1 = 0x10000 + ((c1 & 0x03FF) << 10) + (c2 & 0x03FF);\r\n ++i;\r\n buffer[offset++] = c1 >> 18 | 240;\r\n buffer[offset++] = c1 >> 12 & 63 | 128;\r\n buffer[offset++] = c1 >> 6 & 63 | 128;\r\n buffer[offset++] = c1 & 63 | 128;\r\n } else {\r\n buffer[offset++] = c1 >> 12 | 224;\r\n buffer[offset++] = c1 >> 6 & 63 | 128;\r\n buffer[offset++] = c1 & 63 | 128;\r\n }\r\n }\r\n return offset - start;\r\n};\r\n","\"use strict\";\nvar protobuf = exports;\n\n/**\n * Build type, one of `\"full\"`, `\"light\"` or `\"minimal\"`.\n * @name build\n * @type {string}\n * @const\n */\nprotobuf.build = \"minimal\";\n\n// Serialization\nprotobuf.Writer = require(16);\nprotobuf.BufferWriter = require(17);\nprotobuf.Reader = require(9);\nprotobuf.BufferReader = require(10);\n\n// Utility\nprotobuf.util = require(15);\nprotobuf.rpc = require(12);\nprotobuf.roots = require(11);\nprotobuf.configure = configure;\n\n/* istanbul ignore next */\n/**\n * Reconfigures the library according to the environment.\n * @returns {undefined}\n */\nfunction configure() {\n protobuf.util._configure();\n protobuf.Writer._configure(protobuf.BufferWriter);\n protobuf.Reader._configure(protobuf.BufferReader);\n}\n\n// Set up buffer utility according to the environment\nconfigure();\n","\"use strict\";\nmodule.exports = Reader;\n\nvar util = require(15);\n\nvar BufferReader; // cyclic\n\nvar LongBits = util.LongBits,\n utf8 = util.utf8;\n\n/* istanbul ignore next */\nfunction indexOutOfRange(reader, writeLength) {\n return RangeError(\"index out of range: \" + reader.pos + \" + \" + (writeLength || 1) + \" > \" + reader.len);\n}\n\n/**\n * Constructs a new reader instance using the specified buffer.\n * @classdesc Wire format reader using `Uint8Array` if available, otherwise `Array`.\n * @constructor\n * @param {Uint8Array} buffer Buffer to read from\n */\nfunction Reader(buffer) {\n\n /**\n * Read buffer.\n * @type {Uint8Array}\n */\n this.buf = buffer;\n\n /**\n * Read buffer position.\n * @type {number}\n */\n this.pos = 0;\n\n /**\n * Read buffer length.\n * @type {number}\n */\n this.len = buffer.length;\n}\n\nvar create_array = typeof Uint8Array !== \"undefined\"\n ? function create_typed_array(buffer) {\n if (buffer instanceof Uint8Array || Array.isArray(buffer))\n return new Reader(buffer);\n throw Error(\"illegal buffer\");\n }\n /* istanbul ignore next */\n : function create_array(buffer) {\n if (Array.isArray(buffer))\n return new Reader(buffer);\n throw Error(\"illegal buffer\");\n };\n\nvar create = function create() {\n return util.Buffer\n ? function create_buffer_setup(buffer) {\n return (Reader.create = function create_buffer(buffer) {\n return util.Buffer.isBuffer(buffer)\n ? new BufferReader(buffer)\n /* istanbul ignore next */\n : create_array(buffer);\n })(buffer);\n }\n /* istanbul ignore next */\n : create_array;\n};\n\n/**\n * Creates a new reader using the specified buffer.\n * @function\n * @param {Uint8Array|Buffer} buffer Buffer to read from\n * @returns {Reader|BufferReader} A {@link BufferReader} if `buffer` is a Buffer, otherwise a {@link Reader}\n * @throws {Error} If `buffer` is not a valid buffer\n */\nReader.create = create();\n\nReader.prototype._slice = util.Array.prototype.subarray || /* istanbul ignore next */ util.Array.prototype.slice;\n\n/**\n * Reads a varint as an unsigned 32 bit value.\n * @function\n * @returns {number} Value read\n */\nReader.prototype.uint32 = (function read_uint32_setup() {\n var value = 4294967295; // optimizer type-hint, tends to deopt otherwise (?!)\n return function read_uint32() {\n value = ( this.buf[this.pos] & 127 ) >>> 0; if (this.buf[this.pos++] < 128) return value;\n value = (value | (this.buf[this.pos] & 127) << 7) >>> 0; if (this.buf[this.pos++] < 128) return value;\n value = (value | (this.buf[this.pos] & 127) << 14) >>> 0; if (this.buf[this.pos++] < 128) return value;\n value = (value | (this.buf[this.pos] & 127) << 21) >>> 0; if (this.buf[this.pos++] < 128) return value;\n value = (value | (this.buf[this.pos] & 15) << 28) >>> 0; if (this.buf[this.pos++] < 128) return value;\n\n /* istanbul ignore if */\n if ((this.pos += 5) > this.len) {\n this.pos = this.len;\n throw indexOutOfRange(this, 10);\n }\n return value;\n };\n})();\n\n/**\n * Reads a varint as a signed 32 bit value.\n * @returns {number} Value read\n */\nReader.prototype.int32 = function read_int32() {\n return this.uint32() | 0;\n};\n\n/**\n * Reads a zig-zag encoded varint as a signed 32 bit value.\n * @returns {number} Value read\n */\nReader.prototype.sint32 = function read_sint32() {\n var value = this.uint32();\n return value >>> 1 ^ -(value & 1) | 0;\n};\n\n/* eslint-disable no-invalid-this */\n\nfunction readLongVarint() {\n // tends to deopt with local vars for octet etc.\n var bits = new LongBits(0, 0);\n var i = 0;\n if (this.len - this.pos > 4) { // fast route (lo)\n for (; i < 4; ++i) {\n // 1st..4th\n bits.lo = (bits.lo | (this.buf[this.pos] & 127) << i * 7) >>> 0;\n if (this.buf[this.pos++] < 128)\n return bits;\n }\n // 5th\n bits.lo = (bits.lo | (this.buf[this.pos] & 127) << 28) >>> 0;\n bits.hi = (bits.hi | (this.buf[this.pos] & 127) >> 4) >>> 0;\n if (this.buf[this.pos++] < 128)\n return bits;\n i = 0;\n } else {\n for (; i < 3; ++i) {\n /* istanbul ignore if */\n if (this.pos >= this.len)\n throw indexOutOfRange(this);\n // 1st..3th\n bits.lo = (bits.lo | (this.buf[this.pos] & 127) << i * 7) >>> 0;\n if (this.buf[this.pos++] < 128)\n return bits;\n }\n // 4th\n bits.lo = (bits.lo | (this.buf[this.pos++] & 127) << i * 7) >>> 0;\n return bits;\n }\n if (this.len - this.pos > 4) { // fast route (hi)\n for (; i < 5; ++i) {\n // 6th..10th\n bits.hi = (bits.hi | (this.buf[this.pos] & 127) << i * 7 + 3) >>> 0;\n if (this.buf[this.pos++] < 128)\n return bits;\n }\n } else {\n for (; i < 5; ++i) {\n /* istanbul ignore if */\n if (this.pos >= this.len)\n throw indexOutOfRange(this);\n // 6th..10th\n bits.hi = (bits.hi | (this.buf[this.pos] & 127) << i * 7 + 3) >>> 0;\n if (this.buf[this.pos++] < 128)\n return bits;\n }\n }\n /* istanbul ignore next */\n throw Error(\"invalid varint encoding\");\n}\n\n/* eslint-enable no-invalid-this */\n\n/**\n * Reads a varint as a signed 64 bit value.\n * @name Reader#int64\n * @function\n * @returns {Long} Value read\n */\n\n/**\n * Reads a varint as an unsigned 64 bit value.\n * @name Reader#uint64\n * @function\n * @returns {Long} Value read\n */\n\n/**\n * Reads a zig-zag encoded varint as a signed 64 bit value.\n * @name Reader#sint64\n * @function\n * @returns {Long} Value read\n */\n\n/**\n * Reads a varint as a boolean.\n * @returns {boolean} Value read\n */\nReader.prototype.bool = function read_bool() {\n return this.uint32() !== 0;\n};\n\nfunction readFixed32_end(buf, end) { // note that this uses `end`, not `pos`\n return (buf[end - 4]\n | buf[end - 3] << 8\n | buf[end - 2] << 16\n | buf[end - 1] << 24) >>> 0;\n}\n\n/**\n * Reads fixed 32 bits as an unsigned 32 bit integer.\n * @returns {number} Value read\n */\nReader.prototype.fixed32 = function read_fixed32() {\n\n /* istanbul ignore if */\n if (this.pos + 4 > this.len)\n throw indexOutOfRange(this, 4);\n\n return readFixed32_end(this.buf, this.pos += 4);\n};\n\n/**\n * Reads fixed 32 bits as a signed 32 bit integer.\n * @returns {number} Value read\n */\nReader.prototype.sfixed32 = function read_sfixed32() {\n\n /* istanbul ignore if */\n if (this.pos + 4 > this.len)\n throw indexOutOfRange(this, 4);\n\n return readFixed32_end(this.buf, this.pos += 4) | 0;\n};\n\n/* eslint-disable no-invalid-this */\n\nfunction readFixed64(/* this: Reader */) {\n\n /* istanbul ignore if */\n if (this.pos + 8 > this.len)\n throw indexOutOfRange(this, 8);\n\n return new LongBits(readFixed32_end(this.buf, this.pos += 4), readFixed32_end(this.buf, this.pos += 4));\n}\n\n/* eslint-enable no-invalid-this */\n\n/**\n * Reads fixed 64 bits.\n * @name Reader#fixed64\n * @function\n * @returns {Long} Value read\n */\n\n/**\n * Reads zig-zag encoded fixed 64 bits.\n * @name Reader#sfixed64\n * @function\n * @returns {Long} Value read\n */\n\n/**\n * Reads a float (32 bit) as a number.\n * @function\n * @returns {number} Value read\n */\nReader.prototype.float = function read_float() {\n\n /* istanbul ignore if */\n if (this.pos + 4 > this.len)\n throw indexOutOfRange(this, 4);\n\n var value = util.float.readFloatLE(this.buf, this.pos);\n this.pos += 4;\n return value;\n};\n\n/**\n * Reads a double (64 bit float) as a number.\n * @function\n * @returns {number} Value read\n */\nReader.prototype.double = function read_double() {\n\n /* istanbul ignore if */\n if (this.pos + 8 > this.len)\n throw indexOutOfRange(this, 4);\n\n var value = util.float.readDoubleLE(this.buf, this.pos);\n this.pos += 8;\n return value;\n};\n\n/**\n * Reads a sequence of bytes preceeded by its length as a varint.\n * @returns {Uint8Array} Value read\n */\nReader.prototype.bytes = function read_bytes() {\n var length = this.uint32(),\n start = this.pos,\n end = this.pos + length;\n\n /* istanbul ignore if */\n if (end > this.len)\n throw indexOutOfRange(this, length);\n\n this.pos += length;\n if (Array.isArray(this.buf)) // plain array\n return this.buf.slice(start, end);\n\n if (start === end) { // fix for IE 10/Win8 and others' subarray returning array of size 1\n var nativeBuffer = util.Buffer;\n return nativeBuffer\n ? nativeBuffer.alloc(0)\n : new this.buf.constructor(0);\n }\n return this._slice.call(this.buf, start, end);\n};\n\n/**\n * Reads a string preceeded by its byte length as a varint.\n * @returns {string} Value read\n */\nReader.prototype.string = function read_string() {\n var bytes = this.bytes();\n return utf8.read(bytes, 0, bytes.length);\n};\n\n/**\n * Skips the specified number of bytes if specified, otherwise skips a varint.\n * @param {number} [length] Length if known, otherwise a varint is assumed\n * @returns {Reader} `this`\n */\nReader.prototype.skip = function skip(length) {\n if (typeof length === \"number\") {\n /* istanbul ignore if */\n if (this.pos + length > this.len)\n throw indexOutOfRange(this, length);\n this.pos += length;\n } else {\n do {\n /* istanbul ignore if */\n if (this.pos >= this.len)\n throw indexOutOfRange(this);\n } while (this.buf[this.pos++] & 128);\n }\n return this;\n};\n\n/**\n * Skips the next element of the specified wire type.\n * @param {number} wireType Wire type received\n * @returns {Reader} `this`\n */\nReader.prototype.skipType = function(wireType) {\n switch (wireType) {\n case 0:\n this.skip();\n break;\n case 1:\n this.skip(8);\n break;\n case 2:\n this.skip(this.uint32());\n break;\n case 3:\n while ((wireType = this.uint32() & 7) !== 4) {\n this.skipType(wireType);\n }\n break;\n case 5:\n this.skip(4);\n break;\n\n /* istanbul ignore next */\n default:\n throw Error(\"invalid wire type \" + wireType + \" at offset \" + this.pos);\n }\n return this;\n};\n\nReader._configure = function(BufferReader_) {\n BufferReader = BufferReader_;\n Reader.create = create();\n BufferReader._configure();\n\n var fn = util.Long ? \"toLong\" : /* istanbul ignore next */ \"toNumber\";\n util.merge(Reader.prototype, {\n\n int64: function read_int64() {\n return readLongVarint.call(this)[fn](false);\n },\n\n uint64: function read_uint64() {\n return readLongVarint.call(this)[fn](true);\n },\n\n sint64: function read_sint64() {\n return readLongVarint.call(this).zzDecode()[fn](false);\n },\n\n fixed64: function read_fixed64() {\n return readFixed64.call(this)[fn](true);\n },\n\n sfixed64: function read_sfixed64() {\n return readFixed64.call(this)[fn](false);\n }\n\n });\n};\n","\"use strict\";\nmodule.exports = BufferReader;\n\n// extends Reader\nvar Reader = require(9);\n(BufferReader.prototype = Object.create(Reader.prototype)).constructor = BufferReader;\n\nvar util = require(15);\n\n/**\n * Constructs a new buffer reader instance.\n * @classdesc Wire format reader using node buffers.\n * @extends Reader\n * @constructor\n * @param {Buffer} buffer Buffer to read from\n */\nfunction BufferReader(buffer) {\n Reader.call(this, buffer);\n\n /**\n * Read buffer.\n * @name BufferReader#buf\n * @type {Buffer}\n */\n}\n\nBufferReader._configure = function () {\n /* istanbul ignore else */\n if (util.Buffer)\n BufferReader.prototype._slice = util.Buffer.prototype.slice;\n};\n\n\n/**\n * @override\n */\nBufferReader.prototype.string = function read_string_buffer() {\n var len = this.uint32(); // modifies pos\n return this.buf.utf8Slice\n ? this.buf.utf8Slice(this.pos, this.pos = Math.min(this.pos + len, this.len))\n : this.buf.toString(\"utf-8\", this.pos, this.pos = Math.min(this.pos + len, this.len));\n};\n\n/**\n * Reads a sequence of bytes preceeded by its length as a varint.\n * @name BufferReader#bytes\n * @function\n * @returns {Buffer} Value read\n */\n\nBufferReader._configure();\n","\"use strict\";\nmodule.exports = {};\n\n/**\n * Named roots.\n * This is where pbjs stores generated structures (the option `-r, --root` specifies a name).\n * Can also be used manually to make roots available across modules.\n * @name roots\n * @type {Object.}\n * @example\n * // pbjs -r myroot -o compiled.js ...\n *\n * // in another module:\n * require(\"./compiled.js\");\n *\n * // in any subsequent module:\n * var root = protobuf.roots[\"myroot\"];\n */\n","\"use strict\";\n\n/**\n * Streaming RPC helpers.\n * @namespace\n */\nvar rpc = exports;\n\n/**\n * RPC implementation passed to {@link Service#create} performing a service request on network level, i.e. by utilizing http requests or websockets.\n * @typedef RPCImpl\n * @type {function}\n * @param {Method|rpc.ServiceMethod,Message<{}>>} method Reflected or static method being called\n * @param {Uint8Array} requestData Request data\n * @param {RPCImplCallback} callback Callback function\n * @returns {undefined}\n * @example\n * function rpcImpl(method, requestData, callback) {\n * if (protobuf.util.lcFirst(method.name) !== \"myMethod\") // compatible with static code\n * throw Error(\"no such method\");\n * asynchronouslyObtainAResponse(requestData, function(err, responseData) {\n * callback(err, responseData);\n * });\n * }\n */\n\n/**\n * Node-style callback as used by {@link RPCImpl}.\n * @typedef RPCImplCallback\n * @type {function}\n * @param {Error|null} error Error, if any, otherwise `null`\n * @param {Uint8Array|null} [response] Response data or `null` to signal end of stream, if there hasn't been an error\n * @returns {undefined}\n */\n\nrpc.Service = require(13);\n","\"use strict\";\nmodule.exports = Service;\n\nvar util = require(15);\n\n// Extends EventEmitter\n(Service.prototype = Object.create(util.EventEmitter.prototype)).constructor = Service;\n\n/**\n * A service method callback as used by {@link rpc.ServiceMethod|ServiceMethod}.\n *\n * Differs from {@link RPCImplCallback} in that it is an actual callback of a service method which may not return `response = null`.\n * @typedef rpc.ServiceMethodCallback\n * @template TRes extends Message\n * @type {function}\n * @param {Error|null} error Error, if any\n * @param {TRes} [response] Response message\n * @returns {undefined}\n */\n\n/**\n * A service method part of a {@link rpc.Service} as created by {@link Service.create}.\n * @typedef rpc.ServiceMethod\n * @template TReq extends Message\n * @template TRes extends Message\n * @type {function}\n * @param {TReq|Properties} request Request message or plain object\n * @param {rpc.ServiceMethodCallback} [callback] Node-style callback called with the error, if any, and the response message\n * @returns {Promise>} Promise if `callback` has been omitted, otherwise `undefined`\n */\n\n/**\n * Constructs a new RPC service instance.\n * @classdesc An RPC service as returned by {@link Service#create}.\n * @exports rpc.Service\n * @extends util.EventEmitter\n * @constructor\n * @param {RPCImpl} rpcImpl RPC implementation\n * @param {boolean} [requestDelimited=false] Whether requests are length-delimited\n * @param {boolean} [responseDelimited=false] Whether responses are length-delimited\n */\nfunction Service(rpcImpl, requestDelimited, responseDelimited) {\n\n if (typeof rpcImpl !== \"function\")\n throw TypeError(\"rpcImpl must be a function\");\n\n util.EventEmitter.call(this);\n\n /**\n * RPC implementation. Becomes `null` once the service is ended.\n * @type {RPCImpl|null}\n */\n this.rpcImpl = rpcImpl;\n\n /**\n * Whether requests are length-delimited.\n * @type {boolean}\n */\n this.requestDelimited = Boolean(requestDelimited);\n\n /**\n * Whether responses are length-delimited.\n * @type {boolean}\n */\n this.responseDelimited = Boolean(responseDelimited);\n}\n\n/**\n * Calls a service method through {@link rpc.Service#rpcImpl|rpcImpl}.\n * @param {Method|rpc.ServiceMethod} method Reflected or static method\n * @param {Constructor} requestCtor Request constructor\n * @param {Constructor} responseCtor Response constructor\n * @param {TReq|Properties} request Request message or plain object\n * @param {rpc.ServiceMethodCallback} callback Service callback\n * @returns {undefined}\n * @template TReq extends Message\n * @template TRes extends Message\n */\nService.prototype.rpcCall = function rpcCall(method, requestCtor, responseCtor, request, callback) {\n\n if (!request)\n throw TypeError(\"request must be specified\");\n\n var self = this;\n if (!callback)\n return util.asPromise(rpcCall, self, method, requestCtor, responseCtor, request);\n\n if (!self.rpcImpl) {\n setTimeout(function() { callback(Error(\"already ended\")); }, 0);\n return undefined;\n }\n\n try {\n return self.rpcImpl(\n method,\n requestCtor[self.requestDelimited ? \"encodeDelimited\" : \"encode\"](request).finish(),\n function rpcCallback(err, response) {\n\n if (err) {\n self.emit(\"error\", err, method);\n return callback(err);\n }\n\n if (response === null) {\n self.end(/* endedByRPC */ true);\n return undefined;\n }\n\n if (!(response instanceof responseCtor)) {\n try {\n response = responseCtor[self.responseDelimited ? \"decodeDelimited\" : \"decode\"](response);\n } catch (err) {\n self.emit(\"error\", err, method);\n return callback(err);\n }\n }\n\n self.emit(\"data\", response, method);\n return callback(null, response);\n }\n );\n } catch (err) {\n self.emit(\"error\", err, method);\n setTimeout(function() { callback(err); }, 0);\n return undefined;\n }\n};\n\n/**\n * Ends this service and emits the `end` event.\n * @param {boolean} [endedByRPC=false] Whether the service has been ended by the RPC implementation.\n * @returns {rpc.Service} `this`\n */\nService.prototype.end = function end(endedByRPC) {\n if (this.rpcImpl) {\n if (!endedByRPC) // signal end to rpcImpl\n this.rpcImpl(null, null, null);\n this.rpcImpl = null;\n this.emit(\"end\").off();\n }\n return this;\n};\n","\"use strict\";\nmodule.exports = LongBits;\n\nvar util = require(15);\n\n/**\n * Constructs new long bits.\n * @classdesc Helper class for working with the low and high bits of a 64 bit value.\n * @memberof util\n * @constructor\n * @param {number} lo Low 32 bits, unsigned\n * @param {number} hi High 32 bits, unsigned\n */\nfunction LongBits(lo, hi) {\n\n // note that the casts below are theoretically unnecessary as of today, but older statically\n // generated converter code might still call the ctor with signed 32bits. kept for compat.\n\n /**\n * Low bits.\n * @type {number}\n */\n this.lo = lo >>> 0;\n\n /**\n * High bits.\n * @type {number}\n */\n this.hi = hi >>> 0;\n}\n\n/**\n * Zero bits.\n * @memberof util.LongBits\n * @type {util.LongBits}\n */\nvar zero = LongBits.zero = new LongBits(0, 0);\n\nzero.toNumber = function() { return 0; };\nzero.zzEncode = zero.zzDecode = function() { return this; };\nzero.length = function() { return 1; };\n\n/**\n * Zero hash.\n * @memberof util.LongBits\n * @type {string}\n */\nvar zeroHash = LongBits.zeroHash = \"\\0\\0\\0\\0\\0\\0\\0\\0\";\n\n/**\n * Constructs new long bits from the specified number.\n * @param {number} value Value\n * @returns {util.LongBits} Instance\n */\nLongBits.fromNumber = function fromNumber(value) {\n if (value === 0)\n return zero;\n var sign = value < 0;\n if (sign)\n value = -value;\n var lo = value >>> 0,\n hi = (value - lo) / 4294967296 >>> 0;\n if (sign) {\n hi = ~hi >>> 0;\n lo = ~lo >>> 0;\n if (++lo > 4294967295) {\n lo = 0;\n if (++hi > 4294967295)\n hi = 0;\n }\n }\n return new LongBits(lo, hi);\n};\n\n/**\n * Constructs new long bits from a number, long or string.\n * @param {Long|number|string} value Value\n * @returns {util.LongBits} Instance\n */\nLongBits.from = function from(value) {\n if (typeof value === \"number\")\n return LongBits.fromNumber(value);\n if (util.isString(value)) {\n /* istanbul ignore else */\n if (util.Long)\n value = util.Long.fromString(value);\n else\n return LongBits.fromNumber(parseInt(value, 10));\n }\n return value.low || value.high ? new LongBits(value.low >>> 0, value.high >>> 0) : zero;\n};\n\n/**\n * Converts this long bits to a possibly unsafe JavaScript number.\n * @param {boolean} [unsigned=false] Whether unsigned or not\n * @returns {number} Possibly unsafe number\n */\nLongBits.prototype.toNumber = function toNumber(unsigned) {\n if (!unsigned && this.hi >>> 31) {\n var lo = ~this.lo + 1 >>> 0,\n hi = ~this.hi >>> 0;\n if (!lo)\n hi = hi + 1 >>> 0;\n return -(lo + hi * 4294967296);\n }\n return this.lo + this.hi * 4294967296;\n};\n\n/**\n * Converts this long bits to a long.\n * @param {boolean} [unsigned=false] Whether unsigned or not\n * @returns {Long} Long\n */\nLongBits.prototype.toLong = function toLong(unsigned) {\n return util.Long\n ? new util.Long(this.lo | 0, this.hi | 0, Boolean(unsigned))\n /* istanbul ignore next */\n : { low: this.lo | 0, high: this.hi | 0, unsigned: Boolean(unsigned) };\n};\n\nvar charCodeAt = String.prototype.charCodeAt;\n\n/**\n * Constructs new long bits from the specified 8 characters long hash.\n * @param {string} hash Hash\n * @returns {util.LongBits} Bits\n */\nLongBits.fromHash = function fromHash(hash) {\n if (hash === zeroHash)\n return zero;\n return new LongBits(\n ( charCodeAt.call(hash, 0)\n | charCodeAt.call(hash, 1) << 8\n | charCodeAt.call(hash, 2) << 16\n | charCodeAt.call(hash, 3) << 24) >>> 0\n ,\n ( charCodeAt.call(hash, 4)\n | charCodeAt.call(hash, 5) << 8\n | charCodeAt.call(hash, 6) << 16\n | charCodeAt.call(hash, 7) << 24) >>> 0\n );\n};\n\n/**\n * Converts this long bits to a 8 characters long hash.\n * @returns {string} Hash\n */\nLongBits.prototype.toHash = function toHash() {\n return String.fromCharCode(\n this.lo & 255,\n this.lo >>> 8 & 255,\n this.lo >>> 16 & 255,\n this.lo >>> 24 ,\n this.hi & 255,\n this.hi >>> 8 & 255,\n this.hi >>> 16 & 255,\n this.hi >>> 24\n );\n};\n\n/**\n * Zig-zag encodes this long bits.\n * @returns {util.LongBits} `this`\n */\nLongBits.prototype.zzEncode = function zzEncode() {\n var mask = this.hi >> 31;\n this.hi = ((this.hi << 1 | this.lo >>> 31) ^ mask) >>> 0;\n this.lo = ( this.lo << 1 ^ mask) >>> 0;\n return this;\n};\n\n/**\n * Zig-zag decodes this long bits.\n * @returns {util.LongBits} `this`\n */\nLongBits.prototype.zzDecode = function zzDecode() {\n var mask = -(this.lo & 1);\n this.lo = ((this.lo >>> 1 | this.hi << 31) ^ mask) >>> 0;\n this.hi = ( this.hi >>> 1 ^ mask) >>> 0;\n return this;\n};\n\n/**\n * Calculates the length of this longbits when encoded as a varint.\n * @returns {number} Length\n */\nLongBits.prototype.length = function length() {\n var part0 = this.lo,\n part1 = (this.lo >>> 28 | this.hi << 4) >>> 0,\n part2 = this.hi >>> 24;\n return part2 === 0\n ? part1 === 0\n ? part0 < 16384\n ? part0 < 128 ? 1 : 2\n : part0 < 2097152 ? 3 : 4\n : part1 < 16384\n ? part1 < 128 ? 5 : 6\n : part1 < 2097152 ? 7 : 8\n : part2 < 128 ? 9 : 10;\n};\n","\"use strict\";\nvar util = exports;\n\n// used to return a Promise where callback is omitted\nutil.asPromise = require(1);\n\n// converts to / from base64 encoded strings\nutil.base64 = require(2);\n\n// base class of rpc.Service\nutil.EventEmitter = require(3);\n\n// float handling accross browsers\nutil.float = require(4);\n\n// requires modules optionally and hides the call from bundlers\nutil.inquire = require(5);\n\n// converts to / from utf8 encoded strings\nutil.utf8 = require(7);\n\n// provides a node-like buffer pool in the browser\nutil.pool = require(6);\n\n// utility to work with the low and high bits of a 64 bit value\nutil.LongBits = require(14);\n\n/**\n * Whether running within node or not.\n * @memberof util\n * @type {boolean}\n */\nutil.isNode = Boolean(typeof global !== \"undefined\"\n && global\n && global.process\n && global.process.versions\n && global.process.versions.node);\n\n/**\n * Global object reference.\n * @memberof util\n * @type {Object}\n */\nutil.global = util.isNode && global\n || typeof window !== \"undefined\" && window\n || typeof self !== \"undefined\" && self\n || this; // eslint-disable-line no-invalid-this\n\n/**\n * An immuable empty array.\n * @memberof util\n * @type {Array.<*>}\n * @const\n */\nutil.emptyArray = Object.freeze ? Object.freeze([]) : /* istanbul ignore next */ []; // used on prototypes\n\n/**\n * An immutable empty object.\n * @type {Object}\n * @const\n */\nutil.emptyObject = Object.freeze ? Object.freeze({}) : /* istanbul ignore next */ {}; // used on prototypes\n\n/**\n * Tests if the specified value is an integer.\n * @function\n * @param {*} value Value to test\n * @returns {boolean} `true` if the value is an integer\n */\nutil.isInteger = Number.isInteger || /* istanbul ignore next */ function isInteger(value) {\n return typeof value === \"number\" && isFinite(value) && Math.floor(value) === value;\n};\n\n/**\n * Tests if the specified value is a string.\n * @param {*} value Value to test\n * @returns {boolean} `true` if the value is a string\n */\nutil.isString = function isString(value) {\n return typeof value === \"string\" || value instanceof String;\n};\n\n/**\n * Tests if the specified value is a non-null object.\n * @param {*} value Value to test\n * @returns {boolean} `true` if the value is a non-null object\n */\nutil.isObject = function isObject(value) {\n return value && typeof value === \"object\";\n};\n\n/**\n * Checks if a property on a message is considered to be present.\n * This is an alias of {@link util.isSet}.\n * @function\n * @param {Object} obj Plain object or message instance\n * @param {string} prop Property name\n * @returns {boolean} `true` if considered to be present, otherwise `false`\n */\nutil.isset =\n\n/**\n * Checks if a property on a message is considered to be present.\n * @param {Object} obj Plain object or message instance\n * @param {string} prop Property name\n * @returns {boolean} `true` if considered to be present, otherwise `false`\n */\nutil.isSet = function isSet(obj, prop) {\n var value = obj[prop];\n if (value != null && obj.hasOwnProperty(prop)) // eslint-disable-line eqeqeq, no-prototype-builtins\n return typeof value !== \"object\" || (Array.isArray(value) ? value.length : Object.keys(value).length) > 0;\n return false;\n};\n\n/**\n * Any compatible Buffer instance.\n * This is a minimal stand-alone definition of a Buffer instance. The actual type is that exported by node's typings.\n * @interface Buffer\n * @extends Uint8Array\n */\n\n/**\n * Node's Buffer class if available.\n * @type {Constructor}\n */\nutil.Buffer = (function() {\n try {\n var Buffer = util.inquire(\"buffer\").Buffer;\n // refuse to use non-node buffers if not explicitly assigned (perf reasons):\n return Buffer.prototype.utf8Write ? Buffer : /* istanbul ignore next */ null;\n } catch (e) {\n /* istanbul ignore next */\n return null;\n }\n})();\n\n// Internal alias of or polyfull for Buffer.from.\nutil._Buffer_from = null;\n\n// Internal alias of or polyfill for Buffer.allocUnsafe.\nutil._Buffer_allocUnsafe = null;\n\n/**\n * Creates a new buffer of whatever type supported by the environment.\n * @param {number|number[]} [sizeOrArray=0] Buffer size or number array\n * @returns {Uint8Array|Buffer} Buffer\n */\nutil.newBuffer = function newBuffer(sizeOrArray) {\n /* istanbul ignore next */\n return typeof sizeOrArray === \"number\"\n ? util.Buffer\n ? util._Buffer_allocUnsafe(sizeOrArray)\n : new util.Array(sizeOrArray)\n : util.Buffer\n ? util._Buffer_from(sizeOrArray)\n : typeof Uint8Array === \"undefined\"\n ? sizeOrArray\n : new Uint8Array(sizeOrArray);\n};\n\n/**\n * Array implementation used in the browser. `Uint8Array` if supported, otherwise `Array`.\n * @type {Constructor}\n */\nutil.Array = typeof Uint8Array !== \"undefined\" ? Uint8Array /* istanbul ignore next */ : Array;\n\n/**\n * Any compatible Long instance.\n * This is a minimal stand-alone definition of a Long instance. The actual type is that exported by long.js.\n * @interface Long\n * @property {number} low Low bits\n * @property {number} high High bits\n * @property {boolean} unsigned Whether unsigned or not\n */\n\n/**\n * Long.js's Long class if available.\n * @type {Constructor}\n */\nutil.Long = /* istanbul ignore next */ util.global.dcodeIO && /* istanbul ignore next */ util.global.dcodeIO.Long\n || /* istanbul ignore next */ util.global.Long\n || util.inquire(\"long\");\n\n/**\n * Regular expression used to verify 2 bit (`bool`) map keys.\n * @type {RegExp}\n * @const\n */\nutil.key2Re = /^true|false|0|1$/;\n\n/**\n * Regular expression used to verify 32 bit (`int32` etc.) map keys.\n * @type {RegExp}\n * @const\n */\nutil.key32Re = /^-?(?:0|[1-9][0-9]*)$/;\n\n/**\n * Regular expression used to verify 64 bit (`int64` etc.) map keys.\n * @type {RegExp}\n * @const\n */\nutil.key64Re = /^(?:[\\\\x00-\\\\xff]{8}|-?(?:0|[1-9][0-9]*))$/;\n\n/**\n * Converts a number or long to an 8 characters long hash string.\n * @param {Long|number} value Value to convert\n * @returns {string} Hash\n */\nutil.longToHash = function longToHash(value) {\n return value\n ? util.LongBits.from(value).toHash()\n : util.LongBits.zeroHash;\n};\n\n/**\n * Converts an 8 characters long hash string to a long or number.\n * @param {string} hash Hash\n * @param {boolean} [unsigned=false] Whether unsigned or not\n * @returns {Long|number} Original value\n */\nutil.longFromHash = function longFromHash(hash, unsigned) {\n var bits = util.LongBits.fromHash(hash);\n if (util.Long)\n return util.Long.fromBits(bits.lo, bits.hi, unsigned);\n return bits.toNumber(Boolean(unsigned));\n};\n\n/**\n * Merges the properties of the source object into the destination object.\n * @memberof util\n * @param {Object.} dst Destination object\n * @param {Object.} src Source object\n * @param {boolean} [ifNotSet=false] Merges only if the key is not already set\n * @returns {Object.} Destination object\n */\nfunction merge(dst, src, ifNotSet) { // used by converters\n for (var keys = Object.keys(src), i = 0; i < keys.length; ++i)\n if (dst[keys[i]] === undefined || !ifNotSet)\n dst[keys[i]] = src[keys[i]];\n return dst;\n}\n\nutil.merge = merge;\n\n/**\n * Converts the first character of a string to lower case.\n * @param {string} str String to convert\n * @returns {string} Converted string\n */\nutil.lcFirst = function lcFirst(str) {\n return str.charAt(0).toLowerCase() + str.substring(1);\n};\n\n/**\n * Creates a custom error constructor.\n * @memberof util\n * @param {string} name Error name\n * @returns {Constructor} Custom error constructor\n */\nfunction newError(name) {\n\n function CustomError(message, properties) {\n\n if (!(this instanceof CustomError))\n return new CustomError(message, properties);\n\n // Error.call(this, message);\n // ^ just returns a new error instance because the ctor can be called as a function\n\n Object.defineProperty(this, \"message\", { get: function() { return message; } });\n\n /* istanbul ignore next */\n if (Error.captureStackTrace) // node\n Error.captureStackTrace(this, CustomError);\n else\n Object.defineProperty(this, \"stack\", { value: new Error().stack || \"\" });\n\n if (properties)\n merge(this, properties);\n }\n\n CustomError.prototype = Object.create(Error.prototype, {\n constructor: {\n value: CustomError,\n writable: true,\n enumerable: false,\n configurable: true,\n },\n name: {\n get: function get() { return name; },\n set: undefined,\n enumerable: false,\n // configurable: false would accurately preserve the behavior of\n // the original, but I'm guessing that was not intentional.\n // For an actual error subclass, this property would\n // be configurable.\n configurable: true,\n },\n toString: {\n value: function value() { return this.name + \": \" + this.message; },\n writable: true,\n enumerable: false,\n configurable: true,\n },\n });\n\n return CustomError;\n}\n\nutil.newError = newError;\n\n/**\n * Constructs a new protocol error.\n * @classdesc Error subclass indicating a protocol specifc error.\n * @memberof util\n * @extends Error\n * @template T extends Message\n * @constructor\n * @param {string} message Error message\n * @param {Object.} [properties] Additional properties\n * @example\n * try {\n * MyMessage.decode(someBuffer); // throws if required fields are missing\n * } catch (e) {\n * if (e instanceof ProtocolError && e.instance)\n * console.log(\"decoded so far: \" + JSON.stringify(e.instance));\n * }\n */\nutil.ProtocolError = newError(\"ProtocolError\");\n\n/**\n * So far decoded message instance.\n * @name util.ProtocolError#instance\n * @type {Message}\n */\n\n/**\n * A OneOf getter as returned by {@link util.oneOfGetter}.\n * @typedef OneOfGetter\n * @type {function}\n * @returns {string|undefined} Set field name, if any\n */\n\n/**\n * Builds a getter for a oneof's present field name.\n * @param {string[]} fieldNames Field names\n * @returns {OneOfGetter} Unbound getter\n */\nutil.oneOfGetter = function getOneOf(fieldNames) {\n var fieldMap = {};\n for (var i = 0; i < fieldNames.length; ++i)\n fieldMap[fieldNames[i]] = 1;\n\n /**\n * @returns {string|undefined} Set field name, if any\n * @this Object\n * @ignore\n */\n return function() { // eslint-disable-line consistent-return\n for (var keys = Object.keys(this), i = keys.length - 1; i > -1; --i)\n if (fieldMap[keys[i]] === 1 && this[keys[i]] !== undefined && this[keys[i]] !== null)\n return keys[i];\n };\n};\n\n/**\n * A OneOf setter as returned by {@link util.oneOfSetter}.\n * @typedef OneOfSetter\n * @type {function}\n * @param {string|undefined} value Field name\n * @returns {undefined}\n */\n\n/**\n * Builds a setter for a oneof's present field name.\n * @param {string[]} fieldNames Field names\n * @returns {OneOfSetter} Unbound setter\n */\nutil.oneOfSetter = function setOneOf(fieldNames) {\n\n /**\n * @param {string} name Field name\n * @returns {undefined}\n * @this Object\n * @ignore\n */\n return function(name) {\n for (var i = 0; i < fieldNames.length; ++i)\n if (fieldNames[i] !== name)\n delete this[fieldNames[i]];\n };\n};\n\n/**\n * Default conversion options used for {@link Message#toJSON} implementations.\n *\n * These options are close to proto3's JSON mapping with the exception that internal types like Any are handled just like messages. More precisely:\n *\n * - Longs become strings\n * - Enums become string keys\n * - Bytes become base64 encoded strings\n * - (Sub-)Messages become plain objects\n * - Maps become plain objects with all string keys\n * - Repeated fields become arrays\n * - NaN and Infinity for float and double fields become strings\n *\n * @type {IConversionOptions}\n * @see https://developers.google.com/protocol-buffers/docs/proto3?hl=en#json\n */\nutil.toJSONOptions = {\n longs: String,\n enums: String,\n bytes: String,\n json: true\n};\n\n// Sets up buffer utility according to the environment (called in index-minimal)\nutil._configure = function() {\n var Buffer = util.Buffer;\n /* istanbul ignore if */\n if (!Buffer) {\n util._Buffer_from = util._Buffer_allocUnsafe = null;\n return;\n }\n // because node 4.x buffers are incompatible & immutable\n // see: https://github.com/dcodeIO/protobuf.js/pull/665\n util._Buffer_from = Buffer.from !== Uint8Array.from && Buffer.from ||\n /* istanbul ignore next */\n function Buffer_from(value, encoding) {\n return new Buffer(value, encoding);\n };\n util._Buffer_allocUnsafe = Buffer.allocUnsafe ||\n /* istanbul ignore next */\n function Buffer_allocUnsafe(size) {\n return new Buffer(size);\n };\n};\n","\"use strict\";\nmodule.exports = Writer;\n\nvar util = require(15);\n\nvar BufferWriter; // cyclic\n\nvar LongBits = util.LongBits,\n base64 = util.base64,\n utf8 = util.utf8;\n\n/**\n * Constructs a new writer operation instance.\n * @classdesc Scheduled writer operation.\n * @constructor\n * @param {function(*, Uint8Array, number)} fn Function to call\n * @param {number} len Value byte length\n * @param {*} val Value to write\n * @ignore\n */\nfunction Op(fn, len, val) {\n\n /**\n * Function to call.\n * @type {function(Uint8Array, number, *)}\n */\n this.fn = fn;\n\n /**\n * Value byte length.\n * @type {number}\n */\n this.len = len;\n\n /**\n * Next operation.\n * @type {Writer.Op|undefined}\n */\n this.next = undefined;\n\n /**\n * Value to write.\n * @type {*}\n */\n this.val = val; // type varies\n}\n\n/* istanbul ignore next */\nfunction noop() {} // eslint-disable-line no-empty-function\n\n/**\n * Constructs a new writer state instance.\n * @classdesc Copied writer state.\n * @memberof Writer\n * @constructor\n * @param {Writer} writer Writer to copy state from\n * @ignore\n */\nfunction State(writer) {\n\n /**\n * Current head.\n * @type {Writer.Op}\n */\n this.head = writer.head;\n\n /**\n * Current tail.\n * @type {Writer.Op}\n */\n this.tail = writer.tail;\n\n /**\n * Current buffer length.\n * @type {number}\n */\n this.len = writer.len;\n\n /**\n * Next state.\n * @type {State|null}\n */\n this.next = writer.states;\n}\n\n/**\n * Constructs a new writer instance.\n * @classdesc Wire format writer using `Uint8Array` if available, otherwise `Array`.\n * @constructor\n */\nfunction Writer() {\n\n /**\n * Current length.\n * @type {number}\n */\n this.len = 0;\n\n /**\n * Operations head.\n * @type {Object}\n */\n this.head = new Op(noop, 0, 0);\n\n /**\n * Operations tail\n * @type {Object}\n */\n this.tail = this.head;\n\n /**\n * Linked forked states.\n * @type {Object|null}\n */\n this.states = null;\n\n // When a value is written, the writer calculates its byte length and puts it into a linked\n // list of operations to perform when finish() is called. This both allows us to allocate\n // buffers of the exact required size and reduces the amount of work we have to do compared\n // to first calculating over objects and then encoding over objects. In our case, the encoding\n // part is just a linked list walk calling operations with already prepared values.\n}\n\nvar create = function create() {\n return util.Buffer\n ? function create_buffer_setup() {\n return (Writer.create = function create_buffer() {\n return new BufferWriter();\n })();\n }\n /* istanbul ignore next */\n : function create_array() {\n return new Writer();\n };\n};\n\n/**\n * Creates a new writer.\n * @function\n * @returns {BufferWriter|Writer} A {@link BufferWriter} when Buffers are supported, otherwise a {@link Writer}\n */\nWriter.create = create();\n\n/**\n * Allocates a buffer of the specified size.\n * @param {number} size Buffer size\n * @returns {Uint8Array} Buffer\n */\nWriter.alloc = function alloc(size) {\n return new util.Array(size);\n};\n\n// Use Uint8Array buffer pool in the browser, just like node does with buffers\n/* istanbul ignore else */\nif (util.Array !== Array)\n Writer.alloc = util.pool(Writer.alloc, util.Array.prototype.subarray);\n\n/**\n * Pushes a new operation to the queue.\n * @param {function(Uint8Array, number, *)} fn Function to call\n * @param {number} len Value byte length\n * @param {number} val Value to write\n * @returns {Writer} `this`\n * @private\n */\nWriter.prototype._push = function push(fn, len, val) {\n this.tail = this.tail.next = new Op(fn, len, val);\n this.len += len;\n return this;\n};\n\nfunction writeByte(val, buf, pos) {\n buf[pos] = val & 255;\n}\n\nfunction writeVarint32(val, buf, pos) {\n while (val > 127) {\n buf[pos++] = val & 127 | 128;\n val >>>= 7;\n }\n buf[pos] = val;\n}\n\n/**\n * Constructs a new varint writer operation instance.\n * @classdesc Scheduled varint writer operation.\n * @extends Op\n * @constructor\n * @param {number} len Value byte length\n * @param {number} val Value to write\n * @ignore\n */\nfunction VarintOp(len, val) {\n this.len = len;\n this.next = undefined;\n this.val = val;\n}\n\nVarintOp.prototype = Object.create(Op.prototype);\nVarintOp.prototype.fn = writeVarint32;\n\n/**\n * Writes an unsigned 32 bit value as a varint.\n * @param {number} value Value to write\n * @returns {Writer} `this`\n */\nWriter.prototype.uint32 = function write_uint32(value) {\n // here, the call to this.push has been inlined and a varint specific Op subclass is used.\n // uint32 is by far the most frequently used operation and benefits significantly from this.\n this.len += (this.tail = this.tail.next = new VarintOp(\n (value = value >>> 0)\n < 128 ? 1\n : value < 16384 ? 2\n : value < 2097152 ? 3\n : value < 268435456 ? 4\n : 5,\n value)).len;\n return this;\n};\n\n/**\n * Writes a signed 32 bit value as a varint.\n * @function\n * @param {number} value Value to write\n * @returns {Writer} `this`\n */\nWriter.prototype.int32 = function write_int32(value) {\n return value < 0\n ? this._push(writeVarint64, 10, LongBits.fromNumber(value)) // 10 bytes per spec\n : this.uint32(value);\n};\n\n/**\n * Writes a 32 bit value as a varint, zig-zag encoded.\n * @param {number} value Value to write\n * @returns {Writer} `this`\n */\nWriter.prototype.sint32 = function write_sint32(value) {\n return this.uint32((value << 1 ^ value >> 31) >>> 0);\n};\n\nfunction writeVarint64(val, buf, pos) {\n while (val.hi) {\n buf[pos++] = val.lo & 127 | 128;\n val.lo = (val.lo >>> 7 | val.hi << 25) >>> 0;\n val.hi >>>= 7;\n }\n while (val.lo > 127) {\n buf[pos++] = val.lo & 127 | 128;\n val.lo = val.lo >>> 7;\n }\n buf[pos++] = val.lo;\n}\n\n/**\n * Writes an unsigned 64 bit value as a varint.\n * @param {Long|number|string} value Value to write\n * @returns {Writer} `this`\n * @throws {TypeError} If `value` is a string and no long library is present.\n */\nWriter.prototype.uint64 = function write_uint64(value) {\n var bits = LongBits.from(value);\n return this._push(writeVarint64, bits.length(), bits);\n};\n\n/**\n * Writes a signed 64 bit value as a varint.\n * @function\n * @param {Long|number|string} value Value to write\n * @returns {Writer} `this`\n * @throws {TypeError} If `value` is a string and no long library is present.\n */\nWriter.prototype.int64 = Writer.prototype.uint64;\n\n/**\n * Writes a signed 64 bit value as a varint, zig-zag encoded.\n * @param {Long|number|string} value Value to write\n * @returns {Writer} `this`\n * @throws {TypeError} If `value` is a string and no long library is present.\n */\nWriter.prototype.sint64 = function write_sint64(value) {\n var bits = LongBits.from(value).zzEncode();\n return this._push(writeVarint64, bits.length(), bits);\n};\n\n/**\n * Writes a boolish value as a varint.\n * @param {boolean} value Value to write\n * @returns {Writer} `this`\n */\nWriter.prototype.bool = function write_bool(value) {\n return this._push(writeByte, 1, value ? 1 : 0);\n};\n\nfunction writeFixed32(val, buf, pos) {\n buf[pos ] = val & 255;\n buf[pos + 1] = val >>> 8 & 255;\n buf[pos + 2] = val >>> 16 & 255;\n buf[pos + 3] = val >>> 24;\n}\n\n/**\n * Writes an unsigned 32 bit value as fixed 32 bits.\n * @param {number} value Value to write\n * @returns {Writer} `this`\n */\nWriter.prototype.fixed32 = function write_fixed32(value) {\n return this._push(writeFixed32, 4, value >>> 0);\n};\n\n/**\n * Writes a signed 32 bit value as fixed 32 bits.\n * @function\n * @param {number} value Value to write\n * @returns {Writer} `this`\n */\nWriter.prototype.sfixed32 = Writer.prototype.fixed32;\n\n/**\n * Writes an unsigned 64 bit value as fixed 64 bits.\n * @param {Long|number|string} value Value to write\n * @returns {Writer} `this`\n * @throws {TypeError} If `value` is a string and no long library is present.\n */\nWriter.prototype.fixed64 = function write_fixed64(value) {\n var bits = LongBits.from(value);\n return this._push(writeFixed32, 4, bits.lo)._push(writeFixed32, 4, bits.hi);\n};\n\n/**\n * Writes a signed 64 bit value as fixed 64 bits.\n * @function\n * @param {Long|number|string} value Value to write\n * @returns {Writer} `this`\n * @throws {TypeError} If `value` is a string and no long library is present.\n */\nWriter.prototype.sfixed64 = Writer.prototype.fixed64;\n\n/**\n * Writes a float (32 bit).\n * @function\n * @param {number} value Value to write\n * @returns {Writer} `this`\n */\nWriter.prototype.float = function write_float(value) {\n return this._push(util.float.writeFloatLE, 4, value);\n};\n\n/**\n * Writes a double (64 bit float).\n * @function\n * @param {number} value Value to write\n * @returns {Writer} `this`\n */\nWriter.prototype.double = function write_double(value) {\n return this._push(util.float.writeDoubleLE, 8, value);\n};\n\nvar writeBytes = util.Array.prototype.set\n ? function writeBytes_set(val, buf, pos) {\n buf.set(val, pos); // also works for plain array values\n }\n /* istanbul ignore next */\n : function writeBytes_for(val, buf, pos) {\n for (var i = 0; i < val.length; ++i)\n buf[pos + i] = val[i];\n };\n\n/**\n * Writes a sequence of bytes.\n * @param {Uint8Array|string} value Buffer or base64 encoded string to write\n * @returns {Writer} `this`\n */\nWriter.prototype.bytes = function write_bytes(value) {\n var len = value.length >>> 0;\n if (!len)\n return this._push(writeByte, 1, 0);\n if (util.isString(value)) {\n var buf = Writer.alloc(len = base64.length(value));\n base64.decode(value, buf, 0);\n value = buf;\n }\n return this.uint32(len)._push(writeBytes, len, value);\n};\n\n/**\n * Writes a string.\n * @param {string} value Value to write\n * @returns {Writer} `this`\n */\nWriter.prototype.string = function write_string(value) {\n var len = utf8.length(value);\n return len\n ? this.uint32(len)._push(utf8.write, len, value)\n : this._push(writeByte, 1, 0);\n};\n\n/**\n * Forks this writer's state by pushing it to a stack.\n * Calling {@link Writer#reset|reset} or {@link Writer#ldelim|ldelim} resets the writer to the previous state.\n * @returns {Writer} `this`\n */\nWriter.prototype.fork = function fork() {\n this.states = new State(this);\n this.head = this.tail = new Op(noop, 0, 0);\n this.len = 0;\n return this;\n};\n\n/**\n * Resets this instance to the last state.\n * @returns {Writer} `this`\n */\nWriter.prototype.reset = function reset() {\n if (this.states) {\n this.head = this.states.head;\n this.tail = this.states.tail;\n this.len = this.states.len;\n this.states = this.states.next;\n } else {\n this.head = this.tail = new Op(noop, 0, 0);\n this.len = 0;\n }\n return this;\n};\n\n/**\n * Resets to the last state and appends the fork state's current write length as a varint followed by its operations.\n * @returns {Writer} `this`\n */\nWriter.prototype.ldelim = function ldelim() {\n var head = this.head,\n tail = this.tail,\n len = this.len;\n this.reset().uint32(len);\n if (len) {\n this.tail.next = head.next; // skip noop\n this.tail = tail;\n this.len += len;\n }\n return this;\n};\n\n/**\n * Finishes the write operation.\n * @returns {Uint8Array} Finished buffer\n */\nWriter.prototype.finish = function finish() {\n var head = this.head.next, // skip noop\n buf = this.constructor.alloc(this.len),\n pos = 0;\n while (head) {\n head.fn(head.val, buf, pos);\n pos += head.len;\n head = head.next;\n }\n // this.head = this.tail = null;\n return buf;\n};\n\nWriter._configure = function(BufferWriter_) {\n BufferWriter = BufferWriter_;\n Writer.create = create();\n BufferWriter._configure();\n};\n","\"use strict\";\nmodule.exports = BufferWriter;\n\n// extends Writer\nvar Writer = require(16);\n(BufferWriter.prototype = Object.create(Writer.prototype)).constructor = BufferWriter;\n\nvar util = require(15);\n\n/**\n * Constructs a new buffer writer instance.\n * @classdesc Wire format writer using node buffers.\n * @extends Writer\n * @constructor\n */\nfunction BufferWriter() {\n Writer.call(this);\n}\n\nBufferWriter._configure = function () {\n /**\n * Allocates a buffer of the specified size.\n * @function\n * @param {number} size Buffer size\n * @returns {Buffer} Buffer\n */\n BufferWriter.alloc = util._Buffer_allocUnsafe;\n\n BufferWriter.writeBytesBuffer = util.Buffer && util.Buffer.prototype instanceof Uint8Array && util.Buffer.prototype.set.name === \"set\"\n ? function writeBytesBuffer_set(val, buf, pos) {\n buf.set(val, pos); // faster than copy (requires node >= 4 where Buffers extend Uint8Array and set is properly inherited)\n // also works for plain array values\n }\n /* istanbul ignore next */\n : function writeBytesBuffer_copy(val, buf, pos) {\n if (val.copy) // Buffer values\n val.copy(buf, pos, 0, val.length);\n else for (var i = 0; i < val.length;) // plain array values\n buf[pos++] = val[i++];\n };\n};\n\n\n/**\n * @override\n */\nBufferWriter.prototype.bytes = function write_bytes_buffer(value) {\n if (util.isString(value))\n value = util._Buffer_from(value, \"base64\");\n var len = value.length >>> 0;\n this.uint32(len);\n if (len)\n this._push(BufferWriter.writeBytesBuffer, len, value);\n return this;\n};\n\nfunction writeStringBuffer(val, buf, pos) {\n if (val.length < 40) // plain js is faster for short strings (probably due to redundant assertions)\n util.utf8.write(val, buf, pos);\n else if (buf.utf8Write)\n buf.utf8Write(val, pos);\n else\n buf.write(val, pos);\n}\n\n/**\n * @override\n */\nBufferWriter.prototype.string = function write_string_buffer(value) {\n var len = util.Buffer.byteLength(value);\n this.uint32(len);\n if (len)\n this._push(writeStringBuffer, len, value);\n return this;\n};\n\n\n/**\n * Finishes the write operation.\n * @name BufferWriter#finish\n * @function\n * @returns {Buffer} Finished buffer\n */\n\nBufferWriter._configure();\n"],"sourceRoot":"."} \ No newline at end of file diff --git a/node_modules/protobufjs/dist/minimal/protobuf.min.js b/node_modules/protobufjs/dist/minimal/protobuf.min.js new file mode 100644 index 0000000..224b503 --- /dev/null +++ b/node_modules/protobufjs/dist/minimal/protobuf.min.js @@ -0,0 +1,8 @@ +/*! + * protobuf.js v7.3.0 (c) 2016, daniel wirtz + * compiled fri, 10 may 2024 03:38:35 utc + * licensed under the bsd-3-clause license + * see: https://github.com/dcodeio/protobuf.js for details + */ +!function(d){"use strict";!function(r,u,t){var n=function t(n){var i=u[n];return i||r[n][0].call(i=u[n]={exports:{}},t,i,i.exports),i.exports}(t[0]);n.util.global.protobuf=n,"function"==typeof define&&define.amd&&define(["long"],function(t){return t&&t.isLong&&(n.util.Long=t,n.configure()),n}),"object"==typeof module&&module&&module.exports&&(module.exports=n)}({1:[function(t,n,i){n.exports=function(t,n){var i=Array(arguments.length-1),e=0,r=2,s=!0;for(;r>2],r=(3&o)<<4,h=1;break;case 1:e[s++]=f[r|o>>4],r=(15&o)<<2,h=2;break;case 2:e[s++]=f[r|o>>6],e[s++]=f[63&o],h=0}8191>4,r=h,e=2;break;case 2:n[i++]=(15&r)<<4|(60&h)>>2,r=h,e=3;break;case 3:n[i++]=(3&r)<<6|h,e=0}}if(1===e)throw Error(c);return i-u},i.test=function(t){return/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(t)}},{}],3:[function(t,n,i){function r(){this.t={}}(n.exports=r).prototype.on=function(t,n,i){return(this.t[t]||(this.t[t]=[])).push({fn:n,ctx:i||this}),this},r.prototype.off=function(t,n){if(t===d)this.t={};else if(n===d)this.t[t]=[];else for(var i=this.t[t],r=0;r>>0:n<11754943508222875e-54?(u<<31|Math.round(n/1401298464324817e-60))>>>0:(u<<31|127+(t=Math.floor(Math.log(n)/Math.LN2))<<23|8388607&Math.round(n*Math.pow(2,-t)*8388608))>>>0,i,r)}function i(t,n,i){t=t(n,i),n=2*(t>>31)+1,i=t>>>23&255,t&=8388607;return 255==i?t?NaN:1/0*n:0==i?1401298464324817e-60*n*t:n*Math.pow(2,i-150)*(8388608+t)}function r(t,n,i){h[0]=t,n[i]=o[0],n[i+1]=o[1],n[i+2]=o[2],n[i+3]=o[3]}function u(t,n,i){h[0]=t,n[i]=o[3],n[i+1]=o[2],n[i+2]=o[1],n[i+3]=o[0]}function e(t,n){return o[0]=t[n],o[1]=t[n+1],o[2]=t[n+2],o[3]=t[n+3],h[0]}function s(t,n){return o[3]=t[n],o[2]=t[n+1],o[1]=t[n+2],o[0]=t[n+3],h[0]}var h,o,f,c,a;function l(t,n,i,r,u,e){var s,h=r<0?1:0;0===(r=h?-r:r)?(t(0,u,e+n),t(0<1/r?0:2147483648,u,e+i)):isNaN(r)?(t(0,u,e+n),t(2146959360,u,e+i)):17976931348623157e292>>0,u,e+i)):r<22250738585072014e-324?(t((s=r/5e-324)>>>0,u,e+n),t((h<<31|s/4294967296)>>>0,u,e+i)):(t(4503599627370496*(s=r*Math.pow(2,-(r=1024===(r=Math.floor(Math.log(r)/Math.LN2))?1023:r)))>>>0,u,e+n),t((h<<31|r+1023<<20|1048576*s&1048575)>>>0,u,e+i))}function v(t,n,i,r,u){n=t(r,u+n),t=t(r,u+i),r=2*(t>>31)+1,u=t>>>20&2047,i=4294967296*(1048575&t)+n;return 2047==u?i?NaN:1/0*r:0==u?5e-324*r*i:r*Math.pow(2,u-1075)*(i+4503599627370496)}function w(t,n,i){f[0]=t,n[i]=c[0],n[i+1]=c[1],n[i+2]=c[2],n[i+3]=c[3],n[i+4]=c[4],n[i+5]=c[5],n[i+6]=c[6],n[i+7]=c[7]}function b(t,n,i){f[0]=t,n[i]=c[7],n[i+1]=c[6],n[i+2]=c[5],n[i+3]=c[4],n[i+4]=c[3],n[i+5]=c[2],n[i+6]=c[1],n[i+7]=c[0]}function y(t,n){return c[0]=t[n],c[1]=t[n+1],c[2]=t[n+2],c[3]=t[n+3],c[4]=t[n+4],c[5]=t[n+5],c[6]=t[n+6],c[7]=t[n+7],f[0]}function g(t,n){return c[7]=t[n],c[6]=t[n+1],c[5]=t[n+2],c[4]=t[n+3],c[3]=t[n+4],c[2]=t[n+5],c[1]=t[n+6],c[0]=t[n+7],f[0]}return"undefined"!=typeof Float32Array?(h=new Float32Array([-0]),o=new Uint8Array(h.buffer),a=128===o[3],t.writeFloatLE=a?r:u,t.writeFloatBE=a?u:r,t.readFloatLE=a?e:s,t.readFloatBE=a?s:e):(t.writeFloatLE=n.bind(null,d),t.writeFloatBE=n.bind(null,A),t.readFloatLE=i.bind(null,p),t.readFloatBE=i.bind(null,m)),"undefined"!=typeof Float64Array?(f=new Float64Array([-0]),c=new Uint8Array(f.buffer),a=128===c[7],t.writeDoubleLE=a?w:b,t.writeDoubleBE=a?b:w,t.readDoubleLE=a?y:g,t.readDoubleBE=a?g:y):(t.writeDoubleLE=l.bind(null,d,0,4),t.writeDoubleBE=l.bind(null,A,4,0),t.readDoubleLE=v.bind(null,p,0,4),t.readDoubleBE=v.bind(null,m,4,0)),t}function d(t,n,i){n[i]=255&t,n[i+1]=t>>>8&255,n[i+2]=t>>>16&255,n[i+3]=t>>>24}function A(t,n,i){n[i]=t>>>24,n[i+1]=t>>>16&255,n[i+2]=t>>>8&255,n[i+3]=255&t}function p(t,n){return(t[n]|t[n+1]<<8|t[n+2]<<16|t[n+3]<<24)>>>0}function m(t,n){return(t[n]<<24|t[n+1]<<16|t[n+2]<<8|t[n+3])>>>0}n.exports=r(r)},{}],5:[function(t,n,i){function r(t){try{var n=eval("require")(t);if(n&&(n.length||Object.keys(n).length))return n}catch(t){}return null}n.exports=r},{}],6:[function(t,n,i){n.exports=function(n,i,t){var r=t||8192,u=r>>>1,e=null,s=r;return function(t){if(t<1||u>10),e[s++]=56320+(1023&r)):e[s++]=(15&r)<<12|(63&t[n++])<<6|63&t[n++],8191>6|192:(55296==(64512&r)&&56320==(64512&(u=t.charCodeAt(s+1)))?(++s,n[i++]=(r=65536+((1023&r)<<10)+(1023&u))>>18|240,n[i++]=r>>12&63|128):n[i++]=r>>12|224,n[i++]=r>>6&63|128),n[i++]=63&r|128);return i-e}},{}],8:[function(t,n,i){var r=i;function u(){r.util.n(),r.Writer.n(r.BufferWriter),r.Reader.n(r.BufferReader)}r.build="minimal",r.Writer=t(16),r.BufferWriter=t(17),r.Reader=t(9),r.BufferReader=t(10),r.util=t(15),r.rpc=t(12),r.roots=t(11),r.configure=u,u()},{10:10,11:11,12:12,15:15,16:16,17:17,9:9}],9:[function(t,n,i){n.exports=o;var r,u=t(15),e=u.LongBits,s=u.utf8;function h(t,n){return RangeError("index out of range: "+t.pos+" + "+(n||1)+" > "+t.len)}function o(t){this.buf=t,this.pos=0,this.len=t.length}function f(){return u.Buffer?function(t){return(o.create=function(t){return u.Buffer.isBuffer(t)?new r(t):a(t)})(t)}:a}var c,a="undefined"!=typeof Uint8Array?function(t){if(t instanceof Uint8Array||Array.isArray(t))return new o(t);throw Error("illegal buffer")}:function(t){if(Array.isArray(t))return new o(t);throw Error("illegal buffer")};function l(){var t=new e(0,0),n=0;if(!(4=this.len)throw h(this);if(t.lo=(t.lo|(127&this.buf[this.pos])<<7*n)>>>0,this.buf[this.pos++]<128)return t}return t.lo=(t.lo|(127&this.buf[this.pos++])<<7*n)>>>0,t}for(;n<4;++n)if(t.lo=(t.lo|(127&this.buf[this.pos])<<7*n)>>>0,this.buf[this.pos++]<128)return t;if(t.lo=(t.lo|(127&this.buf[this.pos])<<28)>>>0,t.hi=(t.hi|(127&this.buf[this.pos])>>4)>>>0,this.buf[this.pos++]<128)return t;if(n=0,4>>0,this.buf[this.pos++]<128)return t}else for(;n<5;++n){if(this.pos>=this.len)throw h(this);if(t.hi=(t.hi|(127&this.buf[this.pos])<<7*n+3)>>>0,this.buf[this.pos++]<128)return t}throw Error("invalid varint encoding")}function v(t,n){return(t[n-4]|t[n-3]<<8|t[n-2]<<16|t[n-1]<<24)>>>0}function w(){if(this.pos+8>this.len)throw h(this,8);return new e(v(this.buf,this.pos+=4),v(this.buf,this.pos+=4))}o.create=f(),o.prototype.i=u.Array.prototype.subarray||u.Array.prototype.slice,o.prototype.uint32=(c=4294967295,function(){if(c=(127&this.buf[this.pos])>>>0,this.buf[this.pos++]<128||(c=(c|(127&this.buf[this.pos])<<7)>>>0,this.buf[this.pos++]<128||(c=(c|(127&this.buf[this.pos])<<14)>>>0,this.buf[this.pos++]<128||(c=(c|(127&this.buf[this.pos])<<21)>>>0,this.buf[this.pos++]<128||(c=(c|(15&this.buf[this.pos])<<28)>>>0,this.buf[this.pos++]<128||!((this.pos+=5)>this.len))))))return c;throw this.pos=this.len,h(this,10)}),o.prototype.int32=function(){return 0|this.uint32()},o.prototype.sint32=function(){var t=this.uint32();return t>>>1^-(1&t)|0},o.prototype.bool=function(){return 0!==this.uint32()},o.prototype.fixed32=function(){if(this.pos+4>this.len)throw h(this,4);return v(this.buf,this.pos+=4)},o.prototype.sfixed32=function(){if(this.pos+4>this.len)throw h(this,4);return 0|v(this.buf,this.pos+=4)},o.prototype.float=function(){if(this.pos+4>this.len)throw h(this,4);var t=u.float.readFloatLE(this.buf,this.pos);return this.pos+=4,t},o.prototype.double=function(){if(this.pos+8>this.len)throw h(this,4);var t=u.float.readDoubleLE(this.buf,this.pos);return this.pos+=8,t},o.prototype.bytes=function(){var t=this.uint32(),n=this.pos,i=this.pos+t;if(i>this.len)throw h(this,t);return this.pos+=t,Array.isArray(this.buf)?this.buf.slice(n,i):n===i?(t=u.Buffer)?t.alloc(0):new this.buf.constructor(0):this.i.call(this.buf,n,i)},o.prototype.string=function(){var t=this.bytes();return s.read(t,0,t.length)},o.prototype.skip=function(t){if("number"==typeof t){if(this.pos+t>this.len)throw h(this,t);this.pos+=t}else do{if(this.pos>=this.len)throw h(this)}while(128&this.buf[this.pos++]);return this},o.prototype.skipType=function(t){switch(t){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;4!=(t=7&this.uint32());)this.skipType(t);break;case 5:this.skip(4);break;default:throw Error("invalid wire type "+t+" at offset "+this.pos)}return this},o.n=function(t){r=t,o.create=f(),r.n();var n=u.Long?"toLong":"toNumber";u.merge(o.prototype,{int64:function(){return l.call(this)[n](!1)},uint64:function(){return l.call(this)[n](!0)},sint64:function(){return l.call(this).zzDecode()[n](!1)},fixed64:function(){return w.call(this)[n](!0)},sfixed64:function(){return w.call(this)[n](!1)}})}},{15:15}],10:[function(t,n,i){n.exports=e;var r=t(9),u=((e.prototype=Object.create(r.prototype)).constructor=e,t(15));function e(t){r.call(this,t)}e.n=function(){u.Buffer&&(e.prototype.i=u.Buffer.prototype.slice)},e.prototype.string=function(){var t=this.uint32();return this.buf.utf8Slice?this.buf.utf8Slice(this.pos,this.pos=Math.min(this.pos+t,this.len)):this.buf.toString("utf-8",this.pos,this.pos=Math.min(this.pos+t,this.len))},e.n()},{15:15,9:9}],11:[function(t,n,i){n.exports={}},{}],12:[function(t,n,i){i.Service=t(13)},{13:13}],13:[function(t,n,i){n.exports=r;var h=t(15);function r(t,n,i){if("function"!=typeof t)throw TypeError("rpcImpl must be a function");h.EventEmitter.call(this),this.rpcImpl=t,this.requestDelimited=!!n,this.responseDelimited=!!i}((r.prototype=Object.create(h.EventEmitter.prototype)).constructor=r).prototype.rpcCall=function t(i,n,r,u,e){if(!u)throw TypeError("request must be specified");var s=this;if(!e)return h.asPromise(t,s,i,n,r,u);if(!s.rpcImpl)return setTimeout(function(){e(Error("already ended"))},0),d;try{return s.rpcImpl(i,n[s.requestDelimited?"encodeDelimited":"encode"](u).finish(),function(t,n){if(t)return s.emit("error",t,i),e(t);if(null===n)return s.end(!0),d;if(!(n instanceof r))try{n=r[s.responseDelimited?"decodeDelimited":"decode"](n)}catch(t){return s.emit("error",t,i),e(t)}return s.emit("data",n,i),e(null,n)})}catch(t){return s.emit("error",t,i),setTimeout(function(){e(t)},0),d}},r.prototype.end=function(t){return this.rpcImpl&&(t||this.rpcImpl(null,null,null),this.rpcImpl=null,this.emit("end").off()),this}},{15:15}],14:[function(t,n,i){n.exports=u;var r=t(15);function u(t,n){this.lo=t>>>0,this.hi=n>>>0}var e=u.zero=new u(0,0),s=(e.toNumber=function(){return 0},e.zzEncode=e.zzDecode=function(){return this},e.length=function(){return 1},u.zeroHash="\0\0\0\0\0\0\0\0",u.fromNumber=function(t){var n,i;return 0===t?e:(i=(t=(n=t<0)?-t:t)>>>0,t=(t-i)/4294967296>>>0,n&&(t=~t>>>0,i=~i>>>0,4294967295<++i&&(i=0,4294967295<++t&&(t=0))),new u(i,t))},u.from=function(t){if("number"==typeof t)return u.fromNumber(t);if(r.isString(t)){if(!r.Long)return u.fromNumber(parseInt(t,10));t=r.Long.fromString(t)}return t.low||t.high?new u(t.low>>>0,t.high>>>0):e},u.prototype.toNumber=function(t){var n;return!t&&this.hi>>>31?(t=1+~this.lo>>>0,n=~this.hi>>>0,-(t+4294967296*(n=t?n:n+1>>>0))):this.lo+4294967296*this.hi},u.prototype.toLong=function(t){return r.Long?new r.Long(0|this.lo,0|this.hi,!!t):{low:0|this.lo,high:0|this.hi,unsigned:!!t}},String.prototype.charCodeAt);u.fromHash=function(t){return"\0\0\0\0\0\0\0\0"===t?e:new u((s.call(t,0)|s.call(t,1)<<8|s.call(t,2)<<16|s.call(t,3)<<24)>>>0,(s.call(t,4)|s.call(t,5)<<8|s.call(t,6)<<16|s.call(t,7)<<24)>>>0)},u.prototype.toHash=function(){return String.fromCharCode(255&this.lo,this.lo>>>8&255,this.lo>>>16&255,this.lo>>>24,255&this.hi,this.hi>>>8&255,this.hi>>>16&255,this.hi>>>24)},u.prototype.zzEncode=function(){var t=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^t)>>>0,this.lo=(this.lo<<1^t)>>>0,this},u.prototype.zzDecode=function(){var t=-(1&this.lo);return this.lo=((this.lo>>>1|this.hi<<31)^t)>>>0,this.hi=(this.hi>>>1^t)>>>0,this},u.prototype.length=function(){var t=this.lo,n=(this.lo>>>28|this.hi<<4)>>>0,i=this.hi>>>24;return 0==i?0==n?t<16384?t<128?1:2:t<2097152?3:4:n<16384?n<128?5:6:n<2097152?7:8:i<128?9:10}},{15:15}],15:[function(t,n,i){var r=i;function u(t,n,i){for(var r=Object.keys(n),u=0;u>>7|t.hi<<25)>>>0,t.hi>>>=7;for(;127>>7;n[i++]=t.lo}function y(t,n,i){n[i]=255&t,n[i+1]=t>>>8&255,n[i+2]=t>>>16&255,n[i+3]=t>>>24}a.create=l(),a.alloc=function(t){return new u.Array(t)},u.Array!==Array&&(a.alloc=u.pool(a.alloc,u.Array.prototype.subarray)),a.prototype.e=function(t,n,i){return this.tail=this.tail.next=new o(t,n,i),this.len+=n,this},(w.prototype=Object.create(o.prototype)).fn=function(t,n,i){for(;127>>=7;n[i]=t},a.prototype.uint32=function(t){return this.len+=(this.tail=this.tail.next=new w((t>>>=0)<128?1:t<16384?2:t<2097152?3:t<268435456?4:5,t)).len,this},a.prototype.int32=function(t){return t<0?this.e(b,10,e.fromNumber(t)):this.uint32(t)},a.prototype.sint32=function(t){return this.uint32((t<<1^t>>31)>>>0)},a.prototype.int64=a.prototype.uint64=function(t){t=e.from(t);return this.e(b,t.length(),t)},a.prototype.sint64=function(t){t=e.from(t).zzEncode();return this.e(b,t.length(),t)},a.prototype.bool=function(t){return this.e(v,1,t?1:0)},a.prototype.sfixed32=a.prototype.fixed32=function(t){return this.e(y,4,t>>>0)},a.prototype.sfixed64=a.prototype.fixed64=function(t){t=e.from(t);return this.e(y,4,t.lo).e(y,4,t.hi)},a.prototype.float=function(t){return this.e(u.float.writeFloatLE,4,t)},a.prototype.double=function(t){return this.e(u.float.writeDoubleLE,8,t)};var g=u.Array.prototype.set?function(t,n,i){n.set(t,i)}:function(t,n,i){for(var r=0;r>>0;return i?(u.isString(t)&&(n=a.alloc(i=s.length(t)),s.decode(t,n,0),t=n),this.uint32(i).e(g,i,t)):this.e(v,1,0)},a.prototype.string=function(t){var n=h.length(t);return n?this.uint32(n).e(h.write,n,t):this.e(v,1,0)},a.prototype.fork=function(){return this.states=new c(this),this.head=this.tail=new o(f,0,0),this.len=0,this},a.prototype.reset=function(){return this.states?(this.head=this.states.head,this.tail=this.states.tail,this.len=this.states.len,this.states=this.states.next):(this.head=this.tail=new o(f,0,0),this.len=0),this},a.prototype.ldelim=function(){var t=this.head,n=this.tail,i=this.len;return this.reset().uint32(i),i&&(this.tail.next=t.next,this.tail=n,this.len+=i),this},a.prototype.finish=function(){for(var t=this.head.next,n=this.constructor.alloc(this.len),i=0;t;)t.fn(t.val,n,i),i+=t.len,t=t.next;return n},a.n=function(t){r=t,a.create=l(),r.n()}},{15:15}],17:[function(t,n,i){n.exports=e;var r=t(16),u=((e.prototype=Object.create(r.prototype)).constructor=e,t(15));function e(){r.call(this)}function s(t,n,i){t.length<40?u.utf8.write(t,n,i):n.utf8Write?n.utf8Write(t,i):n.write(t,i)}e.n=function(){e.alloc=u.u,e.writeBytesBuffer=u.Buffer&&u.Buffer.prototype instanceof Uint8Array&&"set"===u.Buffer.prototype.set.name?function(t,n,i){n.set(t,i)}:function(t,n,i){if(t.copy)t.copy(n,i,0,t.length);else for(var r=0;r>>0;return this.uint32(n),n&&this.e(e.writeBytesBuffer,n,t),this},e.prototype.string=function(t){var n=u.Buffer.byteLength(t);return this.uint32(n),n&&this.e(s,n,t),this},e.n()},{15:15,16:16}]},{},[8])}(); +//# sourceMappingURL=protobuf.min.js.map diff --git a/node_modules/protobufjs/dist/minimal/protobuf.min.js.map b/node_modules/protobufjs/dist/minimal/protobuf.min.js.map new file mode 100644 index 0000000..9647827 --- /dev/null +++ b/node_modules/protobufjs/dist/minimal/protobuf.min.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["lib/prelude.js","../node_modules/@protobufjs/aspromise/index.js","../node_modules/@protobufjs/base64/index.js","../node_modules/@protobufjs/eventemitter/index.js","../node_modules/@protobufjs/float/index.js","../node_modules/@protobufjs/inquire/index.js","../node_modules/@protobufjs/pool/index.js","../node_modules/@protobufjs/utf8/index.js","../src/index-minimal","../src/reader.js","../src/reader_buffer.js","../src/roots.js","../src/rpc.js","../src/rpc/service.js","../src/util/longbits.js","../src/util/minimal.js","../src/writer.js","../src/writer_buffer.js"],"names":["undefined","modules","cache","entries","protobuf","$require","name","$module","call","exports","util","global","define","amd","Long","isLong","configure","module","1","require","fn","ctx","params","Array","arguments","length","offset","index","pending","Promise","resolve","reject","err","apply","base64","string","p","n","Math","ceil","b64","s64","i","encode","buffer","start","end","t","parts","chunk","j","b","push","String","fromCharCode","slice","join","invalidEncoding","decode","c","charCodeAt","Error","test","EventEmitter","this","_listeners","prototype","on","evt","off","listeners","splice","emit","args","factory","writeFloat_ieee754","writeUint","val","buf","pos","sign","isNaN","round","exponent","floor","log","LN2","pow","readFloat_ieee754","readUint","uint","mantissa","NaN","Infinity","writeFloat_f32_cpy","f32","f8b","writeFloat_f32_rev","readFloat_f32_cpy","readFloat_f32_rev","f64","le","writeDouble_ieee754","off0","off1","readDouble_ieee754","lo","hi","writeDouble_f64_cpy","writeDouble_f64_rev","readDouble_f64_cpy","readDouble_f64_rev","Float32Array","Uint8Array","writeFloatLE","writeFloatBE","readFloatLE","readFloatBE","bind","writeUintLE","writeUintBE","readUintLE","readUintBE","Float64Array","writeDoubleLE","writeDoubleBE","readDoubleLE","readDoubleBE","inquire","moduleName","mod","eval","Object","keys","e","alloc","size","SIZE","MAX","slab","utf8","len","read","write","c1","c2","_configure","Writer","BufferWriter","Reader","BufferReader","build","rpc","roots","LongBits","indexOutOfRange","reader","writeLength","RangeError","create","Buffer","isBuffer","create_array","value","isArray","readLongVarint","bits","readFixed32_end","readFixed64","_slice","subarray","uint32","int32","sint32","bool","fixed32","sfixed32","float","double","bytes","nativeBuffer","constructor","skip","skipType","wireType","BufferReader_","merge","int64","uint64","sint64","zzDecode","fixed64","sfixed64","utf8Slice","min","toString","Service","rpcImpl","requestDelimited","responseDelimited","TypeError","Boolean","rpcCall","method","requestCtor","responseCtor","request","callback","self","asPromise","setTimeout","finish","response","endedByRPC","zero","toNumber","zzEncode","zeroHash","fromNumber","from","isString","parseInt","fromString","low","high","unsigned","toLong","fromHash","hash","toHash","mask","part0","part1","part2","dst","src","ifNotSet","newError","CustomError","message","properties","defineProperty","get","captureStackTrace","stack","writable","enumerable","configurable","set","pool","isNode","process","versions","node","window","emptyArray","freeze","emptyObject","isInteger","Number","isFinite","isObject","isset","isSet","obj","prop","hasOwnProperty","utf8Write","_Buffer_from","_Buffer_allocUnsafe","newBuffer","sizeOrArray","dcodeIO","key2Re","key32Re","key64Re","longToHash","longFromHash","fromBits","lcFirst","str","toLowerCase","substring","ProtocolError","oneOfGetter","fieldNames","fieldMap","oneOfSetter","toJSONOptions","longs","enums","json","encoding","allocUnsafe","Op","next","noop","State","writer","head","tail","states","writeByte","VarintOp","writeVarint64","writeFixed32","_push","writeBytes","fork","reset","ldelim","BufferWriter_","writeStringBuffer","writeBytesBuffer","copy","byteLength"],"mappings":";;;;;;AAAA,CAAA,SAAAA,GAAA,aAAA,CAAA,SAAAC,EAAAC,EAAAC,GAcA,IAAAC,EAPA,SAAAC,EAAAC,GACA,IAAAC,EAAAL,EAAAI,GAGA,OAFAC,GACAN,EAAAK,GAAA,GAAAE,KAAAD,EAAAL,EAAAI,GAAA,CAAAG,QAAA,EAAA,EAAAJ,EAAAE,EAAAA,EAAAE,OAAA,EACAF,EAAAE,OACA,EAEAN,EAAA,EAAA,EAGAC,EAAAM,KAAAC,OAAAP,SAAAA,EAGA,YAAA,OAAAQ,QAAAA,OAAAC,KACAD,OAAA,CAAA,QAAA,SAAAE,GAKA,OAJAA,GAAAA,EAAAC,SACAX,EA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HAuC,KAAA2G,OAAA9B,CAAA,EACAA,GACA7E,KAAAkP,EAAA9J,EAAAqK,iBAAA5K,EAAAsB,CAAA,EACAnG,IACA,EAcAoF,EAAAlF,UAAA/B,OAAA,SAAAgI,GACA,IAAAtB,EAAAnI,EAAAsJ,OAAA2J,WAAAxJ,CAAA,EAIA,OAHAnG,KAAA2G,OAAA9B,CAAA,EACAA,GACA7E,KAAAkP,EAAAM,EAAA3K,EAAAsB,CAAA,EACAnG,IACA,EAUAoF,EAAAF,EAAA","file":"protobuf.min.js","sourcesContent":["(function prelude(modules, cache, entries) {\n\n // This is the prelude used to bundle protobuf.js for the browser. Wraps up the CommonJS\n // sources through a conflict-free require shim and is again wrapped within an iife that\n // provides a minification-friendly `undefined` var plus a global \"use strict\" directive\n // so that minification can remove the directives of each module.\n\n function $require(name) {\n var $module = cache[name];\n if (!$module)\n modules[name][0].call($module = cache[name] = { exports: {} }, $require, $module, $module.exports);\n return $module.exports;\n }\n\n var protobuf = $require(entries[0]);\n\n // Expose globally\n protobuf.util.global.protobuf = protobuf;\n\n // Be nice to AMD\n if (typeof define === \"function\" && define.amd)\n define([\"long\"], function(Long) {\n if (Long && Long.isLong) {\n protobuf.util.Long = Long;\n protobuf.configure();\n }\n return protobuf;\n });\n\n // Be nice to CommonJS\n if (typeof module === \"object\" && module && module.exports)\n module.exports = protobuf;\n\n})/* end of prelude */","\"use strict\";\r\nmodule.exports = asPromise;\r\n\r\n/**\r\n * Callback as used by {@link util.asPromise}.\r\n * @typedef asPromiseCallback\r\n * @type {function}\r\n * @param {Error|null} error Error, if any\r\n * @param {...*} params Additional arguments\r\n * @returns {undefined}\r\n */\r\n\r\n/**\r\n * Returns a promise from a node-style callback function.\r\n * @memberof util\r\n * @param {asPromiseCallback} fn Function to call\r\n * @param {*} ctx Function context\r\n * @param {...*} params Function arguments\r\n * @returns {Promise<*>} Promisified function\r\n */\r\nfunction asPromise(fn, ctx/*, varargs */) {\r\n var params = new Array(arguments.length - 1),\r\n offset = 0,\r\n index = 2,\r\n pending = true;\r\n while (index < arguments.length)\r\n params[offset++] = arguments[index++];\r\n return new Promise(function executor(resolve, reject) {\r\n params[offset] = function callback(err/*, varargs */) {\r\n if (pending) {\r\n pending = false;\r\n if (err)\r\n reject(err);\r\n else {\r\n var params = new Array(arguments.length - 1),\r\n offset = 0;\r\n while (offset < params.length)\r\n params[offset++] = arguments[offset];\r\n resolve.apply(null, params);\r\n }\r\n }\r\n };\r\n try {\r\n fn.apply(ctx || null, params);\r\n } catch (err) {\r\n if (pending) {\r\n pending = false;\r\n reject(err);\r\n }\r\n }\r\n });\r\n}\r\n","\"use strict\";\r\n\r\n/**\r\n * A minimal base64 implementation for number arrays.\r\n * @memberof util\r\n * @namespace\r\n */\r\nvar base64 = exports;\r\n\r\n/**\r\n * Calculates the byte length of a base64 encoded string.\r\n * @param {string} string Base64 encoded string\r\n * @returns {number} Byte length\r\n */\r\nbase64.length = function length(string) {\r\n var p = string.length;\r\n if (!p)\r\n return 0;\r\n var n = 0;\r\n while (--p % 4 > 1 && string.charAt(p) === \"=\")\r\n ++n;\r\n return Math.ceil(string.length * 3) / 4 - n;\r\n};\r\n\r\n// Base64 encoding table\r\nvar b64 = new Array(64);\r\n\r\n// Base64 decoding table\r\nvar s64 = new Array(123);\r\n\r\n// 65..90, 97..122, 48..57, 43, 47\r\nfor (var i = 0; i < 64;)\r\n s64[b64[i] = i < 26 ? i + 65 : i < 52 ? i + 71 : i < 62 ? i - 4 : i - 59 | 43] = i++;\r\n\r\n/**\r\n * Encodes a buffer to a base64 encoded string.\r\n * @param {Uint8Array} buffer Source buffer\r\n * @param {number} start Source start\r\n * @param {number} end Source end\r\n * @returns {string} Base64 encoded string\r\n */\r\nbase64.encode = function encode(buffer, start, end) {\r\n var parts = null,\r\n chunk = [];\r\n var i = 0, // output index\r\n j = 0, // goto index\r\n t; // temporary\r\n while (start < end) {\r\n var b = buffer[start++];\r\n switch (j) {\r\n case 0:\r\n chunk[i++] = b64[b >> 2];\r\n t = (b & 3) << 4;\r\n j = 1;\r\n break;\r\n case 1:\r\n chunk[i++] = b64[t | b >> 4];\r\n t = (b & 15) << 2;\r\n j = 2;\r\n break;\r\n case 2:\r\n chunk[i++] = b64[t | b >> 6];\r\n chunk[i++] = b64[b & 63];\r\n j = 0;\r\n break;\r\n }\r\n if (i > 8191) {\r\n (parts || (parts = [])).push(String.fromCharCode.apply(String, chunk));\r\n i = 0;\r\n }\r\n }\r\n if (j) {\r\n chunk[i++] = b64[t];\r\n chunk[i++] = 61;\r\n if (j === 1)\r\n chunk[i++] = 61;\r\n }\r\n if (parts) {\r\n if (i)\r\n parts.push(String.fromCharCode.apply(String, chunk.slice(0, i)));\r\n return parts.join(\"\");\r\n }\r\n return String.fromCharCode.apply(String, chunk.slice(0, i));\r\n};\r\n\r\nvar invalidEncoding = \"invalid encoding\";\r\n\r\n/**\r\n * Decodes a base64 encoded string to a buffer.\r\n * @param {string} string Source string\r\n * @param {Uint8Array} buffer Destination buffer\r\n * @param {number} offset Destination offset\r\n * @returns {number} Number of bytes written\r\n * @throws {Error} If encoding is invalid\r\n */\r\nbase64.decode = function decode(string, buffer, offset) {\r\n var start = offset;\r\n var j = 0, // goto index\r\n t; // temporary\r\n for (var i = 0; i < string.length;) {\r\n var c = string.charCodeAt(i++);\r\n if (c === 61 && j > 1)\r\n break;\r\n if ((c = s64[c]) === undefined)\r\n throw Error(invalidEncoding);\r\n switch (j) {\r\n case 0:\r\n t = c;\r\n j = 1;\r\n break;\r\n case 1:\r\n buffer[offset++] = t << 2 | (c & 48) >> 4;\r\n t = c;\r\n j = 2;\r\n break;\r\n case 2:\r\n buffer[offset++] = (t & 15) << 4 | (c & 60) >> 2;\r\n t = c;\r\n j = 3;\r\n break;\r\n case 3:\r\n buffer[offset++] = (t & 3) << 6 | c;\r\n j = 0;\r\n break;\r\n }\r\n }\r\n if (j === 1)\r\n throw Error(invalidEncoding);\r\n return offset - start;\r\n};\r\n\r\n/**\r\n * Tests if the specified string appears to be base64 encoded.\r\n * @param {string} string String to test\r\n * @returns {boolean} `true` if probably base64 encoded, otherwise false\r\n */\r\nbase64.test = function test(string) {\r\n return /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(string);\r\n};\r\n","\"use strict\";\r\nmodule.exports = EventEmitter;\r\n\r\n/**\r\n * Constructs a new event emitter instance.\r\n * @classdesc A minimal event emitter.\r\n * @memberof util\r\n * @constructor\r\n */\r\nfunction EventEmitter() {\r\n\r\n /**\r\n * Registered listeners.\r\n * @type {Object.}\r\n * @private\r\n */\r\n this._listeners = {};\r\n}\r\n\r\n/**\r\n * Registers an event listener.\r\n * @param {string} evt Event name\r\n * @param {function} fn Listener\r\n * @param {*} [ctx] Listener context\r\n * @returns {util.EventEmitter} `this`\r\n */\r\nEventEmitter.prototype.on = function on(evt, fn, ctx) {\r\n (this._listeners[evt] || (this._listeners[evt] = [])).push({\r\n fn : fn,\r\n ctx : ctx || this\r\n });\r\n return this;\r\n};\r\n\r\n/**\r\n * Removes an event listener or any matching listeners if arguments are omitted.\r\n * @param {string} [evt] Event name. Removes all listeners if omitted.\r\n * @param {function} [fn] Listener to remove. Removes all listeners of `evt` if omitted.\r\n * @returns {util.EventEmitter} `this`\r\n */\r\nEventEmitter.prototype.off = function off(evt, fn) {\r\n if (evt === undefined)\r\n this._listeners = {};\r\n else {\r\n if (fn === undefined)\r\n this._listeners[evt] = [];\r\n else {\r\n var listeners = this._listeners[evt];\r\n for (var i = 0; i < listeners.length;)\r\n if (listeners[i].fn === fn)\r\n listeners.splice(i, 1);\r\n else\r\n ++i;\r\n }\r\n }\r\n return this;\r\n};\r\n\r\n/**\r\n * Emits an event by calling its listeners with the specified arguments.\r\n * @param {string} evt Event name\r\n * @param {...*} args Arguments\r\n * @returns {util.EventEmitter} `this`\r\n */\r\nEventEmitter.prototype.emit = function emit(evt) {\r\n var listeners = this._listeners[evt];\r\n if (listeners) {\r\n var args = [],\r\n i = 1;\r\n for (; i < arguments.length;)\r\n args.push(arguments[i++]);\r\n for (i = 0; i < listeners.length;)\r\n listeners[i].fn.apply(listeners[i++].ctx, args);\r\n }\r\n return this;\r\n};\r\n","\"use strict\";\r\n\r\nmodule.exports = factory(factory);\r\n\r\n/**\r\n * Reads / writes floats / doubles from / to buffers.\r\n * @name util.float\r\n * @namespace\r\n */\r\n\r\n/**\r\n * Writes a 32 bit float to a buffer using little endian byte order.\r\n * @name util.float.writeFloatLE\r\n * @function\r\n * @param {number} val Value to write\r\n * @param {Uint8Array} buf Target buffer\r\n * @param {number} pos Target buffer offset\r\n * @returns {undefined}\r\n */\r\n\r\n/**\r\n * Writes a 32 bit float to a buffer using big endian byte order.\r\n * @name util.float.writeFloatBE\r\n * @function\r\n * @param {number} val Value to write\r\n * @param {Uint8Array} buf Target buffer\r\n * @param {number} pos Target buffer offset\r\n * @returns {undefined}\r\n */\r\n\r\n/**\r\n * Reads a 32 bit float from a buffer using little endian byte order.\r\n * @name util.float.readFloatLE\r\n * @function\r\n * @param {Uint8Array} buf Source buffer\r\n * @param {number} pos Source buffer offset\r\n * @returns {number} Value read\r\n */\r\n\r\n/**\r\n * Reads a 32 bit float from a buffer using big endian byte order.\r\n * @name util.float.readFloatBE\r\n * @function\r\n * @param {Uint8Array} buf Source buffer\r\n * @param {number} pos Source buffer offset\r\n * @returns {number} Value read\r\n */\r\n\r\n/**\r\n * Writes a 64 bit double to a buffer using little endian byte order.\r\n * @name util.float.writeDoubleLE\r\n * @function\r\n * @param {number} val Value to write\r\n * @param {Uint8Array} buf Target buffer\r\n * @param {number} pos Target buffer offset\r\n * @returns {undefined}\r\n */\r\n\r\n/**\r\n * Writes a 64 bit double to a buffer using big endian byte order.\r\n * @name util.float.writeDoubleBE\r\n * @function\r\n * @param {number} val Value to write\r\n * @param {Uint8Array} buf Target buffer\r\n * @param {number} pos Target buffer offset\r\n * @returns {undefined}\r\n */\r\n\r\n/**\r\n * Reads a 64 bit double from a buffer using little endian byte order.\r\n * @name util.float.readDoubleLE\r\n * @function\r\n * @param {Uint8Array} buf Source buffer\r\n * @param {number} pos Source buffer offset\r\n * @returns {number} Value read\r\n */\r\n\r\n/**\r\n * Reads a 64 bit double from a buffer using big endian byte order.\r\n * @name util.float.readDoubleBE\r\n * @function\r\n * @param {Uint8Array} buf Source buffer\r\n * @param {number} pos Source buffer offset\r\n * @returns {number} Value read\r\n */\r\n\r\n// Factory function for the purpose of node-based testing in modified global environments\r\nfunction factory(exports) {\r\n\r\n // float: typed array\r\n if (typeof Float32Array !== \"undefined\") (function() {\r\n\r\n var f32 = new Float32Array([ -0 ]),\r\n f8b = new Uint8Array(f32.buffer),\r\n le = f8b[3] === 128;\r\n\r\n function writeFloat_f32_cpy(val, buf, pos) {\r\n f32[0] = val;\r\n buf[pos ] = f8b[0];\r\n buf[pos + 1] = f8b[1];\r\n buf[pos + 2] = f8b[2];\r\n buf[pos + 3] = f8b[3];\r\n }\r\n\r\n function writeFloat_f32_rev(val, buf, pos) {\r\n f32[0] = val;\r\n buf[pos ] = f8b[3];\r\n buf[pos + 1] = f8b[2];\r\n buf[pos + 2] = f8b[1];\r\n buf[pos + 3] = f8b[0];\r\n }\r\n\r\n /* istanbul ignore next */\r\n exports.writeFloatLE = le ? writeFloat_f32_cpy : writeFloat_f32_rev;\r\n /* istanbul ignore next */\r\n exports.writeFloatBE = le ? writeFloat_f32_rev : writeFloat_f32_cpy;\r\n\r\n function readFloat_f32_cpy(buf, pos) {\r\n f8b[0] = buf[pos ];\r\n f8b[1] = buf[pos + 1];\r\n f8b[2] = buf[pos + 2];\r\n f8b[3] = buf[pos + 3];\r\n return f32[0];\r\n }\r\n\r\n function readFloat_f32_rev(buf, pos) {\r\n f8b[3] = buf[pos ];\r\n f8b[2] = buf[pos + 1];\r\n f8b[1] = buf[pos + 2];\r\n f8b[0] = buf[pos + 3];\r\n return f32[0];\r\n }\r\n\r\n /* istanbul ignore next */\r\n exports.readFloatLE = le ? readFloat_f32_cpy : readFloat_f32_rev;\r\n /* istanbul ignore next */\r\n exports.readFloatBE = le ? readFloat_f32_rev : readFloat_f32_cpy;\r\n\r\n // float: ieee754\r\n })(); else (function() {\r\n\r\n function writeFloat_ieee754(writeUint, val, buf, pos) {\r\n var sign = val < 0 ? 1 : 0;\r\n if (sign)\r\n val = -val;\r\n if (val === 0)\r\n writeUint(1 / val > 0 ? /* positive */ 0 : /* negative 0 */ 2147483648, buf, pos);\r\n else if (isNaN(val))\r\n writeUint(2143289344, buf, pos);\r\n else if (val > 3.4028234663852886e+38) // +-Infinity\r\n writeUint((sign << 31 | 2139095040) >>> 0, buf, pos);\r\n else if (val < 1.1754943508222875e-38) // denormal\r\n writeUint((sign << 31 | Math.round(val / 1.401298464324817e-45)) >>> 0, buf, pos);\r\n else {\r\n var exponent = Math.floor(Math.log(val) / Math.LN2),\r\n mantissa = Math.round(val * Math.pow(2, -exponent) * 8388608) & 8388607;\r\n writeUint((sign << 31 | exponent + 127 << 23 | mantissa) >>> 0, buf, pos);\r\n }\r\n }\r\n\r\n exports.writeFloatLE = writeFloat_ieee754.bind(null, writeUintLE);\r\n exports.writeFloatBE = writeFloat_ieee754.bind(null, writeUintBE);\r\n\r\n function readFloat_ieee754(readUint, buf, pos) {\r\n var uint = readUint(buf, pos),\r\n sign = (uint >> 31) * 2 + 1,\r\n exponent = uint >>> 23 & 255,\r\n mantissa = uint & 8388607;\r\n return exponent === 255\r\n ? mantissa\r\n ? NaN\r\n : sign * Infinity\r\n : exponent === 0 // denormal\r\n ? sign * 1.401298464324817e-45 * mantissa\r\n : sign * Math.pow(2, exponent - 150) * (mantissa + 8388608);\r\n }\r\n\r\n exports.readFloatLE = readFloat_ieee754.bind(null, readUintLE);\r\n exports.readFloatBE = readFloat_ieee754.bind(null, readUintBE);\r\n\r\n })();\r\n\r\n // double: typed array\r\n if (typeof Float64Array !== \"undefined\") (function() {\r\n\r\n var f64 = new Float64Array([-0]),\r\n f8b = new Uint8Array(f64.buffer),\r\n le = f8b[7] === 128;\r\n\r\n function writeDouble_f64_cpy(val, buf, pos) {\r\n f64[0] = val;\r\n buf[pos ] = f8b[0];\r\n buf[pos + 1] = f8b[1];\r\n buf[pos + 2] = f8b[2];\r\n buf[pos + 3] = f8b[3];\r\n buf[pos + 4] = f8b[4];\r\n buf[pos + 5] = f8b[5];\r\n buf[pos + 6] = f8b[6];\r\n buf[pos + 7] = f8b[7];\r\n }\r\n\r\n function writeDouble_f64_rev(val, buf, pos) {\r\n f64[0] = val;\r\n buf[pos ] = f8b[7];\r\n buf[pos + 1] = f8b[6];\r\n buf[pos + 2] = f8b[5];\r\n buf[pos + 3] = f8b[4];\r\n buf[pos + 4] = f8b[3];\r\n buf[pos + 5] = f8b[2];\r\n buf[pos + 6] = f8b[1];\r\n buf[pos + 7] = f8b[0];\r\n }\r\n\r\n /* istanbul ignore next */\r\n exports.writeDoubleLE = le ? writeDouble_f64_cpy : writeDouble_f64_rev;\r\n /* istanbul ignore next */\r\n exports.writeDoubleBE = le ? writeDouble_f64_rev : writeDouble_f64_cpy;\r\n\r\n function readDouble_f64_cpy(buf, pos) {\r\n f8b[0] = buf[pos ];\r\n f8b[1] = buf[pos + 1];\r\n f8b[2] = buf[pos + 2];\r\n f8b[3] = buf[pos + 3];\r\n f8b[4] = buf[pos + 4];\r\n f8b[5] = buf[pos + 5];\r\n f8b[6] = buf[pos + 6];\r\n f8b[7] = buf[pos + 7];\r\n return f64[0];\r\n }\r\n\r\n function readDouble_f64_rev(buf, pos) {\r\n f8b[7] = buf[pos ];\r\n f8b[6] = buf[pos + 1];\r\n f8b[5] = buf[pos + 2];\r\n f8b[4] = buf[pos + 3];\r\n f8b[3] = buf[pos + 4];\r\n f8b[2] = buf[pos + 5];\r\n f8b[1] = buf[pos + 6];\r\n f8b[0] = buf[pos + 7];\r\n return f64[0];\r\n }\r\n\r\n /* istanbul ignore next */\r\n exports.readDoubleLE = le ? readDouble_f64_cpy : readDouble_f64_rev;\r\n /* istanbul ignore next */\r\n exports.readDoubleBE = le ? readDouble_f64_rev : readDouble_f64_cpy;\r\n\r\n // double: ieee754\r\n })(); else (function() {\r\n\r\n function writeDouble_ieee754(writeUint, off0, off1, val, buf, pos) {\r\n var sign = val < 0 ? 1 : 0;\r\n if (sign)\r\n val = -val;\r\n if (val === 0) {\r\n writeUint(0, buf, pos + off0);\r\n writeUint(1 / val > 0 ? /* positive */ 0 : /* negative 0 */ 2147483648, buf, pos + off1);\r\n } else if (isNaN(val)) {\r\n writeUint(0, buf, pos + off0);\r\n writeUint(2146959360, buf, pos + off1);\r\n } else if (val > 1.7976931348623157e+308) { // +-Infinity\r\n writeUint(0, buf, pos + off0);\r\n writeUint((sign << 31 | 2146435072) >>> 0, buf, pos + off1);\r\n } else {\r\n var mantissa;\r\n if (val < 2.2250738585072014e-308) { // denormal\r\n mantissa = val / 5e-324;\r\n writeUint(mantissa >>> 0, buf, pos + off0);\r\n writeUint((sign << 31 | mantissa / 4294967296) >>> 0, buf, pos + off1);\r\n } else {\r\n var exponent = Math.floor(Math.log(val) / Math.LN2);\r\n if (exponent === 1024)\r\n exponent = 1023;\r\n mantissa = val * Math.pow(2, -exponent);\r\n writeUint(mantissa * 4503599627370496 >>> 0, buf, pos + off0);\r\n writeUint((sign << 31 | exponent + 1023 << 20 | mantissa * 1048576 & 1048575) >>> 0, buf, pos + off1);\r\n }\r\n }\r\n }\r\n\r\n exports.writeDoubleLE = writeDouble_ieee754.bind(null, writeUintLE, 0, 4);\r\n exports.writeDoubleBE = writeDouble_ieee754.bind(null, writeUintBE, 4, 0);\r\n\r\n function readDouble_ieee754(readUint, off0, off1, buf, pos) {\r\n var lo = readUint(buf, pos + off0),\r\n hi = readUint(buf, pos + off1);\r\n var sign = (hi >> 31) * 2 + 1,\r\n exponent = hi >>> 20 & 2047,\r\n mantissa = 4294967296 * (hi & 1048575) + lo;\r\n return exponent === 2047\r\n ? mantissa\r\n ? NaN\r\n : sign * Infinity\r\n : exponent === 0 // denormal\r\n ? sign * 5e-324 * mantissa\r\n : sign * Math.pow(2, exponent - 1075) * (mantissa + 4503599627370496);\r\n }\r\n\r\n exports.readDoubleLE = readDouble_ieee754.bind(null, readUintLE, 0, 4);\r\n exports.readDoubleBE = readDouble_ieee754.bind(null, readUintBE, 4, 0);\r\n\r\n })();\r\n\r\n return exports;\r\n}\r\n\r\n// uint helpers\r\n\r\nfunction writeUintLE(val, buf, pos) {\r\n buf[pos ] = val & 255;\r\n buf[pos + 1] = val >>> 8 & 255;\r\n buf[pos + 2] = val >>> 16 & 255;\r\n buf[pos + 3] = val >>> 24;\r\n}\r\n\r\nfunction writeUintBE(val, buf, pos) {\r\n buf[pos ] = val >>> 24;\r\n buf[pos + 1] = val >>> 16 & 255;\r\n buf[pos + 2] = val >>> 8 & 255;\r\n buf[pos + 3] = val & 255;\r\n}\r\n\r\nfunction readUintLE(buf, pos) {\r\n return (buf[pos ]\r\n | buf[pos + 1] << 8\r\n | buf[pos + 2] << 16\r\n | buf[pos + 3] << 24) >>> 0;\r\n}\r\n\r\nfunction readUintBE(buf, pos) {\r\n return (buf[pos ] << 24\r\n | buf[pos + 1] << 16\r\n | buf[pos + 2] << 8\r\n | buf[pos + 3]) >>> 0;\r\n}\r\n","\"use strict\";\r\nmodule.exports = inquire;\r\n\r\n/**\r\n * Requires a module only if available.\r\n * @memberof util\r\n * @param {string} moduleName Module to require\r\n * @returns {?Object} Required module if available and not empty, otherwise `null`\r\n */\r\nfunction inquire(moduleName) {\r\n try {\r\n var mod = eval(\"quire\".replace(/^/,\"re\"))(moduleName); // eslint-disable-line no-eval\r\n if (mod && (mod.length || Object.keys(mod).length))\r\n return mod;\r\n } catch (e) {} // eslint-disable-line no-empty\r\n return null;\r\n}\r\n","\"use strict\";\r\nmodule.exports = pool;\r\n\r\n/**\r\n * An allocator as used by {@link util.pool}.\r\n * @typedef PoolAllocator\r\n * @type {function}\r\n * @param {number} size Buffer size\r\n * @returns {Uint8Array} Buffer\r\n */\r\n\r\n/**\r\n * A slicer as used by {@link util.pool}.\r\n * @typedef PoolSlicer\r\n * @type {function}\r\n * @param {number} start Start offset\r\n * @param {number} end End offset\r\n * @returns {Uint8Array} Buffer slice\r\n * @this {Uint8Array}\r\n */\r\n\r\n/**\r\n * A general purpose buffer pool.\r\n * @memberof util\r\n * @function\r\n * @param {PoolAllocator} alloc Allocator\r\n * @param {PoolSlicer} slice Slicer\r\n * @param {number} [size=8192] Slab size\r\n * @returns {PoolAllocator} Pooled allocator\r\n */\r\nfunction pool(alloc, slice, size) {\r\n var SIZE = size || 8192;\r\n var MAX = SIZE >>> 1;\r\n var slab = null;\r\n var offset = SIZE;\r\n return function pool_alloc(size) {\r\n if (size < 1 || size > MAX)\r\n return alloc(size);\r\n if (offset + size > SIZE) {\r\n slab = alloc(SIZE);\r\n offset = 0;\r\n }\r\n var buf = slice.call(slab, offset, offset += size);\r\n if (offset & 7) // align to 32 bit\r\n offset = (offset | 7) + 1;\r\n return buf;\r\n };\r\n}\r\n","\"use strict\";\r\n\r\n/**\r\n * A minimal UTF8 implementation for number arrays.\r\n * @memberof util\r\n * @namespace\r\n */\r\nvar utf8 = exports;\r\n\r\n/**\r\n * Calculates the UTF8 byte length of a string.\r\n * @param {string} string String\r\n * @returns {number} Byte length\r\n */\r\nutf8.length = function utf8_length(string) {\r\n var len = 0,\r\n c = 0;\r\n for (var i = 0; i < string.length; ++i) {\r\n c = string.charCodeAt(i);\r\n if (c < 128)\r\n len += 1;\r\n else if (c < 2048)\r\n len += 2;\r\n else if ((c & 0xFC00) === 0xD800 && (string.charCodeAt(i + 1) & 0xFC00) === 0xDC00) {\r\n ++i;\r\n len += 4;\r\n } else\r\n len += 3;\r\n }\r\n return len;\r\n};\r\n\r\n/**\r\n * Reads UTF8 bytes as a string.\r\n * @param {Uint8Array} buffer Source buffer\r\n * @param {number} start Source start\r\n * @param {number} end Source end\r\n * @returns {string} String read\r\n */\r\nutf8.read = function utf8_read(buffer, start, end) {\r\n var len = end - start;\r\n if (len < 1)\r\n return \"\";\r\n var parts = null,\r\n chunk = [],\r\n i = 0, // char offset\r\n t; // temporary\r\n while (start < end) {\r\n t = buffer[start++];\r\n if (t < 128)\r\n chunk[i++] = t;\r\n else if (t > 191 && t < 224)\r\n chunk[i++] = (t & 31) << 6 | buffer[start++] & 63;\r\n else if (t > 239 && t < 365) {\r\n t = ((t & 7) << 18 | (buffer[start++] & 63) << 12 | (buffer[start++] & 63) << 6 | buffer[start++] & 63) - 0x10000;\r\n chunk[i++] = 0xD800 + (t >> 10);\r\n chunk[i++] = 0xDC00 + (t & 1023);\r\n } else\r\n chunk[i++] = (t & 15) << 12 | (buffer[start++] & 63) << 6 | buffer[start++] & 63;\r\n if (i > 8191) {\r\n (parts || (parts = [])).push(String.fromCharCode.apply(String, chunk));\r\n i = 0;\r\n }\r\n }\r\n if (parts) {\r\n if (i)\r\n parts.push(String.fromCharCode.apply(String, chunk.slice(0, i)));\r\n return parts.join(\"\");\r\n }\r\n return String.fromCharCode.apply(String, chunk.slice(0, i));\r\n};\r\n\r\n/**\r\n * Writes a string as UTF8 bytes.\r\n * @param {string} string Source string\r\n * @param {Uint8Array} buffer Destination buffer\r\n * @param {number} offset Destination offset\r\n * @returns {number} Bytes written\r\n */\r\nutf8.write = function utf8_write(string, buffer, offset) {\r\n var start = offset,\r\n c1, // character 1\r\n c2; // character 2\r\n for (var i = 0; i < string.length; ++i) {\r\n c1 = string.charCodeAt(i);\r\n if (c1 < 128) {\r\n buffer[offset++] = c1;\r\n } else if (c1 < 2048) {\r\n buffer[offset++] = c1 >> 6 | 192;\r\n buffer[offset++] = c1 & 63 | 128;\r\n } else if ((c1 & 0xFC00) === 0xD800 && ((c2 = string.charCodeAt(i + 1)) & 0xFC00) === 0xDC00) {\r\n c1 = 0x10000 + ((c1 & 0x03FF) << 10) + (c2 & 0x03FF);\r\n ++i;\r\n buffer[offset++] = c1 >> 18 | 240;\r\n buffer[offset++] = c1 >> 12 & 63 | 128;\r\n buffer[offset++] = c1 >> 6 & 63 | 128;\r\n buffer[offset++] = c1 & 63 | 128;\r\n } else {\r\n buffer[offset++] = c1 >> 12 | 224;\r\n buffer[offset++] = c1 >> 6 & 63 | 128;\r\n buffer[offset++] = c1 & 63 | 128;\r\n }\r\n }\r\n return offset - start;\r\n};\r\n","\"use strict\";\nvar protobuf = exports;\n\n/**\n * Build type, one of `\"full\"`, `\"light\"` or `\"minimal\"`.\n * @name build\n * @type {string}\n * @const\n */\nprotobuf.build = \"minimal\";\n\n// Serialization\nprotobuf.Writer = require(16);\nprotobuf.BufferWriter = require(17);\nprotobuf.Reader = require(9);\nprotobuf.BufferReader = require(10);\n\n// Utility\nprotobuf.util = require(15);\nprotobuf.rpc = require(12);\nprotobuf.roots = require(11);\nprotobuf.configure = configure;\n\n/* istanbul ignore next */\n/**\n * Reconfigures the library according to the environment.\n * @returns {undefined}\n */\nfunction configure() {\n protobuf.util._configure();\n protobuf.Writer._configure(protobuf.BufferWriter);\n protobuf.Reader._configure(protobuf.BufferReader);\n}\n\n// Set up buffer utility according to the environment\nconfigure();\n","\"use strict\";\nmodule.exports = Reader;\n\nvar util = require(15);\n\nvar BufferReader; // cyclic\n\nvar LongBits = util.LongBits,\n utf8 = util.utf8;\n\n/* istanbul ignore next */\nfunction indexOutOfRange(reader, writeLength) {\n return RangeError(\"index out of range: \" + reader.pos + \" + \" + (writeLength || 1) + \" > \" + reader.len);\n}\n\n/**\n * Constructs a new reader instance using the specified buffer.\n * @classdesc Wire format reader using `Uint8Array` if available, otherwise `Array`.\n * @constructor\n * @param {Uint8Array} buffer Buffer to read from\n */\nfunction Reader(buffer) {\n\n /**\n * Read buffer.\n * @type {Uint8Array}\n */\n this.buf = buffer;\n\n /**\n * Read buffer position.\n * @type {number}\n */\n this.pos = 0;\n\n /**\n * Read buffer length.\n * @type {number}\n */\n this.len = buffer.length;\n}\n\nvar create_array = typeof Uint8Array !== \"undefined\"\n ? function create_typed_array(buffer) {\n if (buffer instanceof Uint8Array || Array.isArray(buffer))\n return new Reader(buffer);\n throw Error(\"illegal buffer\");\n }\n /* istanbul ignore next */\n : function create_array(buffer) {\n if (Array.isArray(buffer))\n return new Reader(buffer);\n throw Error(\"illegal buffer\");\n };\n\nvar create = function create() {\n return util.Buffer\n ? function create_buffer_setup(buffer) {\n return (Reader.create = function create_buffer(buffer) {\n return util.Buffer.isBuffer(buffer)\n ? new BufferReader(buffer)\n /* istanbul ignore next */\n : create_array(buffer);\n })(buffer);\n }\n /* istanbul ignore next */\n : create_array;\n};\n\n/**\n * Creates a new reader using the specified buffer.\n * @function\n * @param {Uint8Array|Buffer} buffer Buffer to read from\n * @returns {Reader|BufferReader} A {@link BufferReader} if `buffer` is a Buffer, otherwise a {@link Reader}\n * @throws {Error} If `buffer` is not a valid buffer\n */\nReader.create = create();\n\nReader.prototype._slice = util.Array.prototype.subarray || /* istanbul ignore next */ util.Array.prototype.slice;\n\n/**\n * Reads a varint as an unsigned 32 bit value.\n * @function\n * @returns {number} Value read\n */\nReader.prototype.uint32 = (function read_uint32_setup() {\n var value = 4294967295; // optimizer type-hint, tends to deopt otherwise (?!)\n return function read_uint32() {\n value = ( this.buf[this.pos] & 127 ) >>> 0; if (this.buf[this.pos++] < 128) return value;\n value = (value | (this.buf[this.pos] & 127) << 7) >>> 0; if (this.buf[this.pos++] < 128) return value;\n value = (value | (this.buf[this.pos] & 127) << 14) >>> 0; if (this.buf[this.pos++] < 128) return value;\n value = (value | (this.buf[this.pos] & 127) << 21) >>> 0; if (this.buf[this.pos++] < 128) return value;\n value = (value | (this.buf[this.pos] & 15) << 28) >>> 0; if (this.buf[this.pos++] < 128) return value;\n\n /* istanbul ignore if */\n if ((this.pos += 5) > this.len) {\n this.pos = this.len;\n throw indexOutOfRange(this, 10);\n }\n return value;\n };\n})();\n\n/**\n * Reads a varint as a signed 32 bit value.\n * @returns {number} Value read\n */\nReader.prototype.int32 = function read_int32() {\n return this.uint32() | 0;\n};\n\n/**\n * Reads a zig-zag encoded varint as a signed 32 bit value.\n * @returns {number} Value read\n */\nReader.prototype.sint32 = function read_sint32() {\n var value = this.uint32();\n return value >>> 1 ^ -(value & 1) | 0;\n};\n\n/* eslint-disable no-invalid-this */\n\nfunction readLongVarint() {\n // tends to deopt with local vars for octet etc.\n var bits = new LongBits(0, 0);\n var i = 0;\n if (this.len - this.pos > 4) { // fast route (lo)\n for (; i < 4; ++i) {\n // 1st..4th\n bits.lo = (bits.lo | (this.buf[this.pos] & 127) << i * 7) >>> 0;\n if (this.buf[this.pos++] < 128)\n return bits;\n }\n // 5th\n bits.lo = (bits.lo | (this.buf[this.pos] & 127) << 28) >>> 0;\n bits.hi = (bits.hi | (this.buf[this.pos] & 127) >> 4) >>> 0;\n if (this.buf[this.pos++] < 128)\n return bits;\n i = 0;\n } else {\n for (; i < 3; ++i) {\n /* istanbul ignore if */\n if (this.pos >= this.len)\n throw indexOutOfRange(this);\n // 1st..3th\n bits.lo = (bits.lo | (this.buf[this.pos] & 127) << i * 7) >>> 0;\n if (this.buf[this.pos++] < 128)\n return bits;\n }\n // 4th\n bits.lo = (bits.lo | (this.buf[this.pos++] & 127) << i * 7) >>> 0;\n return bits;\n }\n if (this.len - this.pos > 4) { // fast route (hi)\n for (; i < 5; ++i) {\n // 6th..10th\n bits.hi = (bits.hi | (this.buf[this.pos] & 127) << i * 7 + 3) >>> 0;\n if (this.buf[this.pos++] < 128)\n return bits;\n }\n } else {\n for (; i < 5; ++i) {\n /* istanbul ignore if */\n if (this.pos >= this.len)\n throw indexOutOfRange(this);\n // 6th..10th\n bits.hi = (bits.hi | (this.buf[this.pos] & 127) << i * 7 + 3) >>> 0;\n if (this.buf[this.pos++] < 128)\n return bits;\n }\n }\n /* istanbul ignore next */\n throw Error(\"invalid varint encoding\");\n}\n\n/* eslint-enable no-invalid-this */\n\n/**\n * Reads a varint as a signed 64 bit value.\n * @name Reader#int64\n * @function\n * @returns {Long} Value read\n */\n\n/**\n * Reads a varint as an unsigned 64 bit value.\n * @name Reader#uint64\n * @function\n * @returns {Long} Value read\n */\n\n/**\n * Reads a zig-zag encoded varint as a signed 64 bit value.\n * @name Reader#sint64\n * @function\n * @returns {Long} Value read\n */\n\n/**\n * Reads a varint as a boolean.\n * @returns {boolean} Value read\n */\nReader.prototype.bool = function read_bool() {\n return this.uint32() !== 0;\n};\n\nfunction readFixed32_end(buf, end) { // note that this uses `end`, not `pos`\n return (buf[end - 4]\n | buf[end - 3] << 8\n | buf[end - 2] << 16\n | buf[end - 1] << 24) >>> 0;\n}\n\n/**\n * Reads fixed 32 bits as an unsigned 32 bit integer.\n * @returns {number} Value read\n */\nReader.prototype.fixed32 = function read_fixed32() {\n\n /* istanbul ignore if */\n if (this.pos + 4 > this.len)\n throw indexOutOfRange(this, 4);\n\n return readFixed32_end(this.buf, this.pos += 4);\n};\n\n/**\n * Reads fixed 32 bits as a signed 32 bit integer.\n * @returns {number} Value read\n */\nReader.prototype.sfixed32 = function read_sfixed32() {\n\n /* istanbul ignore if */\n if (this.pos + 4 > this.len)\n throw indexOutOfRange(this, 4);\n\n return readFixed32_end(this.buf, this.pos += 4) | 0;\n};\n\n/* eslint-disable no-invalid-this */\n\nfunction readFixed64(/* this: Reader */) {\n\n /* istanbul ignore if */\n if (this.pos + 8 > this.len)\n throw indexOutOfRange(this, 8);\n\n return new LongBits(readFixed32_end(this.buf, this.pos += 4), readFixed32_end(this.buf, this.pos += 4));\n}\n\n/* eslint-enable no-invalid-this */\n\n/**\n * Reads fixed 64 bits.\n * @name Reader#fixed64\n * @function\n * @returns {Long} Value read\n */\n\n/**\n * Reads zig-zag encoded fixed 64 bits.\n * @name Reader#sfixed64\n * @function\n * @returns {Long} Value read\n */\n\n/**\n * Reads a float (32 bit) as a number.\n * @function\n * @returns {number} Value read\n */\nReader.prototype.float = function read_float() {\n\n /* istanbul ignore if */\n if (this.pos + 4 > this.len)\n throw indexOutOfRange(this, 4);\n\n var value = util.float.readFloatLE(this.buf, this.pos);\n this.pos += 4;\n return value;\n};\n\n/**\n * Reads a double (64 bit float) as a number.\n * @function\n * @returns {number} Value read\n */\nReader.prototype.double = function read_double() {\n\n /* istanbul ignore if */\n if (this.pos + 8 > this.len)\n throw indexOutOfRange(this, 4);\n\n var value = util.float.readDoubleLE(this.buf, this.pos);\n this.pos += 8;\n return value;\n};\n\n/**\n * Reads a sequence of bytes preceeded by its length as a varint.\n * @returns {Uint8Array} Value read\n */\nReader.prototype.bytes = function read_bytes() {\n var length = this.uint32(),\n start = this.pos,\n end = this.pos + length;\n\n /* istanbul ignore if */\n if (end > this.len)\n throw indexOutOfRange(this, length);\n\n this.pos += length;\n if (Array.isArray(this.buf)) // plain array\n return this.buf.slice(start, end);\n\n if (start === end) { // fix for IE 10/Win8 and others' subarray returning array of size 1\n var nativeBuffer = util.Buffer;\n return nativeBuffer\n ? nativeBuffer.alloc(0)\n : new this.buf.constructor(0);\n }\n return this._slice.call(this.buf, start, end);\n};\n\n/**\n * Reads a string preceeded by its byte length as a varint.\n * @returns {string} Value read\n */\nReader.prototype.string = function read_string() {\n var bytes = this.bytes();\n return utf8.read(bytes, 0, bytes.length);\n};\n\n/**\n * Skips the specified number of bytes if specified, otherwise skips a varint.\n * @param {number} [length] Length if known, otherwise a varint is assumed\n * @returns {Reader} `this`\n */\nReader.prototype.skip = function skip(length) {\n if (typeof length === \"number\") {\n /* istanbul ignore if */\n if (this.pos + length > this.len)\n throw indexOutOfRange(this, length);\n this.pos += length;\n } else {\n do {\n /* istanbul ignore if */\n if (this.pos >= this.len)\n throw indexOutOfRange(this);\n } while (this.buf[this.pos++] & 128);\n }\n return this;\n};\n\n/**\n * Skips the next element of the specified wire type.\n * @param {number} wireType Wire type received\n * @returns {Reader} `this`\n */\nReader.prototype.skipType = function(wireType) {\n switch (wireType) {\n case 0:\n this.skip();\n break;\n case 1:\n this.skip(8);\n break;\n case 2:\n this.skip(this.uint32());\n break;\n case 3:\n while ((wireType = this.uint32() & 7) !== 4) {\n this.skipType(wireType);\n }\n break;\n case 5:\n this.skip(4);\n break;\n\n /* istanbul ignore next */\n default:\n throw Error(\"invalid wire type \" + wireType + \" at offset \" + this.pos);\n }\n return this;\n};\n\nReader._configure = function(BufferReader_) {\n BufferReader = BufferReader_;\n Reader.create = create();\n BufferReader._configure();\n\n var fn = util.Long ? \"toLong\" : /* istanbul ignore next */ \"toNumber\";\n util.merge(Reader.prototype, {\n\n int64: function read_int64() {\n return readLongVarint.call(this)[fn](false);\n },\n\n uint64: function read_uint64() {\n return readLongVarint.call(this)[fn](true);\n },\n\n sint64: function read_sint64() {\n return readLongVarint.call(this).zzDecode()[fn](false);\n },\n\n fixed64: function read_fixed64() {\n return readFixed64.call(this)[fn](true);\n },\n\n sfixed64: function read_sfixed64() {\n return readFixed64.call(this)[fn](false);\n }\n\n });\n};\n","\"use strict\";\nmodule.exports = BufferReader;\n\n// extends Reader\nvar Reader = require(9);\n(BufferReader.prototype = Object.create(Reader.prototype)).constructor = BufferReader;\n\nvar util = require(15);\n\n/**\n * Constructs a new buffer reader instance.\n * @classdesc Wire format reader using node buffers.\n * @extends Reader\n * @constructor\n * @param {Buffer} buffer Buffer to read from\n */\nfunction BufferReader(buffer) {\n Reader.call(this, buffer);\n\n /**\n * Read buffer.\n * @name BufferReader#buf\n * @type {Buffer}\n */\n}\n\nBufferReader._configure = function () {\n /* istanbul ignore else */\n if (util.Buffer)\n BufferReader.prototype._slice = util.Buffer.prototype.slice;\n};\n\n\n/**\n * @override\n */\nBufferReader.prototype.string = function read_string_buffer() {\n var len = this.uint32(); // modifies pos\n return this.buf.utf8Slice\n ? this.buf.utf8Slice(this.pos, this.pos = Math.min(this.pos + len, this.len))\n : this.buf.toString(\"utf-8\", this.pos, this.pos = Math.min(this.pos + len, this.len));\n};\n\n/**\n * Reads a sequence of bytes preceeded by its length as a varint.\n * @name BufferReader#bytes\n * @function\n * @returns {Buffer} Value read\n */\n\nBufferReader._configure();\n","\"use strict\";\nmodule.exports = {};\n\n/**\n * Named roots.\n * This is where pbjs stores generated structures (the option `-r, --root` specifies a name).\n * Can also be used manually to make roots available across modules.\n * @name roots\n * @type {Object.}\n * @example\n * // pbjs -r myroot -o compiled.js ...\n *\n * // in another module:\n * require(\"./compiled.js\");\n *\n * // in any subsequent module:\n * var root = protobuf.roots[\"myroot\"];\n */\n","\"use strict\";\n\n/**\n * Streaming RPC helpers.\n * @namespace\n */\nvar rpc = exports;\n\n/**\n * RPC implementation passed to {@link Service#create} performing a service request on network level, i.e. by utilizing http requests or websockets.\n * @typedef RPCImpl\n * @type {function}\n * @param {Method|rpc.ServiceMethod,Message<{}>>} method Reflected or static method being called\n * @param {Uint8Array} requestData Request data\n * @param {RPCImplCallback} callback Callback function\n * @returns {undefined}\n * @example\n * function rpcImpl(method, requestData, callback) {\n * if (protobuf.util.lcFirst(method.name) !== \"myMethod\") // compatible with static code\n * throw Error(\"no such method\");\n * asynchronouslyObtainAResponse(requestData, function(err, responseData) {\n * callback(err, responseData);\n * });\n * }\n */\n\n/**\n * Node-style callback as used by {@link RPCImpl}.\n * @typedef RPCImplCallback\n * @type {function}\n * @param {Error|null} error Error, if any, otherwise `null`\n * @param {Uint8Array|null} [response] Response data or `null` to signal end of stream, if there hasn't been an error\n * @returns {undefined}\n */\n\nrpc.Service = require(13);\n","\"use strict\";\nmodule.exports = Service;\n\nvar util = require(15);\n\n// Extends EventEmitter\n(Service.prototype = Object.create(util.EventEmitter.prototype)).constructor = Service;\n\n/**\n * A service method callback as used by {@link rpc.ServiceMethod|ServiceMethod}.\n *\n * Differs from {@link RPCImplCallback} in that it is an actual callback of a service method which may not return `response = null`.\n * @typedef rpc.ServiceMethodCallback\n * @template TRes extends Message\n * @type {function}\n * @param {Error|null} error Error, if any\n * @param {TRes} [response] Response message\n * @returns {undefined}\n */\n\n/**\n * A service method part of a {@link rpc.Service} as created by {@link Service.create}.\n * @typedef rpc.ServiceMethod\n * @template TReq extends Message\n * @template TRes extends Message\n * @type {function}\n * @param {TReq|Properties} request Request message or plain object\n * @param {rpc.ServiceMethodCallback} [callback] Node-style callback called with the error, if any, and the response message\n * @returns {Promise>} Promise if `callback` has been omitted, otherwise `undefined`\n */\n\n/**\n * Constructs a new RPC service instance.\n * @classdesc An RPC service as returned by {@link Service#create}.\n * @exports rpc.Service\n * @extends util.EventEmitter\n * @constructor\n * @param {RPCImpl} rpcImpl RPC implementation\n * @param {boolean} [requestDelimited=false] Whether requests are length-delimited\n * @param {boolean} [responseDelimited=false] Whether responses are length-delimited\n */\nfunction Service(rpcImpl, requestDelimited, responseDelimited) {\n\n if (typeof rpcImpl !== \"function\")\n throw TypeError(\"rpcImpl must be a function\");\n\n util.EventEmitter.call(this);\n\n /**\n * RPC implementation. Becomes `null` once the service is ended.\n * @type {RPCImpl|null}\n */\n this.rpcImpl = rpcImpl;\n\n /**\n * Whether requests are length-delimited.\n * @type {boolean}\n */\n this.requestDelimited = Boolean(requestDelimited);\n\n /**\n * Whether responses are length-delimited.\n * @type {boolean}\n */\n this.responseDelimited = Boolean(responseDelimited);\n}\n\n/**\n * Calls a service method through {@link rpc.Service#rpcImpl|rpcImpl}.\n * @param {Method|rpc.ServiceMethod} method Reflected or static method\n * @param {Constructor} requestCtor Request constructor\n * @param {Constructor} responseCtor Response constructor\n * @param {TReq|Properties} request Request message or plain object\n * @param {rpc.ServiceMethodCallback} callback Service callback\n * @returns {undefined}\n * @template TReq extends Message\n * @template TRes extends Message\n */\nService.prototype.rpcCall = function rpcCall(method, requestCtor, responseCtor, request, callback) {\n\n if (!request)\n throw TypeError(\"request must be specified\");\n\n var self = this;\n if (!callback)\n return util.asPromise(rpcCall, self, method, requestCtor, responseCtor, request);\n\n if (!self.rpcImpl) {\n setTimeout(function() { callback(Error(\"already ended\")); }, 0);\n return undefined;\n }\n\n try {\n return self.rpcImpl(\n method,\n requestCtor[self.requestDelimited ? \"encodeDelimited\" : \"encode\"](request).finish(),\n function rpcCallback(err, response) {\n\n if (err) {\n self.emit(\"error\", err, method);\n return callback(err);\n }\n\n if (response === null) {\n self.end(/* endedByRPC */ true);\n return undefined;\n }\n\n if (!(response instanceof responseCtor)) {\n try {\n response = responseCtor[self.responseDelimited ? \"decodeDelimited\" : \"decode\"](response);\n } catch (err) {\n self.emit(\"error\", err, method);\n return callback(err);\n }\n }\n\n self.emit(\"data\", response, method);\n return callback(null, response);\n }\n );\n } catch (err) {\n self.emit(\"error\", err, method);\n setTimeout(function() { callback(err); }, 0);\n return undefined;\n }\n};\n\n/**\n * Ends this service and emits the `end` event.\n * @param {boolean} [endedByRPC=false] Whether the service has been ended by the RPC implementation.\n * @returns {rpc.Service} `this`\n */\nService.prototype.end = function end(endedByRPC) {\n if (this.rpcImpl) {\n if (!endedByRPC) // signal end to rpcImpl\n this.rpcImpl(null, null, null);\n this.rpcImpl = null;\n this.emit(\"end\").off();\n }\n return this;\n};\n","\"use strict\";\nmodule.exports = LongBits;\n\nvar util = require(15);\n\n/**\n * Constructs new long bits.\n * @classdesc Helper class for working with the low and high bits of a 64 bit value.\n * @memberof util\n * @constructor\n * @param {number} lo Low 32 bits, unsigned\n * @param {number} hi High 32 bits, unsigned\n */\nfunction LongBits(lo, hi) {\n\n // note that the casts below are theoretically unnecessary as of today, but older statically\n // generated converter code might still call the ctor with signed 32bits. kept for compat.\n\n /**\n * Low bits.\n * @type {number}\n */\n this.lo = lo >>> 0;\n\n /**\n * High bits.\n * @type {number}\n */\n this.hi = hi >>> 0;\n}\n\n/**\n * Zero bits.\n * @memberof util.LongBits\n * @type {util.LongBits}\n */\nvar zero = LongBits.zero = new LongBits(0, 0);\n\nzero.toNumber = function() { return 0; };\nzero.zzEncode = zero.zzDecode = function() { return this; };\nzero.length = function() { return 1; };\n\n/**\n * Zero hash.\n * @memberof util.LongBits\n * @type {string}\n */\nvar zeroHash = LongBits.zeroHash = \"\\0\\0\\0\\0\\0\\0\\0\\0\";\n\n/**\n * Constructs new long bits from the specified number.\n * @param {number} value Value\n * @returns {util.LongBits} Instance\n */\nLongBits.fromNumber = function fromNumber(value) {\n if (value === 0)\n return zero;\n var sign = value < 0;\n if (sign)\n value = -value;\n var lo = value >>> 0,\n hi = (value - lo) / 4294967296 >>> 0;\n if (sign) {\n hi = ~hi >>> 0;\n lo = ~lo >>> 0;\n if (++lo > 4294967295) {\n lo = 0;\n if (++hi > 4294967295)\n hi = 0;\n }\n }\n return new LongBits(lo, hi);\n};\n\n/**\n * Constructs new long bits from a number, long or string.\n * @param {Long|number|string} value Value\n * @returns {util.LongBits} Instance\n */\nLongBits.from = function from(value) {\n if (typeof value === \"number\")\n return LongBits.fromNumber(value);\n if (util.isString(value)) {\n /* istanbul ignore else */\n if (util.Long)\n value = util.Long.fromString(value);\n else\n return LongBits.fromNumber(parseInt(value, 10));\n }\n return value.low || value.high ? new LongBits(value.low >>> 0, value.high >>> 0) : zero;\n};\n\n/**\n * Converts this long bits to a possibly unsafe JavaScript number.\n * @param {boolean} [unsigned=false] Whether unsigned or not\n * @returns {number} Possibly unsafe number\n */\nLongBits.prototype.toNumber = function toNumber(unsigned) {\n if (!unsigned && this.hi >>> 31) {\n var lo = ~this.lo + 1 >>> 0,\n hi = ~this.hi >>> 0;\n if (!lo)\n hi = hi + 1 >>> 0;\n return -(lo + hi * 4294967296);\n }\n return this.lo + this.hi * 4294967296;\n};\n\n/**\n * Converts this long bits to a long.\n * @param {boolean} [unsigned=false] Whether unsigned or not\n * @returns {Long} Long\n */\nLongBits.prototype.toLong = function toLong(unsigned) {\n return util.Long\n ? new util.Long(this.lo | 0, this.hi | 0, Boolean(unsigned))\n /* istanbul ignore next */\n : { low: this.lo | 0, high: this.hi | 0, unsigned: Boolean(unsigned) };\n};\n\nvar charCodeAt = String.prototype.charCodeAt;\n\n/**\n * Constructs new long bits from the specified 8 characters long hash.\n * @param {string} hash Hash\n * @returns {util.LongBits} Bits\n */\nLongBits.fromHash = function fromHash(hash) {\n if (hash === zeroHash)\n return zero;\n return new LongBits(\n ( charCodeAt.call(hash, 0)\n | charCodeAt.call(hash, 1) << 8\n | charCodeAt.call(hash, 2) << 16\n | charCodeAt.call(hash, 3) << 24) >>> 0\n ,\n ( charCodeAt.call(hash, 4)\n | charCodeAt.call(hash, 5) << 8\n | charCodeAt.call(hash, 6) << 16\n | charCodeAt.call(hash, 7) << 24) >>> 0\n );\n};\n\n/**\n * Converts this long bits to a 8 characters long hash.\n * @returns {string} Hash\n */\nLongBits.prototype.toHash = function toHash() {\n return String.fromCharCode(\n this.lo & 255,\n this.lo >>> 8 & 255,\n this.lo >>> 16 & 255,\n this.lo >>> 24 ,\n this.hi & 255,\n this.hi >>> 8 & 255,\n this.hi >>> 16 & 255,\n this.hi >>> 24\n );\n};\n\n/**\n * Zig-zag encodes this long bits.\n * @returns {util.LongBits} `this`\n */\nLongBits.prototype.zzEncode = function zzEncode() {\n var mask = this.hi >> 31;\n this.hi = ((this.hi << 1 | this.lo >>> 31) ^ mask) >>> 0;\n this.lo = ( this.lo << 1 ^ mask) >>> 0;\n return this;\n};\n\n/**\n * Zig-zag decodes this long bits.\n * @returns {util.LongBits} `this`\n */\nLongBits.prototype.zzDecode = function zzDecode() {\n var mask = -(this.lo & 1);\n this.lo = ((this.lo >>> 1 | this.hi << 31) ^ mask) >>> 0;\n this.hi = ( this.hi >>> 1 ^ mask) >>> 0;\n return this;\n};\n\n/**\n * Calculates the length of this longbits when encoded as a varint.\n * @returns {number} Length\n */\nLongBits.prototype.length = function length() {\n var part0 = this.lo,\n part1 = (this.lo >>> 28 | this.hi << 4) >>> 0,\n part2 = this.hi >>> 24;\n return part2 === 0\n ? part1 === 0\n ? part0 < 16384\n ? part0 < 128 ? 1 : 2\n : part0 < 2097152 ? 3 : 4\n : part1 < 16384\n ? part1 < 128 ? 5 : 6\n : part1 < 2097152 ? 7 : 8\n : part2 < 128 ? 9 : 10;\n};\n","\"use strict\";\nvar util = exports;\n\n// used to return a Promise where callback is omitted\nutil.asPromise = require(1);\n\n// converts to / from base64 encoded strings\nutil.base64 = require(2);\n\n// base class of rpc.Service\nutil.EventEmitter = require(3);\n\n// float handling accross browsers\nutil.float = require(4);\n\n// requires modules optionally and hides the call from bundlers\nutil.inquire = require(5);\n\n// converts to / from utf8 encoded strings\nutil.utf8 = require(7);\n\n// provides a node-like buffer pool in the browser\nutil.pool = require(6);\n\n// utility to work with the low and high bits of a 64 bit value\nutil.LongBits = require(14);\n\n/**\n * Whether running within node or not.\n * @memberof util\n * @type {boolean}\n */\nutil.isNode = Boolean(typeof global !== \"undefined\"\n && global\n && global.process\n && global.process.versions\n && global.process.versions.node);\n\n/**\n * Global object reference.\n * @memberof util\n * @type {Object}\n */\nutil.global = util.isNode && global\n || typeof window !== \"undefined\" && window\n || typeof self !== \"undefined\" && self\n || this; // eslint-disable-line no-invalid-this\n\n/**\n * An immuable empty array.\n * @memberof util\n * @type {Array.<*>}\n * @const\n */\nutil.emptyArray = Object.freeze ? Object.freeze([]) : /* istanbul ignore next */ []; // used on prototypes\n\n/**\n * An immutable empty object.\n * @type {Object}\n * @const\n */\nutil.emptyObject = Object.freeze ? Object.freeze({}) : /* istanbul ignore next */ {}; // used on prototypes\n\n/**\n * Tests if the specified value is an integer.\n * @function\n * @param {*} value Value to test\n * @returns {boolean} `true` if the value is an integer\n */\nutil.isInteger = Number.isInteger || /* istanbul ignore next */ function isInteger(value) {\n return typeof value === \"number\" && isFinite(value) && Math.floor(value) === value;\n};\n\n/**\n * Tests if the specified value is a string.\n * @param {*} value Value to test\n * @returns {boolean} `true` if the value is a string\n */\nutil.isString = function isString(value) {\n return typeof value === \"string\" || value instanceof String;\n};\n\n/**\n * Tests if the specified value is a non-null object.\n * @param {*} value Value to test\n * @returns {boolean} `true` if the value is a non-null object\n */\nutil.isObject = function isObject(value) {\n return value && typeof value === \"object\";\n};\n\n/**\n * Checks if a property on a message is considered to be present.\n * This is an alias of {@link util.isSet}.\n * @function\n * @param {Object} obj Plain object or message instance\n * @param {string} prop Property name\n * @returns {boolean} `true` if considered to be present, otherwise `false`\n */\nutil.isset =\n\n/**\n * Checks if a property on a message is considered to be present.\n * @param {Object} obj Plain object or message instance\n * @param {string} prop Property name\n * @returns {boolean} `true` if considered to be present, otherwise `false`\n */\nutil.isSet = function isSet(obj, prop) {\n var value = obj[prop];\n if (value != null && obj.hasOwnProperty(prop)) // eslint-disable-line eqeqeq, no-prototype-builtins\n return typeof value !== \"object\" || (Array.isArray(value) ? value.length : Object.keys(value).length) > 0;\n return false;\n};\n\n/**\n * Any compatible Buffer instance.\n * This is a minimal stand-alone definition of a Buffer instance. The actual type is that exported by node's typings.\n * @interface Buffer\n * @extends Uint8Array\n */\n\n/**\n * Node's Buffer class if available.\n * @type {Constructor}\n */\nutil.Buffer = (function() {\n try {\n var Buffer = util.inquire(\"buffer\").Buffer;\n // refuse to use non-node buffers if not explicitly assigned (perf reasons):\n return Buffer.prototype.utf8Write ? Buffer : /* istanbul ignore next */ null;\n } catch (e) {\n /* istanbul ignore next */\n return null;\n }\n})();\n\n// Internal alias of or polyfull for Buffer.from.\nutil._Buffer_from = null;\n\n// Internal alias of or polyfill for Buffer.allocUnsafe.\nutil._Buffer_allocUnsafe = null;\n\n/**\n * Creates a new buffer of whatever type supported by the environment.\n * @param {number|number[]} [sizeOrArray=0] Buffer size or number array\n * @returns {Uint8Array|Buffer} Buffer\n */\nutil.newBuffer = function newBuffer(sizeOrArray) {\n /* istanbul ignore next */\n return typeof sizeOrArray === \"number\"\n ? util.Buffer\n ? util._Buffer_allocUnsafe(sizeOrArray)\n : new util.Array(sizeOrArray)\n : util.Buffer\n ? util._Buffer_from(sizeOrArray)\n : typeof Uint8Array === \"undefined\"\n ? sizeOrArray\n : new Uint8Array(sizeOrArray);\n};\n\n/**\n * Array implementation used in the browser. `Uint8Array` if supported, otherwise `Array`.\n * @type {Constructor}\n */\nutil.Array = typeof Uint8Array !== \"undefined\" ? Uint8Array /* istanbul ignore next */ : Array;\n\n/**\n * Any compatible Long instance.\n * This is a minimal stand-alone definition of a Long instance. The actual type is that exported by long.js.\n * @interface Long\n * @property {number} low Low bits\n * @property {number} high High bits\n * @property {boolean} unsigned Whether unsigned or not\n */\n\n/**\n * Long.js's Long class if available.\n * @type {Constructor}\n */\nutil.Long = /* istanbul ignore next */ util.global.dcodeIO && /* istanbul ignore next */ util.global.dcodeIO.Long\n || /* istanbul ignore next */ util.global.Long\n || util.inquire(\"long\");\n\n/**\n * Regular expression used to verify 2 bit (`bool`) map keys.\n * @type {RegExp}\n * @const\n */\nutil.key2Re = /^true|false|0|1$/;\n\n/**\n * Regular expression used to verify 32 bit (`int32` etc.) map keys.\n * @type {RegExp}\n * @const\n */\nutil.key32Re = /^-?(?:0|[1-9][0-9]*)$/;\n\n/**\n * Regular expression used to verify 64 bit (`int64` etc.) map keys.\n * @type {RegExp}\n * @const\n */\nutil.key64Re = /^(?:[\\\\x00-\\\\xff]{8}|-?(?:0|[1-9][0-9]*))$/;\n\n/**\n * Converts a number or long to an 8 characters long hash string.\n * @param {Long|number} value Value to convert\n * @returns {string} Hash\n */\nutil.longToHash = function longToHash(value) {\n return value\n ? util.LongBits.from(value).toHash()\n : util.LongBits.zeroHash;\n};\n\n/**\n * Converts an 8 characters long hash string to a long or number.\n * @param {string} hash Hash\n * @param {boolean} [unsigned=false] Whether unsigned or not\n * @returns {Long|number} Original value\n */\nutil.longFromHash = function longFromHash(hash, unsigned) {\n var bits = util.LongBits.fromHash(hash);\n if (util.Long)\n return util.Long.fromBits(bits.lo, bits.hi, unsigned);\n return bits.toNumber(Boolean(unsigned));\n};\n\n/**\n * Merges the properties of the source object into the destination object.\n * @memberof util\n * @param {Object.} dst Destination object\n * @param {Object.} src Source object\n * @param {boolean} [ifNotSet=false] Merges only if the key is not already set\n * @returns {Object.} Destination object\n */\nfunction merge(dst, src, ifNotSet) { // used by converters\n for (var keys = Object.keys(src), i = 0; i < keys.length; ++i)\n if (dst[keys[i]] === undefined || !ifNotSet)\n dst[keys[i]] = src[keys[i]];\n return dst;\n}\n\nutil.merge = merge;\n\n/**\n * Converts the first character of a string to lower case.\n * @param {string} str String to convert\n * @returns {string} Converted string\n */\nutil.lcFirst = function lcFirst(str) {\n return str.charAt(0).toLowerCase() + str.substring(1);\n};\n\n/**\n * Creates a custom error constructor.\n * @memberof util\n * @param {string} name Error name\n * @returns {Constructor} Custom error constructor\n */\nfunction newError(name) {\n\n function CustomError(message, properties) {\n\n if (!(this instanceof CustomError))\n return new CustomError(message, properties);\n\n // Error.call(this, message);\n // ^ just returns a new error instance because the ctor can be called as a function\n\n Object.defineProperty(this, \"message\", { get: function() { return message; } });\n\n /* istanbul ignore next */\n if (Error.captureStackTrace) // node\n Error.captureStackTrace(this, CustomError);\n else\n Object.defineProperty(this, \"stack\", { value: new Error().stack || \"\" });\n\n if (properties)\n merge(this, properties);\n }\n\n CustomError.prototype = Object.create(Error.prototype, {\n constructor: {\n value: CustomError,\n writable: true,\n enumerable: false,\n configurable: true,\n },\n name: {\n get: function get() { return name; },\n set: undefined,\n enumerable: false,\n // configurable: false would accurately preserve the behavior of\n // the original, but I'm guessing that was not intentional.\n // For an actual error subclass, this property would\n // be configurable.\n configurable: true,\n },\n toString: {\n value: function value() { return this.name + \": \" + this.message; },\n writable: true,\n enumerable: false,\n configurable: true,\n },\n });\n\n return CustomError;\n}\n\nutil.newError = newError;\n\n/**\n * Constructs a new protocol error.\n * @classdesc Error subclass indicating a protocol specifc error.\n * @memberof util\n * @extends Error\n * @template T extends Message\n * @constructor\n * @param {string} message Error message\n * @param {Object.} [properties] Additional properties\n * @example\n * try {\n * MyMessage.decode(someBuffer); // throws if required fields are missing\n * } catch (e) {\n * if (e instanceof ProtocolError && e.instance)\n * console.log(\"decoded so far: \" + JSON.stringify(e.instance));\n * }\n */\nutil.ProtocolError = newError(\"ProtocolError\");\n\n/**\n * So far decoded message instance.\n * @name util.ProtocolError#instance\n * @type {Message}\n */\n\n/**\n * A OneOf getter as returned by {@link util.oneOfGetter}.\n * @typedef OneOfGetter\n * @type {function}\n * @returns {string|undefined} Set field name, if any\n */\n\n/**\n * Builds a getter for a oneof's present field name.\n * @param {string[]} fieldNames Field names\n * @returns {OneOfGetter} Unbound getter\n */\nutil.oneOfGetter = function getOneOf(fieldNames) {\n var fieldMap = {};\n for (var i = 0; i < fieldNames.length; ++i)\n fieldMap[fieldNames[i]] = 1;\n\n /**\n * @returns {string|undefined} Set field name, if any\n * @this Object\n * @ignore\n */\n return function() { // eslint-disable-line consistent-return\n for (var keys = Object.keys(this), i = keys.length - 1; i > -1; --i)\n if (fieldMap[keys[i]] === 1 && this[keys[i]] !== undefined && this[keys[i]] !== null)\n return keys[i];\n };\n};\n\n/**\n * A OneOf setter as returned by {@link util.oneOfSetter}.\n * @typedef OneOfSetter\n * @type {function}\n * @param {string|undefined} value Field name\n * @returns {undefined}\n */\n\n/**\n * Builds a setter for a oneof's present field name.\n * @param {string[]} fieldNames Field names\n * @returns {OneOfSetter} Unbound setter\n */\nutil.oneOfSetter = function setOneOf(fieldNames) {\n\n /**\n * @param {string} name Field name\n * @returns {undefined}\n * @this Object\n * @ignore\n */\n return function(name) {\n for (var i = 0; i < fieldNames.length; ++i)\n if (fieldNames[i] !== name)\n delete this[fieldNames[i]];\n };\n};\n\n/**\n * Default conversion options used for {@link Message#toJSON} implementations.\n *\n * These options are close to proto3's JSON mapping with the exception that internal types like Any are handled just like messages. More precisely:\n *\n * - Longs become strings\n * - Enums become string keys\n * - Bytes become base64 encoded strings\n * - (Sub-)Messages become plain objects\n * - Maps become plain objects with all string keys\n * - Repeated fields become arrays\n * - NaN and Infinity for float and double fields become strings\n *\n * @type {IConversionOptions}\n * @see https://developers.google.com/protocol-buffers/docs/proto3?hl=en#json\n */\nutil.toJSONOptions = {\n longs: String,\n enums: String,\n bytes: String,\n json: true\n};\n\n// Sets up buffer utility according to the environment (called in index-minimal)\nutil._configure = function() {\n var Buffer = util.Buffer;\n /* istanbul ignore if */\n if (!Buffer) {\n util._Buffer_from = util._Buffer_allocUnsafe = null;\n return;\n }\n // because node 4.x buffers are incompatible & immutable\n // see: https://github.com/dcodeIO/protobuf.js/pull/665\n util._Buffer_from = Buffer.from !== Uint8Array.from && Buffer.from ||\n /* istanbul ignore next */\n function Buffer_from(value, encoding) {\n return new Buffer(value, encoding);\n };\n util._Buffer_allocUnsafe = Buffer.allocUnsafe ||\n /* istanbul ignore next */\n function Buffer_allocUnsafe(size) {\n return new Buffer(size);\n };\n};\n","\"use strict\";\nmodule.exports = Writer;\n\nvar util = require(15);\n\nvar BufferWriter; // cyclic\n\nvar LongBits = util.LongBits,\n base64 = util.base64,\n utf8 = util.utf8;\n\n/**\n * Constructs a new writer operation instance.\n * @classdesc Scheduled writer operation.\n * @constructor\n * @param {function(*, Uint8Array, number)} fn Function to call\n * @param {number} len Value byte length\n * @param {*} val Value to write\n * @ignore\n */\nfunction Op(fn, len, val) {\n\n /**\n * Function to call.\n * @type {function(Uint8Array, number, *)}\n */\n this.fn = fn;\n\n /**\n * Value byte length.\n * @type {number}\n */\n this.len = len;\n\n /**\n * Next operation.\n * @type {Writer.Op|undefined}\n */\n this.next = undefined;\n\n /**\n * Value to write.\n * @type {*}\n */\n this.val = val; // type varies\n}\n\n/* istanbul ignore next */\nfunction noop() {} // eslint-disable-line no-empty-function\n\n/**\n * Constructs a new writer state instance.\n * @classdesc Copied writer state.\n * @memberof Writer\n * @constructor\n * @param {Writer} writer Writer to copy state from\n * @ignore\n */\nfunction State(writer) {\n\n /**\n * Current head.\n * @type {Writer.Op}\n */\n this.head = writer.head;\n\n /**\n * Current tail.\n * @type {Writer.Op}\n */\n this.tail = writer.tail;\n\n /**\n * Current buffer length.\n * @type {number}\n */\n this.len = writer.len;\n\n /**\n * Next state.\n * @type {State|null}\n */\n this.next = writer.states;\n}\n\n/**\n * Constructs a new writer instance.\n * @classdesc Wire format writer using `Uint8Array` if available, otherwise `Array`.\n * @constructor\n */\nfunction Writer() {\n\n /**\n * Current length.\n * @type {number}\n */\n this.len = 0;\n\n /**\n * Operations head.\n * @type {Object}\n */\n this.head = new Op(noop, 0, 0);\n\n /**\n * Operations tail\n * @type {Object}\n */\n this.tail = this.head;\n\n /**\n * Linked forked states.\n * @type {Object|null}\n */\n this.states = null;\n\n // When a value is written, the writer calculates its byte length and puts it into a linked\n // list of operations to perform when finish() is called. This both allows us to allocate\n // buffers of the exact required size and reduces the amount of work we have to do compared\n // to first calculating over objects and then encoding over objects. In our case, the encoding\n // part is just a linked list walk calling operations with already prepared values.\n}\n\nvar create = function create() {\n return util.Buffer\n ? function create_buffer_setup() {\n return (Writer.create = function create_buffer() {\n return new BufferWriter();\n })();\n }\n /* istanbul ignore next */\n : function create_array() {\n return new Writer();\n };\n};\n\n/**\n * Creates a new writer.\n * @function\n * @returns {BufferWriter|Writer} A {@link BufferWriter} when Buffers are supported, otherwise a {@link Writer}\n */\nWriter.create = create();\n\n/**\n * Allocates a buffer of the specified size.\n * @param {number} size Buffer size\n * @returns {Uint8Array} Buffer\n */\nWriter.alloc = function alloc(size) {\n return new util.Array(size);\n};\n\n// Use Uint8Array buffer pool in the browser, just like node does with buffers\n/* istanbul ignore else */\nif (util.Array !== Array)\n Writer.alloc = util.pool(Writer.alloc, util.Array.prototype.subarray);\n\n/**\n * Pushes a new operation to the queue.\n * @param {function(Uint8Array, number, *)} fn Function to call\n * @param {number} len Value byte length\n * @param {number} val Value to write\n * @returns {Writer} `this`\n * @private\n */\nWriter.prototype._push = function push(fn, len, val) {\n this.tail = this.tail.next = new Op(fn, len, val);\n this.len += len;\n return this;\n};\n\nfunction writeByte(val, buf, pos) {\n buf[pos] = val & 255;\n}\n\nfunction writeVarint32(val, buf, pos) {\n while (val > 127) {\n buf[pos++] = val & 127 | 128;\n val >>>= 7;\n }\n buf[pos] = val;\n}\n\n/**\n * Constructs a new varint writer operation instance.\n * @classdesc Scheduled varint writer operation.\n * @extends Op\n * @constructor\n * @param {number} len Value byte length\n * @param {number} val Value to write\n * @ignore\n */\nfunction VarintOp(len, val) {\n this.len = len;\n this.next = undefined;\n this.val = val;\n}\n\nVarintOp.prototype = Object.create(Op.prototype);\nVarintOp.prototype.fn = writeVarint32;\n\n/**\n * Writes an unsigned 32 bit value as a varint.\n * @param {number} value Value to write\n * @returns {Writer} `this`\n */\nWriter.prototype.uint32 = function write_uint32(value) {\n // here, the call to this.push has been inlined and a varint specific Op subclass is used.\n // uint32 is by far the most frequently used operation and benefits significantly from this.\n this.len += (this.tail = this.tail.next = new VarintOp(\n (value = value >>> 0)\n < 128 ? 1\n : value < 16384 ? 2\n : value < 2097152 ? 3\n : value < 268435456 ? 4\n : 5,\n value)).len;\n return this;\n};\n\n/**\n * Writes a signed 32 bit value as a varint.\n * @function\n * @param {number} value Value to write\n * @returns {Writer} `this`\n */\nWriter.prototype.int32 = function write_int32(value) {\n return value < 0\n ? this._push(writeVarint64, 10, LongBits.fromNumber(value)) // 10 bytes per spec\n : this.uint32(value);\n};\n\n/**\n * Writes a 32 bit value as a varint, zig-zag encoded.\n * @param {number} value Value to write\n * @returns {Writer} `this`\n */\nWriter.prototype.sint32 = function write_sint32(value) {\n return this.uint32((value << 1 ^ value >> 31) >>> 0);\n};\n\nfunction writeVarint64(val, buf, pos) {\n while (val.hi) {\n buf[pos++] = val.lo & 127 | 128;\n val.lo = (val.lo >>> 7 | val.hi << 25) >>> 0;\n val.hi >>>= 7;\n }\n while (val.lo > 127) {\n buf[pos++] = val.lo & 127 | 128;\n val.lo = val.lo >>> 7;\n }\n buf[pos++] = val.lo;\n}\n\n/**\n * Writes an unsigned 64 bit value as a varint.\n * @param {Long|number|string} value Value to write\n * @returns {Writer} `this`\n * @throws {TypeError} If `value` is a string and no long library is present.\n */\nWriter.prototype.uint64 = function write_uint64(value) {\n var bits = LongBits.from(value);\n return this._push(writeVarint64, bits.length(), bits);\n};\n\n/**\n * Writes a signed 64 bit value as a varint.\n * @function\n * @param {Long|number|string} value Value to write\n * @returns {Writer} `this`\n * @throws {TypeError} If `value` is a string and no long library is present.\n */\nWriter.prototype.int64 = Writer.prototype.uint64;\n\n/**\n * Writes a signed 64 bit value as a varint, zig-zag encoded.\n * @param {Long|number|string} value Value to write\n * @returns {Writer} `this`\n * @throws {TypeError} If `value` is a string and no long library is present.\n */\nWriter.prototype.sint64 = function write_sint64(value) {\n var bits = LongBits.from(value).zzEncode();\n return this._push(writeVarint64, bits.length(), bits);\n};\n\n/**\n * Writes a boolish value as a varint.\n * @param {boolean} value Value to write\n * @returns {Writer} `this`\n */\nWriter.prototype.bool = function write_bool(value) {\n return this._push(writeByte, 1, value ? 1 : 0);\n};\n\nfunction writeFixed32(val, buf, pos) {\n buf[pos ] = val & 255;\n buf[pos + 1] = val >>> 8 & 255;\n buf[pos + 2] = val >>> 16 & 255;\n buf[pos + 3] = val >>> 24;\n}\n\n/**\n * Writes an unsigned 32 bit value as fixed 32 bits.\n * @param {number} value Value to write\n * @returns {Writer} `this`\n */\nWriter.prototype.fixed32 = function write_fixed32(value) {\n return this._push(writeFixed32, 4, value >>> 0);\n};\n\n/**\n * Writes a signed 32 bit value as fixed 32 bits.\n * @function\n * @param {number} value Value to write\n * @returns {Writer} `this`\n */\nWriter.prototype.sfixed32 = Writer.prototype.fixed32;\n\n/**\n * Writes an unsigned 64 bit value as fixed 64 bits.\n * @param {Long|number|string} value Value to write\n * @returns {Writer} `this`\n * @throws {TypeError} If `value` is a string and no long library is present.\n */\nWriter.prototype.fixed64 = function write_fixed64(value) {\n var bits = LongBits.from(value);\n return this._push(writeFixed32, 4, bits.lo)._push(writeFixed32, 4, bits.hi);\n};\n\n/**\n * Writes a signed 64 bit value as fixed 64 bits.\n * @function\n * @param {Long|number|string} value Value to write\n * @returns {Writer} `this`\n * @throws {TypeError} If `value` is a string and no long library is present.\n */\nWriter.prototype.sfixed64 = Writer.prototype.fixed64;\n\n/**\n * Writes a float (32 bit).\n * @function\n * @param {number} value Value to write\n * @returns {Writer} `this`\n */\nWriter.prototype.float = function write_float(value) {\n return this._push(util.float.writeFloatLE, 4, value);\n};\n\n/**\n * Writes a double (64 bit float).\n * @function\n * @param {number} value Value to write\n * @returns {Writer} `this`\n */\nWriter.prototype.double = function write_double(value) {\n return this._push(util.float.writeDoubleLE, 8, value);\n};\n\nvar writeBytes = util.Array.prototype.set\n ? function writeBytes_set(val, buf, pos) {\n buf.set(val, pos); // also works for plain array values\n }\n /* istanbul ignore next */\n : function writeBytes_for(val, buf, pos) {\n for (var i = 0; i < val.length; ++i)\n buf[pos + i] = val[i];\n };\n\n/**\n * Writes a sequence of bytes.\n * @param {Uint8Array|string} value Buffer or base64 encoded string to write\n * @returns {Writer} `this`\n */\nWriter.prototype.bytes = function write_bytes(value) {\n var len = value.length >>> 0;\n if (!len)\n return this._push(writeByte, 1, 0);\n if (util.isString(value)) {\n var buf = Writer.alloc(len = base64.length(value));\n base64.decode(value, buf, 0);\n value = buf;\n }\n return this.uint32(len)._push(writeBytes, len, value);\n};\n\n/**\n * Writes a string.\n * @param {string} value Value to write\n * @returns {Writer} `this`\n */\nWriter.prototype.string = function write_string(value) {\n var len = utf8.length(value);\n return len\n ? this.uint32(len)._push(utf8.write, len, value)\n : this._push(writeByte, 1, 0);\n};\n\n/**\n * Forks this writer's state by pushing it to a stack.\n * Calling {@link Writer#reset|reset} or {@link Writer#ldelim|ldelim} resets the writer to the previous state.\n * @returns {Writer} `this`\n */\nWriter.prototype.fork = function fork() {\n this.states = new State(this);\n this.head = this.tail = new Op(noop, 0, 0);\n this.len = 0;\n return this;\n};\n\n/**\n * Resets this instance to the last state.\n * @returns {Writer} `this`\n */\nWriter.prototype.reset = function reset() {\n if (this.states) {\n this.head = this.states.head;\n this.tail = this.states.tail;\n this.len = this.states.len;\n this.states = this.states.next;\n } else {\n this.head = this.tail = new Op(noop, 0, 0);\n this.len = 0;\n }\n return this;\n};\n\n/**\n * Resets to the last state and appends the fork state's current write length as a varint followed by its operations.\n * @returns {Writer} `this`\n */\nWriter.prototype.ldelim = function ldelim() {\n var head = this.head,\n tail = this.tail,\n len = this.len;\n this.reset().uint32(len);\n if (len) {\n this.tail.next = head.next; // skip noop\n this.tail = tail;\n this.len += len;\n }\n return this;\n};\n\n/**\n * Finishes the write operation.\n * @returns {Uint8Array} Finished buffer\n */\nWriter.prototype.finish = function finish() {\n var head = this.head.next, // skip noop\n buf = this.constructor.alloc(this.len),\n pos = 0;\n while (head) {\n head.fn(head.val, buf, pos);\n pos += head.len;\n head = head.next;\n }\n // this.head = this.tail = null;\n return buf;\n};\n\nWriter._configure = function(BufferWriter_) {\n BufferWriter = BufferWriter_;\n Writer.create = create();\n BufferWriter._configure();\n};\n","\"use strict\";\nmodule.exports = BufferWriter;\n\n// extends Writer\nvar Writer = require(16);\n(BufferWriter.prototype = Object.create(Writer.prototype)).constructor = BufferWriter;\n\nvar util = require(15);\n\n/**\n * Constructs a new buffer writer instance.\n * @classdesc Wire format writer using node buffers.\n * @extends Writer\n * @constructor\n */\nfunction BufferWriter() {\n Writer.call(this);\n}\n\nBufferWriter._configure = function () {\n /**\n * Allocates a buffer of the specified size.\n * @function\n * @param {number} size Buffer size\n * @returns {Buffer} Buffer\n */\n BufferWriter.alloc = util._Buffer_allocUnsafe;\n\n BufferWriter.writeBytesBuffer = util.Buffer && util.Buffer.prototype instanceof Uint8Array && util.Buffer.prototype.set.name === \"set\"\n ? function writeBytesBuffer_set(val, buf, pos) {\n buf.set(val, pos); // faster than copy (requires node >= 4 where Buffers extend Uint8Array and set is properly inherited)\n // also works for plain array values\n }\n /* istanbul ignore next */\n : function writeBytesBuffer_copy(val, buf, pos) {\n if (val.copy) // Buffer values\n val.copy(buf, pos, 0, val.length);\n else for (var i = 0; i < val.length;) // plain array values\n buf[pos++] = val[i++];\n };\n};\n\n\n/**\n * @override\n */\nBufferWriter.prototype.bytes = function write_bytes_buffer(value) {\n if (util.isString(value))\n value = util._Buffer_from(value, \"base64\");\n var len = value.length >>> 0;\n this.uint32(len);\n if (len)\n this._push(BufferWriter.writeBytesBuffer, len, value);\n return this;\n};\n\nfunction writeStringBuffer(val, buf, pos) {\n if (val.length < 40) // plain js is faster for short strings (probably due to redundant assertions)\n util.utf8.write(val, buf, pos);\n else if (buf.utf8Write)\n buf.utf8Write(val, pos);\n else\n buf.write(val, pos);\n}\n\n/**\n * @override\n */\nBufferWriter.prototype.string = function write_string_buffer(value) {\n var len = util.Buffer.byteLength(value);\n this.uint32(len);\n if (len)\n this._push(writeStringBuffer, len, value);\n return this;\n};\n\n\n/**\n * Finishes the write operation.\n * @name BufferWriter#finish\n * @function\n * @returns {Buffer} Finished buffer\n */\n\nBufferWriter._configure();\n"],"sourceRoot":"."} \ No newline at end of file diff --git a/node_modules/protobufjs/dist/protobuf.js b/node_modules/protobufjs/dist/protobuf.js new file mode 100644 index 0000000..62727bd --- /dev/null +++ b/node_modules/protobufjs/dist/protobuf.js @@ -0,0 +1,9105 @@ +/*! + * protobuf.js v7.3.0 (c) 2016, daniel wirtz + * compiled fri, 10 may 2024 03:38:34 utc + * licensed under the bsd-3-clause license + * see: https://github.com/dcodeio/protobuf.js for details + */ +(function(undefined){"use strict";(function prelude(modules, cache, entries) { + + // This is the prelude used to bundle protobuf.js for the browser. Wraps up the CommonJS + // sources through a conflict-free require shim and is again wrapped within an iife that + // provides a minification-friendly `undefined` var plus a global "use strict" directive + // so that minification can remove the directives of each module. + + function $require(name) { + var $module = cache[name]; + if (!$module) + modules[name][0].call($module = cache[name] = { exports: {} }, $require, $module, $module.exports); + return $module.exports; + } + + var protobuf = $require(entries[0]); + + // Expose globally + protobuf.util.global.protobuf = protobuf; + + // Be nice to AMD + if (typeof define === "function" && define.amd) + define(["long"], function(Long) { + if (Long && Long.isLong) { + protobuf.util.Long = Long; + protobuf.configure(); + } + return protobuf; + }); + + // Be nice to CommonJS + if (typeof module === "object" && module && module.exports) + module.exports = protobuf; + +})/* end of prelude */({1:[function(require,module,exports){ +"use strict"; +module.exports = asPromise; + +/** + * Callback as used by {@link util.asPromise}. + * @typedef asPromiseCallback + * @type {function} + * @param {Error|null} error Error, if any + * @param {...*} params Additional arguments + * @returns {undefined} + */ + +/** + * Returns a promise from a node-style callback function. + * @memberof util + * @param {asPromiseCallback} fn Function to call + * @param {*} ctx Function context + * @param {...*} params Function arguments + * @returns {Promise<*>} Promisified function + */ +function asPromise(fn, ctx/*, varargs */) { + var params = new Array(arguments.length - 1), + offset = 0, + index = 2, + pending = true; + while (index < arguments.length) + params[offset++] = arguments[index++]; + return new Promise(function executor(resolve, reject) { + params[offset] = function callback(err/*, varargs */) { + if (pending) { + pending = false; + if (err) + reject(err); + else { + var params = new Array(arguments.length - 1), + offset = 0; + while (offset < params.length) + params[offset++] = arguments[offset]; + resolve.apply(null, params); + } + } + }; + try { + fn.apply(ctx || null, params); + } catch (err) { + if (pending) { + pending = false; + reject(err); + } + } + }); +} + +},{}],2:[function(require,module,exports){ +"use strict"; + +/** + * A minimal base64 implementation for number arrays. + * @memberof util + * @namespace + */ +var base64 = exports; + +/** + * Calculates the byte length of a base64 encoded string. + * @param {string} string Base64 encoded string + * @returns {number} Byte length + */ +base64.length = function length(string) { + var p = string.length; + if (!p) + return 0; + var n = 0; + while (--p % 4 > 1 && string.charAt(p) === "=") + ++n; + return Math.ceil(string.length * 3) / 4 - n; +}; + +// Base64 encoding table +var b64 = new Array(64); + +// Base64 decoding table +var s64 = new Array(123); + +// 65..90, 97..122, 48..57, 43, 47 +for (var i = 0; i < 64;) + s64[b64[i] = i < 26 ? i + 65 : i < 52 ? i + 71 : i < 62 ? i - 4 : i - 59 | 43] = i++; + +/** + * Encodes a buffer to a base64 encoded string. + * @param {Uint8Array} buffer Source buffer + * @param {number} start Source start + * @param {number} end Source end + * @returns {string} Base64 encoded string + */ +base64.encode = function encode(buffer, start, end) { + var parts = null, + chunk = []; + var i = 0, // output index + j = 0, // goto index + t; // temporary + while (start < end) { + var b = buffer[start++]; + switch (j) { + case 0: + chunk[i++] = b64[b >> 2]; + t = (b & 3) << 4; + j = 1; + break; + case 1: + chunk[i++] = b64[t | b >> 4]; + t = (b & 15) << 2; + j = 2; + break; + case 2: + chunk[i++] = b64[t | b >> 6]; + chunk[i++] = b64[b & 63]; + j = 0; + break; + } + if (i > 8191) { + (parts || (parts = [])).push(String.fromCharCode.apply(String, chunk)); + i = 0; + } + } + if (j) { + chunk[i++] = b64[t]; + chunk[i++] = 61; + if (j === 1) + chunk[i++] = 61; + } + if (parts) { + if (i) + parts.push(String.fromCharCode.apply(String, chunk.slice(0, i))); + return parts.join(""); + } + return String.fromCharCode.apply(String, chunk.slice(0, i)); +}; + +var invalidEncoding = "invalid encoding"; + +/** + * Decodes a base64 encoded string to a buffer. + * @param {string} string Source string + * @param {Uint8Array} buffer Destination buffer + * @param {number} offset Destination offset + * @returns {number} Number of bytes written + * @throws {Error} If encoding is invalid + */ +base64.decode = function decode(string, buffer, offset) { + var start = offset; + var j = 0, // goto index + t; // temporary + for (var i = 0; i < string.length;) { + var c = string.charCodeAt(i++); + if (c === 61 && j > 1) + break; + if ((c = s64[c]) === undefined) + throw Error(invalidEncoding); + switch (j) { + case 0: + t = c; + j = 1; + break; + case 1: + buffer[offset++] = t << 2 | (c & 48) >> 4; + t = c; + j = 2; + break; + case 2: + buffer[offset++] = (t & 15) << 4 | (c & 60) >> 2; + t = c; + j = 3; + break; + case 3: + buffer[offset++] = (t & 3) << 6 | c; + j = 0; + break; + } + } + if (j === 1) + throw Error(invalidEncoding); + return offset - start; +}; + +/** + * Tests if the specified string appears to be base64 encoded. + * @param {string} string String to test + * @returns {boolean} `true` if probably base64 encoded, otherwise false + */ +base64.test = function test(string) { + return /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(string); +}; + +},{}],3:[function(require,module,exports){ +"use strict"; +module.exports = codegen; + +/** + * Begins generating a function. + * @memberof util + * @param {string[]} functionParams Function parameter names + * @param {string} [functionName] Function name if not anonymous + * @returns {Codegen} Appender that appends code to the function's body + */ +function codegen(functionParams, functionName) { + + /* istanbul ignore if */ + if (typeof functionParams === "string") { + functionName = functionParams; + functionParams = undefined; + } + + var body = []; + + /** + * Appends code to the function's body or finishes generation. + * @typedef Codegen + * @type {function} + * @param {string|Object.} [formatStringOrScope] Format string or, to finish the function, an object of additional scope variables, if any + * @param {...*} [formatParams] Format parameters + * @returns {Codegen|Function} Itself or the generated function if finished + * @throws {Error} If format parameter counts do not match + */ + + function Codegen(formatStringOrScope) { + // note that explicit array handling below makes this ~50% faster + + // finish the function + if (typeof formatStringOrScope !== "string") { + var source = toString(); + if (codegen.verbose) + console.log("codegen: " + source); // eslint-disable-line no-console + source = "return " + source; + if (formatStringOrScope) { + var scopeKeys = Object.keys(formatStringOrScope), + scopeParams = new Array(scopeKeys.length + 1), + scopeValues = new Array(scopeKeys.length), + scopeOffset = 0; + while (scopeOffset < scopeKeys.length) { + scopeParams[scopeOffset] = scopeKeys[scopeOffset]; + scopeValues[scopeOffset] = formatStringOrScope[scopeKeys[scopeOffset++]]; + } + scopeParams[scopeOffset] = source; + return Function.apply(null, scopeParams).apply(null, scopeValues); // eslint-disable-line no-new-func + } + return Function(source)(); // eslint-disable-line no-new-func + } + + // otherwise append to body + var formatParams = new Array(arguments.length - 1), + formatOffset = 0; + while (formatOffset < formatParams.length) + formatParams[formatOffset] = arguments[++formatOffset]; + formatOffset = 0; + formatStringOrScope = formatStringOrScope.replace(/%([%dfijs])/g, function replace($0, $1) { + var value = formatParams[formatOffset++]; + switch ($1) { + case "d": case "f": return String(Number(value)); + case "i": return String(Math.floor(value)); + case "j": return JSON.stringify(value); + case "s": return String(value); + } + return "%"; + }); + if (formatOffset !== formatParams.length) + throw Error("parameter count mismatch"); + body.push(formatStringOrScope); + return Codegen; + } + + function toString(functionNameOverride) { + return "function " + (functionNameOverride || functionName || "") + "(" + (functionParams && functionParams.join(",") || "") + "){\n " + body.join("\n ") + "\n}"; + } + + Codegen.toString = toString; + return Codegen; +} + +/** + * Begins generating a function. + * @memberof util + * @function codegen + * @param {string} [functionName] Function name if not anonymous + * @returns {Codegen} Appender that appends code to the function's body + * @variation 2 + */ + +/** + * When set to `true`, codegen will log generated code to console. Useful for debugging. + * @name util.codegen.verbose + * @type {boolean} + */ +codegen.verbose = false; + +},{}],4:[function(require,module,exports){ +"use strict"; +module.exports = EventEmitter; + +/** + * Constructs a new event emitter instance. + * @classdesc A minimal event emitter. + * @memberof util + * @constructor + */ +function EventEmitter() { + + /** + * Registered listeners. + * @type {Object.} + * @private + */ + this._listeners = {}; +} + +/** + * Registers an event listener. + * @param {string} evt Event name + * @param {function} fn Listener + * @param {*} [ctx] Listener context + * @returns {util.EventEmitter} `this` + */ +EventEmitter.prototype.on = function on(evt, fn, ctx) { + (this._listeners[evt] || (this._listeners[evt] = [])).push({ + fn : fn, + ctx : ctx || this + }); + return this; +}; + +/** + * Removes an event listener or any matching listeners if arguments are omitted. + * @param {string} [evt] Event name. Removes all listeners if omitted. + * @param {function} [fn] Listener to remove. Removes all listeners of `evt` if omitted. + * @returns {util.EventEmitter} `this` + */ +EventEmitter.prototype.off = function off(evt, fn) { + if (evt === undefined) + this._listeners = {}; + else { + if (fn === undefined) + this._listeners[evt] = []; + else { + var listeners = this._listeners[evt]; + for (var i = 0; i < listeners.length;) + if (listeners[i].fn === fn) + listeners.splice(i, 1); + else + ++i; + } + } + return this; +}; + +/** + * Emits an event by calling its listeners with the specified arguments. + * @param {string} evt Event name + * @param {...*} args Arguments + * @returns {util.EventEmitter} `this` + */ +EventEmitter.prototype.emit = function emit(evt) { + var listeners = this._listeners[evt]; + if (listeners) { + var args = [], + i = 1; + for (; i < arguments.length;) + args.push(arguments[i++]); + for (i = 0; i < listeners.length;) + listeners[i].fn.apply(listeners[i++].ctx, args); + } + return this; +}; + +},{}],5:[function(require,module,exports){ +"use strict"; +module.exports = fetch; + +var asPromise = require(1), + inquire = require(7); + +var fs = inquire("fs"); + +/** + * Node-style callback as used by {@link util.fetch}. + * @typedef FetchCallback + * @type {function} + * @param {?Error} error Error, if any, otherwise `null` + * @param {string} [contents] File contents, if there hasn't been an error + * @returns {undefined} + */ + +/** + * Options as used by {@link util.fetch}. + * @typedef FetchOptions + * @type {Object} + * @property {boolean} [binary=false] Whether expecting a binary response + * @property {boolean} [xhr=false] If `true`, forces the use of XMLHttpRequest + */ + +/** + * Fetches the contents of a file. + * @memberof util + * @param {string} filename File path or url + * @param {FetchOptions} options Fetch options + * @param {FetchCallback} callback Callback function + * @returns {undefined} + */ +function fetch(filename, options, callback) { + if (typeof options === "function") { + callback = options; + options = {}; + } else if (!options) + options = {}; + + if (!callback) + return asPromise(fetch, this, filename, options); // eslint-disable-line no-invalid-this + + // if a node-like filesystem is present, try it first but fall back to XHR if nothing is found. + if (!options.xhr && fs && fs.readFile) + return fs.readFile(filename, function fetchReadFileCallback(err, contents) { + return err && typeof XMLHttpRequest !== "undefined" + ? fetch.xhr(filename, options, callback) + : err + ? callback(err) + : callback(null, options.binary ? contents : contents.toString("utf8")); + }); + + // use the XHR version otherwise. + return fetch.xhr(filename, options, callback); +} + +/** + * Fetches the contents of a file. + * @name util.fetch + * @function + * @param {string} path File path or url + * @param {FetchCallback} callback Callback function + * @returns {undefined} + * @variation 2 + */ + +/** + * Fetches the contents of a file. + * @name util.fetch + * @function + * @param {string} path File path or url + * @param {FetchOptions} [options] Fetch options + * @returns {Promise} Promise + * @variation 3 + */ + +/**/ +fetch.xhr = function fetch_xhr(filename, options, callback) { + var xhr = new XMLHttpRequest(); + xhr.onreadystatechange /* works everywhere */ = function fetchOnReadyStateChange() { + + if (xhr.readyState !== 4) + return undefined; + + // local cors security errors return status 0 / empty string, too. afaik this cannot be + // reliably distinguished from an actually empty file for security reasons. feel free + // to send a pull request if you are aware of a solution. + if (xhr.status !== 0 && xhr.status !== 200) + return callback(Error("status " + xhr.status)); + + // if binary data is expected, make sure that some sort of array is returned, even if + // ArrayBuffers are not supported. the binary string fallback, however, is unsafe. + if (options.binary) { + var buffer = xhr.response; + if (!buffer) { + buffer = []; + for (var i = 0; i < xhr.responseText.length; ++i) + buffer.push(xhr.responseText.charCodeAt(i) & 255); + } + return callback(null, typeof Uint8Array !== "undefined" ? new Uint8Array(buffer) : buffer); + } + return callback(null, xhr.responseText); + }; + + if (options.binary) { + // ref: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Sending_and_Receiving_Binary_Data#Receiving_binary_data_in_older_browsers + if ("overrideMimeType" in xhr) + xhr.overrideMimeType("text/plain; charset=x-user-defined"); + xhr.responseType = "arraybuffer"; + } + + xhr.open("GET", filename); + xhr.send(); +}; + +},{"1":1,"7":7}],6:[function(require,module,exports){ +"use strict"; + +module.exports = factory(factory); + +/** + * Reads / writes floats / doubles from / to buffers. + * @name util.float + * @namespace + */ + +/** + * Writes a 32 bit float to a buffer using little endian byte order. + * @name util.float.writeFloatLE + * @function + * @param {number} val Value to write + * @param {Uint8Array} buf Target buffer + * @param {number} pos Target buffer offset + * @returns {undefined} + */ + +/** + * Writes a 32 bit float to a buffer using big endian byte order. + * @name util.float.writeFloatBE + * @function + * @param {number} val Value to write + * @param {Uint8Array} buf Target buffer + * @param {number} pos Target buffer offset + * @returns {undefined} + */ + +/** + * Reads a 32 bit float from a buffer using little endian byte order. + * @name util.float.readFloatLE + * @function + * @param {Uint8Array} buf Source buffer + * @param {number} pos Source buffer offset + * @returns {number} Value read + */ + +/** + * Reads a 32 bit float from a buffer using big endian byte order. + * @name util.float.readFloatBE + * @function + * @param {Uint8Array} buf Source buffer + * @param {number} pos Source buffer offset + * @returns {number} Value read + */ + +/** + * Writes a 64 bit double to a buffer using little endian byte order. + * @name util.float.writeDoubleLE + * @function + * @param {number} val Value to write + * @param {Uint8Array} buf Target buffer + * @param {number} pos Target buffer offset + * @returns {undefined} + */ + +/** + * Writes a 64 bit double to a buffer using big endian byte order. + * @name util.float.writeDoubleBE + * @function + * @param {number} val Value to write + * @param {Uint8Array} buf Target buffer + * @param {number} pos Target buffer offset + * @returns {undefined} + */ + +/** + * Reads a 64 bit double from a buffer using little endian byte order. + * @name util.float.readDoubleLE + * @function + * @param {Uint8Array} buf Source buffer + * @param {number} pos Source buffer offset + * @returns {number} Value read + */ + +/** + * Reads a 64 bit double from a buffer using big endian byte order. + * @name util.float.readDoubleBE + * @function + * @param {Uint8Array} buf Source buffer + * @param {number} pos Source buffer offset + * @returns {number} Value read + */ + +// Factory function for the purpose of node-based testing in modified global environments +function factory(exports) { + + // float: typed array + if (typeof Float32Array !== "undefined") (function() { + + var f32 = new Float32Array([ -0 ]), + f8b = new Uint8Array(f32.buffer), + le = f8b[3] === 128; + + function writeFloat_f32_cpy(val, buf, pos) { + f32[0] = val; + buf[pos ] = f8b[0]; + buf[pos + 1] = f8b[1]; + buf[pos + 2] = f8b[2]; + buf[pos + 3] = f8b[3]; + } + + function writeFloat_f32_rev(val, buf, pos) { + f32[0] = val; + buf[pos ] = f8b[3]; + buf[pos + 1] = f8b[2]; + buf[pos + 2] = f8b[1]; + buf[pos + 3] = f8b[0]; + } + + /* istanbul ignore next */ + exports.writeFloatLE = le ? writeFloat_f32_cpy : writeFloat_f32_rev; + /* istanbul ignore next */ + exports.writeFloatBE = le ? writeFloat_f32_rev : writeFloat_f32_cpy; + + function readFloat_f32_cpy(buf, pos) { + f8b[0] = buf[pos ]; + f8b[1] = buf[pos + 1]; + f8b[2] = buf[pos + 2]; + f8b[3] = buf[pos + 3]; + return f32[0]; + } + + function readFloat_f32_rev(buf, pos) { + f8b[3] = buf[pos ]; + f8b[2] = buf[pos + 1]; + f8b[1] = buf[pos + 2]; + f8b[0] = buf[pos + 3]; + return f32[0]; + } + + /* istanbul ignore next */ + exports.readFloatLE = le ? readFloat_f32_cpy : readFloat_f32_rev; + /* istanbul ignore next */ + exports.readFloatBE = le ? readFloat_f32_rev : readFloat_f32_cpy; + + // float: ieee754 + })(); else (function() { + + function writeFloat_ieee754(writeUint, val, buf, pos) { + var sign = val < 0 ? 1 : 0; + if (sign) + val = -val; + if (val === 0) + writeUint(1 / val > 0 ? /* positive */ 0 : /* negative 0 */ 2147483648, buf, pos); + else if (isNaN(val)) + writeUint(2143289344, buf, pos); + else if (val > 3.4028234663852886e+38) // +-Infinity + writeUint((sign << 31 | 2139095040) >>> 0, buf, pos); + else if (val < 1.1754943508222875e-38) // denormal + writeUint((sign << 31 | Math.round(val / 1.401298464324817e-45)) >>> 0, buf, pos); + else { + var exponent = Math.floor(Math.log(val) / Math.LN2), + mantissa = Math.round(val * Math.pow(2, -exponent) * 8388608) & 8388607; + writeUint((sign << 31 | exponent + 127 << 23 | mantissa) >>> 0, buf, pos); + } + } + + exports.writeFloatLE = writeFloat_ieee754.bind(null, writeUintLE); + exports.writeFloatBE = writeFloat_ieee754.bind(null, writeUintBE); + + function readFloat_ieee754(readUint, buf, pos) { + var uint = readUint(buf, pos), + sign = (uint >> 31) * 2 + 1, + exponent = uint >>> 23 & 255, + mantissa = uint & 8388607; + return exponent === 255 + ? mantissa + ? NaN + : sign * Infinity + : exponent === 0 // denormal + ? sign * 1.401298464324817e-45 * mantissa + : sign * Math.pow(2, exponent - 150) * (mantissa + 8388608); + } + + exports.readFloatLE = readFloat_ieee754.bind(null, readUintLE); + exports.readFloatBE = readFloat_ieee754.bind(null, readUintBE); + + })(); + + // double: typed array + if (typeof Float64Array !== "undefined") (function() { + + var f64 = new Float64Array([-0]), + f8b = new Uint8Array(f64.buffer), + le = f8b[7] === 128; + + function writeDouble_f64_cpy(val, buf, pos) { + f64[0] = val; + buf[pos ] = f8b[0]; + buf[pos + 1] = f8b[1]; + buf[pos + 2] = f8b[2]; + buf[pos + 3] = f8b[3]; + buf[pos + 4] = f8b[4]; + buf[pos + 5] = f8b[5]; + buf[pos + 6] = f8b[6]; + buf[pos + 7] = f8b[7]; + } + + function writeDouble_f64_rev(val, buf, pos) { + f64[0] = val; + buf[pos ] = f8b[7]; + buf[pos + 1] = f8b[6]; + buf[pos + 2] = f8b[5]; + buf[pos + 3] = f8b[4]; + buf[pos + 4] = f8b[3]; + buf[pos + 5] = f8b[2]; + buf[pos + 6] = f8b[1]; + buf[pos + 7] = f8b[0]; + } + + /* istanbul ignore next */ + exports.writeDoubleLE = le ? writeDouble_f64_cpy : writeDouble_f64_rev; + /* istanbul ignore next */ + exports.writeDoubleBE = le ? writeDouble_f64_rev : writeDouble_f64_cpy; + + function readDouble_f64_cpy(buf, pos) { + f8b[0] = buf[pos ]; + f8b[1] = buf[pos + 1]; + f8b[2] = buf[pos + 2]; + f8b[3] = buf[pos + 3]; + f8b[4] = buf[pos + 4]; + f8b[5] = buf[pos + 5]; + f8b[6] = buf[pos + 6]; + f8b[7] = buf[pos + 7]; + return f64[0]; + } + + function readDouble_f64_rev(buf, pos) { + f8b[7] = buf[pos ]; + f8b[6] = buf[pos + 1]; + f8b[5] = buf[pos + 2]; + f8b[4] = buf[pos + 3]; + f8b[3] = buf[pos + 4]; + f8b[2] = buf[pos + 5]; + f8b[1] = buf[pos + 6]; + f8b[0] = buf[pos + 7]; + return f64[0]; + } + + /* istanbul ignore next */ + exports.readDoubleLE = le ? readDouble_f64_cpy : readDouble_f64_rev; + /* istanbul ignore next */ + exports.readDoubleBE = le ? readDouble_f64_rev : readDouble_f64_cpy; + + // double: ieee754 + })(); else (function() { + + function writeDouble_ieee754(writeUint, off0, off1, val, buf, pos) { + var sign = val < 0 ? 1 : 0; + if (sign) + val = -val; + if (val === 0) { + writeUint(0, buf, pos + off0); + writeUint(1 / val > 0 ? /* positive */ 0 : /* negative 0 */ 2147483648, buf, pos + off1); + } else if (isNaN(val)) { + writeUint(0, buf, pos + off0); + writeUint(2146959360, buf, pos + off1); + } else if (val > 1.7976931348623157e+308) { // +-Infinity + writeUint(0, buf, pos + off0); + writeUint((sign << 31 | 2146435072) >>> 0, buf, pos + off1); + } else { + var mantissa; + if (val < 2.2250738585072014e-308) { // denormal + mantissa = val / 5e-324; + writeUint(mantissa >>> 0, buf, pos + off0); + writeUint((sign << 31 | mantissa / 4294967296) >>> 0, buf, pos + off1); + } else { + var exponent = Math.floor(Math.log(val) / Math.LN2); + if (exponent === 1024) + exponent = 1023; + mantissa = val * Math.pow(2, -exponent); + writeUint(mantissa * 4503599627370496 >>> 0, buf, pos + off0); + writeUint((sign << 31 | exponent + 1023 << 20 | mantissa * 1048576 & 1048575) >>> 0, buf, pos + off1); + } + } + } + + exports.writeDoubleLE = writeDouble_ieee754.bind(null, writeUintLE, 0, 4); + exports.writeDoubleBE = writeDouble_ieee754.bind(null, writeUintBE, 4, 0); + + function readDouble_ieee754(readUint, off0, off1, buf, pos) { + var lo = readUint(buf, pos + off0), + hi = readUint(buf, pos + off1); + var sign = (hi >> 31) * 2 + 1, + exponent = hi >>> 20 & 2047, + mantissa = 4294967296 * (hi & 1048575) + lo; + return exponent === 2047 + ? mantissa + ? NaN + : sign * Infinity + : exponent === 0 // denormal + ? sign * 5e-324 * mantissa + : sign * Math.pow(2, exponent - 1075) * (mantissa + 4503599627370496); + } + + exports.readDoubleLE = readDouble_ieee754.bind(null, readUintLE, 0, 4); + exports.readDoubleBE = readDouble_ieee754.bind(null, readUintBE, 4, 0); + + })(); + + return exports; +} + +// uint helpers + +function writeUintLE(val, buf, pos) { + buf[pos ] = val & 255; + buf[pos + 1] = val >>> 8 & 255; + buf[pos + 2] = val >>> 16 & 255; + buf[pos + 3] = val >>> 24; +} + +function writeUintBE(val, buf, pos) { + buf[pos ] = val >>> 24; + buf[pos + 1] = val >>> 16 & 255; + buf[pos + 2] = val >>> 8 & 255; + buf[pos + 3] = val & 255; +} + +function readUintLE(buf, pos) { + return (buf[pos ] + | buf[pos + 1] << 8 + | buf[pos + 2] << 16 + | buf[pos + 3] << 24) >>> 0; +} + +function readUintBE(buf, pos) { + return (buf[pos ] << 24 + | buf[pos + 1] << 16 + | buf[pos + 2] << 8 + | buf[pos + 3]) >>> 0; +} + +},{}],7:[function(require,module,exports){ +"use strict"; +module.exports = inquire; + +/** + * Requires a module only if available. + * @memberof util + * @param {string} moduleName Module to require + * @returns {?Object} Required module if available and not empty, otherwise `null` + */ +function inquire(moduleName) { + try { + var mod = eval("quire".replace(/^/,"re"))(moduleName); // eslint-disable-line no-eval + if (mod && (mod.length || Object.keys(mod).length)) + return mod; + } catch (e) {} // eslint-disable-line no-empty + return null; +} + +},{}],8:[function(require,module,exports){ +"use strict"; + +/** + * A minimal path module to resolve Unix, Windows and URL paths alike. + * @memberof util + * @namespace + */ +var path = exports; + +var isAbsolute = +/** + * Tests if the specified path is absolute. + * @param {string} path Path to test + * @returns {boolean} `true` if path is absolute + */ +path.isAbsolute = function isAbsolute(path) { + return /^(?:\/|\w+:)/.test(path); +}; + +var normalize = +/** + * Normalizes the specified path. + * @param {string} path Path to normalize + * @returns {string} Normalized path + */ +path.normalize = function normalize(path) { + path = path.replace(/\\/g, "/") + .replace(/\/{2,}/g, "/"); + var parts = path.split("/"), + absolute = isAbsolute(path), + prefix = ""; + if (absolute) + prefix = parts.shift() + "/"; + for (var i = 0; i < parts.length;) { + if (parts[i] === "..") { + if (i > 0 && parts[i - 1] !== "..") + parts.splice(--i, 2); + else if (absolute) + parts.splice(i, 1); + else + ++i; + } else if (parts[i] === ".") + parts.splice(i, 1); + else + ++i; + } + return prefix + parts.join("/"); +}; + +/** + * Resolves the specified include path against the specified origin path. + * @param {string} originPath Path to the origin file + * @param {string} includePath Include path relative to origin path + * @param {boolean} [alreadyNormalized=false] `true` if both paths are already known to be normalized + * @returns {string} Path to the include file + */ +path.resolve = function resolve(originPath, includePath, alreadyNormalized) { + if (!alreadyNormalized) + includePath = normalize(includePath); + if (isAbsolute(includePath)) + return includePath; + if (!alreadyNormalized) + originPath = normalize(originPath); + return (originPath = originPath.replace(/(?:\/|^)[^/]+$/, "")).length ? normalize(originPath + "/" + includePath) : includePath; +}; + +},{}],9:[function(require,module,exports){ +"use strict"; +module.exports = pool; + +/** + * An allocator as used by {@link util.pool}. + * @typedef PoolAllocator + * @type {function} + * @param {number} size Buffer size + * @returns {Uint8Array} Buffer + */ + +/** + * A slicer as used by {@link util.pool}. + * @typedef PoolSlicer + * @type {function} + * @param {number} start Start offset + * @param {number} end End offset + * @returns {Uint8Array} Buffer slice + * @this {Uint8Array} + */ + +/** + * A general purpose buffer pool. + * @memberof util + * @function + * @param {PoolAllocator} alloc Allocator + * @param {PoolSlicer} slice Slicer + * @param {number} [size=8192] Slab size + * @returns {PoolAllocator} Pooled allocator + */ +function pool(alloc, slice, size) { + var SIZE = size || 8192; + var MAX = SIZE >>> 1; + var slab = null; + var offset = SIZE; + return function pool_alloc(size) { + if (size < 1 || size > MAX) + return alloc(size); + if (offset + size > SIZE) { + slab = alloc(SIZE); + offset = 0; + } + var buf = slice.call(slab, offset, offset += size); + if (offset & 7) // align to 32 bit + offset = (offset | 7) + 1; + return buf; + }; +} + +},{}],10:[function(require,module,exports){ +"use strict"; + +/** + * A minimal UTF8 implementation for number arrays. + * @memberof util + * @namespace + */ +var utf8 = exports; + +/** + * Calculates the UTF8 byte length of a string. + * @param {string} string String + * @returns {number} Byte length + */ +utf8.length = function utf8_length(string) { + var len = 0, + c = 0; + for (var i = 0; i < string.length; ++i) { + c = string.charCodeAt(i); + if (c < 128) + len += 1; + else if (c < 2048) + len += 2; + else if ((c & 0xFC00) === 0xD800 && (string.charCodeAt(i + 1) & 0xFC00) === 0xDC00) { + ++i; + len += 4; + } else + len += 3; + } + return len; +}; + +/** + * Reads UTF8 bytes as a string. + * @param {Uint8Array} buffer Source buffer + * @param {number} start Source start + * @param {number} end Source end + * @returns {string} String read + */ +utf8.read = function utf8_read(buffer, start, end) { + var len = end - start; + if (len < 1) + return ""; + var parts = null, + chunk = [], + i = 0, // char offset + t; // temporary + while (start < end) { + t = buffer[start++]; + if (t < 128) + chunk[i++] = t; + else if (t > 191 && t < 224) + chunk[i++] = (t & 31) << 6 | buffer[start++] & 63; + else if (t > 239 && t < 365) { + t = ((t & 7) << 18 | (buffer[start++] & 63) << 12 | (buffer[start++] & 63) << 6 | buffer[start++] & 63) - 0x10000; + chunk[i++] = 0xD800 + (t >> 10); + chunk[i++] = 0xDC00 + (t & 1023); + } else + chunk[i++] = (t & 15) << 12 | (buffer[start++] & 63) << 6 | buffer[start++] & 63; + if (i > 8191) { + (parts || (parts = [])).push(String.fromCharCode.apply(String, chunk)); + i = 0; + } + } + if (parts) { + if (i) + parts.push(String.fromCharCode.apply(String, chunk.slice(0, i))); + return parts.join(""); + } + return String.fromCharCode.apply(String, chunk.slice(0, i)); +}; + +/** + * Writes a string as UTF8 bytes. + * @param {string} string Source string + * @param {Uint8Array} buffer Destination buffer + * @param {number} offset Destination offset + * @returns {number} Bytes written + */ +utf8.write = function utf8_write(string, buffer, offset) { + var start = offset, + c1, // character 1 + c2; // character 2 + for (var i = 0; i < string.length; ++i) { + c1 = string.charCodeAt(i); + if (c1 < 128) { + buffer[offset++] = c1; + } else if (c1 < 2048) { + buffer[offset++] = c1 >> 6 | 192; + buffer[offset++] = c1 & 63 | 128; + } else if ((c1 & 0xFC00) === 0xD800 && ((c2 = string.charCodeAt(i + 1)) & 0xFC00) === 0xDC00) { + c1 = 0x10000 + ((c1 & 0x03FF) << 10) + (c2 & 0x03FF); + ++i; + buffer[offset++] = c1 >> 18 | 240; + buffer[offset++] = c1 >> 12 & 63 | 128; + buffer[offset++] = c1 >> 6 & 63 | 128; + buffer[offset++] = c1 & 63 | 128; + } else { + buffer[offset++] = c1 >> 12 | 224; + buffer[offset++] = c1 >> 6 & 63 | 128; + buffer[offset++] = c1 & 63 | 128; + } + } + return offset - start; +}; + +},{}],11:[function(require,module,exports){ +"use strict"; +module.exports = common; + +var commonRe = /\/|\./; + +/** + * Provides common type definitions. + * Can also be used to provide additional google types or your own custom types. + * @param {string} name Short name as in `google/protobuf/[name].proto` or full file name + * @param {Object.} json JSON definition within `google.protobuf` if a short name, otherwise the file's root definition + * @returns {undefined} + * @property {INamespace} google/protobuf/any.proto Any + * @property {INamespace} google/protobuf/duration.proto Duration + * @property {INamespace} google/protobuf/empty.proto Empty + * @property {INamespace} google/protobuf/field_mask.proto FieldMask + * @property {INamespace} google/protobuf/struct.proto Struct, Value, NullValue and ListValue + * @property {INamespace} google/protobuf/timestamp.proto Timestamp + * @property {INamespace} google/protobuf/wrappers.proto Wrappers + * @example + * // manually provides descriptor.proto (assumes google/protobuf/ namespace and .proto extension) + * protobuf.common("descriptor", descriptorJson); + * + * // manually provides a custom definition (uses my.foo namespace) + * protobuf.common("my/foo/bar.proto", myFooBarJson); + */ +function common(name, json) { + if (!commonRe.test(name)) { + name = "google/protobuf/" + name + ".proto"; + json = { nested: { google: { nested: { protobuf: { nested: json } } } } }; + } + common[name] = json; +} + +// Not provided because of limited use (feel free to discuss or to provide yourself): +// +// google/protobuf/descriptor.proto +// google/protobuf/source_context.proto +// google/protobuf/type.proto +// +// Stripped and pre-parsed versions of these non-bundled files are instead available as part of +// the repository or package within the google/protobuf directory. + +common("any", { + + /** + * Properties of a google.protobuf.Any message. + * @interface IAny + * @type {Object} + * @property {string} [typeUrl] + * @property {Uint8Array} [bytes] + * @memberof common + */ + Any: { + fields: { + type_url: { + type: "string", + id: 1 + }, + value: { + type: "bytes", + id: 2 + } + } + } +}); + +var timeType; + +common("duration", { + + /** + * Properties of a google.protobuf.Duration message. + * @interface IDuration + * @type {Object} + * @property {number|Long} [seconds] + * @property {number} [nanos] + * @memberof common + */ + Duration: timeType = { + fields: { + seconds: { + type: "int64", + id: 1 + }, + nanos: { + type: "int32", + id: 2 + } + } + } +}); + +common("timestamp", { + + /** + * Properties of a google.protobuf.Timestamp message. + * @interface ITimestamp + * @type {Object} + * @property {number|Long} [seconds] + * @property {number} [nanos] + * @memberof common + */ + Timestamp: timeType +}); + +common("empty", { + + /** + * Properties of a google.protobuf.Empty message. + * @interface IEmpty + * @memberof common + */ + Empty: { + fields: {} + } +}); + +common("struct", { + + /** + * Properties of a google.protobuf.Struct message. + * @interface IStruct + * @type {Object} + * @property {Object.} [fields] + * @memberof common + */ + Struct: { + fields: { + fields: { + keyType: "string", + type: "Value", + id: 1 + } + } + }, + + /** + * Properties of a google.protobuf.Value message. + * @interface IValue + * @type {Object} + * @property {string} [kind] + * @property {0} [nullValue] + * @property {number} [numberValue] + * @property {string} [stringValue] + * @property {boolean} [boolValue] + * @property {IStruct} [structValue] + * @property {IListValue} [listValue] + * @memberof common + */ + Value: { + oneofs: { + kind: { + oneof: [ + "nullValue", + "numberValue", + "stringValue", + "boolValue", + "structValue", + "listValue" + ] + } + }, + fields: { + nullValue: { + type: "NullValue", + id: 1 + }, + numberValue: { + type: "double", + id: 2 + }, + stringValue: { + type: "string", + id: 3 + }, + boolValue: { + type: "bool", + id: 4 + }, + structValue: { + type: "Struct", + id: 5 + }, + listValue: { + type: "ListValue", + id: 6 + } + } + }, + + NullValue: { + values: { + NULL_VALUE: 0 + } + }, + + /** + * Properties of a google.protobuf.ListValue message. + * @interface IListValue + * @type {Object} + * @property {Array.} [values] + * @memberof common + */ + ListValue: { + fields: { + values: { + rule: "repeated", + type: "Value", + id: 1 + } + } + } +}); + +common("wrappers", { + + /** + * Properties of a google.protobuf.DoubleValue message. + * @interface IDoubleValue + * @type {Object} + * @property {number} [value] + * @memberof common + */ + DoubleValue: { + fields: { + value: { + type: "double", + id: 1 + } + } + }, + + /** + * Properties of a google.protobuf.FloatValue message. + * @interface IFloatValue + * @type {Object} + * @property {number} [value] + * @memberof common + */ + FloatValue: { + fields: { + value: { + type: "float", + id: 1 + } + } + }, + + /** + * Properties of a google.protobuf.Int64Value message. + * @interface IInt64Value + * @type {Object} + * @property {number|Long} [value] + * @memberof common + */ + Int64Value: { + fields: { + value: { + type: "int64", + id: 1 + } + } + }, + + /** + * Properties of a google.protobuf.UInt64Value message. + * @interface IUInt64Value + * @type {Object} + * @property {number|Long} [value] + * @memberof common + */ + UInt64Value: { + fields: { + value: { + type: "uint64", + id: 1 + } + } + }, + + /** + * Properties of a google.protobuf.Int32Value message. + * @interface IInt32Value + * @type {Object} + * @property {number} [value] + * @memberof common + */ + Int32Value: { + fields: { + value: { + type: "int32", + id: 1 + } + } + }, + + /** + * Properties of a google.protobuf.UInt32Value message. + * @interface IUInt32Value + * @type {Object} + * @property {number} [value] + * @memberof common + */ + UInt32Value: { + fields: { + value: { + type: "uint32", + id: 1 + } + } + }, + + /** + * Properties of a google.protobuf.BoolValue message. + * @interface IBoolValue + * @type {Object} + * @property {boolean} [value] + * @memberof common + */ + BoolValue: { + fields: { + value: { + type: "bool", + id: 1 + } + } + }, + + /** + * Properties of a google.protobuf.StringValue message. + * @interface IStringValue + * @type {Object} + * @property {string} [value] + * @memberof common + */ + StringValue: { + fields: { + value: { + type: "string", + id: 1 + } + } + }, + + /** + * Properties of a google.protobuf.BytesValue message. + * @interface IBytesValue + * @type {Object} + * @property {Uint8Array} [value] + * @memberof common + */ + BytesValue: { + fields: { + value: { + type: "bytes", + id: 1 + } + } + } +}); + +common("field_mask", { + + /** + * Properties of a google.protobuf.FieldMask message. + * @interface IDoubleValue + * @type {Object} + * @property {number} [value] + * @memberof common + */ + FieldMask: { + fields: { + paths: { + rule: "repeated", + type: "string", + id: 1 + } + } + } +}); + +/** + * Gets the root definition of the specified common proto file. + * + * Bundled definitions are: + * - google/protobuf/any.proto + * - google/protobuf/duration.proto + * - google/protobuf/empty.proto + * - google/protobuf/field_mask.proto + * - google/protobuf/struct.proto + * - google/protobuf/timestamp.proto + * - google/protobuf/wrappers.proto + * + * @param {string} file Proto file name + * @returns {INamespace|null} Root definition or `null` if not defined + */ +common.get = function get(file) { + return common[file] || null; +}; + +},{}],12:[function(require,module,exports){ +"use strict"; +/** + * Runtime message from/to plain object converters. + * @namespace + */ +var converter = exports; + +var Enum = require(15), + util = require(37); + +/** + * Generates a partial value fromObject conveter. + * @param {Codegen} gen Codegen instance + * @param {Field} field Reflected field + * @param {number} fieldIndex Field index + * @param {string} prop Property reference + * @returns {Codegen} Codegen instance + * @ignore + */ +function genValuePartial_fromObject(gen, field, fieldIndex, prop) { + var defaultAlreadyEmitted = false; + /* eslint-disable no-unexpected-multiline, block-scoped-var, no-redeclare */ + if (field.resolvedType) { + if (field.resolvedType instanceof Enum) { gen + ("switch(d%s){", prop); + for (var values = field.resolvedType.values, keys = Object.keys(values), i = 0; i < keys.length; ++i) { + // enum unknown values passthrough + if (values[keys[i]] === field.typeDefault && !defaultAlreadyEmitted) { gen + ("default:") + ("if(typeof(d%s)===\"number\"){m%s=d%s;break}", prop, prop, prop); + if (!field.repeated) gen // fallback to default value only for + // arrays, to avoid leaving holes. + ("break"); // for non-repeated fields, just ignore + defaultAlreadyEmitted = true; + } + gen + ("case%j:", keys[i]) + ("case %i:", values[keys[i]]) + ("m%s=%j", prop, values[keys[i]]) + ("break"); + } gen + ("}"); + } else gen + ("if(typeof d%s!==\"object\")", prop) + ("throw TypeError(%j)", field.fullName + ": object expected") + ("m%s=types[%i].fromObject(d%s)", prop, fieldIndex, prop); + } else { + var isUnsigned = false; + switch (field.type) { + case "double": + case "float": gen + ("m%s=Number(d%s)", prop, prop); // also catches "NaN", "Infinity" + break; + case "uint32": + case "fixed32": gen + ("m%s=d%s>>>0", prop, prop); + break; + case "int32": + case "sint32": + case "sfixed32": gen + ("m%s=d%s|0", prop, prop); + break; + case "uint64": + isUnsigned = true; + // eslint-disable-next-line no-fallthrough + case "int64": + case "sint64": + case "fixed64": + case "sfixed64": gen + ("if(util.Long)") + ("(m%s=util.Long.fromValue(d%s)).unsigned=%j", prop, prop, isUnsigned) + ("else if(typeof d%s===\"string\")", prop) + ("m%s=parseInt(d%s,10)", prop, prop) + ("else if(typeof d%s===\"number\")", prop) + ("m%s=d%s", prop, prop) + ("else if(typeof d%s===\"object\")", prop) + ("m%s=new util.LongBits(d%s.low>>>0,d%s.high>>>0).toNumber(%s)", prop, prop, prop, isUnsigned ? "true" : ""); + break; + case "bytes": gen + ("if(typeof d%s===\"string\")", prop) + ("util.base64.decode(d%s,m%s=util.newBuffer(util.base64.length(d%s)),0)", prop, prop, prop) + ("else if(d%s.length >= 0)", prop) + ("m%s=d%s", prop, prop); + break; + case "string": gen + ("m%s=String(d%s)", prop, prop); + break; + case "bool": gen + ("m%s=Boolean(d%s)", prop, prop); + break; + /* default: gen + ("m%s=d%s", prop, prop); + break; */ + } + } + return gen; + /* eslint-enable no-unexpected-multiline, block-scoped-var, no-redeclare */ +} + +/** + * Generates a plain object to runtime message converter specific to the specified message type. + * @param {Type} mtype Message type + * @returns {Codegen} Codegen instance + */ +converter.fromObject = function fromObject(mtype) { + /* eslint-disable no-unexpected-multiline, block-scoped-var, no-redeclare */ + var fields = mtype.fieldsArray; + var gen = util.codegen(["d"], mtype.name + "$fromObject") + ("if(d instanceof this.ctor)") + ("return d"); + if (!fields.length) return gen + ("return new this.ctor"); + gen + ("var m=new this.ctor"); + for (var i = 0; i < fields.length; ++i) { + var field = fields[i].resolve(), + prop = util.safeProp(field.name); + + // Map fields + if (field.map) { gen + ("if(d%s){", prop) + ("if(typeof d%s!==\"object\")", prop) + ("throw TypeError(%j)", field.fullName + ": object expected") + ("m%s={}", prop) + ("for(var ks=Object.keys(d%s),i=0;i>>0,m%s.high>>>0).toNumber(%s):m%s", prop, prop, prop, prop, isUnsigned ? "true": "", prop); + break; + case "bytes": gen + ("d%s=o.bytes===String?util.base64.encode(m%s,0,m%s.length):o.bytes===Array?Array.prototype.slice.call(m%s):m%s", prop, prop, prop, prop, prop); + break; + default: gen + ("d%s=m%s", prop, prop); + break; + } + } + return gen; + /* eslint-enable no-unexpected-multiline, block-scoped-var, no-redeclare */ +} + +/** + * Generates a runtime message to plain object converter specific to the specified message type. + * @param {Type} mtype Message type + * @returns {Codegen} Codegen instance + */ +converter.toObject = function toObject(mtype) { + /* eslint-disable no-unexpected-multiline, block-scoped-var, no-redeclare */ + var fields = mtype.fieldsArray.slice().sort(util.compareFieldsById); + if (!fields.length) + return util.codegen()("return {}"); + var gen = util.codegen(["m", "o"], mtype.name + "$toObject") + ("if(!o)") + ("o={}") + ("var d={}"); + + var repeatedFields = [], + mapFields = [], + normalFields = [], + i = 0; + for (; i < fields.length; ++i) + if (!fields[i].partOf) + ( fields[i].resolve().repeated ? repeatedFields + : fields[i].map ? mapFields + : normalFields).push(fields[i]); + + if (repeatedFields.length) { gen + ("if(o.arrays||o.defaults){"); + for (i = 0; i < repeatedFields.length; ++i) gen + ("d%s=[]", util.safeProp(repeatedFields[i].name)); + gen + ("}"); + } + + if (mapFields.length) { gen + ("if(o.objects||o.defaults){"); + for (i = 0; i < mapFields.length; ++i) gen + ("d%s={}", util.safeProp(mapFields[i].name)); + gen + ("}"); + } + + if (normalFields.length) { gen + ("if(o.defaults){"); + for (i = 0; i < normalFields.length; ++i) { + var field = normalFields[i], + prop = util.safeProp(field.name); + if (field.resolvedType instanceof Enum) gen + ("d%s=o.enums===String?%j:%j", prop, field.resolvedType.valuesById[field.typeDefault], field.typeDefault); + else if (field.long) gen + ("if(util.Long){") + ("var n=new util.Long(%i,%i,%j)", field.typeDefault.low, field.typeDefault.high, field.typeDefault.unsigned) + ("d%s=o.longs===String?n.toString():o.longs===Number?n.toNumber():n", prop) + ("}else") + ("d%s=o.longs===String?%j:%i", prop, field.typeDefault.toString(), field.typeDefault.toNumber()); + else if (field.bytes) { + var arrayDefault = "[" + Array.prototype.slice.call(field.typeDefault).join(",") + "]"; + gen + ("if(o.bytes===String)d%s=%j", prop, String.fromCharCode.apply(String, field.typeDefault)) + ("else{") + ("d%s=%s", prop, arrayDefault) + ("if(o.bytes!==Array)d%s=util.newBuffer(d%s)", prop, prop) + ("}"); + } else gen + ("d%s=%j", prop, field.typeDefault); // also messages (=null) + } gen + ("}"); + } + var hasKs2 = false; + for (i = 0; i < fields.length; ++i) { + var field = fields[i], + index = mtype._fieldsArray.indexOf(field), + prop = util.safeProp(field.name); + if (field.map) { + if (!hasKs2) { hasKs2 = true; gen + ("var ks2"); + } gen + ("if(m%s&&(ks2=Object.keys(m%s)).length){", prop, prop) + ("d%s={}", prop) + ("for(var j=0;j>>3){"); + + var i = 0; + for (; i < /* initializes */ mtype.fieldsArray.length; ++i) { + var field = mtype._fieldsArray[i].resolve(), + type = field.resolvedType instanceof Enum ? "int32" : field.type, + ref = "m" + util.safeProp(field.name); gen + ("case %i: {", field.id); + + // Map fields + if (field.map) { gen + ("if(%s===util.emptyObject)", ref) + ("%s={}", ref) + ("var c2 = r.uint32()+r.pos"); + + if (types.defaults[field.keyType] !== undefined) gen + ("k=%j", types.defaults[field.keyType]); + else gen + ("k=null"); + + if (types.defaults[type] !== undefined) gen + ("value=%j", types.defaults[type]); + else gen + ("value=null"); + + gen + ("while(r.pos>>3){") + ("case 1: k=r.%s(); break", field.keyType) + ("case 2:"); + + if (types.basic[type] === undefined) gen + ("value=types[%i].decode(r,r.uint32())", i); // can't be groups + else gen + ("value=r.%s()", type); + + gen + ("break") + ("default:") + ("r.skipType(tag2&7)") + ("break") + ("}") + ("}"); + + if (types.long[field.keyType] !== undefined) gen + ("%s[typeof k===\"object\"?util.longToHash(k):k]=value", ref); + else gen + ("%s[k]=value", ref); + + // Repeated fields + } else if (field.repeated) { gen + + ("if(!(%s&&%s.length))", ref, ref) + ("%s=[]", ref); + + // Packable (always check for forward and backward compatiblity) + if (types.packed[type] !== undefined) gen + ("if((t&7)===2){") + ("var c2=r.uint32()+r.pos") + ("while(r.pos>> 0, (field.id << 3 | 4) >>> 0) + : gen("types[%i].encode(%s,w.uint32(%i).fork()).ldelim()", fieldIndex, ref, (field.id << 3 | 2) >>> 0); +} + +/** + * Generates an encoder specific to the specified message type. + * @param {Type} mtype Message type + * @returns {Codegen} Codegen instance + */ +function encoder(mtype) { + /* eslint-disable no-unexpected-multiline, block-scoped-var, no-redeclare */ + var gen = util.codegen(["m", "w"], mtype.name + "$encode") + ("if(!w)") + ("w=Writer.create()"); + + var i, ref; + + // "when a message is serialized its known fields should be written sequentially by field number" + var fields = /* initializes */ mtype.fieldsArray.slice().sort(util.compareFieldsById); + + for (var i = 0; i < fields.length; ++i) { + var field = fields[i].resolve(), + index = mtype._fieldsArray.indexOf(field), + type = field.resolvedType instanceof Enum ? "int32" : field.type, + wireType = types.basic[type]; + ref = "m" + util.safeProp(field.name); + + // Map fields + if (field.map) { + gen + ("if(%s!=null&&Object.hasOwnProperty.call(m,%j)){", ref, field.name) // !== undefined && !== null + ("for(var ks=Object.keys(%s),i=0;i>> 0, 8 | types.mapKey[field.keyType], field.keyType); + if (wireType === undefined) gen + ("types[%i].encode(%s[ks[i]],w.uint32(18).fork()).ldelim().ldelim()", index, ref); // can't be groups + else gen + (".uint32(%i).%s(%s[ks[i]]).ldelim()", 16 | wireType, type, ref); + gen + ("}") + ("}"); + + // Repeated fields + } else if (field.repeated) { gen + ("if(%s!=null&&%s.length){", ref, ref); // !== undefined && !== null + + // Packed repeated + if (field.packed && types.packed[type] !== undefined) { gen + + ("w.uint32(%i).fork()", (field.id << 3 | 2) >>> 0) + ("for(var i=0;i<%s.length;++i)", ref) + ("w.%s(%s[i])", type, ref) + ("w.ldelim()"); + + // Non-packed + } else { gen + + ("for(var i=0;i<%s.length;++i)", ref); + if (wireType === undefined) + genTypePartial(gen, field, index, ref + "[i]"); + else gen + ("w.uint32(%i).%s(%s[i])", (field.id << 3 | wireType) >>> 0, type, ref); + + } gen + ("}"); + + // Non-repeated + } else { + if (field.optional) gen + ("if(%s!=null&&Object.hasOwnProperty.call(m,%j))", ref, field.name); // !== undefined && !== null + + if (wireType === undefined) + genTypePartial(gen, field, index, ref); + else gen + ("w.uint32(%i).%s(%s)", (field.id << 3 | wireType) >>> 0, type, ref); + + } + } + + return gen + ("return w"); + /* eslint-enable no-unexpected-multiline, block-scoped-var, no-redeclare */ +} + +},{"15":15,"36":36,"37":37}],15:[function(require,module,exports){ +"use strict"; +module.exports = Enum; + +// extends ReflectionObject +var ReflectionObject = require(24); +((Enum.prototype = Object.create(ReflectionObject.prototype)).constructor = Enum).className = "Enum"; + +var Namespace = require(23), + util = require(37); + +/** + * Constructs a new enum instance. + * @classdesc Reflected enum. + * @extends ReflectionObject + * @constructor + * @param {string} name Unique name within its namespace + * @param {Object.} [values] Enum values as an object, by name + * @param {Object.} [options] Declared options + * @param {string} [comment] The comment for this enum + * @param {Object.} [comments] The value comments for this enum + * @param {Object.>|undefined} [valuesOptions] The value options for this enum + */ +function Enum(name, values, options, comment, comments, valuesOptions) { + ReflectionObject.call(this, name, options); + + if (values && typeof values !== "object") + throw TypeError("values must be an object"); + + /** + * Enum values by id. + * @type {Object.} + */ + this.valuesById = {}; + + /** + * Enum values by name. + * @type {Object.} + */ + this.values = Object.create(this.valuesById); // toJSON, marker + + /** + * Enum comment text. + * @type {string|null} + */ + this.comment = comment; + + /** + * Value comment texts, if any. + * @type {Object.} + */ + this.comments = comments || {}; + + /** + * Values options, if any + * @type {Object>|undefined} + */ + this.valuesOptions = valuesOptions; + + /** + * Reserved ranges, if any. + * @type {Array.} + */ + this.reserved = undefined; // toJSON + + // Note that values inherit valuesById on their prototype which makes them a TypeScript- + // compatible enum. This is used by pbts to write actual enum definitions that work for + // static and reflection code alike instead of emitting generic object definitions. + + if (values) + for (var keys = Object.keys(values), i = 0; i < keys.length; ++i) + if (typeof values[keys[i]] === "number") // use forward entries only + this.valuesById[ this.values[keys[i]] = values[keys[i]] ] = keys[i]; +} + +/** + * Enum descriptor. + * @interface IEnum + * @property {Object.} values Enum values + * @property {Object.} [options] Enum options + */ + +/** + * Constructs an enum from an enum descriptor. + * @param {string} name Enum name + * @param {IEnum} json Enum descriptor + * @returns {Enum} Created enum + * @throws {TypeError} If arguments are invalid + */ +Enum.fromJSON = function fromJSON(name, json) { + var enm = new Enum(name, json.values, json.options, json.comment, json.comments); + enm.reserved = json.reserved; + return enm; +}; + +/** + * Converts this enum to an enum descriptor. + * @param {IToJSONOptions} [toJSONOptions] JSON conversion options + * @returns {IEnum} Enum descriptor + */ +Enum.prototype.toJSON = function toJSON(toJSONOptions) { + var keepComments = toJSONOptions ? Boolean(toJSONOptions.keepComments) : false; + return util.toObject([ + "options" , this.options, + "valuesOptions" , this.valuesOptions, + "values" , this.values, + "reserved" , this.reserved && this.reserved.length ? this.reserved : undefined, + "comment" , keepComments ? this.comment : undefined, + "comments" , keepComments ? this.comments : undefined + ]); +}; + +/** + * Adds a value to this enum. + * @param {string} name Value name + * @param {number} id Value id + * @param {string} [comment] Comment, if any + * @param {Object.|undefined} [options] Options, if any + * @returns {Enum} `this` + * @throws {TypeError} If arguments are invalid + * @throws {Error} If there is already a value with this name or id + */ +Enum.prototype.add = function add(name, id, comment, options) { + // utilized by the parser but not by .fromJSON + + if (!util.isString(name)) + throw TypeError("name must be a string"); + + if (!util.isInteger(id)) + throw TypeError("id must be an integer"); + + if (this.values[name] !== undefined) + throw Error("duplicate name '" + name + "' in " + this); + + if (this.isReservedId(id)) + throw Error("id " + id + " is reserved in " + this); + + if (this.isReservedName(name)) + throw Error("name '" + name + "' is reserved in " + this); + + if (this.valuesById[id] !== undefined) { + if (!(this.options && this.options.allow_alias)) + throw Error("duplicate id " + id + " in " + this); + this.values[name] = id; + } else + this.valuesById[this.values[name] = id] = name; + + if (options) { + if (this.valuesOptions === undefined) + this.valuesOptions = {}; + this.valuesOptions[name] = options || null; + } + + this.comments[name] = comment || null; + return this; +}; + +/** + * Removes a value from this enum + * @param {string} name Value name + * @returns {Enum} `this` + * @throws {TypeError} If arguments are invalid + * @throws {Error} If `name` is not a name of this enum + */ +Enum.prototype.remove = function remove(name) { + + if (!util.isString(name)) + throw TypeError("name must be a string"); + + var val = this.values[name]; + if (val == null) + throw Error("name '" + name + "' does not exist in " + this); + + delete this.valuesById[val]; + delete this.values[name]; + delete this.comments[name]; + if (this.valuesOptions) + delete this.valuesOptions[name]; + + return this; +}; + +/** + * Tests if the specified id is reserved. + * @param {number} id Id to test + * @returns {boolean} `true` if reserved, otherwise `false` + */ +Enum.prototype.isReservedId = function isReservedId(id) { + return Namespace.isReservedId(this.reserved, id); +}; + +/** + * Tests if the specified name is reserved. + * @param {string} name Name to test + * @returns {boolean} `true` if reserved, otherwise `false` + */ +Enum.prototype.isReservedName = function isReservedName(name) { + return Namespace.isReservedName(this.reserved, name); +}; + +},{"23":23,"24":24,"37":37}],16:[function(require,module,exports){ +"use strict"; +module.exports = Field; + +// extends ReflectionObject +var ReflectionObject = require(24); +((Field.prototype = Object.create(ReflectionObject.prototype)).constructor = Field).className = "Field"; + +var Enum = require(15), + types = require(36), + util = require(37); + +var Type; // cyclic + +var ruleRe = /^required|optional|repeated$/; + +/** + * Constructs a new message field instance. Note that {@link MapField|map fields} have their own class. + * @name Field + * @classdesc Reflected message field. + * @extends FieldBase + * @constructor + * @param {string} name Unique name within its namespace + * @param {number} id Unique id within its namespace + * @param {string} type Value type + * @param {string|Object.} [rule="optional"] Field rule + * @param {string|Object.} [extend] Extended type if different from parent + * @param {Object.} [options] Declared options + */ + +/** + * Constructs a field from a field descriptor. + * @param {string} name Field name + * @param {IField} json Field descriptor + * @returns {Field} Created field + * @throws {TypeError} If arguments are invalid + */ +Field.fromJSON = function fromJSON(name, json) { + return new Field(name, json.id, json.type, json.rule, json.extend, json.options, json.comment); +}; + +/** + * Not an actual constructor. Use {@link Field} instead. + * @classdesc Base class of all reflected message fields. This is not an actual class but here for the sake of having consistent type definitions. + * @exports FieldBase + * @extends ReflectionObject + * @constructor + * @param {string} name Unique name within its namespace + * @param {number} id Unique id within its namespace + * @param {string} type Value type + * @param {string|Object.} [rule="optional"] Field rule + * @param {string|Object.} [extend] Extended type if different from parent + * @param {Object.} [options] Declared options + * @param {string} [comment] Comment associated with this field + */ +function Field(name, id, type, rule, extend, options, comment) { + + if (util.isObject(rule)) { + comment = extend; + options = rule; + rule = extend = undefined; + } else if (util.isObject(extend)) { + comment = options; + options = extend; + extend = undefined; + } + + ReflectionObject.call(this, name, options); + + if (!util.isInteger(id) || id < 0) + throw TypeError("id must be a non-negative integer"); + + if (!util.isString(type)) + throw TypeError("type must be a string"); + + if (rule !== undefined && !ruleRe.test(rule = rule.toString().toLowerCase())) + throw TypeError("rule must be a string rule"); + + if (extend !== undefined && !util.isString(extend)) + throw TypeError("extend must be a string"); + + /** + * Field rule, if any. + * @type {string|undefined} + */ + if (rule === "proto3_optional") { + rule = "optional"; + } + this.rule = rule && rule !== "optional" ? rule : undefined; // toJSON + + /** + * Field type. + * @type {string} + */ + this.type = type; // toJSON + + /** + * Unique field id. + * @type {number} + */ + this.id = id; // toJSON, marker + + /** + * Extended type if different from parent. + * @type {string|undefined} + */ + this.extend = extend || undefined; // toJSON + + /** + * Whether this field is required. + * @type {boolean} + */ + this.required = rule === "required"; + + /** + * Whether this field is optional. + * @type {boolean} + */ + this.optional = !this.required; + + /** + * Whether this field is repeated. + * @type {boolean} + */ + this.repeated = rule === "repeated"; + + /** + * Whether this field is a map or not. + * @type {boolean} + */ + this.map = false; + + /** + * Message this field belongs to. + * @type {Type|null} + */ + this.message = null; + + /** + * OneOf this field belongs to, if any, + * @type {OneOf|null} + */ + this.partOf = null; + + /** + * The field type's default value. + * @type {*} + */ + this.typeDefault = null; + + /** + * The field's default value on prototypes. + * @type {*} + */ + this.defaultValue = null; + + /** + * Whether this field's value should be treated as a long. + * @type {boolean} + */ + this.long = util.Long ? types.long[type] !== undefined : /* istanbul ignore next */ false; + + /** + * Whether this field's value is a buffer. + * @type {boolean} + */ + this.bytes = type === "bytes"; + + /** + * Resolved type if not a basic type. + * @type {Type|Enum|null} + */ + this.resolvedType = null; + + /** + * Sister-field within the extended type if a declaring extension field. + * @type {Field|null} + */ + this.extensionField = null; + + /** + * Sister-field within the declaring namespace if an extended field. + * @type {Field|null} + */ + this.declaringField = null; + + /** + * Internally remembers whether this field is packed. + * @type {boolean|null} + * @private + */ + this._packed = null; + + /** + * Comment for this field. + * @type {string|null} + */ + this.comment = comment; +} + +/** + * Determines whether this field is packed. Only relevant when repeated and working with proto2. + * @name Field#packed + * @type {boolean} + * @readonly + */ +Object.defineProperty(Field.prototype, "packed", { + get: function() { + // defaults to packed=true if not explicity set to false + if (this._packed === null) + this._packed = this.getOption("packed") !== false; + return this._packed; + } +}); + +/** + * @override + */ +Field.prototype.setOption = function setOption(name, value, ifNotSet) { + if (name === "packed") // clear cached before setting + this._packed = null; + return ReflectionObject.prototype.setOption.call(this, name, value, ifNotSet); +}; + +/** + * Field descriptor. + * @interface IField + * @property {string} [rule="optional"] Field rule + * @property {string} type Field type + * @property {number} id Field id + * @property {Object.} [options] Field options + */ + +/** + * Extension field descriptor. + * @interface IExtensionField + * @extends IField + * @property {string} extend Extended type + */ + +/** + * Converts this field to a field descriptor. + * @param {IToJSONOptions} [toJSONOptions] JSON conversion options + * @returns {IField} Field descriptor + */ +Field.prototype.toJSON = function toJSON(toJSONOptions) { + var keepComments = toJSONOptions ? Boolean(toJSONOptions.keepComments) : false; + return util.toObject([ + "rule" , this.rule !== "optional" && this.rule || undefined, + "type" , this.type, + "id" , this.id, + "extend" , this.extend, + "options" , this.options, + "comment" , keepComments ? this.comment : undefined + ]); +}; + +/** + * Resolves this field's type references. + * @returns {Field} `this` + * @throws {Error} If any reference cannot be resolved + */ +Field.prototype.resolve = function resolve() { + + if (this.resolved) + return this; + + if ((this.typeDefault = types.defaults[this.type]) === undefined) { // if not a basic type, resolve it + this.resolvedType = (this.declaringField ? this.declaringField.parent : this.parent).lookupTypeOrEnum(this.type); + if (this.resolvedType instanceof Type) + this.typeDefault = null; + else // instanceof Enum + this.typeDefault = this.resolvedType.values[Object.keys(this.resolvedType.values)[0]]; // first defined + } else if (this.options && this.options.proto3_optional) { + // proto3 scalar value marked optional; should default to null + this.typeDefault = null; + } + + // use explicitly set default value if present + if (this.options && this.options["default"] != null) { + this.typeDefault = this.options["default"]; + if (this.resolvedType instanceof Enum && typeof this.typeDefault === "string") + this.typeDefault = this.resolvedType.values[this.typeDefault]; + } + + // remove unnecessary options + if (this.options) { + if (this.options.packed === true || this.options.packed !== undefined && this.resolvedType && !(this.resolvedType instanceof Enum)) + delete this.options.packed; + if (!Object.keys(this.options).length) + this.options = undefined; + } + + // convert to internal data type if necesssary + if (this.long) { + this.typeDefault = util.Long.fromNumber(this.typeDefault, this.type.charAt(0) === "u"); + + /* istanbul ignore else */ + if (Object.freeze) + Object.freeze(this.typeDefault); // long instances are meant to be immutable anyway (i.e. use small int cache that even requires it) + + } else if (this.bytes && typeof this.typeDefault === "string") { + var buf; + if (util.base64.test(this.typeDefault)) + util.base64.decode(this.typeDefault, buf = util.newBuffer(util.base64.length(this.typeDefault)), 0); + else + util.utf8.write(this.typeDefault, buf = util.newBuffer(util.utf8.length(this.typeDefault)), 0); + this.typeDefault = buf; + } + + // take special care of maps and repeated fields + if (this.map) + this.defaultValue = util.emptyObject; + else if (this.repeated) + this.defaultValue = util.emptyArray; + else + this.defaultValue = this.typeDefault; + + // ensure proper value on prototype + if (this.parent instanceof Type) + this.parent.ctor.prototype[this.name] = this.defaultValue; + + return ReflectionObject.prototype.resolve.call(this); +}; + +/** + * Decorator function as returned by {@link Field.d} and {@link MapField.d} (TypeScript). + * @typedef FieldDecorator + * @type {function} + * @param {Object} prototype Target prototype + * @param {string} fieldName Field name + * @returns {undefined} + */ + +/** + * Field decorator (TypeScript). + * @name Field.d + * @function + * @param {number} fieldId Field id + * @param {"double"|"float"|"int32"|"uint32"|"sint32"|"fixed32"|"sfixed32"|"int64"|"uint64"|"sint64"|"fixed64"|"sfixed64"|"string"|"bool"|"bytes"|Object} fieldType Field type + * @param {"optional"|"required"|"repeated"} [fieldRule="optional"] Field rule + * @param {T} [defaultValue] Default value + * @returns {FieldDecorator} Decorator function + * @template T extends number | number[] | Long | Long[] | string | string[] | boolean | boolean[] | Uint8Array | Uint8Array[] | Buffer | Buffer[] + */ +Field.d = function decorateField(fieldId, fieldType, fieldRule, defaultValue) { + + // submessage: decorate the submessage and use its name as the type + if (typeof fieldType === "function") + fieldType = util.decorateType(fieldType).name; + + // enum reference: create a reflected copy of the enum and keep reuseing it + else if (fieldType && typeof fieldType === "object") + fieldType = util.decorateEnum(fieldType).name; + + return function fieldDecorator(prototype, fieldName) { + util.decorateType(prototype.constructor) + .add(new Field(fieldName, fieldId, fieldType, fieldRule, { "default": defaultValue })); + }; +}; + +/** + * Field decorator (TypeScript). + * @name Field.d + * @function + * @param {number} fieldId Field id + * @param {Constructor|string} fieldType Field type + * @param {"optional"|"required"|"repeated"} [fieldRule="optional"] Field rule + * @returns {FieldDecorator} Decorator function + * @template T extends Message + * @variation 2 + */ +// like Field.d but without a default value + +// Sets up cyclic dependencies (called in index-light) +Field._configure = function configure(Type_) { + Type = Type_; +}; + +},{"15":15,"24":24,"36":36,"37":37}],17:[function(require,module,exports){ +"use strict"; +var protobuf = module.exports = require(18); + +protobuf.build = "light"; + +/** + * A node-style callback as used by {@link load} and {@link Root#load}. + * @typedef LoadCallback + * @type {function} + * @param {Error|null} error Error, if any, otherwise `null` + * @param {Root} [root] Root, if there hasn't been an error + * @returns {undefined} + */ + +/** + * Loads one or multiple .proto or preprocessed .json files into a common root namespace and calls the callback. + * @param {string|string[]} filename One or multiple files to load + * @param {Root} root Root namespace, defaults to create a new one if omitted. + * @param {LoadCallback} callback Callback function + * @returns {undefined} + * @see {@link Root#load} + */ +function load(filename, root, callback) { + if (typeof root === "function") { + callback = root; + root = new protobuf.Root(); + } else if (!root) + root = new protobuf.Root(); + return root.load(filename, callback); +} + +/** + * Loads one or multiple .proto or preprocessed .json files into a common root namespace and calls the callback. + * @name load + * @function + * @param {string|string[]} filename One or multiple files to load + * @param {LoadCallback} callback Callback function + * @returns {undefined} + * @see {@link Root#load} + * @variation 2 + */ +// function load(filename:string, callback:LoadCallback):undefined + +/** + * Loads one or multiple .proto or preprocessed .json files into a common root namespace and returns a promise. + * @name load + * @function + * @param {string|string[]} filename One or multiple files to load + * @param {Root} [root] Root namespace, defaults to create a new one if omitted. + * @returns {Promise} Promise + * @see {@link Root#load} + * @variation 3 + */ +// function load(filename:string, [root:Root]):Promise + +protobuf.load = load; + +/** + * Synchronously loads one or multiple .proto or preprocessed .json files into a common root namespace (node only). + * @param {string|string[]} filename One or multiple files to load + * @param {Root} [root] Root namespace, defaults to create a new one if omitted. + * @returns {Root} Root namespace + * @throws {Error} If synchronous fetching is not supported (i.e. in browsers) or if a file's syntax is invalid + * @see {@link Root#loadSync} + */ +function loadSync(filename, root) { + if (!root) + root = new protobuf.Root(); + return root.loadSync(filename); +} + +protobuf.loadSync = loadSync; + +// Serialization +protobuf.encoder = require(14); +protobuf.decoder = require(13); +protobuf.verifier = require(40); +protobuf.converter = require(12); + +// Reflection +protobuf.ReflectionObject = require(24); +protobuf.Namespace = require(23); +protobuf.Root = require(29); +protobuf.Enum = require(15); +protobuf.Type = require(35); +protobuf.Field = require(16); +protobuf.OneOf = require(25); +protobuf.MapField = require(20); +protobuf.Service = require(33); +protobuf.Method = require(22); + +// Runtime +protobuf.Message = require(21); +protobuf.wrappers = require(41); + +// Utility +protobuf.types = require(36); +protobuf.util = require(37); + +// Set up possibly cyclic reflection dependencies +protobuf.ReflectionObject._configure(protobuf.Root); +protobuf.Namespace._configure(protobuf.Type, protobuf.Service, protobuf.Enum); +protobuf.Root._configure(protobuf.Type); +protobuf.Field._configure(protobuf.Type); + +},{"12":12,"13":13,"14":14,"15":15,"16":16,"18":18,"20":20,"21":21,"22":22,"23":23,"24":24,"25":25,"29":29,"33":33,"35":35,"36":36,"37":37,"40":40,"41":41}],18:[function(require,module,exports){ +"use strict"; +var protobuf = exports; + +/** + * Build type, one of `"full"`, `"light"` or `"minimal"`. + * @name build + * @type {string} + * @const + */ +protobuf.build = "minimal"; + +// Serialization +protobuf.Writer = require(42); +protobuf.BufferWriter = require(43); +protobuf.Reader = require(27); +protobuf.BufferReader = require(28); + +// Utility +protobuf.util = require(39); +protobuf.rpc = require(31); +protobuf.roots = require(30); +protobuf.configure = configure; + +/* istanbul ignore next */ +/** + * Reconfigures the library according to the environment. + * @returns {undefined} + */ +function configure() { + protobuf.util._configure(); + protobuf.Writer._configure(protobuf.BufferWriter); + protobuf.Reader._configure(protobuf.BufferReader); +} + +// Set up buffer utility according to the environment +configure(); + +},{"27":27,"28":28,"30":30,"31":31,"39":39,"42":42,"43":43}],19:[function(require,module,exports){ +"use strict"; +var protobuf = module.exports = require(17); + +protobuf.build = "full"; + +// Parser +protobuf.tokenize = require(34); +protobuf.parse = require(26); +protobuf.common = require(11); + +// Configure parser +protobuf.Root._configure(protobuf.Type, protobuf.parse, protobuf.common); + +},{"11":11,"17":17,"26":26,"34":34}],20:[function(require,module,exports){ +"use strict"; +module.exports = MapField; + +// extends Field +var Field = require(16); +((MapField.prototype = Object.create(Field.prototype)).constructor = MapField).className = "MapField"; + +var types = require(36), + util = require(37); + +/** + * Constructs a new map field instance. + * @classdesc Reflected map field. + * @extends FieldBase + * @constructor + * @param {string} name Unique name within its namespace + * @param {number} id Unique id within its namespace + * @param {string} keyType Key type + * @param {string} type Value type + * @param {Object.} [options] Declared options + * @param {string} [comment] Comment associated with this field + */ +function MapField(name, id, keyType, type, options, comment) { + Field.call(this, name, id, type, undefined, undefined, options, comment); + + /* istanbul ignore if */ + if (!util.isString(keyType)) + throw TypeError("keyType must be a string"); + + /** + * Key type. + * @type {string} + */ + this.keyType = keyType; // toJSON, marker + + /** + * Resolved key type if not a basic type. + * @type {ReflectionObject|null} + */ + this.resolvedKeyType = null; + + // Overrides Field#map + this.map = true; +} + +/** + * Map field descriptor. + * @interface IMapField + * @extends {IField} + * @property {string} keyType Key type + */ + +/** + * Extension map field descriptor. + * @interface IExtensionMapField + * @extends IMapField + * @property {string} extend Extended type + */ + +/** + * Constructs a map field from a map field descriptor. + * @param {string} name Field name + * @param {IMapField} json Map field descriptor + * @returns {MapField} Created map field + * @throws {TypeError} If arguments are invalid + */ +MapField.fromJSON = function fromJSON(name, json) { + return new MapField(name, json.id, json.keyType, json.type, json.options, json.comment); +}; + +/** + * Converts this map field to a map field descriptor. + * @param {IToJSONOptions} [toJSONOptions] JSON conversion options + * @returns {IMapField} Map field descriptor + */ +MapField.prototype.toJSON = function toJSON(toJSONOptions) { + var keepComments = toJSONOptions ? Boolean(toJSONOptions.keepComments) : false; + return util.toObject([ + "keyType" , this.keyType, + "type" , this.type, + "id" , this.id, + "extend" , this.extend, + "options" , this.options, + "comment" , keepComments ? this.comment : undefined + ]); +}; + +/** + * @override + */ +MapField.prototype.resolve = function resolve() { + if (this.resolved) + return this; + + // Besides a value type, map fields have a key type that may be "any scalar type except for floating point types and bytes" + if (types.mapKey[this.keyType] === undefined) + throw Error("invalid key type: " + this.keyType); + + return Field.prototype.resolve.call(this); +}; + +/** + * Map field decorator (TypeScript). + * @name MapField.d + * @function + * @param {number} fieldId Field id + * @param {"int32"|"uint32"|"sint32"|"fixed32"|"sfixed32"|"int64"|"uint64"|"sint64"|"fixed64"|"sfixed64"|"bool"|"string"} fieldKeyType Field key type + * @param {"double"|"float"|"int32"|"uint32"|"sint32"|"fixed32"|"sfixed32"|"int64"|"uint64"|"sint64"|"fixed64"|"sfixed64"|"bool"|"string"|"bytes"|Object|Constructor<{}>} fieldValueType Field value type + * @returns {FieldDecorator} Decorator function + * @template T extends { [key: string]: number | Long | string | boolean | Uint8Array | Buffer | number[] | Message<{}> } + */ +MapField.d = function decorateMapField(fieldId, fieldKeyType, fieldValueType) { + + // submessage value: decorate the submessage and use its name as the type + if (typeof fieldValueType === "function") + fieldValueType = util.decorateType(fieldValueType).name; + + // enum reference value: create a reflected copy of the enum and keep reuseing it + else if (fieldValueType && typeof fieldValueType === "object") + fieldValueType = util.decorateEnum(fieldValueType).name; + + return function mapFieldDecorator(prototype, fieldName) { + util.decorateType(prototype.constructor) + .add(new MapField(fieldName, fieldId, fieldKeyType, fieldValueType)); + }; +}; + +},{"16":16,"36":36,"37":37}],21:[function(require,module,exports){ +"use strict"; +module.exports = Message; + +var util = require(39); + +/** + * Constructs a new message instance. + * @classdesc Abstract runtime message. + * @constructor + * @param {Properties} [properties] Properties to set + * @template T extends object = object + */ +function Message(properties) { + // not used internally + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + this[keys[i]] = properties[keys[i]]; +} + +/** + * Reference to the reflected type. + * @name Message.$type + * @type {Type} + * @readonly + */ + +/** + * Reference to the reflected type. + * @name Message#$type + * @type {Type} + * @readonly + */ + +/*eslint-disable valid-jsdoc*/ + +/** + * Creates a new message of this type using the specified properties. + * @param {Object.} [properties] Properties to set + * @returns {Message} Message instance + * @template T extends Message + * @this Constructor + */ +Message.create = function create(properties) { + return this.$type.create(properties); +}; + +/** + * Encodes a message of this type. + * @param {T|Object.} message Message to encode + * @param {Writer} [writer] Writer to use + * @returns {Writer} Writer + * @template T extends Message + * @this Constructor + */ +Message.encode = function encode(message, writer) { + return this.$type.encode(message, writer); +}; + +/** + * Encodes a message of this type preceeded by its length as a varint. + * @param {T|Object.} message Message to encode + * @param {Writer} [writer] Writer to use + * @returns {Writer} Writer + * @template T extends Message + * @this Constructor + */ +Message.encodeDelimited = function encodeDelimited(message, writer) { + return this.$type.encodeDelimited(message, writer); +}; + +/** + * Decodes a message of this type. + * @name Message.decode + * @function + * @param {Reader|Uint8Array} reader Reader or buffer to decode + * @returns {T} Decoded message + * @template T extends Message + * @this Constructor + */ +Message.decode = function decode(reader) { + return this.$type.decode(reader); +}; + +/** + * Decodes a message of this type preceeded by its length as a varint. + * @name Message.decodeDelimited + * @function + * @param {Reader|Uint8Array} reader Reader or buffer to decode + * @returns {T} Decoded message + * @template T extends Message + * @this Constructor + */ +Message.decodeDelimited = function decodeDelimited(reader) { + return this.$type.decodeDelimited(reader); +}; + +/** + * Verifies a message of this type. + * @name Message.verify + * @function + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ +Message.verify = function verify(message) { + return this.$type.verify(message); +}; + +/** + * Creates a new message of this type from a plain object. Also converts values to their respective internal types. + * @param {Object.} object Plain object + * @returns {T} Message instance + * @template T extends Message + * @this Constructor + */ +Message.fromObject = function fromObject(object) { + return this.$type.fromObject(object); +}; + +/** + * Creates a plain object from a message of this type. Also converts values to other types if specified. + * @param {T} message Message instance + * @param {IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + * @template T extends Message + * @this Constructor + */ +Message.toObject = function toObject(message, options) { + return this.$type.toObject(message, options); +}; + +/** + * Converts this message to JSON. + * @returns {Object.} JSON object + */ +Message.prototype.toJSON = function toJSON() { + return this.$type.toObject(this, util.toJSONOptions); +}; + +/*eslint-enable valid-jsdoc*/ +},{"39":39}],22:[function(require,module,exports){ +"use strict"; +module.exports = Method; + +// extends ReflectionObject +var ReflectionObject = require(24); +((Method.prototype = Object.create(ReflectionObject.prototype)).constructor = Method).className = "Method"; + +var util = require(37); + +/** + * Constructs a new service method instance. + * @classdesc Reflected service method. + * @extends ReflectionObject + * @constructor + * @param {string} name Method name + * @param {string|undefined} type Method type, usually `"rpc"` + * @param {string} requestType Request message type + * @param {string} responseType Response message type + * @param {boolean|Object.} [requestStream] Whether the request is streamed + * @param {boolean|Object.} [responseStream] Whether the response is streamed + * @param {Object.} [options] Declared options + * @param {string} [comment] The comment for this method + * @param {Object.} [parsedOptions] Declared options, properly parsed into an object + */ +function Method(name, type, requestType, responseType, requestStream, responseStream, options, comment, parsedOptions) { + + /* istanbul ignore next */ + if (util.isObject(requestStream)) { + options = requestStream; + requestStream = responseStream = undefined; + } else if (util.isObject(responseStream)) { + options = responseStream; + responseStream = undefined; + } + + /* istanbul ignore if */ + if (!(type === undefined || util.isString(type))) + throw TypeError("type must be a string"); + + /* istanbul ignore if */ + if (!util.isString(requestType)) + throw TypeError("requestType must be a string"); + + /* istanbul ignore if */ + if (!util.isString(responseType)) + throw TypeError("responseType must be a string"); + + ReflectionObject.call(this, name, options); + + /** + * Method type. + * @type {string} + */ + this.type = type || "rpc"; // toJSON + + /** + * Request type. + * @type {string} + */ + this.requestType = requestType; // toJSON, marker + + /** + * Whether requests are streamed or not. + * @type {boolean|undefined} + */ + this.requestStream = requestStream ? true : undefined; // toJSON + + /** + * Response type. + * @type {string} + */ + this.responseType = responseType; // toJSON + + /** + * Whether responses are streamed or not. + * @type {boolean|undefined} + */ + this.responseStream = responseStream ? true : undefined; // toJSON + + /** + * Resolved request type. + * @type {Type|null} + */ + this.resolvedRequestType = null; + + /** + * Resolved response type. + * @type {Type|null} + */ + this.resolvedResponseType = null; + + /** + * Comment for this method + * @type {string|null} + */ + this.comment = comment; + + /** + * Options properly parsed into an object + */ + this.parsedOptions = parsedOptions; +} + +/** + * Method descriptor. + * @interface IMethod + * @property {string} [type="rpc"] Method type + * @property {string} requestType Request type + * @property {string} responseType Response type + * @property {boolean} [requestStream=false] Whether requests are streamed + * @property {boolean} [responseStream=false] Whether responses are streamed + * @property {Object.} [options] Method options + * @property {string} comment Method comments + * @property {Object.} [parsedOptions] Method options properly parsed into an object + */ + +/** + * Constructs a method from a method descriptor. + * @param {string} name Method name + * @param {IMethod} json Method descriptor + * @returns {Method} Created method + * @throws {TypeError} If arguments are invalid + */ +Method.fromJSON = function fromJSON(name, json) { + return new Method(name, json.type, json.requestType, json.responseType, json.requestStream, json.responseStream, json.options, json.comment, json.parsedOptions); +}; + +/** + * Converts this method to a method descriptor. + * @param {IToJSONOptions} [toJSONOptions] JSON conversion options + * @returns {IMethod} Method descriptor + */ +Method.prototype.toJSON = function toJSON(toJSONOptions) { + var keepComments = toJSONOptions ? Boolean(toJSONOptions.keepComments) : false; + return util.toObject([ + "type" , this.type !== "rpc" && /* istanbul ignore next */ this.type || undefined, + "requestType" , this.requestType, + "requestStream" , this.requestStream, + "responseType" , this.responseType, + "responseStream" , this.responseStream, + "options" , this.options, + "comment" , keepComments ? this.comment : undefined, + "parsedOptions" , this.parsedOptions, + ]); +}; + +/** + * @override + */ +Method.prototype.resolve = function resolve() { + + /* istanbul ignore if */ + if (this.resolved) + return this; + + this.resolvedRequestType = this.parent.lookupType(this.requestType); + this.resolvedResponseType = this.parent.lookupType(this.responseType); + + return ReflectionObject.prototype.resolve.call(this); +}; + +},{"24":24,"37":37}],23:[function(require,module,exports){ +"use strict"; +module.exports = Namespace; + +// extends ReflectionObject +var ReflectionObject = require(24); +((Namespace.prototype = Object.create(ReflectionObject.prototype)).constructor = Namespace).className = "Namespace"; + +var Field = require(16), + util = require(37), + OneOf = require(25); + +var Type, // cyclic + Service, + Enum; + +/** + * Constructs a new namespace instance. + * @name Namespace + * @classdesc Reflected namespace. + * @extends NamespaceBase + * @constructor + * @param {string} name Namespace name + * @param {Object.} [options] Declared options + */ + +/** + * Constructs a namespace from JSON. + * @memberof Namespace + * @function + * @param {string} name Namespace name + * @param {Object.} json JSON object + * @returns {Namespace} Created namespace + * @throws {TypeError} If arguments are invalid + */ +Namespace.fromJSON = function fromJSON(name, json) { + return new Namespace(name, json.options).addJSON(json.nested); +}; + +/** + * Converts an array of reflection objects to JSON. + * @memberof Namespace + * @param {ReflectionObject[]} array Object array + * @param {IToJSONOptions} [toJSONOptions] JSON conversion options + * @returns {Object.|undefined} JSON object or `undefined` when array is empty + */ +function arrayToJSON(array, toJSONOptions) { + if (!(array && array.length)) + return undefined; + var obj = {}; + for (var i = 0; i < array.length; ++i) + obj[array[i].name] = array[i].toJSON(toJSONOptions); + return obj; +} + +Namespace.arrayToJSON = arrayToJSON; + +/** + * Tests if the specified id is reserved. + * @param {Array.|undefined} reserved Array of reserved ranges and names + * @param {number} id Id to test + * @returns {boolean} `true` if reserved, otherwise `false` + */ +Namespace.isReservedId = function isReservedId(reserved, id) { + if (reserved) + for (var i = 0; i < reserved.length; ++i) + if (typeof reserved[i] !== "string" && reserved[i][0] <= id && reserved[i][1] > id) + return true; + return false; +}; + +/** + * Tests if the specified name is reserved. + * @param {Array.|undefined} reserved Array of reserved ranges and names + * @param {string} name Name to test + * @returns {boolean} `true` if reserved, otherwise `false` + */ +Namespace.isReservedName = function isReservedName(reserved, name) { + if (reserved) + for (var i = 0; i < reserved.length; ++i) + if (reserved[i] === name) + return true; + return false; +}; + +/** + * Not an actual constructor. Use {@link Namespace} instead. + * @classdesc Base class of all reflection objects containing nested objects. This is not an actual class but here for the sake of having consistent type definitions. + * @exports NamespaceBase + * @extends ReflectionObject + * @abstract + * @constructor + * @param {string} name Namespace name + * @param {Object.} [options] Declared options + * @see {@link Namespace} + */ +function Namespace(name, options) { + ReflectionObject.call(this, name, options); + + /** + * Nested objects by name. + * @type {Object.|undefined} + */ + this.nested = undefined; // toJSON + + /** + * Cached nested objects as an array. + * @type {ReflectionObject[]|null} + * @private + */ + this._nestedArray = null; +} + +function clearCache(namespace) { + namespace._nestedArray = null; + return namespace; +} + +/** + * Nested objects of this namespace as an array for iteration. + * @name NamespaceBase#nestedArray + * @type {ReflectionObject[]} + * @readonly + */ +Object.defineProperty(Namespace.prototype, "nestedArray", { + get: function() { + return this._nestedArray || (this._nestedArray = util.toArray(this.nested)); + } +}); + +/** + * Namespace descriptor. + * @interface INamespace + * @property {Object.} [options] Namespace options + * @property {Object.} [nested] Nested object descriptors + */ + +/** + * Any extension field descriptor. + * @typedef AnyExtensionField + * @type {IExtensionField|IExtensionMapField} + */ + +/** + * Any nested object descriptor. + * @typedef AnyNestedObject + * @type {IEnum|IType|IService|AnyExtensionField|INamespace|IOneOf} + */ + +/** + * Converts this namespace to a namespace descriptor. + * @param {IToJSONOptions} [toJSONOptions] JSON conversion options + * @returns {INamespace} Namespace descriptor + */ +Namespace.prototype.toJSON = function toJSON(toJSONOptions) { + return util.toObject([ + "options" , this.options, + "nested" , arrayToJSON(this.nestedArray, toJSONOptions) + ]); +}; + +/** + * Adds nested objects to this namespace from nested object descriptors. + * @param {Object.} nestedJson Any nested object descriptors + * @returns {Namespace} `this` + */ +Namespace.prototype.addJSON = function addJSON(nestedJson) { + var ns = this; + /* istanbul ignore else */ + if (nestedJson) { + for (var names = Object.keys(nestedJson), i = 0, nested; i < names.length; ++i) { + nested = nestedJson[names[i]]; + ns.add( // most to least likely + ( nested.fields !== undefined + ? Type.fromJSON + : nested.values !== undefined + ? Enum.fromJSON + : nested.methods !== undefined + ? Service.fromJSON + : nested.id !== undefined + ? Field.fromJSON + : Namespace.fromJSON )(names[i], nested) + ); + } + } + return this; +}; + +/** + * Gets the nested object of the specified name. + * @param {string} name Nested object name + * @returns {ReflectionObject|null} The reflection object or `null` if it doesn't exist + */ +Namespace.prototype.get = function get(name) { + return this.nested && this.nested[name] + || null; +}; + +/** + * Gets the values of the nested {@link Enum|enum} of the specified name. + * This methods differs from {@link Namespace#get|get} in that it returns an enum's values directly and throws instead of returning `null`. + * @param {string} name Nested enum name + * @returns {Object.} Enum values + * @throws {Error} If there is no such enum + */ +Namespace.prototype.getEnum = function getEnum(name) { + if (this.nested && this.nested[name] instanceof Enum) + return this.nested[name].values; + throw Error("no such enum: " + name); +}; + +/** + * Adds a nested object to this namespace. + * @param {ReflectionObject} object Nested object to add + * @returns {Namespace} `this` + * @throws {TypeError} If arguments are invalid + * @throws {Error} If there is already a nested object with this name + */ +Namespace.prototype.add = function add(object) { + + if (!(object instanceof Field && object.extend !== undefined || object instanceof Type || object instanceof OneOf || object instanceof Enum || object instanceof Service || object instanceof Namespace)) + throw TypeError("object must be a valid nested object"); + + if (!this.nested) + this.nested = {}; + else { + var prev = this.get(object.name); + if (prev) { + if (prev instanceof Namespace && object instanceof Namespace && !(prev instanceof Type || prev instanceof Service)) { + // replace plain namespace but keep existing nested elements and options + var nested = prev.nestedArray; + for (var i = 0; i < nested.length; ++i) + object.add(nested[i]); + this.remove(prev); + if (!this.nested) + this.nested = {}; + object.setOptions(prev.options, true); + + } else + throw Error("duplicate name '" + object.name + "' in " + this); + } + } + this.nested[object.name] = object; + object.onAdd(this); + return clearCache(this); +}; + +/** + * Removes a nested object from this namespace. + * @param {ReflectionObject} object Nested object to remove + * @returns {Namespace} `this` + * @throws {TypeError} If arguments are invalid + * @throws {Error} If `object` is not a member of this namespace + */ +Namespace.prototype.remove = function remove(object) { + + if (!(object instanceof ReflectionObject)) + throw TypeError("object must be a ReflectionObject"); + if (object.parent !== this) + throw Error(object + " is not a member of " + this); + + delete this.nested[object.name]; + if (!Object.keys(this.nested).length) + this.nested = undefined; + + object.onRemove(this); + return clearCache(this); +}; + +/** + * Defines additial namespaces within this one if not yet existing. + * @param {string|string[]} path Path to create + * @param {*} [json] Nested types to create from JSON + * @returns {Namespace} Pointer to the last namespace created or `this` if path is empty + */ +Namespace.prototype.define = function define(path, json) { + + if (util.isString(path)) + path = path.split("."); + else if (!Array.isArray(path)) + throw TypeError("illegal path"); + if (path && path.length && path[0] === "") + throw Error("path must be relative"); + + var ptr = this; + while (path.length > 0) { + var part = path.shift(); + if (ptr.nested && ptr.nested[part]) { + ptr = ptr.nested[part]; + if (!(ptr instanceof Namespace)) + throw Error("path conflicts with non-namespace objects"); + } else + ptr.add(ptr = new Namespace(part)); + } + if (json) + ptr.addJSON(json); + return ptr; +}; + +/** + * Resolves this namespace's and all its nested objects' type references. Useful to validate a reflection tree, but comes at a cost. + * @returns {Namespace} `this` + */ +Namespace.prototype.resolveAll = function resolveAll() { + var nested = this.nestedArray, i = 0; + while (i < nested.length) + if (nested[i] instanceof Namespace) + nested[i++].resolveAll(); + else + nested[i++].resolve(); + return this.resolve(); +}; + +/** + * Recursively looks up the reflection object matching the specified path in the scope of this namespace. + * @param {string|string[]} path Path to look up + * @param {*|Array.<*>} filterTypes Filter types, any combination of the constructors of `protobuf.Type`, `protobuf.Enum`, `protobuf.Service` etc. + * @param {boolean} [parentAlreadyChecked=false] If known, whether the parent has already been checked + * @returns {ReflectionObject|null} Looked up object or `null` if none could be found + */ +Namespace.prototype.lookup = function lookup(path, filterTypes, parentAlreadyChecked) { + + /* istanbul ignore next */ + if (typeof filterTypes === "boolean") { + parentAlreadyChecked = filterTypes; + filterTypes = undefined; + } else if (filterTypes && !Array.isArray(filterTypes)) + filterTypes = [ filterTypes ]; + + if (util.isString(path) && path.length) { + if (path === ".") + return this.root; + path = path.split("."); + } else if (!path.length) + return this; + + // Start at root if path is absolute + if (path[0] === "") + return this.root.lookup(path.slice(1), filterTypes); + + // Test if the first part matches any nested object, and if so, traverse if path contains more + var found = this.get(path[0]); + if (found) { + if (path.length === 1) { + if (!filterTypes || filterTypes.indexOf(found.constructor) > -1) + return found; + } else if (found instanceof Namespace && (found = found.lookup(path.slice(1), filterTypes, true))) + return found; + + // Otherwise try each nested namespace + } else + for (var i = 0; i < this.nestedArray.length; ++i) + if (this._nestedArray[i] instanceof Namespace && (found = this._nestedArray[i].lookup(path, filterTypes, true))) + return found; + + // If there hasn't been a match, try again at the parent + if (this.parent === null || parentAlreadyChecked) + return null; + return this.parent.lookup(path, filterTypes); +}; + +/** + * Looks up the reflection object at the specified path, relative to this namespace. + * @name NamespaceBase#lookup + * @function + * @param {string|string[]} path Path to look up + * @param {boolean} [parentAlreadyChecked=false] Whether the parent has already been checked + * @returns {ReflectionObject|null} Looked up object or `null` if none could be found + * @variation 2 + */ +// lookup(path: string, [parentAlreadyChecked: boolean]) + +/** + * Looks up the {@link Type|type} at the specified path, relative to this namespace. + * Besides its signature, this methods differs from {@link Namespace#lookup|lookup} in that it throws instead of returning `null`. + * @param {string|string[]} path Path to look up + * @returns {Type} Looked up type + * @throws {Error} If `path` does not point to a type + */ +Namespace.prototype.lookupType = function lookupType(path) { + var found = this.lookup(path, [ Type ]); + if (!found) + throw Error("no such type: " + path); + return found; +}; + +/** + * Looks up the values of the {@link Enum|enum} at the specified path, relative to this namespace. + * Besides its signature, this methods differs from {@link Namespace#lookup|lookup} in that it throws instead of returning `null`. + * @param {string|string[]} path Path to look up + * @returns {Enum} Looked up enum + * @throws {Error} If `path` does not point to an enum + */ +Namespace.prototype.lookupEnum = function lookupEnum(path) { + var found = this.lookup(path, [ Enum ]); + if (!found) + throw Error("no such Enum '" + path + "' in " + this); + return found; +}; + +/** + * Looks up the {@link Type|type} or {@link Enum|enum} at the specified path, relative to this namespace. + * Besides its signature, this methods differs from {@link Namespace#lookup|lookup} in that it throws instead of returning `null`. + * @param {string|string[]} path Path to look up + * @returns {Type} Looked up type or enum + * @throws {Error} If `path` does not point to a type or enum + */ +Namespace.prototype.lookupTypeOrEnum = function lookupTypeOrEnum(path) { + var found = this.lookup(path, [ Type, Enum ]); + if (!found) + throw Error("no such Type or Enum '" + path + "' in " + this); + return found; +}; + +/** + * Looks up the {@link Service|service} at the specified path, relative to this namespace. + * Besides its signature, this methods differs from {@link Namespace#lookup|lookup} in that it throws instead of returning `null`. + * @param {string|string[]} path Path to look up + * @returns {Service} Looked up service + * @throws {Error} If `path` does not point to a service + */ +Namespace.prototype.lookupService = function lookupService(path) { + var found = this.lookup(path, [ Service ]); + if (!found) + throw Error("no such Service '" + path + "' in " + this); + return found; +}; + +// Sets up cyclic dependencies (called in index-light) +Namespace._configure = function(Type_, Service_, Enum_) { + Type = Type_; + Service = Service_; + Enum = Enum_; +}; + +},{"16":16,"24":24,"25":25,"37":37}],24:[function(require,module,exports){ +"use strict"; +module.exports = ReflectionObject; + +ReflectionObject.className = "ReflectionObject"; + +var util = require(37); + +var Root; // cyclic + +/** + * Constructs a new reflection object instance. + * @classdesc Base class of all reflection objects. + * @constructor + * @param {string} name Object name + * @param {Object.} [options] Declared options + * @abstract + */ +function ReflectionObject(name, options) { + + if (!util.isString(name)) + throw TypeError("name must be a string"); + + if (options && !util.isObject(options)) + throw TypeError("options must be an object"); + + /** + * Options. + * @type {Object.|undefined} + */ + this.options = options; // toJSON + + /** + * Parsed Options. + * @type {Array.>|undefined} + */ + this.parsedOptions = null; + + /** + * Unique name within its namespace. + * @type {string} + */ + this.name = name; + + /** + * Parent namespace. + * @type {Namespace|null} + */ + this.parent = null; + + /** + * Whether already resolved or not. + * @type {boolean} + */ + this.resolved = false; + + /** + * Comment text, if any. + * @type {string|null} + */ + this.comment = null; + + /** + * Defining file name. + * @type {string|null} + */ + this.filename = null; +} + +Object.defineProperties(ReflectionObject.prototype, { + + /** + * Reference to the root namespace. + * @name ReflectionObject#root + * @type {Root} + * @readonly + */ + root: { + get: function() { + var ptr = this; + while (ptr.parent !== null) + ptr = ptr.parent; + return ptr; + } + }, + + /** + * Full name including leading dot. + * @name ReflectionObject#fullName + * @type {string} + * @readonly + */ + fullName: { + get: function() { + var path = [ this.name ], + ptr = this.parent; + while (ptr) { + path.unshift(ptr.name); + ptr = ptr.parent; + } + return path.join("."); + } + } +}); + +/** + * Converts this reflection object to its descriptor representation. + * @returns {Object.} Descriptor + * @abstract + */ +ReflectionObject.prototype.toJSON = /* istanbul ignore next */ function toJSON() { + throw Error(); // not implemented, shouldn't happen +}; + +/** + * Called when this object is added to a parent. + * @param {ReflectionObject} parent Parent added to + * @returns {undefined} + */ +ReflectionObject.prototype.onAdd = function onAdd(parent) { + if (this.parent && this.parent !== parent) + this.parent.remove(this); + this.parent = parent; + this.resolved = false; + var root = parent.root; + if (root instanceof Root) + root._handleAdd(this); +}; + +/** + * Called when this object is removed from a parent. + * @param {ReflectionObject} parent Parent removed from + * @returns {undefined} + */ +ReflectionObject.prototype.onRemove = function onRemove(parent) { + var root = parent.root; + if (root instanceof Root) + root._handleRemove(this); + this.parent = null; + this.resolved = false; +}; + +/** + * Resolves this objects type references. + * @returns {ReflectionObject} `this` + */ +ReflectionObject.prototype.resolve = function resolve() { + if (this.resolved) + return this; + if (this.root instanceof Root) + this.resolved = true; // only if part of a root + return this; +}; + +/** + * Gets an option value. + * @param {string} name Option name + * @returns {*} Option value or `undefined` if not set + */ +ReflectionObject.prototype.getOption = function getOption(name) { + if (this.options) + return this.options[name]; + return undefined; +}; + +/** + * Sets an option. + * @param {string} name Option name + * @param {*} value Option value + * @param {boolean} [ifNotSet] Sets the option only if it isn't currently set + * @returns {ReflectionObject} `this` + */ +ReflectionObject.prototype.setOption = function setOption(name, value, ifNotSet) { + if (!ifNotSet || !this.options || this.options[name] === undefined) + (this.options || (this.options = {}))[name] = value; + return this; +}; + +/** + * Sets a parsed option. + * @param {string} name parsed Option name + * @param {*} value Option value + * @param {string} propName dot '.' delimited full path of property within the option to set. if undefined\empty, will add a new option with that value + * @returns {ReflectionObject} `this` + */ +ReflectionObject.prototype.setParsedOption = function setParsedOption(name, value, propName) { + if (!this.parsedOptions) { + this.parsedOptions = []; + } + var parsedOptions = this.parsedOptions; + if (propName) { + // If setting a sub property of an option then try to merge it + // with an existing option + var opt = parsedOptions.find(function (opt) { + return Object.prototype.hasOwnProperty.call(opt, name); + }); + if (opt) { + // If we found an existing option - just merge the property value + var newValue = opt[name]; + util.setProperty(newValue, propName, value); + } else { + // otherwise, create a new option, set it's property and add it to the list + opt = {}; + opt[name] = util.setProperty({}, propName, value); + parsedOptions.push(opt); + } + } else { + // Always create a new option when setting the value of the option itself + var newOpt = {}; + newOpt[name] = value; + parsedOptions.push(newOpt); + } + return this; +}; + +/** + * Sets multiple options. + * @param {Object.} options Options to set + * @param {boolean} [ifNotSet] Sets an option only if it isn't currently set + * @returns {ReflectionObject} `this` + */ +ReflectionObject.prototype.setOptions = function setOptions(options, ifNotSet) { + if (options) + for (var keys = Object.keys(options), i = 0; i < keys.length; ++i) + this.setOption(keys[i], options[keys[i]], ifNotSet); + return this; +}; + +/** + * Converts this instance to its string representation. + * @returns {string} Class name[, space, full name] + */ +ReflectionObject.prototype.toString = function toString() { + var className = this.constructor.className, + fullName = this.fullName; + if (fullName.length) + return className + " " + fullName; + return className; +}; + +// Sets up cyclic dependencies (called in index-light) +ReflectionObject._configure = function(Root_) { + Root = Root_; +}; + +},{"37":37}],25:[function(require,module,exports){ +"use strict"; +module.exports = OneOf; + +// extends ReflectionObject +var ReflectionObject = require(24); +((OneOf.prototype = Object.create(ReflectionObject.prototype)).constructor = OneOf).className = "OneOf"; + +var Field = require(16), + util = require(37); + +/** + * Constructs a new oneof instance. + * @classdesc Reflected oneof. + * @extends ReflectionObject + * @constructor + * @param {string} name Oneof name + * @param {string[]|Object.} [fieldNames] Field names + * @param {Object.} [options] Declared options + * @param {string} [comment] Comment associated with this field + */ +function OneOf(name, fieldNames, options, comment) { + if (!Array.isArray(fieldNames)) { + options = fieldNames; + fieldNames = undefined; + } + ReflectionObject.call(this, name, options); + + /* istanbul ignore if */ + if (!(fieldNames === undefined || Array.isArray(fieldNames))) + throw TypeError("fieldNames must be an Array"); + + /** + * Field names that belong to this oneof. + * @type {string[]} + */ + this.oneof = fieldNames || []; // toJSON, marker + + /** + * Fields that belong to this oneof as an array for iteration. + * @type {Field[]} + * @readonly + */ + this.fieldsArray = []; // declared readonly for conformance, possibly not yet added to parent + + /** + * Comment for this field. + * @type {string|null} + */ + this.comment = comment; +} + +/** + * Oneof descriptor. + * @interface IOneOf + * @property {Array.} oneof Oneof field names + * @property {Object.} [options] Oneof options + */ + +/** + * Constructs a oneof from a oneof descriptor. + * @param {string} name Oneof name + * @param {IOneOf} json Oneof descriptor + * @returns {OneOf} Created oneof + * @throws {TypeError} If arguments are invalid + */ +OneOf.fromJSON = function fromJSON(name, json) { + return new OneOf(name, json.oneof, json.options, json.comment); +}; + +/** + * Converts this oneof to a oneof descriptor. + * @param {IToJSONOptions} [toJSONOptions] JSON conversion options + * @returns {IOneOf} Oneof descriptor + */ +OneOf.prototype.toJSON = function toJSON(toJSONOptions) { + var keepComments = toJSONOptions ? Boolean(toJSONOptions.keepComments) : false; + return util.toObject([ + "options" , this.options, + "oneof" , this.oneof, + "comment" , keepComments ? this.comment : undefined + ]); +}; + +/** + * Adds the fields of the specified oneof to the parent if not already done so. + * @param {OneOf} oneof The oneof + * @returns {undefined} + * @inner + * @ignore + */ +function addFieldsToParent(oneof) { + if (oneof.parent) + for (var i = 0; i < oneof.fieldsArray.length; ++i) + if (!oneof.fieldsArray[i].parent) + oneof.parent.add(oneof.fieldsArray[i]); +} + +/** + * Adds a field to this oneof and removes it from its current parent, if any. + * @param {Field} field Field to add + * @returns {OneOf} `this` + */ +OneOf.prototype.add = function add(field) { + + /* istanbul ignore if */ + if (!(field instanceof Field)) + throw TypeError("field must be a Field"); + + if (field.parent && field.parent !== this.parent) + field.parent.remove(field); + this.oneof.push(field.name); + this.fieldsArray.push(field); + field.partOf = this; // field.parent remains null + addFieldsToParent(this); + return this; +}; + +/** + * Removes a field from this oneof and puts it back to the oneof's parent. + * @param {Field} field Field to remove + * @returns {OneOf} `this` + */ +OneOf.prototype.remove = function remove(field) { + + /* istanbul ignore if */ + if (!(field instanceof Field)) + throw TypeError("field must be a Field"); + + var index = this.fieldsArray.indexOf(field); + + /* istanbul ignore if */ + if (index < 0) + throw Error(field + " is not a member of " + this); + + this.fieldsArray.splice(index, 1); + index = this.oneof.indexOf(field.name); + + /* istanbul ignore else */ + if (index > -1) // theoretical + this.oneof.splice(index, 1); + + field.partOf = null; + return this; +}; + +/** + * @override + */ +OneOf.prototype.onAdd = function onAdd(parent) { + ReflectionObject.prototype.onAdd.call(this, parent); + var self = this; + // Collect present fields + for (var i = 0; i < this.oneof.length; ++i) { + var field = parent.get(this.oneof[i]); + if (field && !field.partOf) { + field.partOf = self; + self.fieldsArray.push(field); + } + } + // Add not yet present fields + addFieldsToParent(this); +}; + +/** + * @override + */ +OneOf.prototype.onRemove = function onRemove(parent) { + for (var i = 0, field; i < this.fieldsArray.length; ++i) + if ((field = this.fieldsArray[i]).parent) + field.parent.remove(field); + ReflectionObject.prototype.onRemove.call(this, parent); +}; + +/** + * Decorator function as returned by {@link OneOf.d} (TypeScript). + * @typedef OneOfDecorator + * @type {function} + * @param {Object} prototype Target prototype + * @param {string} oneofName OneOf name + * @returns {undefined} + */ + +/** + * OneOf decorator (TypeScript). + * @function + * @param {...string} fieldNames Field names + * @returns {OneOfDecorator} Decorator function + * @template T extends string + */ +OneOf.d = function decorateOneOf() { + var fieldNames = new Array(arguments.length), + index = 0; + while (index < arguments.length) + fieldNames[index] = arguments[index++]; + return function oneOfDecorator(prototype, oneofName) { + util.decorateType(prototype.constructor) + .add(new OneOf(oneofName, fieldNames)); + Object.defineProperty(prototype, oneofName, { + get: util.oneOfGetter(fieldNames), + set: util.oneOfSetter(fieldNames) + }); + }; +}; + +},{"16":16,"24":24,"37":37}],26:[function(require,module,exports){ +"use strict"; +module.exports = parse; + +parse.filename = null; +parse.defaults = { keepCase: false }; + +var tokenize = require(34), + Root = require(29), + Type = require(35), + Field = require(16), + MapField = require(20), + OneOf = require(25), + Enum = require(15), + Service = require(33), + Method = require(22), + types = require(36), + util = require(37); + +var base10Re = /^[1-9][0-9]*$/, + base10NegRe = /^-?[1-9][0-9]*$/, + base16Re = /^0[x][0-9a-fA-F]+$/, + base16NegRe = /^-?0[x][0-9a-fA-F]+$/, + base8Re = /^0[0-7]+$/, + base8NegRe = /^-?0[0-7]+$/, + numberRe = /^(?![eE])[0-9]*(?:\.[0-9]*)?(?:[eE][+-]?[0-9]+)?$/, + nameRe = /^[a-zA-Z_][a-zA-Z_0-9]*$/, + typeRefRe = /^(?:\.?[a-zA-Z_][a-zA-Z_0-9]*)(?:\.[a-zA-Z_][a-zA-Z_0-9]*)*$/, + fqTypeRefRe = /^(?:\.[a-zA-Z_][a-zA-Z_0-9]*)+$/; + +/** + * Result object returned from {@link parse}. + * @interface IParserResult + * @property {string|undefined} package Package name, if declared + * @property {string[]|undefined} imports Imports, if any + * @property {string[]|undefined} weakImports Weak imports, if any + * @property {string|undefined} syntax Syntax, if specified (either `"proto2"` or `"proto3"`) + * @property {Root} root Populated root instance + */ + +/** + * Options modifying the behavior of {@link parse}. + * @interface IParseOptions + * @property {boolean} [keepCase=false] Keeps field casing instead of converting to camel case + * @property {boolean} [alternateCommentMode=false] Recognize double-slash comments in addition to doc-block comments. + * @property {boolean} [preferTrailingComment=false] Use trailing comment when both leading comment and trailing comment exist. + */ + +/** + * Options modifying the behavior of JSON serialization. + * @interface IToJSONOptions + * @property {boolean} [keepComments=false] Serializes comments. + */ + +/** + * Parses the given .proto source and returns an object with the parsed contents. + * @param {string} source Source contents + * @param {Root} root Root to populate + * @param {IParseOptions} [options] Parse options. Defaults to {@link parse.defaults} when omitted. + * @returns {IParserResult} Parser result + * @property {string} filename=null Currently processing file name for error reporting, if known + * @property {IParseOptions} defaults Default {@link IParseOptions} + */ +function parse(source, root, options) { + /* eslint-disable callback-return */ + if (!(root instanceof Root)) { + options = root; + root = new Root(); + } + if (!options) + options = parse.defaults; + + var preferTrailingComment = options.preferTrailingComment || false; + var tn = tokenize(source, options.alternateCommentMode || false), + next = tn.next, + push = tn.push, + peek = tn.peek, + skip = tn.skip, + cmnt = tn.cmnt; + + var head = true, + pkg, + imports, + weakImports, + syntax, + isProto3 = false; + + var ptr = root; + + var applyCase = options.keepCase ? function(name) { return name; } : util.camelCase; + + /* istanbul ignore next */ + function illegal(token, name, insideTryCatch) { + var filename = parse.filename; + if (!insideTryCatch) + parse.filename = null; + return Error("illegal " + (name || "token") + " '" + token + "' (" + (filename ? filename + ", " : "") + "line " + tn.line + ")"); + } + + function readString() { + var values = [], + token; + do { + /* istanbul ignore if */ + if ((token = next()) !== "\"" && token !== "'") + throw illegal(token); + + values.push(next()); + skip(token); + token = peek(); + } while (token === "\"" || token === "'"); + return values.join(""); + } + + function readValue(acceptTypeRef) { + var token = next(); + switch (token) { + case "'": + case "\"": + push(token); + return readString(); + case "true": case "TRUE": + return true; + case "false": case "FALSE": + return false; + } + try { + return parseNumber(token, /* insideTryCatch */ true); + } catch (e) { + + /* istanbul ignore else */ + if (acceptTypeRef && typeRefRe.test(token)) + return token; + + /* istanbul ignore next */ + throw illegal(token, "value"); + } + } + + function readRanges(target, acceptStrings) { + var token, start; + do { + if (acceptStrings && ((token = peek()) === "\"" || token === "'")) + target.push(readString()); + else + target.push([ start = parseId(next()), skip("to", true) ? parseId(next()) : start ]); + } while (skip(",", true)); + var dummy = {options: undefined}; + dummy.setOption = function(name, value) { + if (this.options === undefined) this.options = {}; + this.options[name] = value; + }; + ifBlock( + dummy, + function parseRange_block(token) { + /* istanbul ignore else */ + if (token === "option") { + parseOption(dummy, token); // skip + skip(";"); + } else + throw illegal(token); + }, + function parseRange_line() { + parseInlineOptions(dummy); // skip + }); + } + + function parseNumber(token, insideTryCatch) { + var sign = 1; + if (token.charAt(0) === "-") { + sign = -1; + token = token.substring(1); + } + switch (token) { + case "inf": case "INF": case "Inf": + return sign * Infinity; + case "nan": case "NAN": case "Nan": case "NaN": + return NaN; + case "0": + return 0; + } + if (base10Re.test(token)) + return sign * parseInt(token, 10); + if (base16Re.test(token)) + return sign * parseInt(token, 16); + if (base8Re.test(token)) + return sign * parseInt(token, 8); + + /* istanbul ignore else */ + if (numberRe.test(token)) + return sign * parseFloat(token); + + /* istanbul ignore next */ + throw illegal(token, "number", insideTryCatch); + } + + function parseId(token, acceptNegative) { + switch (token) { + case "max": case "MAX": case "Max": + return 536870911; + case "0": + return 0; + } + + /* istanbul ignore if */ + if (!acceptNegative && token.charAt(0) === "-") + throw illegal(token, "id"); + + if (base10NegRe.test(token)) + return parseInt(token, 10); + if (base16NegRe.test(token)) + return parseInt(token, 16); + + /* istanbul ignore else */ + if (base8NegRe.test(token)) + return parseInt(token, 8); + + /* istanbul ignore next */ + throw illegal(token, "id"); + } + + function parsePackage() { + + /* istanbul ignore if */ + if (pkg !== undefined) + throw illegal("package"); + + pkg = next(); + + /* istanbul ignore if */ + if (!typeRefRe.test(pkg)) + throw illegal(pkg, "name"); + + ptr = ptr.define(pkg); + skip(";"); + } + + function parseImport() { + var token = peek(); + var whichImports; + switch (token) { + case "weak": + whichImports = weakImports || (weakImports = []); + next(); + break; + case "public": + next(); + // eslint-disable-next-line no-fallthrough + default: + whichImports = imports || (imports = []); + break; + } + token = readString(); + skip(";"); + whichImports.push(token); + } + + function parseSyntax() { + skip("="); + syntax = readString(); + isProto3 = syntax === "proto3"; + + /* istanbul ignore if */ + if (!isProto3 && syntax !== "proto2") + throw illegal(syntax, "syntax"); + + skip(";"); + } + + function parseCommon(parent, token) { + switch (token) { + + case "option": + parseOption(parent, token); + skip(";"); + return true; + + case "message": + parseType(parent, token); + return true; + + case "enum": + parseEnum(parent, token); + return true; + + case "service": + parseService(parent, token); + return true; + + case "extend": + parseExtension(parent, token); + return true; + } + return false; + } + + function ifBlock(obj, fnIf, fnElse) { + var trailingLine = tn.line; + if (obj) { + if(typeof obj.comment !== "string") { + obj.comment = cmnt(); // try block-type comment + } + obj.filename = parse.filename; + } + if (skip("{", true)) { + var token; + while ((token = next()) !== "}") + fnIf(token); + skip(";", true); + } else { + if (fnElse) + fnElse(); + skip(";"); + if (obj && (typeof obj.comment !== "string" || preferTrailingComment)) + obj.comment = cmnt(trailingLine) || obj.comment; // try line-type comment + } + } + + function parseType(parent, token) { + + /* istanbul ignore if */ + if (!nameRe.test(token = next())) + throw illegal(token, "type name"); + + var type = new Type(token); + ifBlock(type, function parseType_block(token) { + if (parseCommon(type, token)) + return; + + switch (token) { + + case "map": + parseMapField(type, token); + break; + + case "required": + case "repeated": + parseField(type, token); + break; + + case "optional": + /* istanbul ignore if */ + if (isProto3) { + parseField(type, "proto3_optional"); + } else { + parseField(type, "optional"); + } + break; + + case "oneof": + parseOneOf(type, token); + break; + + case "extensions": + readRanges(type.extensions || (type.extensions = [])); + break; + + case "reserved": + readRanges(type.reserved || (type.reserved = []), true); + break; + + default: + /* istanbul ignore if */ + if (!isProto3 || !typeRefRe.test(token)) + throw illegal(token); + + push(token); + parseField(type, "optional"); + break; + } + }); + parent.add(type); + } + + function parseField(parent, rule, extend) { + var type = next(); + if (type === "group") { + parseGroup(parent, rule); + return; + } + // Type names can consume multiple tokens, in multiple variants: + // package.subpackage field tokens: "package.subpackage" [TYPE NAME ENDS HERE] "field" + // package . subpackage field tokens: "package" "." "subpackage" [TYPE NAME ENDS HERE] "field" + // package. subpackage field tokens: "package." "subpackage" [TYPE NAME ENDS HERE] "field" + // package .subpackage field tokens: "package" ".subpackage" [TYPE NAME ENDS HERE] "field" + // Keep reading tokens until we get a type name with no period at the end, + // and the next token does not start with a period. + while (type.endsWith(".") || peek().startsWith(".")) { + type += next(); + } + + /* istanbul ignore if */ + if (!typeRefRe.test(type)) + throw illegal(type, "type"); + + var name = next(); + + /* istanbul ignore if */ + if (!nameRe.test(name)) + throw illegal(name, "name"); + + name = applyCase(name); + skip("="); + + var field = new Field(name, parseId(next()), type, rule, extend); + ifBlock(field, function parseField_block(token) { + + /* istanbul ignore else */ + if (token === "option") { + parseOption(field, token); + skip(";"); + } else + throw illegal(token); + + }, function parseField_line() { + parseInlineOptions(field); + }); + + if (rule === "proto3_optional") { + // for proto3 optional fields, we create a single-member Oneof to mimic "optional" behavior + var oneof = new OneOf("_" + name); + field.setOption("proto3_optional", true); + oneof.add(field); + parent.add(oneof); + } else { + parent.add(field); + } + + // JSON defaults to packed=true if not set so we have to set packed=false explicity when + // parsing proto2 descriptors without the option, where applicable. This must be done for + // all known packable types and anything that could be an enum (= is not a basic type). + if (!isProto3 && field.repeated && (types.packed[type] !== undefined || types.basic[type] === undefined)) + field.setOption("packed", false, /* ifNotSet */ true); + } + + function parseGroup(parent, rule) { + var name = next(); + + /* istanbul ignore if */ + if (!nameRe.test(name)) + throw illegal(name, "name"); + + var fieldName = util.lcFirst(name); + if (name === fieldName) + name = util.ucFirst(name); + skip("="); + var id = parseId(next()); + var type = new Type(name); + type.group = true; + var field = new Field(fieldName, id, name, rule); + field.filename = parse.filename; + ifBlock(type, function parseGroup_block(token) { + switch (token) { + + case "option": + parseOption(type, token); + skip(";"); + break; + + case "required": + case "repeated": + parseField(type, token); + break; + + case "optional": + /* istanbul ignore if */ + if (isProto3) { + parseField(type, "proto3_optional"); + } else { + parseField(type, "optional"); + } + break; + + case "message": + parseType(type, token); + break; + + case "enum": + parseEnum(type, token); + break; + + /* istanbul ignore next */ + default: + throw illegal(token); // there are no groups with proto3 semantics + } + }); + parent.add(type) + .add(field); + } + + function parseMapField(parent) { + skip("<"); + var keyType = next(); + + /* istanbul ignore if */ + if (types.mapKey[keyType] === undefined) + throw illegal(keyType, "type"); + + skip(","); + var valueType = next(); + + /* istanbul ignore if */ + if (!typeRefRe.test(valueType)) + throw illegal(valueType, "type"); + + skip(">"); + var name = next(); + + /* istanbul ignore if */ + if (!nameRe.test(name)) + throw illegal(name, "name"); + + skip("="); + var field = new MapField(applyCase(name), parseId(next()), keyType, valueType); + ifBlock(field, function parseMapField_block(token) { + + /* istanbul ignore else */ + if (token === "option") { + parseOption(field, token); + skip(";"); + } else + throw illegal(token); + + }, function parseMapField_line() { + parseInlineOptions(field); + }); + parent.add(field); + } + + function parseOneOf(parent, token) { + + /* istanbul ignore if */ + if (!nameRe.test(token = next())) + throw illegal(token, "name"); + + var oneof = new OneOf(applyCase(token)); + ifBlock(oneof, function parseOneOf_block(token) { + if (token === "option") { + parseOption(oneof, token); + skip(";"); + } else { + push(token); + parseField(oneof, "optional"); + } + }); + parent.add(oneof); + } + + function parseEnum(parent, token) { + + /* istanbul ignore if */ + if (!nameRe.test(token = next())) + throw illegal(token, "name"); + + var enm = new Enum(token); + ifBlock(enm, function parseEnum_block(token) { + switch(token) { + case "option": + parseOption(enm, token); + skip(";"); + break; + + case "reserved": + readRanges(enm.reserved || (enm.reserved = []), true); + break; + + default: + parseEnumValue(enm, token); + } + }); + parent.add(enm); + } + + function parseEnumValue(parent, token) { + + /* istanbul ignore if */ + if (!nameRe.test(token)) + throw illegal(token, "name"); + + skip("="); + var value = parseId(next(), true), + dummy = { + options: undefined + }; + dummy.setOption = function(name, value) { + if (this.options === undefined) + this.options = {}; + this.options[name] = value; + }; + ifBlock(dummy, function parseEnumValue_block(token) { + + /* istanbul ignore else */ + if (token === "option") { + parseOption(dummy, token); // skip + skip(";"); + } else + throw illegal(token); + + }, function parseEnumValue_line() { + parseInlineOptions(dummy); // skip + }); + parent.add(token, value, dummy.comment, dummy.options); + } + + function parseOption(parent, token) { + var isCustom = skip("(", true); + + /* istanbul ignore if */ + if (!typeRefRe.test(token = next())) + throw illegal(token, "name"); + + var name = token; + var option = name; + var propName; + + if (isCustom) { + skip(")"); + name = "(" + name + ")"; + option = name; + token = peek(); + if (fqTypeRefRe.test(token)) { + propName = token.slice(1); //remove '.' before property name + name += token; + next(); + } + } + skip("="); + var optionValue = parseOptionValue(parent, name); + setParsedOption(parent, option, optionValue, propName); + } + + function parseOptionValue(parent, name) { + // { a: "foo" b { c: "bar" } } + if (skip("{", true)) { + var objectResult = {}; + + while (!skip("}", true)) { + /* istanbul ignore if */ + if (!nameRe.test(token = next())) { + throw illegal(token, "name"); + } + if (token === null) { + throw illegal(token, "end of input"); + } + + var value; + var propName = token; + + skip(":", true); + + if (peek() === "{") + value = parseOptionValue(parent, name + "." + token); + else if (peek() === "[") { + // option (my_option) = { + // repeated_value: [ "foo", "bar" ] + // }; + value = []; + var lastValue; + if (skip("[", true)) { + do { + lastValue = readValue(true); + value.push(lastValue); + } while (skip(",", true)); + skip("]"); + if (typeof lastValue !== "undefined") { + setOption(parent, name + "." + token, lastValue); + } + } + } else { + value = readValue(true); + setOption(parent, name + "." + token, value); + } + + var prevValue = objectResult[propName]; + + if (prevValue) + value = [].concat(prevValue).concat(value); + + objectResult[propName] = value; + + // Semicolons and commas can be optional + skip(",", true); + skip(";", true); + } + + return objectResult; + } + + var simpleValue = readValue(true); + setOption(parent, name, simpleValue); + return simpleValue; + // Does not enforce a delimiter to be universal + } + + function setOption(parent, name, value) { + if (parent.setOption) + parent.setOption(name, value); + } + + function setParsedOption(parent, name, value, propName) { + if (parent.setParsedOption) + parent.setParsedOption(name, value, propName); + } + + function parseInlineOptions(parent) { + if (skip("[", true)) { + do { + parseOption(parent, "option"); + } while (skip(",", true)); + skip("]"); + } + return parent; + } + + function parseService(parent, token) { + + /* istanbul ignore if */ + if (!nameRe.test(token = next())) + throw illegal(token, "service name"); + + var service = new Service(token); + ifBlock(service, function parseService_block(token) { + if (parseCommon(service, token)) + return; + + /* istanbul ignore else */ + if (token === "rpc") + parseMethod(service, token); + else + throw illegal(token); + }); + parent.add(service); + } + + function parseMethod(parent, token) { + // Get the comment of the preceding line now (if one exists) in case the + // method is defined across multiple lines. + var commentText = cmnt(); + + var type = token; + + /* istanbul ignore if */ + if (!nameRe.test(token = next())) + throw illegal(token, "name"); + + var name = token, + requestType, requestStream, + responseType, responseStream; + + skip("("); + if (skip("stream", true)) + requestStream = true; + + /* istanbul ignore if */ + if (!typeRefRe.test(token = next())) + throw illegal(token); + + requestType = token; + skip(")"); skip("returns"); skip("("); + if (skip("stream", true)) + responseStream = true; + + /* istanbul ignore if */ + if (!typeRefRe.test(token = next())) + throw illegal(token); + + responseType = token; + skip(")"); + + var method = new Method(name, type, requestType, responseType, requestStream, responseStream); + method.comment = commentText; + ifBlock(method, function parseMethod_block(token) { + + /* istanbul ignore else */ + if (token === "option") { + parseOption(method, token); + skip(";"); + } else + throw illegal(token); + + }); + parent.add(method); + } + + function parseExtension(parent, token) { + + /* istanbul ignore if */ + if (!typeRefRe.test(token = next())) + throw illegal(token, "reference"); + + var reference = token; + ifBlock(null, function parseExtension_block(token) { + switch (token) { + + case "required": + case "repeated": + parseField(parent, token, reference); + break; + + case "optional": + /* istanbul ignore if */ + if (isProto3) { + parseField(parent, "proto3_optional", reference); + } else { + parseField(parent, "optional", reference); + } + break; + + default: + /* istanbul ignore if */ + if (!isProto3 || !typeRefRe.test(token)) + throw illegal(token); + push(token); + parseField(parent, "optional", reference); + break; + } + }); + } + + var token; + while ((token = next()) !== null) { + switch (token) { + + case "package": + + /* istanbul ignore if */ + if (!head) + throw illegal(token); + + parsePackage(); + break; + + case "import": + + /* istanbul ignore if */ + if (!head) + throw illegal(token); + + parseImport(); + break; + + case "syntax": + + /* istanbul ignore if */ + if (!head) + throw illegal(token); + + parseSyntax(); + break; + + case "option": + + parseOption(ptr, token); + skip(";"); + break; + + default: + + /* istanbul ignore else */ + if (parseCommon(ptr, token)) { + head = false; + continue; + } + + /* istanbul ignore next */ + throw illegal(token); + } + } + + parse.filename = null; + return { + "package" : pkg, + "imports" : imports, + weakImports : weakImports, + syntax : syntax, + root : root + }; +} + +/** + * Parses the given .proto source and returns an object with the parsed contents. + * @name parse + * @function + * @param {string} source Source contents + * @param {IParseOptions} [options] Parse options. Defaults to {@link parse.defaults} when omitted. + * @returns {IParserResult} Parser result + * @property {string} filename=null Currently processing file name for error reporting, if known + * @property {IParseOptions} defaults Default {@link IParseOptions} + * @variation 2 + */ + +},{"15":15,"16":16,"20":20,"22":22,"25":25,"29":29,"33":33,"34":34,"35":35,"36":36,"37":37}],27:[function(require,module,exports){ +"use strict"; +module.exports = Reader; + +var util = require(39); + +var BufferReader; // cyclic + +var LongBits = util.LongBits, + utf8 = util.utf8; + +/* istanbul ignore next */ +function indexOutOfRange(reader, writeLength) { + return RangeError("index out of range: " + reader.pos + " + " + (writeLength || 1) + " > " + reader.len); +} + +/** + * Constructs a new reader instance using the specified buffer. + * @classdesc Wire format reader using `Uint8Array` if available, otherwise `Array`. + * @constructor + * @param {Uint8Array} buffer Buffer to read from + */ +function Reader(buffer) { + + /** + * Read buffer. + * @type {Uint8Array} + */ + this.buf = buffer; + + /** + * Read buffer position. + * @type {number} + */ + this.pos = 0; + + /** + * Read buffer length. + * @type {number} + */ + this.len = buffer.length; +} + +var create_array = typeof Uint8Array !== "undefined" + ? function create_typed_array(buffer) { + if (buffer instanceof Uint8Array || Array.isArray(buffer)) + return new Reader(buffer); + throw Error("illegal buffer"); + } + /* istanbul ignore next */ + : function create_array(buffer) { + if (Array.isArray(buffer)) + return new Reader(buffer); + throw Error("illegal buffer"); + }; + +var create = function create() { + return util.Buffer + ? function create_buffer_setup(buffer) { + return (Reader.create = function create_buffer(buffer) { + return util.Buffer.isBuffer(buffer) + ? new BufferReader(buffer) + /* istanbul ignore next */ + : create_array(buffer); + })(buffer); + } + /* istanbul ignore next */ + : create_array; +}; + +/** + * Creates a new reader using the specified buffer. + * @function + * @param {Uint8Array|Buffer} buffer Buffer to read from + * @returns {Reader|BufferReader} A {@link BufferReader} if `buffer` is a Buffer, otherwise a {@link Reader} + * @throws {Error} If `buffer` is not a valid buffer + */ +Reader.create = create(); + +Reader.prototype._slice = util.Array.prototype.subarray || /* istanbul ignore next */ util.Array.prototype.slice; + +/** + * Reads a varint as an unsigned 32 bit value. + * @function + * @returns {number} Value read + */ +Reader.prototype.uint32 = (function read_uint32_setup() { + var value = 4294967295; // optimizer type-hint, tends to deopt otherwise (?!) + return function read_uint32() { + value = ( this.buf[this.pos] & 127 ) >>> 0; if (this.buf[this.pos++] < 128) return value; + value = (value | (this.buf[this.pos] & 127) << 7) >>> 0; if (this.buf[this.pos++] < 128) return value; + value = (value | (this.buf[this.pos] & 127) << 14) >>> 0; if (this.buf[this.pos++] < 128) return value; + value = (value | (this.buf[this.pos] & 127) << 21) >>> 0; if (this.buf[this.pos++] < 128) return value; + value = (value | (this.buf[this.pos] & 15) << 28) >>> 0; if (this.buf[this.pos++] < 128) return value; + + /* istanbul ignore if */ + if ((this.pos += 5) > this.len) { + this.pos = this.len; + throw indexOutOfRange(this, 10); + } + return value; + }; +})(); + +/** + * Reads a varint as a signed 32 bit value. + * @returns {number} Value read + */ +Reader.prototype.int32 = function read_int32() { + return this.uint32() | 0; +}; + +/** + * Reads a zig-zag encoded varint as a signed 32 bit value. + * @returns {number} Value read + */ +Reader.prototype.sint32 = function read_sint32() { + var value = this.uint32(); + return value >>> 1 ^ -(value & 1) | 0; +}; + +/* eslint-disable no-invalid-this */ + +function readLongVarint() { + // tends to deopt with local vars for octet etc. + var bits = new LongBits(0, 0); + var i = 0; + if (this.len - this.pos > 4) { // fast route (lo) + for (; i < 4; ++i) { + // 1st..4th + bits.lo = (bits.lo | (this.buf[this.pos] & 127) << i * 7) >>> 0; + if (this.buf[this.pos++] < 128) + return bits; + } + // 5th + bits.lo = (bits.lo | (this.buf[this.pos] & 127) << 28) >>> 0; + bits.hi = (bits.hi | (this.buf[this.pos] & 127) >> 4) >>> 0; + if (this.buf[this.pos++] < 128) + return bits; + i = 0; + } else { + for (; i < 3; ++i) { + /* istanbul ignore if */ + if (this.pos >= this.len) + throw indexOutOfRange(this); + // 1st..3th + bits.lo = (bits.lo | (this.buf[this.pos] & 127) << i * 7) >>> 0; + if (this.buf[this.pos++] < 128) + return bits; + } + // 4th + bits.lo = (bits.lo | (this.buf[this.pos++] & 127) << i * 7) >>> 0; + return bits; + } + if (this.len - this.pos > 4) { // fast route (hi) + for (; i < 5; ++i) { + // 6th..10th + bits.hi = (bits.hi | (this.buf[this.pos] & 127) << i * 7 + 3) >>> 0; + if (this.buf[this.pos++] < 128) + return bits; + } + } else { + for (; i < 5; ++i) { + /* istanbul ignore if */ + if (this.pos >= this.len) + throw indexOutOfRange(this); + // 6th..10th + bits.hi = (bits.hi | (this.buf[this.pos] & 127) << i * 7 + 3) >>> 0; + if (this.buf[this.pos++] < 128) + return bits; + } + } + /* istanbul ignore next */ + throw Error("invalid varint encoding"); +} + +/* eslint-enable no-invalid-this */ + +/** + * Reads a varint as a signed 64 bit value. + * @name Reader#int64 + * @function + * @returns {Long} Value read + */ + +/** + * Reads a varint as an unsigned 64 bit value. + * @name Reader#uint64 + * @function + * @returns {Long} Value read + */ + +/** + * Reads a zig-zag encoded varint as a signed 64 bit value. + * @name Reader#sint64 + * @function + * @returns {Long} Value read + */ + +/** + * Reads a varint as a boolean. + * @returns {boolean} Value read + */ +Reader.prototype.bool = function read_bool() { + return this.uint32() !== 0; +}; + +function readFixed32_end(buf, end) { // note that this uses `end`, not `pos` + return (buf[end - 4] + | buf[end - 3] << 8 + | buf[end - 2] << 16 + | buf[end - 1] << 24) >>> 0; +} + +/** + * Reads fixed 32 bits as an unsigned 32 bit integer. + * @returns {number} Value read + */ +Reader.prototype.fixed32 = function read_fixed32() { + + /* istanbul ignore if */ + if (this.pos + 4 > this.len) + throw indexOutOfRange(this, 4); + + return readFixed32_end(this.buf, this.pos += 4); +}; + +/** + * Reads fixed 32 bits as a signed 32 bit integer. + * @returns {number} Value read + */ +Reader.prototype.sfixed32 = function read_sfixed32() { + + /* istanbul ignore if */ + if (this.pos + 4 > this.len) + throw indexOutOfRange(this, 4); + + return readFixed32_end(this.buf, this.pos += 4) | 0; +}; + +/* eslint-disable no-invalid-this */ + +function readFixed64(/* this: Reader */) { + + /* istanbul ignore if */ + if (this.pos + 8 > this.len) + throw indexOutOfRange(this, 8); + + return new LongBits(readFixed32_end(this.buf, this.pos += 4), readFixed32_end(this.buf, this.pos += 4)); +} + +/* eslint-enable no-invalid-this */ + +/** + * Reads fixed 64 bits. + * @name Reader#fixed64 + * @function + * @returns {Long} Value read + */ + +/** + * Reads zig-zag encoded fixed 64 bits. + * @name Reader#sfixed64 + * @function + * @returns {Long} Value read + */ + +/** + * Reads a float (32 bit) as a number. + * @function + * @returns {number} Value read + */ +Reader.prototype.float = function read_float() { + + /* istanbul ignore if */ + if (this.pos + 4 > this.len) + throw indexOutOfRange(this, 4); + + var value = util.float.readFloatLE(this.buf, this.pos); + this.pos += 4; + return value; +}; + +/** + * Reads a double (64 bit float) as a number. + * @function + * @returns {number} Value read + */ +Reader.prototype.double = function read_double() { + + /* istanbul ignore if */ + if (this.pos + 8 > this.len) + throw indexOutOfRange(this, 4); + + var value = util.float.readDoubleLE(this.buf, this.pos); + this.pos += 8; + return value; +}; + +/** + * Reads a sequence of bytes preceeded by its length as a varint. + * @returns {Uint8Array} Value read + */ +Reader.prototype.bytes = function read_bytes() { + var length = this.uint32(), + start = this.pos, + end = this.pos + length; + + /* istanbul ignore if */ + if (end > this.len) + throw indexOutOfRange(this, length); + + this.pos += length; + if (Array.isArray(this.buf)) // plain array + return this.buf.slice(start, end); + + if (start === end) { // fix for IE 10/Win8 and others' subarray returning array of size 1 + var nativeBuffer = util.Buffer; + return nativeBuffer + ? nativeBuffer.alloc(0) + : new this.buf.constructor(0); + } + return this._slice.call(this.buf, start, end); +}; + +/** + * Reads a string preceeded by its byte length as a varint. + * @returns {string} Value read + */ +Reader.prototype.string = function read_string() { + var bytes = this.bytes(); + return utf8.read(bytes, 0, bytes.length); +}; + +/** + * Skips the specified number of bytes if specified, otherwise skips a varint. + * @param {number} [length] Length if known, otherwise a varint is assumed + * @returns {Reader} `this` + */ +Reader.prototype.skip = function skip(length) { + if (typeof length === "number") { + /* istanbul ignore if */ + if (this.pos + length > this.len) + throw indexOutOfRange(this, length); + this.pos += length; + } else { + do { + /* istanbul ignore if */ + if (this.pos >= this.len) + throw indexOutOfRange(this); + } while (this.buf[this.pos++] & 128); + } + return this; +}; + +/** + * Skips the next element of the specified wire type. + * @param {number} wireType Wire type received + * @returns {Reader} `this` + */ +Reader.prototype.skipType = function(wireType) { + switch (wireType) { + case 0: + this.skip(); + break; + case 1: + this.skip(8); + break; + case 2: + this.skip(this.uint32()); + break; + case 3: + while ((wireType = this.uint32() & 7) !== 4) { + this.skipType(wireType); + } + break; + case 5: + this.skip(4); + break; + + /* istanbul ignore next */ + default: + throw Error("invalid wire type " + wireType + " at offset " + this.pos); + } + return this; +}; + +Reader._configure = function(BufferReader_) { + BufferReader = BufferReader_; + Reader.create = create(); + BufferReader._configure(); + + var fn = util.Long ? "toLong" : /* istanbul ignore next */ "toNumber"; + util.merge(Reader.prototype, { + + int64: function read_int64() { + return readLongVarint.call(this)[fn](false); + }, + + uint64: function read_uint64() { + return readLongVarint.call(this)[fn](true); + }, + + sint64: function read_sint64() { + return readLongVarint.call(this).zzDecode()[fn](false); + }, + + fixed64: function read_fixed64() { + return readFixed64.call(this)[fn](true); + }, + + sfixed64: function read_sfixed64() { + return readFixed64.call(this)[fn](false); + } + + }); +}; + +},{"39":39}],28:[function(require,module,exports){ +"use strict"; +module.exports = BufferReader; + +// extends Reader +var Reader = require(27); +(BufferReader.prototype = Object.create(Reader.prototype)).constructor = BufferReader; + +var util = require(39); + +/** + * Constructs a new buffer reader instance. + * @classdesc Wire format reader using node buffers. + * @extends Reader + * @constructor + * @param {Buffer} buffer Buffer to read from + */ +function BufferReader(buffer) { + Reader.call(this, buffer); + + /** + * Read buffer. + * @name BufferReader#buf + * @type {Buffer} + */ +} + +BufferReader._configure = function () { + /* istanbul ignore else */ + if (util.Buffer) + BufferReader.prototype._slice = util.Buffer.prototype.slice; +}; + + +/** + * @override + */ +BufferReader.prototype.string = function read_string_buffer() { + var len = this.uint32(); // modifies pos + return this.buf.utf8Slice + ? this.buf.utf8Slice(this.pos, this.pos = Math.min(this.pos + len, this.len)) + : this.buf.toString("utf-8", this.pos, this.pos = Math.min(this.pos + len, this.len)); +}; + +/** + * Reads a sequence of bytes preceeded by its length as a varint. + * @name BufferReader#bytes + * @function + * @returns {Buffer} Value read + */ + +BufferReader._configure(); + +},{"27":27,"39":39}],29:[function(require,module,exports){ +"use strict"; +module.exports = Root; + +// extends Namespace +var Namespace = require(23); +((Root.prototype = Object.create(Namespace.prototype)).constructor = Root).className = "Root"; + +var Field = require(16), + Enum = require(15), + OneOf = require(25), + util = require(37); + +var Type, // cyclic + parse, // might be excluded + common; // " + +/** + * Constructs a new root namespace instance. + * @classdesc Root namespace wrapping all types, enums, services, sub-namespaces etc. that belong together. + * @extends NamespaceBase + * @constructor + * @param {Object.} [options] Top level options + */ +function Root(options) { + Namespace.call(this, "", options); + + /** + * Deferred extension fields. + * @type {Field[]} + */ + this.deferred = []; + + /** + * Resolved file names of loaded files. + * @type {string[]} + */ + this.files = []; +} + +/** + * Loads a namespace descriptor into a root namespace. + * @param {INamespace} json Nameespace descriptor + * @param {Root} [root] Root namespace, defaults to create a new one if omitted + * @returns {Root} Root namespace + */ +Root.fromJSON = function fromJSON(json, root) { + if (!root) + root = new Root(); + if (json.options) + root.setOptions(json.options); + return root.addJSON(json.nested); +}; + +/** + * Resolves the path of an imported file, relative to the importing origin. + * This method exists so you can override it with your own logic in case your imports are scattered over multiple directories. + * @function + * @param {string} origin The file name of the importing file + * @param {string} target The file name being imported + * @returns {string|null} Resolved path to `target` or `null` to skip the file + */ +Root.prototype.resolvePath = util.path.resolve; + +/** + * Fetch content from file path or url + * This method exists so you can override it with your own logic. + * @function + * @param {string} path File path or url + * @param {FetchCallback} callback Callback function + * @returns {undefined} + */ +Root.prototype.fetch = util.fetch; + +// A symbol-like function to safely signal synchronous loading +/* istanbul ignore next */ +function SYNC() {} // eslint-disable-line no-empty-function + +/** + * Loads one or multiple .proto or preprocessed .json files into this root namespace and calls the callback. + * @param {string|string[]} filename Names of one or multiple files to load + * @param {IParseOptions} options Parse options + * @param {LoadCallback} callback Callback function + * @returns {undefined} + */ +Root.prototype.load = function load(filename, options, callback) { + if (typeof options === "function") { + callback = options; + options = undefined; + } + var self = this; + if (!callback) + return util.asPromise(load, self, filename, options); + + var sync = callback === SYNC; // undocumented + + // Finishes loading by calling the callback (exactly once) + function finish(err, root) { + /* istanbul ignore if */ + if (!callback) + return; + if (sync) + throw err; + var cb = callback; + callback = null; + cb(err, root); + } + + // Bundled definition existence checking + function getBundledFileName(filename) { + var idx = filename.lastIndexOf("google/protobuf/"); + if (idx > -1) { + var altname = filename.substring(idx); + if (altname in common) return altname; + } + return null; + } + + // Processes a single file + function process(filename, source) { + try { + if (util.isString(source) && source.charAt(0) === "{") + source = JSON.parse(source); + if (!util.isString(source)) + self.setOptions(source.options).addJSON(source.nested); + else { + parse.filename = filename; + var parsed = parse(source, self, options), + resolved, + i = 0; + if (parsed.imports) + for (; i < parsed.imports.length; ++i) + if (resolved = getBundledFileName(parsed.imports[i]) || self.resolvePath(filename, parsed.imports[i])) + fetch(resolved); + if (parsed.weakImports) + for (i = 0; i < parsed.weakImports.length; ++i) + if (resolved = getBundledFileName(parsed.weakImports[i]) || self.resolvePath(filename, parsed.weakImports[i])) + fetch(resolved, true); + } + } catch (err) { + finish(err); + } + if (!sync && !queued) + finish(null, self); // only once anyway + } + + // Fetches a single file + function fetch(filename, weak) { + filename = getBundledFileName(filename) || filename; + + // Skip if already loaded / attempted + if (self.files.indexOf(filename) > -1) + return; + self.files.push(filename); + + // Shortcut bundled definitions + if (filename in common) { + if (sync) + process(filename, common[filename]); + else { + ++queued; + setTimeout(function() { + --queued; + process(filename, common[filename]); + }); + } + return; + } + + // Otherwise fetch from disk or network + if (sync) { + var source; + try { + source = util.fs.readFileSync(filename).toString("utf8"); + } catch (err) { + if (!weak) + finish(err); + return; + } + process(filename, source); + } else { + ++queued; + self.fetch(filename, function(err, source) { + --queued; + /* istanbul ignore if */ + if (!callback) + return; // terminated meanwhile + if (err) { + /* istanbul ignore else */ + if (!weak) + finish(err); + else if (!queued) // can't be covered reliably + finish(null, self); + return; + } + process(filename, source); + }); + } + } + var queued = 0; + + // Assembling the root namespace doesn't require working type + // references anymore, so we can load everything in parallel + if (util.isString(filename)) + filename = [ filename ]; + for (var i = 0, resolved; i < filename.length; ++i) + if (resolved = self.resolvePath("", filename[i])) + fetch(resolved); + + if (sync) + return self; + if (!queued) + finish(null, self); + return undefined; +}; +// function load(filename:string, options:IParseOptions, callback:LoadCallback):undefined + +/** + * Loads one or multiple .proto or preprocessed .json files into this root namespace and calls the callback. + * @function Root#load + * @param {string|string[]} filename Names of one or multiple files to load + * @param {LoadCallback} callback Callback function + * @returns {undefined} + * @variation 2 + */ +// function load(filename:string, callback:LoadCallback):undefined + +/** + * Loads one or multiple .proto or preprocessed .json files into this root namespace and returns a promise. + * @function Root#load + * @param {string|string[]} filename Names of one or multiple files to load + * @param {IParseOptions} [options] Parse options. Defaults to {@link parse.defaults} when omitted. + * @returns {Promise} Promise + * @variation 3 + */ +// function load(filename:string, [options:IParseOptions]):Promise + +/** + * Synchronously loads one or multiple .proto or preprocessed .json files into this root namespace (node only). + * @function Root#loadSync + * @param {string|string[]} filename Names of one or multiple files to load + * @param {IParseOptions} [options] Parse options. Defaults to {@link parse.defaults} when omitted. + * @returns {Root} Root namespace + * @throws {Error} If synchronous fetching is not supported (i.e. in browsers) or if a file's syntax is invalid + */ +Root.prototype.loadSync = function loadSync(filename, options) { + if (!util.isNode) + throw Error("not supported"); + return this.load(filename, options, SYNC); +}; + +/** + * @override + */ +Root.prototype.resolveAll = function resolveAll() { + if (this.deferred.length) + throw Error("unresolvable extensions: " + this.deferred.map(function(field) { + return "'extend " + field.extend + "' in " + field.parent.fullName; + }).join(", ")); + return Namespace.prototype.resolveAll.call(this); +}; + +// only uppercased (and thus conflict-free) children are exposed, see below +var exposeRe = /^[A-Z]/; + +/** + * Handles a deferred declaring extension field by creating a sister field to represent it within its extended type. + * @param {Root} root Root instance + * @param {Field} field Declaring extension field witin the declaring type + * @returns {boolean} `true` if successfully added to the extended type, `false` otherwise + * @inner + * @ignore + */ +function tryHandleExtension(root, field) { + var extendedType = field.parent.lookup(field.extend); + if (extendedType) { + var sisterField = new Field(field.fullName, field.id, field.type, field.rule, undefined, field.options); + //do not allow to extend same field twice to prevent the error + if (extendedType.get(sisterField.name)) { + return true; + } + sisterField.declaringField = field; + field.extensionField = sisterField; + extendedType.add(sisterField); + return true; + } + return false; +} + +/** + * Called when any object is added to this root or its sub-namespaces. + * @param {ReflectionObject} object Object added + * @returns {undefined} + * @private + */ +Root.prototype._handleAdd = function _handleAdd(object) { + if (object instanceof Field) { + + if (/* an extension field (implies not part of a oneof) */ object.extend !== undefined && /* not already handled */ !object.extensionField) + if (!tryHandleExtension(this, object)) + this.deferred.push(object); + + } else if (object instanceof Enum) { + + if (exposeRe.test(object.name)) + object.parent[object.name] = object.values; // expose enum values as property of its parent + + } else if (!(object instanceof OneOf)) /* everything else is a namespace */ { + + if (object instanceof Type) // Try to handle any deferred extensions + for (var i = 0; i < this.deferred.length;) + if (tryHandleExtension(this, this.deferred[i])) + this.deferred.splice(i, 1); + else + ++i; + for (var j = 0; j < /* initializes */ object.nestedArray.length; ++j) // recurse into the namespace + this._handleAdd(object._nestedArray[j]); + if (exposeRe.test(object.name)) + object.parent[object.name] = object; // expose namespace as property of its parent + } + + // The above also adds uppercased (and thus conflict-free) nested types, services and enums as + // properties of namespaces just like static code does. This allows using a .d.ts generated for + // a static module with reflection-based solutions where the condition is met. +}; + +/** + * Called when any object is removed from this root or its sub-namespaces. + * @param {ReflectionObject} object Object removed + * @returns {undefined} + * @private + */ +Root.prototype._handleRemove = function _handleRemove(object) { + if (object instanceof Field) { + + if (/* an extension field */ object.extend !== undefined) { + if (/* already handled */ object.extensionField) { // remove its sister field + object.extensionField.parent.remove(object.extensionField); + object.extensionField = null; + } else { // cancel the extension + var index = this.deferred.indexOf(object); + /* istanbul ignore else */ + if (index > -1) + this.deferred.splice(index, 1); + } + } + + } else if (object instanceof Enum) { + + if (exposeRe.test(object.name)) + delete object.parent[object.name]; // unexpose enum values + + } else if (object instanceof Namespace) { + + for (var i = 0; i < /* initializes */ object.nestedArray.length; ++i) // recurse into the namespace + this._handleRemove(object._nestedArray[i]); + + if (exposeRe.test(object.name)) + delete object.parent[object.name]; // unexpose namespaces + + } +}; + +// Sets up cyclic dependencies (called in index-light) +Root._configure = function(Type_, parse_, common_) { + Type = Type_; + parse = parse_; + common = common_; +}; + +},{"15":15,"16":16,"23":23,"25":25,"37":37}],30:[function(require,module,exports){ +"use strict"; +module.exports = {}; + +/** + * Named roots. + * This is where pbjs stores generated structures (the option `-r, --root` specifies a name). + * Can also be used manually to make roots available across modules. + * @name roots + * @type {Object.} + * @example + * // pbjs -r myroot -o compiled.js ... + * + * // in another module: + * require("./compiled.js"); + * + * // in any subsequent module: + * var root = protobuf.roots["myroot"]; + */ + +},{}],31:[function(require,module,exports){ +"use strict"; + +/** + * Streaming RPC helpers. + * @namespace + */ +var rpc = exports; + +/** + * RPC implementation passed to {@link Service#create} performing a service request on network level, i.e. by utilizing http requests or websockets. + * @typedef RPCImpl + * @type {function} + * @param {Method|rpc.ServiceMethod,Message<{}>>} method Reflected or static method being called + * @param {Uint8Array} requestData Request data + * @param {RPCImplCallback} callback Callback function + * @returns {undefined} + * @example + * function rpcImpl(method, requestData, callback) { + * if (protobuf.util.lcFirst(method.name) !== "myMethod") // compatible with static code + * throw Error("no such method"); + * asynchronouslyObtainAResponse(requestData, function(err, responseData) { + * callback(err, responseData); + * }); + * } + */ + +/** + * Node-style callback as used by {@link RPCImpl}. + * @typedef RPCImplCallback + * @type {function} + * @param {Error|null} error Error, if any, otherwise `null` + * @param {Uint8Array|null} [response] Response data or `null` to signal end of stream, if there hasn't been an error + * @returns {undefined} + */ + +rpc.Service = require(32); + +},{"32":32}],32:[function(require,module,exports){ +"use strict"; +module.exports = Service; + +var util = require(39); + +// Extends EventEmitter +(Service.prototype = Object.create(util.EventEmitter.prototype)).constructor = Service; + +/** + * A service method callback as used by {@link rpc.ServiceMethod|ServiceMethod}. + * + * Differs from {@link RPCImplCallback} in that it is an actual callback of a service method which may not return `response = null`. + * @typedef rpc.ServiceMethodCallback + * @template TRes extends Message + * @type {function} + * @param {Error|null} error Error, if any + * @param {TRes} [response] Response message + * @returns {undefined} + */ + +/** + * A service method part of a {@link rpc.Service} as created by {@link Service.create}. + * @typedef rpc.ServiceMethod + * @template TReq extends Message + * @template TRes extends Message + * @type {function} + * @param {TReq|Properties} request Request message or plain object + * @param {rpc.ServiceMethodCallback} [callback] Node-style callback called with the error, if any, and the response message + * @returns {Promise>} Promise if `callback` has been omitted, otherwise `undefined` + */ + +/** + * Constructs a new RPC service instance. + * @classdesc An RPC service as returned by {@link Service#create}. + * @exports rpc.Service + * @extends util.EventEmitter + * @constructor + * @param {RPCImpl} rpcImpl RPC implementation + * @param {boolean} [requestDelimited=false] Whether requests are length-delimited + * @param {boolean} [responseDelimited=false] Whether responses are length-delimited + */ +function Service(rpcImpl, requestDelimited, responseDelimited) { + + if (typeof rpcImpl !== "function") + throw TypeError("rpcImpl must be a function"); + + util.EventEmitter.call(this); + + /** + * RPC implementation. Becomes `null` once the service is ended. + * @type {RPCImpl|null} + */ + this.rpcImpl = rpcImpl; + + /** + * Whether requests are length-delimited. + * @type {boolean} + */ + this.requestDelimited = Boolean(requestDelimited); + + /** + * Whether responses are length-delimited. + * @type {boolean} + */ + this.responseDelimited = Boolean(responseDelimited); +} + +/** + * Calls a service method through {@link rpc.Service#rpcImpl|rpcImpl}. + * @param {Method|rpc.ServiceMethod} method Reflected or static method + * @param {Constructor} requestCtor Request constructor + * @param {Constructor} responseCtor Response constructor + * @param {TReq|Properties} request Request message or plain object + * @param {rpc.ServiceMethodCallback} callback Service callback + * @returns {undefined} + * @template TReq extends Message + * @template TRes extends Message + */ +Service.prototype.rpcCall = function rpcCall(method, requestCtor, responseCtor, request, callback) { + + if (!request) + throw TypeError("request must be specified"); + + var self = this; + if (!callback) + return util.asPromise(rpcCall, self, method, requestCtor, responseCtor, request); + + if (!self.rpcImpl) { + setTimeout(function() { callback(Error("already ended")); }, 0); + return undefined; + } + + try { + return self.rpcImpl( + method, + requestCtor[self.requestDelimited ? "encodeDelimited" : "encode"](request).finish(), + function rpcCallback(err, response) { + + if (err) { + self.emit("error", err, method); + return callback(err); + } + + if (response === null) { + self.end(/* endedByRPC */ true); + return undefined; + } + + if (!(response instanceof responseCtor)) { + try { + response = responseCtor[self.responseDelimited ? "decodeDelimited" : "decode"](response); + } catch (err) { + self.emit("error", err, method); + return callback(err); + } + } + + self.emit("data", response, method); + return callback(null, response); + } + ); + } catch (err) { + self.emit("error", err, method); + setTimeout(function() { callback(err); }, 0); + return undefined; + } +}; + +/** + * Ends this service and emits the `end` event. + * @param {boolean} [endedByRPC=false] Whether the service has been ended by the RPC implementation. + * @returns {rpc.Service} `this` + */ +Service.prototype.end = function end(endedByRPC) { + if (this.rpcImpl) { + if (!endedByRPC) // signal end to rpcImpl + this.rpcImpl(null, null, null); + this.rpcImpl = null; + this.emit("end").off(); + } + return this; +}; + +},{"39":39}],33:[function(require,module,exports){ +"use strict"; +module.exports = Service; + +// extends Namespace +var Namespace = require(23); +((Service.prototype = Object.create(Namespace.prototype)).constructor = Service).className = "Service"; + +var Method = require(22), + util = require(37), + rpc = require(31); + +/** + * Constructs a new service instance. + * @classdesc Reflected service. + * @extends NamespaceBase + * @constructor + * @param {string} name Service name + * @param {Object.} [options] Service options + * @throws {TypeError} If arguments are invalid + */ +function Service(name, options) { + Namespace.call(this, name, options); + + /** + * Service methods. + * @type {Object.} + */ + this.methods = {}; // toJSON, marker + + /** + * Cached methods as an array. + * @type {Method[]|null} + * @private + */ + this._methodsArray = null; +} + +/** + * Service descriptor. + * @interface IService + * @extends INamespace + * @property {Object.} methods Method descriptors + */ + +/** + * Constructs a service from a service descriptor. + * @param {string} name Service name + * @param {IService} json Service descriptor + * @returns {Service} Created service + * @throws {TypeError} If arguments are invalid + */ +Service.fromJSON = function fromJSON(name, json) { + var service = new Service(name, json.options); + /* istanbul ignore else */ + if (json.methods) + for (var names = Object.keys(json.methods), i = 0; i < names.length; ++i) + service.add(Method.fromJSON(names[i], json.methods[names[i]])); + if (json.nested) + service.addJSON(json.nested); + service.comment = json.comment; + return service; +}; + +/** + * Converts this service to a service descriptor. + * @param {IToJSONOptions} [toJSONOptions] JSON conversion options + * @returns {IService} Service descriptor + */ +Service.prototype.toJSON = function toJSON(toJSONOptions) { + var inherited = Namespace.prototype.toJSON.call(this, toJSONOptions); + var keepComments = toJSONOptions ? Boolean(toJSONOptions.keepComments) : false; + return util.toObject([ + "options" , inherited && inherited.options || undefined, + "methods" , Namespace.arrayToJSON(this.methodsArray, toJSONOptions) || /* istanbul ignore next */ {}, + "nested" , inherited && inherited.nested || undefined, + "comment" , keepComments ? this.comment : undefined + ]); +}; + +/** + * Methods of this service as an array for iteration. + * @name Service#methodsArray + * @type {Method[]} + * @readonly + */ +Object.defineProperty(Service.prototype, "methodsArray", { + get: function() { + return this._methodsArray || (this._methodsArray = util.toArray(this.methods)); + } +}); + +function clearCache(service) { + service._methodsArray = null; + return service; +} + +/** + * @override + */ +Service.prototype.get = function get(name) { + return this.methods[name] + || Namespace.prototype.get.call(this, name); +}; + +/** + * @override + */ +Service.prototype.resolveAll = function resolveAll() { + var methods = this.methodsArray; + for (var i = 0; i < methods.length; ++i) + methods[i].resolve(); + return Namespace.prototype.resolve.call(this); +}; + +/** + * @override + */ +Service.prototype.add = function add(object) { + + /* istanbul ignore if */ + if (this.get(object.name)) + throw Error("duplicate name '" + object.name + "' in " + this); + + if (object instanceof Method) { + this.methods[object.name] = object; + object.parent = this; + return clearCache(this); + } + return Namespace.prototype.add.call(this, object); +}; + +/** + * @override + */ +Service.prototype.remove = function remove(object) { + if (object instanceof Method) { + + /* istanbul ignore if */ + if (this.methods[object.name] !== object) + throw Error(object + " is not a member of " + this); + + delete this.methods[object.name]; + object.parent = null; + return clearCache(this); + } + return Namespace.prototype.remove.call(this, object); +}; + +/** + * Creates a runtime service using the specified rpc implementation. + * @param {RPCImpl} rpcImpl RPC implementation + * @param {boolean} [requestDelimited=false] Whether requests are length-delimited + * @param {boolean} [responseDelimited=false] Whether responses are length-delimited + * @returns {rpc.Service} RPC service. Useful where requests and/or responses are streamed. + */ +Service.prototype.create = function create(rpcImpl, requestDelimited, responseDelimited) { + var rpcService = new rpc.Service(rpcImpl, requestDelimited, responseDelimited); + for (var i = 0, method; i < /* initializes */ this.methodsArray.length; ++i) { + var methodName = util.lcFirst((method = this._methodsArray[i]).resolve().name).replace(/[^$\w_]/g, ""); + rpcService[methodName] = util.codegen(["r","c"], util.isReserved(methodName) ? methodName + "_" : methodName)("return this.rpcCall(m,q,s,r,c)")({ + m: method, + q: method.resolvedRequestType.ctor, + s: method.resolvedResponseType.ctor + }); + } + return rpcService; +}; + +},{"22":22,"23":23,"31":31,"37":37}],34:[function(require,module,exports){ +"use strict"; +module.exports = tokenize; + +var delimRe = /[\s{}=;:[\],'"()<>]/g, + stringDoubleRe = /(?:"([^"\\]*(?:\\.[^"\\]*)*)")/g, + stringSingleRe = /(?:'([^'\\]*(?:\\.[^'\\]*)*)')/g; + +var setCommentRe = /^ *[*/]+ */, + setCommentAltRe = /^\s*\*?\/*/, + setCommentSplitRe = /\n/g, + whitespaceRe = /\s/, + unescapeRe = /\\(.?)/g; + +var unescapeMap = { + "0": "\0", + "r": "\r", + "n": "\n", + "t": "\t" +}; + +/** + * Unescapes a string. + * @param {string} str String to unescape + * @returns {string} Unescaped string + * @property {Object.} map Special characters map + * @memberof tokenize + */ +function unescape(str) { + return str.replace(unescapeRe, function($0, $1) { + switch ($1) { + case "\\": + case "": + return $1; + default: + return unescapeMap[$1] || ""; + } + }); +} + +tokenize.unescape = unescape; + +/** + * Gets the next token and advances. + * @typedef TokenizerHandleNext + * @type {function} + * @returns {string|null} Next token or `null` on eof + */ + +/** + * Peeks for the next token. + * @typedef TokenizerHandlePeek + * @type {function} + * @returns {string|null} Next token or `null` on eof + */ + +/** + * Pushes a token back to the stack. + * @typedef TokenizerHandlePush + * @type {function} + * @param {string} token Token + * @returns {undefined} + */ + +/** + * Skips the next token. + * @typedef TokenizerHandleSkip + * @type {function} + * @param {string} expected Expected token + * @param {boolean} [optional=false] If optional + * @returns {boolean} Whether the token matched + * @throws {Error} If the token didn't match and is not optional + */ + +/** + * Gets the comment on the previous line or, alternatively, the line comment on the specified line. + * @typedef TokenizerHandleCmnt + * @type {function} + * @param {number} [line] Line number + * @returns {string|null} Comment text or `null` if none + */ + +/** + * Handle object returned from {@link tokenize}. + * @interface ITokenizerHandle + * @property {TokenizerHandleNext} next Gets the next token and advances (`null` on eof) + * @property {TokenizerHandlePeek} peek Peeks for the next token (`null` on eof) + * @property {TokenizerHandlePush} push Pushes a token back to the stack + * @property {TokenizerHandleSkip} skip Skips a token, returns its presence and advances or, if non-optional and not present, throws + * @property {TokenizerHandleCmnt} cmnt Gets the comment on the previous line or the line comment on the specified line, if any + * @property {number} line Current line number + */ + +/** + * Tokenizes the given .proto source and returns an object with useful utility functions. + * @param {string} source Source contents + * @param {boolean} alternateCommentMode Whether we should activate alternate comment parsing mode. + * @returns {ITokenizerHandle} Tokenizer handle + */ +function tokenize(source, alternateCommentMode) { + /* eslint-disable callback-return */ + source = source.toString(); + + var offset = 0, + length = source.length, + line = 1, + lastCommentLine = 0, + comments = {}; + + var stack = []; + + var stringDelim = null; + + /* istanbul ignore next */ + /** + * Creates an error for illegal syntax. + * @param {string} subject Subject + * @returns {Error} Error created + * @inner + */ + function illegal(subject) { + return Error("illegal " + subject + " (line " + line + ")"); + } + + /** + * Reads a string till its end. + * @returns {string} String read + * @inner + */ + function readString() { + var re = stringDelim === "'" ? stringSingleRe : stringDoubleRe; + re.lastIndex = offset - 1; + var match = re.exec(source); + if (!match) + throw illegal("string"); + offset = re.lastIndex; + push(stringDelim); + stringDelim = null; + return unescape(match[1]); + } + + /** + * Gets the character at `pos` within the source. + * @param {number} pos Position + * @returns {string} Character + * @inner + */ + function charAt(pos) { + return source.charAt(pos); + } + + /** + * Sets the current comment text. + * @param {number} start Start offset + * @param {number} end End offset + * @param {boolean} isLeading set if a leading comment + * @returns {undefined} + * @inner + */ + function setComment(start, end, isLeading) { + var comment = { + type: source.charAt(start++), + lineEmpty: false, + leading: isLeading, + }; + var lookback; + if (alternateCommentMode) { + lookback = 2; // alternate comment parsing: "//" or "/*" + } else { + lookback = 3; // "///" or "/**" + } + var commentOffset = start - lookback, + c; + do { + if (--commentOffset < 0 || + (c = source.charAt(commentOffset)) === "\n") { + comment.lineEmpty = true; + break; + } + } while (c === " " || c === "\t"); + var lines = source + .substring(start, end) + .split(setCommentSplitRe); + for (var i = 0; i < lines.length; ++i) + lines[i] = lines[i] + .replace(alternateCommentMode ? setCommentAltRe : setCommentRe, "") + .trim(); + comment.text = lines + .join("\n") + .trim(); + + comments[line] = comment; + lastCommentLine = line; + } + + function isDoubleSlashCommentLine(startOffset) { + var endOffset = findEndOfLine(startOffset); + + // see if remaining line matches comment pattern + var lineText = source.substring(startOffset, endOffset); + var isComment = /^\s*\/\//.test(lineText); + return isComment; + } + + function findEndOfLine(cursor) { + // find end of cursor's line + var endOffset = cursor; + while (endOffset < length && charAt(endOffset) !== "\n") { + endOffset++; + } + return endOffset; + } + + /** + * Obtains the next token. + * @returns {string|null} Next token or `null` on eof + * @inner + */ + function next() { + if (stack.length > 0) + return stack.shift(); + if (stringDelim) + return readString(); + var repeat, + prev, + curr, + start, + isDoc, + isLeadingComment = offset === 0; + do { + if (offset === length) + return null; + repeat = false; + while (whitespaceRe.test(curr = charAt(offset))) { + if (curr === "\n") { + isLeadingComment = true; + ++line; + } + if (++offset === length) + return null; + } + + if (charAt(offset) === "/") { + if (++offset === length) { + throw illegal("comment"); + } + if (charAt(offset) === "/") { // Line + if (!alternateCommentMode) { + // check for triple-slash comment + isDoc = charAt(start = offset + 1) === "/"; + + while (charAt(++offset) !== "\n") { + if (offset === length) { + return null; + } + } + ++offset; + if (isDoc) { + setComment(start, offset - 1, isLeadingComment); + // Trailing comment cannot not be multi-line, + // so leading comment state should be reset to handle potential next comments + isLeadingComment = true; + } + ++line; + repeat = true; + } else { + // check for double-slash comments, consolidating consecutive lines + start = offset; + isDoc = false; + if (isDoubleSlashCommentLine(offset - 1)) { + isDoc = true; + do { + offset = findEndOfLine(offset); + if (offset === length) { + break; + } + offset++; + if (!isLeadingComment) { + // Trailing comment cannot not be multi-line + break; + } + } while (isDoubleSlashCommentLine(offset)); + } else { + offset = Math.min(length, findEndOfLine(offset) + 1); + } + if (isDoc) { + setComment(start, offset, isLeadingComment); + isLeadingComment = true; + } + line++; + repeat = true; + } + } else if ((curr = charAt(offset)) === "*") { /* Block */ + // check for /** (regular comment mode) or /* (alternate comment mode) + start = offset + 1; + isDoc = alternateCommentMode || charAt(start) === "*"; + do { + if (curr === "\n") { + ++line; + } + if (++offset === length) { + throw illegal("comment"); + } + prev = curr; + curr = charAt(offset); + } while (prev !== "*" || curr !== "/"); + ++offset; + if (isDoc) { + setComment(start, offset - 2, isLeadingComment); + isLeadingComment = true; + } + repeat = true; + } else { + return "/"; + } + } + } while (repeat); + + // offset !== length if we got here + + var end = offset; + delimRe.lastIndex = 0; + var delim = delimRe.test(charAt(end++)); + if (!delim) + while (end < length && !delimRe.test(charAt(end))) + ++end; + var token = source.substring(offset, offset = end); + if (token === "\"" || token === "'") + stringDelim = token; + return token; + } + + /** + * Pushes a token back to the stack. + * @param {string} token Token + * @returns {undefined} + * @inner + */ + function push(token) { + stack.push(token); + } + + /** + * Peeks for the next token. + * @returns {string|null} Token or `null` on eof + * @inner + */ + function peek() { + if (!stack.length) { + var token = next(); + if (token === null) + return null; + push(token); + } + return stack[0]; + } + + /** + * Skips a token. + * @param {string} expected Expected token + * @param {boolean} [optional=false] Whether the token is optional + * @returns {boolean} `true` when skipped, `false` if not + * @throws {Error} When a required token is not present + * @inner + */ + function skip(expected, optional) { + var actual = peek(), + equals = actual === expected; + if (equals) { + next(); + return true; + } + if (!optional) + throw illegal("token '" + actual + "', '" + expected + "' expected"); + return false; + } + + /** + * Gets a comment. + * @param {number} [trailingLine] Line number if looking for a trailing comment + * @returns {string|null} Comment text + * @inner + */ + function cmnt(trailingLine) { + var ret = null; + var comment; + if (trailingLine === undefined) { + comment = comments[line - 1]; + delete comments[line - 1]; + if (comment && (alternateCommentMode || comment.type === "*" || comment.lineEmpty)) { + ret = comment.leading ? comment.text : null; + } + } else { + /* istanbul ignore else */ + if (lastCommentLine < trailingLine) { + peek(); + } + comment = comments[trailingLine]; + delete comments[trailingLine]; + if (comment && !comment.lineEmpty && (alternateCommentMode || comment.type === "/")) { + ret = comment.leading ? null : comment.text; + } + } + return ret; + } + + return Object.defineProperty({ + next: next, + peek: peek, + push: push, + skip: skip, + cmnt: cmnt + }, "line", { + get: function() { return line; } + }); + /* eslint-enable callback-return */ +} + +},{}],35:[function(require,module,exports){ +"use strict"; +module.exports = Type; + +// extends Namespace +var Namespace = require(23); +((Type.prototype = Object.create(Namespace.prototype)).constructor = Type).className = "Type"; + +var Enum = require(15), + OneOf = require(25), + Field = require(16), + MapField = require(20), + Service = require(33), + Message = require(21), + Reader = require(27), + Writer = require(42), + util = require(37), + encoder = require(14), + decoder = require(13), + verifier = require(40), + converter = require(12), + wrappers = require(41); + +/** + * Constructs a new reflected message type instance. + * @classdesc Reflected message type. + * @extends NamespaceBase + * @constructor + * @param {string} name Message name + * @param {Object.} [options] Declared options + */ +function Type(name, options) { + Namespace.call(this, name, options); + + /** + * Message fields. + * @type {Object.} + */ + this.fields = {}; // toJSON, marker + + /** + * Oneofs declared within this namespace, if any. + * @type {Object.} + */ + this.oneofs = undefined; // toJSON + + /** + * Extension ranges, if any. + * @type {number[][]} + */ + this.extensions = undefined; // toJSON + + /** + * Reserved ranges, if any. + * @type {Array.} + */ + this.reserved = undefined; // toJSON + + /*? + * Whether this type is a legacy group. + * @type {boolean|undefined} + */ + this.group = undefined; // toJSON + + /** + * Cached fields by id. + * @type {Object.|null} + * @private + */ + this._fieldsById = null; + + /** + * Cached fields as an array. + * @type {Field[]|null} + * @private + */ + this._fieldsArray = null; + + /** + * Cached oneofs as an array. + * @type {OneOf[]|null} + * @private + */ + this._oneofsArray = null; + + /** + * Cached constructor. + * @type {Constructor<{}>} + * @private + */ + this._ctor = null; +} + +Object.defineProperties(Type.prototype, { + + /** + * Message fields by id. + * @name Type#fieldsById + * @type {Object.} + * @readonly + */ + fieldsById: { + get: function() { + + /* istanbul ignore if */ + if (this._fieldsById) + return this._fieldsById; + + this._fieldsById = {}; + for (var names = Object.keys(this.fields), i = 0; i < names.length; ++i) { + var field = this.fields[names[i]], + id = field.id; + + /* istanbul ignore if */ + if (this._fieldsById[id]) + throw Error("duplicate id " + id + " in " + this); + + this._fieldsById[id] = field; + } + return this._fieldsById; + } + }, + + /** + * Fields of this message as an array for iteration. + * @name Type#fieldsArray + * @type {Field[]} + * @readonly + */ + fieldsArray: { + get: function() { + return this._fieldsArray || (this._fieldsArray = util.toArray(this.fields)); + } + }, + + /** + * Oneofs of this message as an array for iteration. + * @name Type#oneofsArray + * @type {OneOf[]} + * @readonly + */ + oneofsArray: { + get: function() { + return this._oneofsArray || (this._oneofsArray = util.toArray(this.oneofs)); + } + }, + + /** + * The registered constructor, if any registered, otherwise a generic constructor. + * Assigning a function replaces the internal constructor. If the function does not extend {@link Message} yet, its prototype will be setup accordingly and static methods will be populated. If it already extends {@link Message}, it will just replace the internal constructor. + * @name Type#ctor + * @type {Constructor<{}>} + */ + ctor: { + get: function() { + return this._ctor || (this.ctor = Type.generateConstructor(this)()); + }, + set: function(ctor) { + + // Ensure proper prototype + var prototype = ctor.prototype; + if (!(prototype instanceof Message)) { + (ctor.prototype = new Message()).constructor = ctor; + util.merge(ctor.prototype, prototype); + } + + // Classes and messages reference their reflected type + ctor.$type = ctor.prototype.$type = this; + + // Mix in static methods + util.merge(ctor, Message, true); + + this._ctor = ctor; + + // Messages have non-enumerable default values on their prototype + var i = 0; + for (; i < /* initializes */ this.fieldsArray.length; ++i) + this._fieldsArray[i].resolve(); // ensures a proper value + + // Messages have non-enumerable getters and setters for each virtual oneof field + var ctorProperties = {}; + for (i = 0; i < /* initializes */ this.oneofsArray.length; ++i) + ctorProperties[this._oneofsArray[i].resolve().name] = { + get: util.oneOfGetter(this._oneofsArray[i].oneof), + set: util.oneOfSetter(this._oneofsArray[i].oneof) + }; + if (i) + Object.defineProperties(ctor.prototype, ctorProperties); + } + } +}); + +/** + * Generates a constructor function for the specified type. + * @param {Type} mtype Message type + * @returns {Codegen} Codegen instance + */ +Type.generateConstructor = function generateConstructor(mtype) { + /* eslint-disable no-unexpected-multiline */ + var gen = util.codegen(["p"], mtype.name); + // explicitly initialize mutable object/array fields so that these aren't just inherited from the prototype + for (var i = 0, field; i < mtype.fieldsArray.length; ++i) + if ((field = mtype._fieldsArray[i]).map) gen + ("this%s={}", util.safeProp(field.name)); + else if (field.repeated) gen + ("this%s=[]", util.safeProp(field.name)); + return gen + ("if(p)for(var ks=Object.keys(p),i=0;i} [oneofs] Oneof descriptors + * @property {Object.} fields Field descriptors + * @property {number[][]} [extensions] Extension ranges + * @property {number[][]} [reserved] Reserved ranges + * @property {boolean} [group=false] Whether a legacy group or not + */ + +/** + * Creates a message type from a message type descriptor. + * @param {string} name Message name + * @param {IType} json Message type descriptor + * @returns {Type} Created message type + */ +Type.fromJSON = function fromJSON(name, json) { + var type = new Type(name, json.options); + type.extensions = json.extensions; + type.reserved = json.reserved; + var names = Object.keys(json.fields), + i = 0; + for (; i < names.length; ++i) + type.add( + ( typeof json.fields[names[i]].keyType !== "undefined" + ? MapField.fromJSON + : Field.fromJSON )(names[i], json.fields[names[i]]) + ); + if (json.oneofs) + for (names = Object.keys(json.oneofs), i = 0; i < names.length; ++i) + type.add(OneOf.fromJSON(names[i], json.oneofs[names[i]])); + if (json.nested) + for (names = Object.keys(json.nested), i = 0; i < names.length; ++i) { + var nested = json.nested[names[i]]; + type.add( // most to least likely + ( nested.id !== undefined + ? Field.fromJSON + : nested.fields !== undefined + ? Type.fromJSON + : nested.values !== undefined + ? Enum.fromJSON + : nested.methods !== undefined + ? Service.fromJSON + : Namespace.fromJSON )(names[i], nested) + ); + } + if (json.extensions && json.extensions.length) + type.extensions = json.extensions; + if (json.reserved && json.reserved.length) + type.reserved = json.reserved; + if (json.group) + type.group = true; + if (json.comment) + type.comment = json.comment; + return type; +}; + +/** + * Converts this message type to a message type descriptor. + * @param {IToJSONOptions} [toJSONOptions] JSON conversion options + * @returns {IType} Message type descriptor + */ +Type.prototype.toJSON = function toJSON(toJSONOptions) { + var inherited = Namespace.prototype.toJSON.call(this, toJSONOptions); + var keepComments = toJSONOptions ? Boolean(toJSONOptions.keepComments) : false; + return util.toObject([ + "options" , inherited && inherited.options || undefined, + "oneofs" , Namespace.arrayToJSON(this.oneofsArray, toJSONOptions), + "fields" , Namespace.arrayToJSON(this.fieldsArray.filter(function(obj) { return !obj.declaringField; }), toJSONOptions) || {}, + "extensions" , this.extensions && this.extensions.length ? this.extensions : undefined, + "reserved" , this.reserved && this.reserved.length ? this.reserved : undefined, + "group" , this.group || undefined, + "nested" , inherited && inherited.nested || undefined, + "comment" , keepComments ? this.comment : undefined + ]); +}; + +/** + * @override + */ +Type.prototype.resolveAll = function resolveAll() { + var fields = this.fieldsArray, i = 0; + while (i < fields.length) + fields[i++].resolve(); + var oneofs = this.oneofsArray; i = 0; + while (i < oneofs.length) + oneofs[i++].resolve(); + return Namespace.prototype.resolveAll.call(this); +}; + +/** + * @override + */ +Type.prototype.get = function get(name) { + return this.fields[name] + || this.oneofs && this.oneofs[name] + || this.nested && this.nested[name] + || null; +}; + +/** + * Adds a nested object to this type. + * @param {ReflectionObject} object Nested object to add + * @returns {Type} `this` + * @throws {TypeError} If arguments are invalid + * @throws {Error} If there is already a nested object with this name or, if a field, when there is already a field with this id + */ +Type.prototype.add = function add(object) { + + if (this.get(object.name)) + throw Error("duplicate name '" + object.name + "' in " + this); + + if (object instanceof Field && object.extend === undefined) { + // NOTE: Extension fields aren't actual fields on the declaring type, but nested objects. + // The root object takes care of adding distinct sister-fields to the respective extended + // type instead. + + // avoids calling the getter if not absolutely necessary because it's called quite frequently + if (this._fieldsById ? /* istanbul ignore next */ this._fieldsById[object.id] : this.fieldsById[object.id]) + throw Error("duplicate id " + object.id + " in " + this); + if (this.isReservedId(object.id)) + throw Error("id " + object.id + " is reserved in " + this); + if (this.isReservedName(object.name)) + throw Error("name '" + object.name + "' is reserved in " + this); + + if (object.parent) + object.parent.remove(object); + this.fields[object.name] = object; + object.message = this; + object.onAdd(this); + return clearCache(this); + } + if (object instanceof OneOf) { + if (!this.oneofs) + this.oneofs = {}; + this.oneofs[object.name] = object; + object.onAdd(this); + return clearCache(this); + } + return Namespace.prototype.add.call(this, object); +}; + +/** + * Removes a nested object from this type. + * @param {ReflectionObject} object Nested object to remove + * @returns {Type} `this` + * @throws {TypeError} If arguments are invalid + * @throws {Error} If `object` is not a member of this type + */ +Type.prototype.remove = function remove(object) { + if (object instanceof Field && object.extend === undefined) { + // See Type#add for the reason why extension fields are excluded here. + + /* istanbul ignore if */ + if (!this.fields || this.fields[object.name] !== object) + throw Error(object + " is not a member of " + this); + + delete this.fields[object.name]; + object.parent = null; + object.onRemove(this); + return clearCache(this); + } + if (object instanceof OneOf) { + + /* istanbul ignore if */ + if (!this.oneofs || this.oneofs[object.name] !== object) + throw Error(object + " is not a member of " + this); + + delete this.oneofs[object.name]; + object.parent = null; + object.onRemove(this); + return clearCache(this); + } + return Namespace.prototype.remove.call(this, object); +}; + +/** + * Tests if the specified id is reserved. + * @param {number} id Id to test + * @returns {boolean} `true` if reserved, otherwise `false` + */ +Type.prototype.isReservedId = function isReservedId(id) { + return Namespace.isReservedId(this.reserved, id); +}; + +/** + * Tests if the specified name is reserved. + * @param {string} name Name to test + * @returns {boolean} `true` if reserved, otherwise `false` + */ +Type.prototype.isReservedName = function isReservedName(name) { + return Namespace.isReservedName(this.reserved, name); +}; + +/** + * Creates a new message of this type using the specified properties. + * @param {Object.} [properties] Properties to set + * @returns {Message<{}>} Message instance + */ +Type.prototype.create = function create(properties) { + return new this.ctor(properties); +}; + +/** + * Sets up {@link Type#encode|encode}, {@link Type#decode|decode} and {@link Type#verify|verify}. + * @returns {Type} `this` + */ +Type.prototype.setup = function setup() { + // Sets up everything at once so that the prototype chain does not have to be re-evaluated + // multiple times (V8, soft-deopt prototype-check). + + var fullName = this.fullName, + types = []; + for (var i = 0; i < /* initializes */ this.fieldsArray.length; ++i) + types.push(this._fieldsArray[i].resolve().resolvedType); + + // Replace setup methods with type-specific generated functions + this.encode = encoder(this)({ + Writer : Writer, + types : types, + util : util + }); + this.decode = decoder(this)({ + Reader : Reader, + types : types, + util : util + }); + this.verify = verifier(this)({ + types : types, + util : util + }); + this.fromObject = converter.fromObject(this)({ + types : types, + util : util + }); + this.toObject = converter.toObject(this)({ + types : types, + util : util + }); + + // Inject custom wrappers for common types + var wrapper = wrappers[fullName]; + if (wrapper) { + var originalThis = Object.create(this); + // if (wrapper.fromObject) { + originalThis.fromObject = this.fromObject; + this.fromObject = wrapper.fromObject.bind(originalThis); + // } + // if (wrapper.toObject) { + originalThis.toObject = this.toObject; + this.toObject = wrapper.toObject.bind(originalThis); + // } + } + + return this; +}; + +/** + * Encodes a message of this type. Does not implicitly {@link Type#verify|verify} messages. + * @param {Message<{}>|Object.} message Message instance or plain object + * @param {Writer} [writer] Writer to encode to + * @returns {Writer} writer + */ +Type.prototype.encode = function encode_setup(message, writer) { + return this.setup().encode(message, writer); // overrides this method +}; + +/** + * Encodes a message of this type preceeded by its byte length as a varint. Does not implicitly {@link Type#verify|verify} messages. + * @param {Message<{}>|Object.} message Message instance or plain object + * @param {Writer} [writer] Writer to encode to + * @returns {Writer} writer + */ +Type.prototype.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer && writer.len ? writer.fork() : writer).ldelim(); +}; + +/** + * Decodes a message of this type. + * @param {Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Length of the message, if known beforehand + * @returns {Message<{}>} Decoded message + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {util.ProtocolError<{}>} If required fields are missing + */ +Type.prototype.decode = function decode_setup(reader, length) { + return this.setup().decode(reader, length); // overrides this method +}; + +/** + * Decodes a message of this type preceeded by its byte length as a varint. + * @param {Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {Message<{}>} Decoded message + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {util.ProtocolError} If required fields are missing + */ +Type.prototype.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof Reader)) + reader = Reader.create(reader); + return this.decode(reader, reader.uint32()); +}; + +/** + * Verifies that field values are valid and that required fields are present. + * @param {Object.} message Plain object to verify + * @returns {null|string} `null` if valid, otherwise the reason why it is not + */ +Type.prototype.verify = function verify_setup(message) { + return this.setup().verify(message); // overrides this method +}; + +/** + * Creates a new message of this type from a plain object. Also converts values to their respective internal types. + * @param {Object.} object Plain object to convert + * @returns {Message<{}>} Message instance + */ +Type.prototype.fromObject = function fromObject(object) { + return this.setup().fromObject(object); +}; + +/** + * Conversion options as used by {@link Type#toObject} and {@link Message.toObject}. + * @interface IConversionOptions + * @property {Function} [longs] Long conversion type. + * Valid values are `String` and `Number` (the global types). + * Defaults to copy the present value, which is a possibly unsafe number without and a {@link Long} with a long library. + * @property {Function} [enums] Enum value conversion type. + * Only valid value is `String` (the global type). + * Defaults to copy the present value, which is the numeric id. + * @property {Function} [bytes] Bytes value conversion type. + * Valid values are `Array` and (a base64 encoded) `String` (the global types). + * Defaults to copy the present value, which usually is a Buffer under node and an Uint8Array in the browser. + * @property {boolean} [defaults=false] Also sets default values on the resulting object + * @property {boolean} [arrays=false] Sets empty arrays for missing repeated fields even if `defaults=false` + * @property {boolean} [objects=false] Sets empty objects for missing map fields even if `defaults=false` + * @property {boolean} [oneofs=false] Includes virtual oneof properties set to the present field's name, if any + * @property {boolean} [json=false] Performs additional JSON compatibility conversions, i.e. NaN and Infinity to strings + */ + +/** + * Creates a plain object from a message of this type. Also converts values to other types if specified. + * @param {Message<{}>} message Message instance + * @param {IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ +Type.prototype.toObject = function toObject(message, options) { + return this.setup().toObject(message, options); +}; + +/** + * Decorator function as returned by {@link Type.d} (TypeScript). + * @typedef TypeDecorator + * @type {function} + * @param {Constructor} target Target constructor + * @returns {undefined} + * @template T extends Message + */ + +/** + * Type decorator (TypeScript). + * @param {string} [typeName] Type name, defaults to the constructor's name + * @returns {TypeDecorator} Decorator function + * @template T extends Message + */ +Type.d = function decorateType(typeName) { + return function typeDecorator(target) { + util.decorateType(target, typeName); + }; +}; + +},{"12":12,"13":13,"14":14,"15":15,"16":16,"20":20,"21":21,"23":23,"25":25,"27":27,"33":33,"37":37,"40":40,"41":41,"42":42}],36:[function(require,module,exports){ +"use strict"; + +/** + * Common type constants. + * @namespace + */ +var types = exports; + +var util = require(37); + +var s = [ + "double", // 0 + "float", // 1 + "int32", // 2 + "uint32", // 3 + "sint32", // 4 + "fixed32", // 5 + "sfixed32", // 6 + "int64", // 7 + "uint64", // 8 + "sint64", // 9 + "fixed64", // 10 + "sfixed64", // 11 + "bool", // 12 + "string", // 13 + "bytes" // 14 +]; + +function bake(values, offset) { + var i = 0, o = {}; + offset |= 0; + while (i < values.length) o[s[i + offset]] = values[i++]; + return o; +} + +/** + * Basic type wire types. + * @type {Object.} + * @const + * @property {number} double=1 Fixed64 wire type + * @property {number} float=5 Fixed32 wire type + * @property {number} int32=0 Varint wire type + * @property {number} uint32=0 Varint wire type + * @property {number} sint32=0 Varint wire type + * @property {number} fixed32=5 Fixed32 wire type + * @property {number} sfixed32=5 Fixed32 wire type + * @property {number} int64=0 Varint wire type + * @property {number} uint64=0 Varint wire type + * @property {number} sint64=0 Varint wire type + * @property {number} fixed64=1 Fixed64 wire type + * @property {number} sfixed64=1 Fixed64 wire type + * @property {number} bool=0 Varint wire type + * @property {number} string=2 Ldelim wire type + * @property {number} bytes=2 Ldelim wire type + */ +types.basic = bake([ + /* double */ 1, + /* float */ 5, + /* int32 */ 0, + /* uint32 */ 0, + /* sint32 */ 0, + /* fixed32 */ 5, + /* sfixed32 */ 5, + /* int64 */ 0, + /* uint64 */ 0, + /* sint64 */ 0, + /* fixed64 */ 1, + /* sfixed64 */ 1, + /* bool */ 0, + /* string */ 2, + /* bytes */ 2 +]); + +/** + * Basic type defaults. + * @type {Object.} + * @const + * @property {number} double=0 Double default + * @property {number} float=0 Float default + * @property {number} int32=0 Int32 default + * @property {number} uint32=0 Uint32 default + * @property {number} sint32=0 Sint32 default + * @property {number} fixed32=0 Fixed32 default + * @property {number} sfixed32=0 Sfixed32 default + * @property {number} int64=0 Int64 default + * @property {number} uint64=0 Uint64 default + * @property {number} sint64=0 Sint32 default + * @property {number} fixed64=0 Fixed64 default + * @property {number} sfixed64=0 Sfixed64 default + * @property {boolean} bool=false Bool default + * @property {string} string="" String default + * @property {Array.} bytes=Array(0) Bytes default + * @property {null} message=null Message default + */ +types.defaults = bake([ + /* double */ 0, + /* float */ 0, + /* int32 */ 0, + /* uint32 */ 0, + /* sint32 */ 0, + /* fixed32 */ 0, + /* sfixed32 */ 0, + /* int64 */ 0, + /* uint64 */ 0, + /* sint64 */ 0, + /* fixed64 */ 0, + /* sfixed64 */ 0, + /* bool */ false, + /* string */ "", + /* bytes */ util.emptyArray, + /* message */ null +]); + +/** + * Basic long type wire types. + * @type {Object.} + * @const + * @property {number} int64=0 Varint wire type + * @property {number} uint64=0 Varint wire type + * @property {number} sint64=0 Varint wire type + * @property {number} fixed64=1 Fixed64 wire type + * @property {number} sfixed64=1 Fixed64 wire type + */ +types.long = bake([ + /* int64 */ 0, + /* uint64 */ 0, + /* sint64 */ 0, + /* fixed64 */ 1, + /* sfixed64 */ 1 +], 7); + +/** + * Allowed types for map keys with their associated wire type. + * @type {Object.} + * @const + * @property {number} int32=0 Varint wire type + * @property {number} uint32=0 Varint wire type + * @property {number} sint32=0 Varint wire type + * @property {number} fixed32=5 Fixed32 wire type + * @property {number} sfixed32=5 Fixed32 wire type + * @property {number} int64=0 Varint wire type + * @property {number} uint64=0 Varint wire type + * @property {number} sint64=0 Varint wire type + * @property {number} fixed64=1 Fixed64 wire type + * @property {number} sfixed64=1 Fixed64 wire type + * @property {number} bool=0 Varint wire type + * @property {number} string=2 Ldelim wire type + */ +types.mapKey = bake([ + /* int32 */ 0, + /* uint32 */ 0, + /* sint32 */ 0, + /* fixed32 */ 5, + /* sfixed32 */ 5, + /* int64 */ 0, + /* uint64 */ 0, + /* sint64 */ 0, + /* fixed64 */ 1, + /* sfixed64 */ 1, + /* bool */ 0, + /* string */ 2 +], 2); + +/** + * Allowed types for packed repeated fields with their associated wire type. + * @type {Object.} + * @const + * @property {number} double=1 Fixed64 wire type + * @property {number} float=5 Fixed32 wire type + * @property {number} int32=0 Varint wire type + * @property {number} uint32=0 Varint wire type + * @property {number} sint32=0 Varint wire type + * @property {number} fixed32=5 Fixed32 wire type + * @property {number} sfixed32=5 Fixed32 wire type + * @property {number} int64=0 Varint wire type + * @property {number} uint64=0 Varint wire type + * @property {number} sint64=0 Varint wire type + * @property {number} fixed64=1 Fixed64 wire type + * @property {number} sfixed64=1 Fixed64 wire type + * @property {number} bool=0 Varint wire type + */ +types.packed = bake([ + /* double */ 1, + /* float */ 5, + /* int32 */ 0, + /* uint32 */ 0, + /* sint32 */ 0, + /* fixed32 */ 5, + /* sfixed32 */ 5, + /* int64 */ 0, + /* uint64 */ 0, + /* sint64 */ 0, + /* fixed64 */ 1, + /* sfixed64 */ 1, + /* bool */ 0 +]); + +},{"37":37}],37:[function(require,module,exports){ +"use strict"; + +/** + * Various utility functions. + * @namespace + */ +var util = module.exports = require(39); + +var roots = require(30); + +var Type, // cyclic + Enum; + +util.codegen = require(3); +util.fetch = require(5); +util.path = require(8); + +/** + * Node's fs module if available. + * @type {Object.} + */ +util.fs = util.inquire("fs"); + +/** + * Converts an object's values to an array. + * @param {Object.} object Object to convert + * @returns {Array.<*>} Converted array + */ +util.toArray = function toArray(object) { + if (object) { + var keys = Object.keys(object), + array = new Array(keys.length), + index = 0; + while (index < keys.length) + array[index] = object[keys[index++]]; + return array; + } + return []; +}; + +/** + * Converts an array of keys immediately followed by their respective value to an object, omitting undefined values. + * @param {Array.<*>} array Array to convert + * @returns {Object.} Converted object + */ +util.toObject = function toObject(array) { + var object = {}, + index = 0; + while (index < array.length) { + var key = array[index++], + val = array[index++]; + if (val !== undefined) + object[key] = val; + } + return object; +}; + +var safePropBackslashRe = /\\/g, + safePropQuoteRe = /"/g; + +/** + * Tests whether the specified name is a reserved word in JS. + * @param {string} name Name to test + * @returns {boolean} `true` if reserved, otherwise `false` + */ +util.isReserved = function isReserved(name) { + return /^(?:do|if|in|for|let|new|try|var|case|else|enum|eval|false|null|this|true|void|with|break|catch|class|const|super|throw|while|yield|delete|export|import|public|return|static|switch|typeof|default|extends|finally|package|private|continue|debugger|function|arguments|interface|protected|implements|instanceof)$/.test(name); +}; + +/** + * Returns a safe property accessor for the specified property name. + * @param {string} prop Property name + * @returns {string} Safe accessor + */ +util.safeProp = function safeProp(prop) { + if (!/^[$\w_]+$/.test(prop) || util.isReserved(prop)) + return "[\"" + prop.replace(safePropBackslashRe, "\\\\").replace(safePropQuoteRe, "\\\"") + "\"]"; + return "." + prop; +}; + +/** + * Converts the first character of a string to upper case. + * @param {string} str String to convert + * @returns {string} Converted string + */ +util.ucFirst = function ucFirst(str) { + return str.charAt(0).toUpperCase() + str.substring(1); +}; + +var camelCaseRe = /_([a-z])/g; + +/** + * Converts a string to camel case. + * @param {string} str String to convert + * @returns {string} Converted string + */ +util.camelCase = function camelCase(str) { + return str.substring(0, 1) + + str.substring(1) + .replace(camelCaseRe, function($0, $1) { return $1.toUpperCase(); }); +}; + +/** + * Compares reflected fields by id. + * @param {Field} a First field + * @param {Field} b Second field + * @returns {number} Comparison value + */ +util.compareFieldsById = function compareFieldsById(a, b) { + return a.id - b.id; +}; + +/** + * Decorator helper for types (TypeScript). + * @param {Constructor} ctor Constructor function + * @param {string} [typeName] Type name, defaults to the constructor's name + * @returns {Type} Reflected type + * @template T extends Message + * @property {Root} root Decorators root + */ +util.decorateType = function decorateType(ctor, typeName) { + + /* istanbul ignore if */ + if (ctor.$type) { + if (typeName && ctor.$type.name !== typeName) { + util.decorateRoot.remove(ctor.$type); + ctor.$type.name = typeName; + util.decorateRoot.add(ctor.$type); + } + return ctor.$type; + } + + /* istanbul ignore next */ + if (!Type) + Type = require(35); + + var type = new Type(typeName || ctor.name); + util.decorateRoot.add(type); + type.ctor = ctor; // sets up .encode, .decode etc. + Object.defineProperty(ctor, "$type", { value: type, enumerable: false }); + Object.defineProperty(ctor.prototype, "$type", { value: type, enumerable: false }); + return type; +}; + +var decorateEnumIndex = 0; + +/** + * Decorator helper for enums (TypeScript). + * @param {Object} object Enum object + * @returns {Enum} Reflected enum + */ +util.decorateEnum = function decorateEnum(object) { + + /* istanbul ignore if */ + if (object.$type) + return object.$type; + + /* istanbul ignore next */ + if (!Enum) + Enum = require(15); + + var enm = new Enum("Enum" + decorateEnumIndex++, object); + util.decorateRoot.add(enm); + Object.defineProperty(object, "$type", { value: enm, enumerable: false }); + return enm; +}; + + +/** + * Sets the value of a property by property path. If a value already exists, it is turned to an array + * @param {Object.} dst Destination object + * @param {string} path dot '.' delimited path of the property to set + * @param {Object} value the value to set + * @returns {Object.} Destination object + */ +util.setProperty = function setProperty(dst, path, value) { + function setProp(dst, path, value) { + var part = path.shift(); + if (part === "__proto__" || part === "prototype") { + return dst; + } + if (path.length > 0) { + dst[part] = setProp(dst[part] || {}, path, value); + } else { + var prevValue = dst[part]; + if (prevValue) + value = [].concat(prevValue).concat(value); + dst[part] = value; + } + return dst; + } + + if (typeof dst !== "object") + throw TypeError("dst must be an object"); + if (!path) + throw TypeError("path must be specified"); + + path = path.split("."); + return setProp(dst, path, value); +}; + +/** + * Decorator root (TypeScript). + * @name util.decorateRoot + * @type {Root} + * @readonly + */ +Object.defineProperty(util, "decorateRoot", { + get: function() { + return roots["decorated"] || (roots["decorated"] = new (require(29))()); + } +}); + +},{"15":15,"29":29,"3":3,"30":30,"35":35,"39":39,"5":5,"8":8}],38:[function(require,module,exports){ +"use strict"; +module.exports = LongBits; + +var util = require(39); + +/** + * Constructs new long bits. + * @classdesc Helper class for working with the low and high bits of a 64 bit value. + * @memberof util + * @constructor + * @param {number} lo Low 32 bits, unsigned + * @param {number} hi High 32 bits, unsigned + */ +function LongBits(lo, hi) { + + // note that the casts below are theoretically unnecessary as of today, but older statically + // generated converter code might still call the ctor with signed 32bits. kept for compat. + + /** + * Low bits. + * @type {number} + */ + this.lo = lo >>> 0; + + /** + * High bits. + * @type {number} + */ + this.hi = hi >>> 0; +} + +/** + * Zero bits. + * @memberof util.LongBits + * @type {util.LongBits} + */ +var zero = LongBits.zero = new LongBits(0, 0); + +zero.toNumber = function() { return 0; }; +zero.zzEncode = zero.zzDecode = function() { return this; }; +zero.length = function() { return 1; }; + +/** + * Zero hash. + * @memberof util.LongBits + * @type {string} + */ +var zeroHash = LongBits.zeroHash = "\0\0\0\0\0\0\0\0"; + +/** + * Constructs new long bits from the specified number. + * @param {number} value Value + * @returns {util.LongBits} Instance + */ +LongBits.fromNumber = function fromNumber(value) { + if (value === 0) + return zero; + var sign = value < 0; + if (sign) + value = -value; + var lo = value >>> 0, + hi = (value - lo) / 4294967296 >>> 0; + if (sign) { + hi = ~hi >>> 0; + lo = ~lo >>> 0; + if (++lo > 4294967295) { + lo = 0; + if (++hi > 4294967295) + hi = 0; + } + } + return new LongBits(lo, hi); +}; + +/** + * Constructs new long bits from a number, long or string. + * @param {Long|number|string} value Value + * @returns {util.LongBits} Instance + */ +LongBits.from = function from(value) { + if (typeof value === "number") + return LongBits.fromNumber(value); + if (util.isString(value)) { + /* istanbul ignore else */ + if (util.Long) + value = util.Long.fromString(value); + else + return LongBits.fromNumber(parseInt(value, 10)); + } + return value.low || value.high ? new LongBits(value.low >>> 0, value.high >>> 0) : zero; +}; + +/** + * Converts this long bits to a possibly unsafe JavaScript number. + * @param {boolean} [unsigned=false] Whether unsigned or not + * @returns {number} Possibly unsafe number + */ +LongBits.prototype.toNumber = function toNumber(unsigned) { + if (!unsigned && this.hi >>> 31) { + var lo = ~this.lo + 1 >>> 0, + hi = ~this.hi >>> 0; + if (!lo) + hi = hi + 1 >>> 0; + return -(lo + hi * 4294967296); + } + return this.lo + this.hi * 4294967296; +}; + +/** + * Converts this long bits to a long. + * @param {boolean} [unsigned=false] Whether unsigned or not + * @returns {Long} Long + */ +LongBits.prototype.toLong = function toLong(unsigned) { + return util.Long + ? new util.Long(this.lo | 0, this.hi | 0, Boolean(unsigned)) + /* istanbul ignore next */ + : { low: this.lo | 0, high: this.hi | 0, unsigned: Boolean(unsigned) }; +}; + +var charCodeAt = String.prototype.charCodeAt; + +/** + * Constructs new long bits from the specified 8 characters long hash. + * @param {string} hash Hash + * @returns {util.LongBits} Bits + */ +LongBits.fromHash = function fromHash(hash) { + if (hash === zeroHash) + return zero; + return new LongBits( + ( charCodeAt.call(hash, 0) + | charCodeAt.call(hash, 1) << 8 + | charCodeAt.call(hash, 2) << 16 + | charCodeAt.call(hash, 3) << 24) >>> 0 + , + ( charCodeAt.call(hash, 4) + | charCodeAt.call(hash, 5) << 8 + | charCodeAt.call(hash, 6) << 16 + | charCodeAt.call(hash, 7) << 24) >>> 0 + ); +}; + +/** + * Converts this long bits to a 8 characters long hash. + * @returns {string} Hash + */ +LongBits.prototype.toHash = function toHash() { + return String.fromCharCode( + this.lo & 255, + this.lo >>> 8 & 255, + this.lo >>> 16 & 255, + this.lo >>> 24 , + this.hi & 255, + this.hi >>> 8 & 255, + this.hi >>> 16 & 255, + this.hi >>> 24 + ); +}; + +/** + * Zig-zag encodes this long bits. + * @returns {util.LongBits} `this` + */ +LongBits.prototype.zzEncode = function zzEncode() { + var mask = this.hi >> 31; + this.hi = ((this.hi << 1 | this.lo >>> 31) ^ mask) >>> 0; + this.lo = ( this.lo << 1 ^ mask) >>> 0; + return this; +}; + +/** + * Zig-zag decodes this long bits. + * @returns {util.LongBits} `this` + */ +LongBits.prototype.zzDecode = function zzDecode() { + var mask = -(this.lo & 1); + this.lo = ((this.lo >>> 1 | this.hi << 31) ^ mask) >>> 0; + this.hi = ( this.hi >>> 1 ^ mask) >>> 0; + return this; +}; + +/** + * Calculates the length of this longbits when encoded as a varint. + * @returns {number} Length + */ +LongBits.prototype.length = function length() { + var part0 = this.lo, + part1 = (this.lo >>> 28 | this.hi << 4) >>> 0, + part2 = this.hi >>> 24; + return part2 === 0 + ? part1 === 0 + ? part0 < 16384 + ? part0 < 128 ? 1 : 2 + : part0 < 2097152 ? 3 : 4 + : part1 < 16384 + ? part1 < 128 ? 5 : 6 + : part1 < 2097152 ? 7 : 8 + : part2 < 128 ? 9 : 10; +}; + +},{"39":39}],39:[function(require,module,exports){ +"use strict"; +var util = exports; + +// used to return a Promise where callback is omitted +util.asPromise = require(1); + +// converts to / from base64 encoded strings +util.base64 = require(2); + +// base class of rpc.Service +util.EventEmitter = require(4); + +// float handling accross browsers +util.float = require(6); + +// requires modules optionally and hides the call from bundlers +util.inquire = require(7); + +// converts to / from utf8 encoded strings +util.utf8 = require(10); + +// provides a node-like buffer pool in the browser +util.pool = require(9); + +// utility to work with the low and high bits of a 64 bit value +util.LongBits = require(38); + +/** + * Whether running within node or not. + * @memberof util + * @type {boolean} + */ +util.isNode = Boolean(typeof global !== "undefined" + && global + && global.process + && global.process.versions + && global.process.versions.node); + +/** + * Global object reference. + * @memberof util + * @type {Object} + */ +util.global = util.isNode && global + || typeof window !== "undefined" && window + || typeof self !== "undefined" && self + || this; // eslint-disable-line no-invalid-this + +/** + * An immuable empty array. + * @memberof util + * @type {Array.<*>} + * @const + */ +util.emptyArray = Object.freeze ? Object.freeze([]) : /* istanbul ignore next */ []; // used on prototypes + +/** + * An immutable empty object. + * @type {Object} + * @const + */ +util.emptyObject = Object.freeze ? Object.freeze({}) : /* istanbul ignore next */ {}; // used on prototypes + +/** + * Tests if the specified value is an integer. + * @function + * @param {*} value Value to test + * @returns {boolean} `true` if the value is an integer + */ +util.isInteger = Number.isInteger || /* istanbul ignore next */ function isInteger(value) { + return typeof value === "number" && isFinite(value) && Math.floor(value) === value; +}; + +/** + * Tests if the specified value is a string. + * @param {*} value Value to test + * @returns {boolean} `true` if the value is a string + */ +util.isString = function isString(value) { + return typeof value === "string" || value instanceof String; +}; + +/** + * Tests if the specified value is a non-null object. + * @param {*} value Value to test + * @returns {boolean} `true` if the value is a non-null object + */ +util.isObject = function isObject(value) { + return value && typeof value === "object"; +}; + +/** + * Checks if a property on a message is considered to be present. + * This is an alias of {@link util.isSet}. + * @function + * @param {Object} obj Plain object or message instance + * @param {string} prop Property name + * @returns {boolean} `true` if considered to be present, otherwise `false` + */ +util.isset = + +/** + * Checks if a property on a message is considered to be present. + * @param {Object} obj Plain object or message instance + * @param {string} prop Property name + * @returns {boolean} `true` if considered to be present, otherwise `false` + */ +util.isSet = function isSet(obj, prop) { + var value = obj[prop]; + if (value != null && obj.hasOwnProperty(prop)) // eslint-disable-line eqeqeq, no-prototype-builtins + return typeof value !== "object" || (Array.isArray(value) ? value.length : Object.keys(value).length) > 0; + return false; +}; + +/** + * Any compatible Buffer instance. + * This is a minimal stand-alone definition of a Buffer instance. The actual type is that exported by node's typings. + * @interface Buffer + * @extends Uint8Array + */ + +/** + * Node's Buffer class if available. + * @type {Constructor} + */ +util.Buffer = (function() { + try { + var Buffer = util.inquire("buffer").Buffer; + // refuse to use non-node buffers if not explicitly assigned (perf reasons): + return Buffer.prototype.utf8Write ? Buffer : /* istanbul ignore next */ null; + } catch (e) { + /* istanbul ignore next */ + return null; + } +})(); + +// Internal alias of or polyfull for Buffer.from. +util._Buffer_from = null; + +// Internal alias of or polyfill for Buffer.allocUnsafe. +util._Buffer_allocUnsafe = null; + +/** + * Creates a new buffer of whatever type supported by the environment. + * @param {number|number[]} [sizeOrArray=0] Buffer size or number array + * @returns {Uint8Array|Buffer} Buffer + */ +util.newBuffer = function newBuffer(sizeOrArray) { + /* istanbul ignore next */ + return typeof sizeOrArray === "number" + ? util.Buffer + ? util._Buffer_allocUnsafe(sizeOrArray) + : new util.Array(sizeOrArray) + : util.Buffer + ? util._Buffer_from(sizeOrArray) + : typeof Uint8Array === "undefined" + ? sizeOrArray + : new Uint8Array(sizeOrArray); +}; + +/** + * Array implementation used in the browser. `Uint8Array` if supported, otherwise `Array`. + * @type {Constructor} + */ +util.Array = typeof Uint8Array !== "undefined" ? Uint8Array /* istanbul ignore next */ : Array; + +/** + * Any compatible Long instance. + * This is a minimal stand-alone definition of a Long instance. The actual type is that exported by long.js. + * @interface Long + * @property {number} low Low bits + * @property {number} high High bits + * @property {boolean} unsigned Whether unsigned or not + */ + +/** + * Long.js's Long class if available. + * @type {Constructor} + */ +util.Long = /* istanbul ignore next */ util.global.dcodeIO && /* istanbul ignore next */ util.global.dcodeIO.Long + || /* istanbul ignore next */ util.global.Long + || util.inquire("long"); + +/** + * Regular expression used to verify 2 bit (`bool`) map keys. + * @type {RegExp} + * @const + */ +util.key2Re = /^true|false|0|1$/; + +/** + * Regular expression used to verify 32 bit (`int32` etc.) map keys. + * @type {RegExp} + * @const + */ +util.key32Re = /^-?(?:0|[1-9][0-9]*)$/; + +/** + * Regular expression used to verify 64 bit (`int64` etc.) map keys. + * @type {RegExp} + * @const + */ +util.key64Re = /^(?:[\\x00-\\xff]{8}|-?(?:0|[1-9][0-9]*))$/; + +/** + * Converts a number or long to an 8 characters long hash string. + * @param {Long|number} value Value to convert + * @returns {string} Hash + */ +util.longToHash = function longToHash(value) { + return value + ? util.LongBits.from(value).toHash() + : util.LongBits.zeroHash; +}; + +/** + * Converts an 8 characters long hash string to a long or number. + * @param {string} hash Hash + * @param {boolean} [unsigned=false] Whether unsigned or not + * @returns {Long|number} Original value + */ +util.longFromHash = function longFromHash(hash, unsigned) { + var bits = util.LongBits.fromHash(hash); + if (util.Long) + return util.Long.fromBits(bits.lo, bits.hi, unsigned); + return bits.toNumber(Boolean(unsigned)); +}; + +/** + * Merges the properties of the source object into the destination object. + * @memberof util + * @param {Object.} dst Destination object + * @param {Object.} src Source object + * @param {boolean} [ifNotSet=false] Merges only if the key is not already set + * @returns {Object.} Destination object + */ +function merge(dst, src, ifNotSet) { // used by converters + for (var keys = Object.keys(src), i = 0; i < keys.length; ++i) + if (dst[keys[i]] === undefined || !ifNotSet) + dst[keys[i]] = src[keys[i]]; + return dst; +} + +util.merge = merge; + +/** + * Converts the first character of a string to lower case. + * @param {string} str String to convert + * @returns {string} Converted string + */ +util.lcFirst = function lcFirst(str) { + return str.charAt(0).toLowerCase() + str.substring(1); +}; + +/** + * Creates a custom error constructor. + * @memberof util + * @param {string} name Error name + * @returns {Constructor} Custom error constructor + */ +function newError(name) { + + function CustomError(message, properties) { + + if (!(this instanceof CustomError)) + return new CustomError(message, properties); + + // Error.call(this, message); + // ^ just returns a new error instance because the ctor can be called as a function + + Object.defineProperty(this, "message", { get: function() { return message; } }); + + /* istanbul ignore next */ + if (Error.captureStackTrace) // node + Error.captureStackTrace(this, CustomError); + else + Object.defineProperty(this, "stack", { value: new Error().stack || "" }); + + if (properties) + merge(this, properties); + } + + CustomError.prototype = Object.create(Error.prototype, { + constructor: { + value: CustomError, + writable: true, + enumerable: false, + configurable: true, + }, + name: { + get: function get() { return name; }, + set: undefined, + enumerable: false, + // configurable: false would accurately preserve the behavior of + // the original, but I'm guessing that was not intentional. + // For an actual error subclass, this property would + // be configurable. + configurable: true, + }, + toString: { + value: function value() { return this.name + ": " + this.message; }, + writable: true, + enumerable: false, + configurable: true, + }, + }); + + return CustomError; +} + +util.newError = newError; + +/** + * Constructs a new protocol error. + * @classdesc Error subclass indicating a protocol specifc error. + * @memberof util + * @extends Error + * @template T extends Message + * @constructor + * @param {string} message Error message + * @param {Object.} [properties] Additional properties + * @example + * try { + * MyMessage.decode(someBuffer); // throws if required fields are missing + * } catch (e) { + * if (e instanceof ProtocolError && e.instance) + * console.log("decoded so far: " + JSON.stringify(e.instance)); + * } + */ +util.ProtocolError = newError("ProtocolError"); + +/** + * So far decoded message instance. + * @name util.ProtocolError#instance + * @type {Message} + */ + +/** + * A OneOf getter as returned by {@link util.oneOfGetter}. + * @typedef OneOfGetter + * @type {function} + * @returns {string|undefined} Set field name, if any + */ + +/** + * Builds a getter for a oneof's present field name. + * @param {string[]} fieldNames Field names + * @returns {OneOfGetter} Unbound getter + */ +util.oneOfGetter = function getOneOf(fieldNames) { + var fieldMap = {}; + for (var i = 0; i < fieldNames.length; ++i) + fieldMap[fieldNames[i]] = 1; + + /** + * @returns {string|undefined} Set field name, if any + * @this Object + * @ignore + */ + return function() { // eslint-disable-line consistent-return + for (var keys = Object.keys(this), i = keys.length - 1; i > -1; --i) + if (fieldMap[keys[i]] === 1 && this[keys[i]] !== undefined && this[keys[i]] !== null) + return keys[i]; + }; +}; + +/** + * A OneOf setter as returned by {@link util.oneOfSetter}. + * @typedef OneOfSetter + * @type {function} + * @param {string|undefined} value Field name + * @returns {undefined} + */ + +/** + * Builds a setter for a oneof's present field name. + * @param {string[]} fieldNames Field names + * @returns {OneOfSetter} Unbound setter + */ +util.oneOfSetter = function setOneOf(fieldNames) { + + /** + * @param {string} name Field name + * @returns {undefined} + * @this Object + * @ignore + */ + return function(name) { + for (var i = 0; i < fieldNames.length; ++i) + if (fieldNames[i] !== name) + delete this[fieldNames[i]]; + }; +}; + +/** + * Default conversion options used for {@link Message#toJSON} implementations. + * + * These options are close to proto3's JSON mapping with the exception that internal types like Any are handled just like messages. More precisely: + * + * - Longs become strings + * - Enums become string keys + * - Bytes become base64 encoded strings + * - (Sub-)Messages become plain objects + * - Maps become plain objects with all string keys + * - Repeated fields become arrays + * - NaN and Infinity for float and double fields become strings + * + * @type {IConversionOptions} + * @see https://developers.google.com/protocol-buffers/docs/proto3?hl=en#json + */ +util.toJSONOptions = { + longs: String, + enums: String, + bytes: String, + json: true +}; + +// Sets up buffer utility according to the environment (called in index-minimal) +util._configure = function() { + var Buffer = util.Buffer; + /* istanbul ignore if */ + if (!Buffer) { + util._Buffer_from = util._Buffer_allocUnsafe = null; + return; + } + // because node 4.x buffers are incompatible & immutable + // see: https://github.com/dcodeIO/protobuf.js/pull/665 + util._Buffer_from = Buffer.from !== Uint8Array.from && Buffer.from || + /* istanbul ignore next */ + function Buffer_from(value, encoding) { + return new Buffer(value, encoding); + }; + util._Buffer_allocUnsafe = Buffer.allocUnsafe || + /* istanbul ignore next */ + function Buffer_allocUnsafe(size) { + return new Buffer(size); + }; +}; + +},{"1":1,"10":10,"2":2,"38":38,"4":4,"6":6,"7":7,"9":9}],40:[function(require,module,exports){ +"use strict"; +module.exports = verifier; + +var Enum = require(15), + util = require(37); + +function invalid(field, expected) { + return field.name + ": " + expected + (field.repeated && expected !== "array" ? "[]" : field.map && expected !== "object" ? "{k:"+field.keyType+"}" : "") + " expected"; +} + +/** + * Generates a partial value verifier. + * @param {Codegen} gen Codegen instance + * @param {Field} field Reflected field + * @param {number} fieldIndex Field index + * @param {string} ref Variable reference + * @returns {Codegen} Codegen instance + * @ignore + */ +function genVerifyValue(gen, field, fieldIndex, ref) { + /* eslint-disable no-unexpected-multiline */ + if (field.resolvedType) { + if (field.resolvedType instanceof Enum) { gen + ("switch(%s){", ref) + ("default:") + ("return%j", invalid(field, "enum value")); + for (var keys = Object.keys(field.resolvedType.values), j = 0; j < keys.length; ++j) gen + ("case %i:", field.resolvedType.values[keys[j]]); + gen + ("break") + ("}"); + } else { + gen + ("{") + ("var e=types[%i].verify(%s);", fieldIndex, ref) + ("if(e)") + ("return%j+e", field.name + ".") + ("}"); + } + } else { + switch (field.type) { + case "int32": + case "uint32": + case "sint32": + case "fixed32": + case "sfixed32": gen + ("if(!util.isInteger(%s))", ref) + ("return%j", invalid(field, "integer")); + break; + case "int64": + case "uint64": + case "sint64": + case "fixed64": + case "sfixed64": gen + ("if(!util.isInteger(%s)&&!(%s&&util.isInteger(%s.low)&&util.isInteger(%s.high)))", ref, ref, ref, ref) + ("return%j", invalid(field, "integer|Long")); + break; + case "float": + case "double": gen + ("if(typeof %s!==\"number\")", ref) + ("return%j", invalid(field, "number")); + break; + case "bool": gen + ("if(typeof %s!==\"boolean\")", ref) + ("return%j", invalid(field, "boolean")); + break; + case "string": gen + ("if(!util.isString(%s))", ref) + ("return%j", invalid(field, "string")); + break; + case "bytes": gen + ("if(!(%s&&typeof %s.length===\"number\"||util.isString(%s)))", ref, ref, ref) + ("return%j", invalid(field, "buffer")); + break; + } + } + return gen; + /* eslint-enable no-unexpected-multiline */ +} + +/** + * Generates a partial key verifier. + * @param {Codegen} gen Codegen instance + * @param {Field} field Reflected field + * @param {string} ref Variable reference + * @returns {Codegen} Codegen instance + * @ignore + */ +function genVerifyKey(gen, field, ref) { + /* eslint-disable no-unexpected-multiline */ + switch (field.keyType) { + case "int32": + case "uint32": + case "sint32": + case "fixed32": + case "sfixed32": gen + ("if(!util.key32Re.test(%s))", ref) + ("return%j", invalid(field, "integer key")); + break; + case "int64": + case "uint64": + case "sint64": + case "fixed64": + case "sfixed64": gen + ("if(!util.key64Re.test(%s))", ref) // see comment above: x is ok, d is not + ("return%j", invalid(field, "integer|Long key")); + break; + case "bool": gen + ("if(!util.key2Re.test(%s))", ref) + ("return%j", invalid(field, "boolean key")); + break; + } + return gen; + /* eslint-enable no-unexpected-multiline */ +} + +/** + * Generates a verifier specific to the specified message type. + * @param {Type} mtype Message type + * @returns {Codegen} Codegen instance + */ +function verifier(mtype) { + /* eslint-disable no-unexpected-multiline */ + + var gen = util.codegen(["m"], mtype.name + "$verify") + ("if(typeof m!==\"object\"||m===null)") + ("return%j", "object expected"); + var oneofs = mtype.oneofsArray, + seenFirstField = {}; + if (oneofs.length) gen + ("var p={}"); + + for (var i = 0; i < /* initializes */ mtype.fieldsArray.length; ++i) { + var field = mtype._fieldsArray[i].resolve(), + ref = "m" + util.safeProp(field.name); + + if (field.optional) gen + ("if(%s!=null&&m.hasOwnProperty(%j)){", ref, field.name); // !== undefined && !== null + + // map fields + if (field.map) { gen + ("if(!util.isObject(%s))", ref) + ("return%j", invalid(field, "object")) + ("var k=Object.keys(%s)", ref) + ("for(var i=0;i} + * @const + */ +var wrappers = exports; + +var Message = require(21); + +/** + * From object converter part of an {@link IWrapper}. + * @typedef WrapperFromObjectConverter + * @type {function} + * @param {Object.} object Plain object + * @returns {Message<{}>} Message instance + * @this Type + */ + +/** + * To object converter part of an {@link IWrapper}. + * @typedef WrapperToObjectConverter + * @type {function} + * @param {Message<{}>} message Message instance + * @param {IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + * @this Type + */ + +/** + * Common type wrapper part of {@link wrappers}. + * @interface IWrapper + * @property {WrapperFromObjectConverter} [fromObject] From object converter + * @property {WrapperToObjectConverter} [toObject] To object converter + */ + +// Custom wrapper for Any +wrappers[".google.protobuf.Any"] = { + + fromObject: function(object) { + + // unwrap value type if mapped + if (object && object["@type"]) { + // Only use fully qualified type name after the last '/' + var name = object["@type"].substring(object["@type"].lastIndexOf("/") + 1); + var type = this.lookup(name); + /* istanbul ignore else */ + if (type) { + // type_url does not accept leading "." + var type_url = object["@type"].charAt(0) === "." ? + object["@type"].slice(1) : object["@type"]; + // type_url prefix is optional, but path seperator is required + if (type_url.indexOf("/") === -1) { + type_url = "/" + type_url; + } + return this.create({ + type_url: type_url, + value: type.encode(type.fromObject(object)).finish() + }); + } + } + + return this.fromObject(object); + }, + + toObject: function(message, options) { + + // Default prefix + var googleApi = "type.googleapis.com/"; + var prefix = ""; + var name = ""; + + // decode value if requested and unmapped + if (options && options.json && message.type_url && message.value) { + // Only use fully qualified type name after the last '/' + name = message.type_url.substring(message.type_url.lastIndexOf("/") + 1); + // Separate the prefix used + prefix = message.type_url.substring(0, message.type_url.lastIndexOf("/") + 1); + var type = this.lookup(name); + /* istanbul ignore else */ + if (type) + message = type.decode(message.value); + } + + // wrap value if unmapped + if (!(message instanceof this.ctor) && message instanceof Message) { + var object = message.$type.toObject(message, options); + var messageName = message.$type.fullName[0] === "." ? + message.$type.fullName.slice(1) : message.$type.fullName; + // Default to type.googleapis.com prefix if no prefix is used + if (prefix === "") { + prefix = googleApi; + } + name = prefix + messageName; + object["@type"] = name; + return object; + } + + return this.toObject(message, options); + } +}; + +},{"21":21}],42:[function(require,module,exports){ +"use strict"; +module.exports = Writer; + +var util = require(39); + +var BufferWriter; // cyclic + +var LongBits = util.LongBits, + base64 = util.base64, + utf8 = util.utf8; + +/** + * Constructs a new writer operation instance. + * @classdesc Scheduled writer operation. + * @constructor + * @param {function(*, Uint8Array, number)} fn Function to call + * @param {number} len Value byte length + * @param {*} val Value to write + * @ignore + */ +function Op(fn, len, val) { + + /** + * Function to call. + * @type {function(Uint8Array, number, *)} + */ + this.fn = fn; + + /** + * Value byte length. + * @type {number} + */ + this.len = len; + + /** + * Next operation. + * @type {Writer.Op|undefined} + */ + this.next = undefined; + + /** + * Value to write. + * @type {*} + */ + this.val = val; // type varies +} + +/* istanbul ignore next */ +function noop() {} // eslint-disable-line no-empty-function + +/** + * Constructs a new writer state instance. + * @classdesc Copied writer state. + * @memberof Writer + * @constructor + * @param {Writer} writer Writer to copy state from + * @ignore + */ +function State(writer) { + + /** + * Current head. + * @type {Writer.Op} + */ + this.head = writer.head; + + /** + * Current tail. + * @type {Writer.Op} + */ + this.tail = writer.tail; + + /** + * Current buffer length. + * @type {number} + */ + this.len = writer.len; + + /** + * Next state. + * @type {State|null} + */ + this.next = writer.states; +} + +/** + * Constructs a new writer instance. + * @classdesc Wire format writer using `Uint8Array` if available, otherwise `Array`. + * @constructor + */ +function Writer() { + + /** + * Current length. + * @type {number} + */ + this.len = 0; + + /** + * Operations head. + * @type {Object} + */ + this.head = new Op(noop, 0, 0); + + /** + * Operations tail + * @type {Object} + */ + this.tail = this.head; + + /** + * Linked forked states. + * @type {Object|null} + */ + this.states = null; + + // When a value is written, the writer calculates its byte length and puts it into a linked + // list of operations to perform when finish() is called. This both allows us to allocate + // buffers of the exact required size and reduces the amount of work we have to do compared + // to first calculating over objects and then encoding over objects. In our case, the encoding + // part is just a linked list walk calling operations with already prepared values. +} + +var create = function create() { + return util.Buffer + ? function create_buffer_setup() { + return (Writer.create = function create_buffer() { + return new BufferWriter(); + })(); + } + /* istanbul ignore next */ + : function create_array() { + return new Writer(); + }; +}; + +/** + * Creates a new writer. + * @function + * @returns {BufferWriter|Writer} A {@link BufferWriter} when Buffers are supported, otherwise a {@link Writer} + */ +Writer.create = create(); + +/** + * Allocates a buffer of the specified size. + * @param {number} size Buffer size + * @returns {Uint8Array} Buffer + */ +Writer.alloc = function alloc(size) { + return new util.Array(size); +}; + +// Use Uint8Array buffer pool in the browser, just like node does with buffers +/* istanbul ignore else */ +if (util.Array !== Array) + Writer.alloc = util.pool(Writer.alloc, util.Array.prototype.subarray); + +/** + * Pushes a new operation to the queue. + * @param {function(Uint8Array, number, *)} fn Function to call + * @param {number} len Value byte length + * @param {number} val Value to write + * @returns {Writer} `this` + * @private + */ +Writer.prototype._push = function push(fn, len, val) { + this.tail = this.tail.next = new Op(fn, len, val); + this.len += len; + return this; +}; + +function writeByte(val, buf, pos) { + buf[pos] = val & 255; +} + +function writeVarint32(val, buf, pos) { + while (val > 127) { + buf[pos++] = val & 127 | 128; + val >>>= 7; + } + buf[pos] = val; +} + +/** + * Constructs a new varint writer operation instance. + * @classdesc Scheduled varint writer operation. + * @extends Op + * @constructor + * @param {number} len Value byte length + * @param {number} val Value to write + * @ignore + */ +function VarintOp(len, val) { + this.len = len; + this.next = undefined; + this.val = val; +} + +VarintOp.prototype = Object.create(Op.prototype); +VarintOp.prototype.fn = writeVarint32; + +/** + * Writes an unsigned 32 bit value as a varint. + * @param {number} value Value to write + * @returns {Writer} `this` + */ +Writer.prototype.uint32 = function write_uint32(value) { + // here, the call to this.push has been inlined and a varint specific Op subclass is used. + // uint32 is by far the most frequently used operation and benefits significantly from this. + this.len += (this.tail = this.tail.next = new VarintOp( + (value = value >>> 0) + < 128 ? 1 + : value < 16384 ? 2 + : value < 2097152 ? 3 + : value < 268435456 ? 4 + : 5, + value)).len; + return this; +}; + +/** + * Writes a signed 32 bit value as a varint. + * @function + * @param {number} value Value to write + * @returns {Writer} `this` + */ +Writer.prototype.int32 = function write_int32(value) { + return value < 0 + ? this._push(writeVarint64, 10, LongBits.fromNumber(value)) // 10 bytes per spec + : this.uint32(value); +}; + +/** + * Writes a 32 bit value as a varint, zig-zag encoded. + * @param {number} value Value to write + * @returns {Writer} `this` + */ +Writer.prototype.sint32 = function write_sint32(value) { + return this.uint32((value << 1 ^ value >> 31) >>> 0); +}; + +function writeVarint64(val, buf, pos) { + while (val.hi) { + buf[pos++] = val.lo & 127 | 128; + val.lo = (val.lo >>> 7 | val.hi << 25) >>> 0; + val.hi >>>= 7; + } + while (val.lo > 127) { + buf[pos++] = val.lo & 127 | 128; + val.lo = val.lo >>> 7; + } + buf[pos++] = val.lo; +} + +/** + * Writes an unsigned 64 bit value as a varint. + * @param {Long|number|string} value Value to write + * @returns {Writer} `this` + * @throws {TypeError} If `value` is a string and no long library is present. + */ +Writer.prototype.uint64 = function write_uint64(value) { + var bits = LongBits.from(value); + return this._push(writeVarint64, bits.length(), bits); +}; + +/** + * Writes a signed 64 bit value as a varint. + * @function + * @param {Long|number|string} value Value to write + * @returns {Writer} `this` + * @throws {TypeError} If `value` is a string and no long library is present. + */ +Writer.prototype.int64 = Writer.prototype.uint64; + +/** + * Writes a signed 64 bit value as a varint, zig-zag encoded. + * @param {Long|number|string} value Value to write + * @returns {Writer} `this` + * @throws {TypeError} If `value` is a string and no long library is present. + */ +Writer.prototype.sint64 = function write_sint64(value) { + var bits = LongBits.from(value).zzEncode(); + return this._push(writeVarint64, bits.length(), bits); +}; + +/** + * Writes a boolish value as a varint. + * @param {boolean} value Value to write + * @returns {Writer} `this` + */ +Writer.prototype.bool = function write_bool(value) { + return this._push(writeByte, 1, value ? 1 : 0); +}; + +function writeFixed32(val, buf, pos) { + buf[pos ] = val & 255; + buf[pos + 1] = val >>> 8 & 255; + buf[pos + 2] = val >>> 16 & 255; + buf[pos + 3] = val >>> 24; +} + +/** + * Writes an unsigned 32 bit value as fixed 32 bits. + * @param {number} value Value to write + * @returns {Writer} `this` + */ +Writer.prototype.fixed32 = function write_fixed32(value) { + return this._push(writeFixed32, 4, value >>> 0); +}; + +/** + * Writes a signed 32 bit value as fixed 32 bits. + * @function + * @param {number} value Value to write + * @returns {Writer} `this` + */ +Writer.prototype.sfixed32 = Writer.prototype.fixed32; + +/** + * Writes an unsigned 64 bit value as fixed 64 bits. + * @param {Long|number|string} value Value to write + * @returns {Writer} `this` + * @throws {TypeError} If `value` is a string and no long library is present. + */ +Writer.prototype.fixed64 = function write_fixed64(value) { + var bits = LongBits.from(value); + return this._push(writeFixed32, 4, bits.lo)._push(writeFixed32, 4, bits.hi); +}; + +/** + * Writes a signed 64 bit value as fixed 64 bits. + * @function + * @param {Long|number|string} value Value to write + * @returns {Writer} `this` + * @throws {TypeError} If `value` is a string and no long library is present. + */ +Writer.prototype.sfixed64 = Writer.prototype.fixed64; + +/** + * Writes a float (32 bit). + * @function + * @param {number} value Value to write + * @returns {Writer} `this` + */ +Writer.prototype.float = function write_float(value) { + return this._push(util.float.writeFloatLE, 4, value); +}; + +/** + * Writes a double (64 bit float). + * @function + * @param {number} value Value to write + * @returns {Writer} `this` + */ +Writer.prototype.double = function write_double(value) { + return this._push(util.float.writeDoubleLE, 8, value); +}; + +var writeBytes = util.Array.prototype.set + ? function writeBytes_set(val, buf, pos) { + buf.set(val, pos); // also works for plain array values + } + /* istanbul ignore next */ + : function writeBytes_for(val, buf, pos) { + for (var i = 0; i < val.length; ++i) + buf[pos + i] = val[i]; + }; + +/** + * Writes a sequence of bytes. + * @param {Uint8Array|string} value Buffer or base64 encoded string to write + * @returns {Writer} `this` + */ +Writer.prototype.bytes = function write_bytes(value) { + var len = value.length >>> 0; + if (!len) + return this._push(writeByte, 1, 0); + if (util.isString(value)) { + var buf = Writer.alloc(len = base64.length(value)); + base64.decode(value, buf, 0); + value = buf; + } + return this.uint32(len)._push(writeBytes, len, value); +}; + +/** + * Writes a string. + * @param {string} value Value to write + * @returns {Writer} `this` + */ +Writer.prototype.string = function write_string(value) { + var len = utf8.length(value); + return len + ? this.uint32(len)._push(utf8.write, len, value) + : this._push(writeByte, 1, 0); +}; + +/** + * Forks this writer's state by pushing it to a stack. + * Calling {@link Writer#reset|reset} or {@link Writer#ldelim|ldelim} resets the writer to the previous state. + * @returns {Writer} `this` + */ +Writer.prototype.fork = function fork() { + this.states = new State(this); + this.head = this.tail = new Op(noop, 0, 0); + this.len = 0; + return this; +}; + +/** + * Resets this instance to the last state. + * @returns {Writer} `this` + */ +Writer.prototype.reset = function reset() { + if (this.states) { + this.head = this.states.head; + this.tail = this.states.tail; + this.len = this.states.len; + this.states = this.states.next; + } else { + this.head = this.tail = new Op(noop, 0, 0); + this.len = 0; + } + return this; +}; + +/** + * Resets to the last state and appends the fork state's current write length as a varint followed by its operations. + * @returns {Writer} `this` + */ +Writer.prototype.ldelim = function ldelim() { + var head = this.head, + tail = this.tail, + len = this.len; + this.reset().uint32(len); + if (len) { + this.tail.next = head.next; // skip noop + this.tail = tail; + this.len += len; + } + return this; +}; + +/** + * Finishes the write operation. + * @returns {Uint8Array} Finished buffer + */ +Writer.prototype.finish = function finish() { + var head = this.head.next, // skip noop + buf = this.constructor.alloc(this.len), + pos = 0; + while (head) { + head.fn(head.val, buf, pos); + pos += head.len; + head = head.next; + } + // this.head = this.tail = null; + return buf; +}; + +Writer._configure = function(BufferWriter_) { + BufferWriter = BufferWriter_; + Writer.create = create(); + BufferWriter._configure(); +}; + +},{"39":39}],43:[function(require,module,exports){ +"use strict"; +module.exports = BufferWriter; + +// extends Writer +var Writer = require(42); +(BufferWriter.prototype = Object.create(Writer.prototype)).constructor = BufferWriter; + +var util = require(39); + +/** + * Constructs a new buffer writer instance. + * @classdesc Wire format writer using node buffers. + * @extends Writer + * @constructor + */ +function BufferWriter() { + Writer.call(this); +} + +BufferWriter._configure = function () { + /** + * Allocates a buffer of the specified size. + * @function + * @param {number} size Buffer size + * @returns {Buffer} Buffer + */ + BufferWriter.alloc = util._Buffer_allocUnsafe; + + BufferWriter.writeBytesBuffer = util.Buffer && util.Buffer.prototype instanceof Uint8Array && util.Buffer.prototype.set.name === "set" + ? function writeBytesBuffer_set(val, buf, pos) { + buf.set(val, pos); // faster than copy (requires node >= 4 where Buffers extend Uint8Array and set is properly inherited) + // also works for plain array values + } + /* istanbul ignore next */ + : function writeBytesBuffer_copy(val, buf, pos) { + if (val.copy) // Buffer values + val.copy(buf, pos, 0, val.length); + else for (var i = 0; i < val.length;) // plain array values + buf[pos++] = val[i++]; + }; +}; + + +/** + * @override + */ +BufferWriter.prototype.bytes = function write_bytes_buffer(value) { + if (util.isString(value)) + value = util._Buffer_from(value, "base64"); + var len = value.length >>> 0; + this.uint32(len); + if (len) + this._push(BufferWriter.writeBytesBuffer, len, value); + return this; +}; + +function writeStringBuffer(val, buf, pos) { + if (val.length < 40) // plain js is faster for short strings (probably due to redundant assertions) + util.utf8.write(val, buf, pos); + else if (buf.utf8Write) + buf.utf8Write(val, pos); + else + buf.write(val, pos); +} + +/** + * @override + */ +BufferWriter.prototype.string = function write_string_buffer(value) { + var len = util.Buffer.byteLength(value); + this.uint32(len); + if (len) + this._push(writeStringBuffer, len, value); + return this; +}; + + +/** + * Finishes the write operation. + * @name BufferWriter#finish + * @function + * @returns {Buffer} Finished buffer + */ + +BufferWriter._configure(); + +},{"39":39,"42":42}]},{},[19]) + +})(); +//# sourceMappingURL=protobuf.js.map diff --git a/node_modules/protobufjs/dist/protobuf.js.map b/node_modules/protobufjs/dist/protobuf.js.map new file mode 100644 index 0000000..50fb02b --- /dev/null +++ b/node_modules/protobufjs/dist/protobuf.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["lib/prelude.js","../node_modules/@protobufjs/aspromise/index.js","../node_modules/@protobufjs/base64/index.js","../node_modules/@protobufjs/codegen/index.js","../node_modules/@protobufjs/eventemitter/index.js","../node_modules/@protobufjs/fetch/index.js","../node_modules/@protobufjs/float/index.js","../node_modules/@protobufjs/inquire/index.js","../node_modules/@protobufjs/path/index.js","../node_modules/@protobufjs/pool/index.js","../node_modules/@protobufjs/utf8/index.js","../src/common.js","../src/converter.js","../src/decoder.js","../src/encoder.js","../src/enum.js","../src/field.js","../src/index-light.js","../src/index-minimal.js","../src/index","../src/mapfield.js","../src/message.js","../src/method.js","../src/namespace.js","../src/object.js","../src/oneof.js","../src/parse.js","../src/reader.js","../src/reader_buffer.js","../src/root.js","../src/roots.js","../src/rpc.js","../src/rpc/service.js","../src/service.js","../src/tokenize.js","../src/type.js","../src/types.js","../src/util.js","../src/util/longbits.js","../src/util/minimal.js","../src/verifier.js","../src/wrappers.js","../src/writer.js","../src/writer_buffer.js"],"names":[],"mappings":";;;;;;AAAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;ACjCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACpDA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC3IA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACnGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC5EA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACnHA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC/UA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACjBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACjEA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AChDA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACzGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC/YA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC7SA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACjIA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACpGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACtMA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACzXA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACxGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACpCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACZA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC9HA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC1IA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AChKA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACjbA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACnPA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC3MA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACz3BA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AChaA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACnDA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AChXA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AClBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACpCA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC9IA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACvKA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AChaA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AC7kBA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACpMA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACpNA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACxMA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACtbA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;AChLA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACtGA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;;ACjdA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA","file":"protobuf.js","sourcesContent":["(function prelude(modules, cache, entries) {\n\n // This is the prelude used to bundle protobuf.js for the browser. Wraps up the CommonJS\n // sources through a conflict-free require shim and is again wrapped within an iife that\n // provides a minification-friendly `undefined` var plus a global \"use strict\" directive\n // so that minification can remove the directives of each module.\n\n function $require(name) {\n var $module = cache[name];\n if (!$module)\n modules[name][0].call($module = cache[name] = { exports: {} }, $require, $module, $module.exports);\n return $module.exports;\n }\n\n var protobuf = $require(entries[0]);\n\n // Expose globally\n protobuf.util.global.protobuf = protobuf;\n\n // Be nice to AMD\n if (typeof define === \"function\" && define.amd)\n define([\"long\"], function(Long) {\n if (Long && Long.isLong) {\n protobuf.util.Long = Long;\n protobuf.configure();\n }\n return protobuf;\n });\n\n // Be nice to CommonJS\n if (typeof module === \"object\" && module && module.exports)\n module.exports = protobuf;\n\n})/* end of prelude */","\"use strict\";\r\nmodule.exports = asPromise;\r\n\r\n/**\r\n * Callback as used by {@link util.asPromise}.\r\n * @typedef asPromiseCallback\r\n * @type {function}\r\n * @param {Error|null} error Error, if any\r\n * @param {...*} params Additional arguments\r\n * @returns {undefined}\r\n */\r\n\r\n/**\r\n * Returns a promise from a node-style callback function.\r\n * @memberof util\r\n * @param {asPromiseCallback} fn Function to call\r\n * @param {*} ctx Function context\r\n * @param {...*} params Function arguments\r\n * @returns {Promise<*>} Promisified function\r\n */\r\nfunction asPromise(fn, ctx/*, varargs */) {\r\n var params = new Array(arguments.length - 1),\r\n offset = 0,\r\n index = 2,\r\n pending = true;\r\n while (index < arguments.length)\r\n params[offset++] = arguments[index++];\r\n return new Promise(function executor(resolve, reject) {\r\n params[offset] = function callback(err/*, varargs */) {\r\n if (pending) {\r\n pending = false;\r\n if (err)\r\n reject(err);\r\n else {\r\n var params = new Array(arguments.length - 1),\r\n offset = 0;\r\n while (offset < params.length)\r\n params[offset++] = arguments[offset];\r\n resolve.apply(null, params);\r\n }\r\n }\r\n };\r\n try {\r\n fn.apply(ctx || null, params);\r\n } catch (err) {\r\n if (pending) {\r\n pending = false;\r\n reject(err);\r\n }\r\n }\r\n });\r\n}\r\n","\"use strict\";\r\n\r\n/**\r\n * A minimal base64 implementation for number arrays.\r\n * @memberof util\r\n * @namespace\r\n */\r\nvar base64 = exports;\r\n\r\n/**\r\n * Calculates the byte length of a base64 encoded string.\r\n * @param {string} string Base64 encoded string\r\n * @returns {number} Byte length\r\n */\r\nbase64.length = function length(string) {\r\n var p = string.length;\r\n if (!p)\r\n return 0;\r\n var n = 0;\r\n while (--p % 4 > 1 && string.charAt(p) === \"=\")\r\n ++n;\r\n return Math.ceil(string.length * 3) / 4 - n;\r\n};\r\n\r\n// Base64 encoding table\r\nvar b64 = new Array(64);\r\n\r\n// Base64 decoding table\r\nvar s64 = new Array(123);\r\n\r\n// 65..90, 97..122, 48..57, 43, 47\r\nfor (var i = 0; i < 64;)\r\n s64[b64[i] = i < 26 ? i + 65 : i < 52 ? i + 71 : i < 62 ? i - 4 : i - 59 | 43] = i++;\r\n\r\n/**\r\n * Encodes a buffer to a base64 encoded string.\r\n * @param {Uint8Array} buffer Source buffer\r\n * @param {number} start Source start\r\n * @param {number} end Source end\r\n * @returns {string} Base64 encoded string\r\n */\r\nbase64.encode = function encode(buffer, start, end) {\r\n var parts = null,\r\n chunk = [];\r\n var i = 0, // output index\r\n j = 0, // goto index\r\n t; // temporary\r\n while (start < end) {\r\n var b = buffer[start++];\r\n switch (j) {\r\n case 0:\r\n chunk[i++] = b64[b >> 2];\r\n t = (b & 3) << 4;\r\n j = 1;\r\n break;\r\n case 1:\r\n chunk[i++] = b64[t | b >> 4];\r\n t = (b & 15) << 2;\r\n j = 2;\r\n break;\r\n case 2:\r\n chunk[i++] = b64[t | b >> 6];\r\n chunk[i++] = b64[b & 63];\r\n j = 0;\r\n break;\r\n }\r\n if (i > 8191) {\r\n (parts || (parts = [])).push(String.fromCharCode.apply(String, chunk));\r\n i = 0;\r\n }\r\n }\r\n if (j) {\r\n chunk[i++] = b64[t];\r\n chunk[i++] = 61;\r\n if (j === 1)\r\n chunk[i++] = 61;\r\n }\r\n if (parts) {\r\n if (i)\r\n parts.push(String.fromCharCode.apply(String, chunk.slice(0, i)));\r\n return parts.join(\"\");\r\n }\r\n return String.fromCharCode.apply(String, chunk.slice(0, i));\r\n};\r\n\r\nvar invalidEncoding = \"invalid encoding\";\r\n\r\n/**\r\n * Decodes a base64 encoded string to a buffer.\r\n * @param {string} string Source string\r\n * @param {Uint8Array} buffer Destination buffer\r\n * @param {number} offset Destination offset\r\n * @returns {number} Number of bytes written\r\n * @throws {Error} If encoding is invalid\r\n */\r\nbase64.decode = function decode(string, buffer, offset) {\r\n var start = offset;\r\n var j = 0, // goto index\r\n t; // temporary\r\n for (var i = 0; i < string.length;) {\r\n var c = string.charCodeAt(i++);\r\n if (c === 61 && j > 1)\r\n break;\r\n if ((c = s64[c]) === undefined)\r\n throw Error(invalidEncoding);\r\n switch (j) {\r\n case 0:\r\n t = c;\r\n j = 1;\r\n break;\r\n case 1:\r\n buffer[offset++] = t << 2 | (c & 48) >> 4;\r\n t = c;\r\n j = 2;\r\n break;\r\n case 2:\r\n buffer[offset++] = (t & 15) << 4 | (c & 60) >> 2;\r\n t = c;\r\n j = 3;\r\n break;\r\n case 3:\r\n buffer[offset++] = (t & 3) << 6 | c;\r\n j = 0;\r\n break;\r\n }\r\n }\r\n if (j === 1)\r\n throw Error(invalidEncoding);\r\n return offset - start;\r\n};\r\n\r\n/**\r\n * Tests if the specified string appears to be base64 encoded.\r\n * @param {string} string String to test\r\n * @returns {boolean} `true` if probably base64 encoded, otherwise false\r\n */\r\nbase64.test = function test(string) {\r\n return /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(string);\r\n};\r\n","\"use strict\";\r\nmodule.exports = codegen;\r\n\r\n/**\r\n * Begins generating a function.\r\n * @memberof util\r\n * @param {string[]} functionParams Function parameter names\r\n * @param {string} [functionName] Function name if not anonymous\r\n * @returns {Codegen} Appender that appends code to the function's body\r\n */\r\nfunction codegen(functionParams, functionName) {\r\n\r\n /* istanbul ignore if */\r\n if (typeof functionParams === \"string\") {\r\n functionName = functionParams;\r\n functionParams = undefined;\r\n }\r\n\r\n var body = [];\r\n\r\n /**\r\n * Appends code to the function's body or finishes generation.\r\n * @typedef Codegen\r\n * @type {function}\r\n * @param {string|Object.} [formatStringOrScope] Format string or, to finish the function, an object of additional scope variables, if any\r\n * @param {...*} [formatParams] Format parameters\r\n * @returns {Codegen|Function} Itself or the generated function if finished\r\n * @throws {Error} If format parameter counts do not match\r\n */\r\n\r\n function Codegen(formatStringOrScope) {\r\n // note that explicit array handling below makes this ~50% faster\r\n\r\n // finish the function\r\n if (typeof formatStringOrScope !== \"string\") {\r\n var source = toString();\r\n if (codegen.verbose)\r\n console.log(\"codegen: \" + source); // eslint-disable-line no-console\r\n source = \"return \" + source;\r\n if (formatStringOrScope) {\r\n var scopeKeys = Object.keys(formatStringOrScope),\r\n scopeParams = new Array(scopeKeys.length + 1),\r\n scopeValues = new Array(scopeKeys.length),\r\n scopeOffset = 0;\r\n while (scopeOffset < scopeKeys.length) {\r\n scopeParams[scopeOffset] = scopeKeys[scopeOffset];\r\n scopeValues[scopeOffset] = formatStringOrScope[scopeKeys[scopeOffset++]];\r\n }\r\n scopeParams[scopeOffset] = source;\r\n return Function.apply(null, scopeParams).apply(null, scopeValues); // eslint-disable-line no-new-func\r\n }\r\n return Function(source)(); // eslint-disable-line no-new-func\r\n }\r\n\r\n // otherwise append to body\r\n var formatParams = new Array(arguments.length - 1),\r\n formatOffset = 0;\r\n while (formatOffset < formatParams.length)\r\n formatParams[formatOffset] = arguments[++formatOffset];\r\n formatOffset = 0;\r\n formatStringOrScope = formatStringOrScope.replace(/%([%dfijs])/g, function replace($0, $1) {\r\n var value = formatParams[formatOffset++];\r\n switch ($1) {\r\n case \"d\": case \"f\": return String(Number(value));\r\n case \"i\": return String(Math.floor(value));\r\n case \"j\": return JSON.stringify(value);\r\n case \"s\": return String(value);\r\n }\r\n return \"%\";\r\n });\r\n if (formatOffset !== formatParams.length)\r\n throw Error(\"parameter count mismatch\");\r\n body.push(formatStringOrScope);\r\n return Codegen;\r\n }\r\n\r\n function toString(functionNameOverride) {\r\n return \"function \" + (functionNameOverride || functionName || \"\") + \"(\" + (functionParams && functionParams.join(\",\") || \"\") + \"){\\n \" + body.join(\"\\n \") + \"\\n}\";\r\n }\r\n\r\n Codegen.toString = toString;\r\n return Codegen;\r\n}\r\n\r\n/**\r\n * Begins generating a function.\r\n * @memberof util\r\n * @function codegen\r\n * @param {string} [functionName] Function name if not anonymous\r\n * @returns {Codegen} Appender that appends code to the function's body\r\n * @variation 2\r\n */\r\n\r\n/**\r\n * When set to `true`, codegen will log generated code to console. Useful for debugging.\r\n * @name util.codegen.verbose\r\n * @type {boolean}\r\n */\r\ncodegen.verbose = false;\r\n","\"use strict\";\r\nmodule.exports = EventEmitter;\r\n\r\n/**\r\n * Constructs a new event emitter instance.\r\n * @classdesc A minimal event emitter.\r\n * @memberof util\r\n * @constructor\r\n */\r\nfunction EventEmitter() {\r\n\r\n /**\r\n * Registered listeners.\r\n * @type {Object.}\r\n * @private\r\n */\r\n this._listeners = {};\r\n}\r\n\r\n/**\r\n * Registers an event listener.\r\n * @param {string} evt Event name\r\n * @param {function} fn Listener\r\n * @param {*} [ctx] Listener context\r\n * @returns {util.EventEmitter} `this`\r\n */\r\nEventEmitter.prototype.on = function on(evt, fn, ctx) {\r\n (this._listeners[evt] || (this._listeners[evt] = [])).push({\r\n fn : fn,\r\n ctx : ctx || this\r\n });\r\n return this;\r\n};\r\n\r\n/**\r\n * Removes an event listener or any matching listeners if arguments are omitted.\r\n * @param {string} [evt] Event name. Removes all listeners if omitted.\r\n * @param {function} [fn] Listener to remove. Removes all listeners of `evt` if omitted.\r\n * @returns {util.EventEmitter} `this`\r\n */\r\nEventEmitter.prototype.off = function off(evt, fn) {\r\n if (evt === undefined)\r\n this._listeners = {};\r\n else {\r\n if (fn === undefined)\r\n this._listeners[evt] = [];\r\n else {\r\n var listeners = this._listeners[evt];\r\n for (var i = 0; i < listeners.length;)\r\n if (listeners[i].fn === fn)\r\n listeners.splice(i, 1);\r\n else\r\n ++i;\r\n }\r\n }\r\n return this;\r\n};\r\n\r\n/**\r\n * Emits an event by calling its listeners with the specified arguments.\r\n * @param {string} evt Event name\r\n * @param {...*} args Arguments\r\n * @returns {util.EventEmitter} `this`\r\n */\r\nEventEmitter.prototype.emit = function emit(evt) {\r\n var listeners = this._listeners[evt];\r\n if (listeners) {\r\n var args = [],\r\n i = 1;\r\n for (; i < arguments.length;)\r\n args.push(arguments[i++]);\r\n for (i = 0; i < listeners.length;)\r\n listeners[i].fn.apply(listeners[i++].ctx, args);\r\n }\r\n return this;\r\n};\r\n","\"use strict\";\r\nmodule.exports = fetch;\r\n\r\nvar asPromise = require(1),\r\n inquire = require(7);\r\n\r\nvar fs = inquire(\"fs\");\r\n\r\n/**\r\n * Node-style callback as used by {@link util.fetch}.\r\n * @typedef FetchCallback\r\n * @type {function}\r\n * @param {?Error} error Error, if any, otherwise `null`\r\n * @param {string} [contents] File contents, if there hasn't been an error\r\n * @returns {undefined}\r\n */\r\n\r\n/**\r\n * Options as used by {@link util.fetch}.\r\n * @typedef FetchOptions\r\n * @type {Object}\r\n * @property {boolean} [binary=false] Whether expecting a binary response\r\n * @property {boolean} [xhr=false] If `true`, forces the use of XMLHttpRequest\r\n */\r\n\r\n/**\r\n * Fetches the contents of a file.\r\n * @memberof util\r\n * @param {string} filename File path or url\r\n * @param {FetchOptions} options Fetch options\r\n * @param {FetchCallback} callback Callback function\r\n * @returns {undefined}\r\n */\r\nfunction fetch(filename, options, callback) {\r\n if (typeof options === \"function\") {\r\n callback = options;\r\n options = {};\r\n } else if (!options)\r\n options = {};\r\n\r\n if (!callback)\r\n return asPromise(fetch, this, filename, options); // eslint-disable-line no-invalid-this\r\n\r\n // if a node-like filesystem is present, try it first but fall back to XHR if nothing is found.\r\n if (!options.xhr && fs && fs.readFile)\r\n return fs.readFile(filename, function fetchReadFileCallback(err, contents) {\r\n return err && typeof XMLHttpRequest !== \"undefined\"\r\n ? fetch.xhr(filename, options, callback)\r\n : err\r\n ? callback(err)\r\n : callback(null, options.binary ? contents : contents.toString(\"utf8\"));\r\n });\r\n\r\n // use the XHR version otherwise.\r\n return fetch.xhr(filename, options, callback);\r\n}\r\n\r\n/**\r\n * Fetches the contents of a file.\r\n * @name util.fetch\r\n * @function\r\n * @param {string} path File path or url\r\n * @param {FetchCallback} callback Callback function\r\n * @returns {undefined}\r\n * @variation 2\r\n */\r\n\r\n/**\r\n * Fetches the contents of a file.\r\n * @name util.fetch\r\n * @function\r\n * @param {string} path File path or url\r\n * @param {FetchOptions} [options] Fetch options\r\n * @returns {Promise} Promise\r\n * @variation 3\r\n */\r\n\r\n/**/\r\nfetch.xhr = function fetch_xhr(filename, options, callback) {\r\n var xhr = new XMLHttpRequest();\r\n xhr.onreadystatechange /* works everywhere */ = function fetchOnReadyStateChange() {\r\n\r\n if (xhr.readyState !== 4)\r\n return undefined;\r\n\r\n // local cors security errors return status 0 / empty string, too. afaik this cannot be\r\n // reliably distinguished from an actually empty file for security reasons. feel free\r\n // to send a pull request if you are aware of a solution.\r\n if (xhr.status !== 0 && xhr.status !== 200)\r\n return callback(Error(\"status \" + xhr.status));\r\n\r\n // if binary data is expected, make sure that some sort of array is returned, even if\r\n // ArrayBuffers are not supported. the binary string fallback, however, is unsafe.\r\n if (options.binary) {\r\n var buffer = xhr.response;\r\n if (!buffer) {\r\n buffer = [];\r\n for (var i = 0; i < xhr.responseText.length; ++i)\r\n buffer.push(xhr.responseText.charCodeAt(i) & 255);\r\n }\r\n return callback(null, typeof Uint8Array !== \"undefined\" ? new Uint8Array(buffer) : buffer);\r\n }\r\n return callback(null, xhr.responseText);\r\n };\r\n\r\n if (options.binary) {\r\n // ref: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Sending_and_Receiving_Binary_Data#Receiving_binary_data_in_older_browsers\r\n if (\"overrideMimeType\" in xhr)\r\n xhr.overrideMimeType(\"text/plain; charset=x-user-defined\");\r\n xhr.responseType = \"arraybuffer\";\r\n }\r\n\r\n xhr.open(\"GET\", filename);\r\n xhr.send();\r\n};\r\n","\"use strict\";\r\n\r\nmodule.exports = factory(factory);\r\n\r\n/**\r\n * Reads / writes floats / doubles from / to buffers.\r\n * @name util.float\r\n * @namespace\r\n */\r\n\r\n/**\r\n * Writes a 32 bit float to a buffer using little endian byte order.\r\n * @name util.float.writeFloatLE\r\n * @function\r\n * @param {number} val Value to write\r\n * @param {Uint8Array} buf Target buffer\r\n * @param {number} pos Target buffer offset\r\n * @returns {undefined}\r\n */\r\n\r\n/**\r\n * Writes a 32 bit float to a buffer using big endian byte order.\r\n * @name util.float.writeFloatBE\r\n * @function\r\n * @param {number} val Value to write\r\n * @param {Uint8Array} buf Target buffer\r\n * @param {number} pos Target buffer offset\r\n * @returns {undefined}\r\n */\r\n\r\n/**\r\n * Reads a 32 bit float from a buffer using little endian byte order.\r\n * @name util.float.readFloatLE\r\n * @function\r\n * @param {Uint8Array} buf Source buffer\r\n * @param {number} pos Source buffer offset\r\n * @returns {number} Value read\r\n */\r\n\r\n/**\r\n * Reads a 32 bit float from a buffer using big endian byte order.\r\n * @name util.float.readFloatBE\r\n * @function\r\n * @param {Uint8Array} buf Source buffer\r\n * @param {number} pos Source buffer offset\r\n * @returns {number} Value read\r\n */\r\n\r\n/**\r\n * Writes a 64 bit double to a buffer using little endian byte order.\r\n * @name util.float.writeDoubleLE\r\n * @function\r\n * @param {number} val Value to write\r\n * @param {Uint8Array} buf Target buffer\r\n * @param {number} pos Target buffer offset\r\n * @returns {undefined}\r\n */\r\n\r\n/**\r\n * Writes a 64 bit double to a buffer using big endian byte order.\r\n * @name util.float.writeDoubleBE\r\n * @function\r\n * @param {number} val Value to write\r\n * @param {Uint8Array} buf Target buffer\r\n * @param {number} pos Target buffer offset\r\n * @returns {undefined}\r\n */\r\n\r\n/**\r\n * Reads a 64 bit double from a buffer using little endian byte order.\r\n * @name util.float.readDoubleLE\r\n * @function\r\n * @param {Uint8Array} buf Source buffer\r\n * @param {number} pos Source buffer offset\r\n * @returns {number} Value read\r\n */\r\n\r\n/**\r\n * Reads a 64 bit double from a buffer using big endian byte order.\r\n * @name util.float.readDoubleBE\r\n * @function\r\n * @param {Uint8Array} buf Source buffer\r\n * @param {number} pos Source buffer offset\r\n * @returns {number} Value read\r\n */\r\n\r\n// Factory function for the purpose of node-based testing in modified global environments\r\nfunction factory(exports) {\r\n\r\n // float: typed array\r\n if (typeof Float32Array !== \"undefined\") (function() {\r\n\r\n var f32 = new Float32Array([ -0 ]),\r\n f8b = new Uint8Array(f32.buffer),\r\n le = f8b[3] === 128;\r\n\r\n function writeFloat_f32_cpy(val, buf, pos) {\r\n f32[0] = val;\r\n buf[pos ] = f8b[0];\r\n buf[pos + 1] = f8b[1];\r\n buf[pos + 2] = f8b[2];\r\n buf[pos + 3] = f8b[3];\r\n }\r\n\r\n function writeFloat_f32_rev(val, buf, pos) {\r\n f32[0] = val;\r\n buf[pos ] = f8b[3];\r\n buf[pos + 1] = f8b[2];\r\n buf[pos + 2] = f8b[1];\r\n buf[pos + 3] = f8b[0];\r\n }\r\n\r\n /* istanbul ignore next */\r\n exports.writeFloatLE = le ? writeFloat_f32_cpy : writeFloat_f32_rev;\r\n /* istanbul ignore next */\r\n exports.writeFloatBE = le ? writeFloat_f32_rev : writeFloat_f32_cpy;\r\n\r\n function readFloat_f32_cpy(buf, pos) {\r\n f8b[0] = buf[pos ];\r\n f8b[1] = buf[pos + 1];\r\n f8b[2] = buf[pos + 2];\r\n f8b[3] = buf[pos + 3];\r\n return f32[0];\r\n }\r\n\r\n function readFloat_f32_rev(buf, pos) {\r\n f8b[3] = buf[pos ];\r\n f8b[2] = buf[pos + 1];\r\n f8b[1] = buf[pos + 2];\r\n f8b[0] = buf[pos + 3];\r\n return f32[0];\r\n }\r\n\r\n /* istanbul ignore next */\r\n exports.readFloatLE = le ? readFloat_f32_cpy : readFloat_f32_rev;\r\n /* istanbul ignore next */\r\n exports.readFloatBE = le ? readFloat_f32_rev : readFloat_f32_cpy;\r\n\r\n // float: ieee754\r\n })(); else (function() {\r\n\r\n function writeFloat_ieee754(writeUint, val, buf, pos) {\r\n var sign = val < 0 ? 1 : 0;\r\n if (sign)\r\n val = -val;\r\n if (val === 0)\r\n writeUint(1 / val > 0 ? /* positive */ 0 : /* negative 0 */ 2147483648, buf, pos);\r\n else if (isNaN(val))\r\n writeUint(2143289344, buf, pos);\r\n else if (val > 3.4028234663852886e+38) // +-Infinity\r\n writeUint((sign << 31 | 2139095040) >>> 0, buf, pos);\r\n else if (val < 1.1754943508222875e-38) // denormal\r\n writeUint((sign << 31 | Math.round(val / 1.401298464324817e-45)) >>> 0, buf, pos);\r\n else {\r\n var exponent = Math.floor(Math.log(val) / Math.LN2),\r\n mantissa = Math.round(val * Math.pow(2, -exponent) * 8388608) & 8388607;\r\n writeUint((sign << 31 | exponent + 127 << 23 | mantissa) >>> 0, buf, pos);\r\n }\r\n }\r\n\r\n exports.writeFloatLE = writeFloat_ieee754.bind(null, writeUintLE);\r\n exports.writeFloatBE = writeFloat_ieee754.bind(null, writeUintBE);\r\n\r\n function readFloat_ieee754(readUint, buf, pos) {\r\n var uint = readUint(buf, pos),\r\n sign = (uint >> 31) * 2 + 1,\r\n exponent = uint >>> 23 & 255,\r\n mantissa = uint & 8388607;\r\n return exponent === 255\r\n ? mantissa\r\n ? NaN\r\n : sign * Infinity\r\n : exponent === 0 // denormal\r\n ? sign * 1.401298464324817e-45 * mantissa\r\n : sign * Math.pow(2, exponent - 150) * (mantissa + 8388608);\r\n }\r\n\r\n exports.readFloatLE = readFloat_ieee754.bind(null, readUintLE);\r\n exports.readFloatBE = readFloat_ieee754.bind(null, readUintBE);\r\n\r\n })();\r\n\r\n // double: typed array\r\n if (typeof Float64Array !== \"undefined\") (function() {\r\n\r\n var f64 = new Float64Array([-0]),\r\n f8b = new Uint8Array(f64.buffer),\r\n le = f8b[7] === 128;\r\n\r\n function writeDouble_f64_cpy(val, buf, pos) {\r\n f64[0] = val;\r\n buf[pos ] = f8b[0];\r\n buf[pos + 1] = f8b[1];\r\n buf[pos + 2] = f8b[2];\r\n buf[pos + 3] = f8b[3];\r\n buf[pos + 4] = f8b[4];\r\n buf[pos + 5] = f8b[5];\r\n buf[pos + 6] = f8b[6];\r\n buf[pos + 7] = f8b[7];\r\n }\r\n\r\n function writeDouble_f64_rev(val, buf, pos) {\r\n f64[0] = val;\r\n buf[pos ] = f8b[7];\r\n buf[pos + 1] = f8b[6];\r\n buf[pos + 2] = f8b[5];\r\n buf[pos + 3] = f8b[4];\r\n buf[pos + 4] = f8b[3];\r\n buf[pos + 5] = f8b[2];\r\n buf[pos + 6] = f8b[1];\r\n buf[pos + 7] = f8b[0];\r\n }\r\n\r\n /* istanbul ignore next */\r\n exports.writeDoubleLE = le ? writeDouble_f64_cpy : writeDouble_f64_rev;\r\n /* istanbul ignore next */\r\n exports.writeDoubleBE = le ? writeDouble_f64_rev : writeDouble_f64_cpy;\r\n\r\n function readDouble_f64_cpy(buf, pos) {\r\n f8b[0] = buf[pos ];\r\n f8b[1] = buf[pos + 1];\r\n f8b[2] = buf[pos + 2];\r\n f8b[3] = buf[pos + 3];\r\n f8b[4] = buf[pos + 4];\r\n f8b[5] = buf[pos + 5];\r\n f8b[6] = buf[pos + 6];\r\n f8b[7] = buf[pos + 7];\r\n return f64[0];\r\n }\r\n\r\n function readDouble_f64_rev(buf, pos) {\r\n f8b[7] = buf[pos ];\r\n f8b[6] = buf[pos + 1];\r\n f8b[5] = buf[pos + 2];\r\n f8b[4] = buf[pos + 3];\r\n f8b[3] = buf[pos + 4];\r\n f8b[2] = buf[pos + 5];\r\n f8b[1] = buf[pos + 6];\r\n f8b[0] = buf[pos + 7];\r\n return f64[0];\r\n }\r\n\r\n /* istanbul ignore next */\r\n exports.readDoubleLE = le ? readDouble_f64_cpy : readDouble_f64_rev;\r\n /* istanbul ignore next */\r\n exports.readDoubleBE = le ? readDouble_f64_rev : readDouble_f64_cpy;\r\n\r\n // double: ieee754\r\n })(); else (function() {\r\n\r\n function writeDouble_ieee754(writeUint, off0, off1, val, buf, pos) {\r\n var sign = val < 0 ? 1 : 0;\r\n if (sign)\r\n val = -val;\r\n if (val === 0) {\r\n writeUint(0, buf, pos + off0);\r\n writeUint(1 / val > 0 ? /* positive */ 0 : /* negative 0 */ 2147483648, buf, pos + off1);\r\n } else if (isNaN(val)) {\r\n writeUint(0, buf, pos + off0);\r\n writeUint(2146959360, buf, pos + off1);\r\n } else if (val > 1.7976931348623157e+308) { // +-Infinity\r\n writeUint(0, buf, pos + off0);\r\n writeUint((sign << 31 | 2146435072) >>> 0, buf, pos + off1);\r\n } else {\r\n var mantissa;\r\n if (val < 2.2250738585072014e-308) { // denormal\r\n mantissa = val / 5e-324;\r\n writeUint(mantissa >>> 0, buf, pos + off0);\r\n writeUint((sign << 31 | mantissa / 4294967296) >>> 0, buf, pos + off1);\r\n } else {\r\n var exponent = Math.floor(Math.log(val) / Math.LN2);\r\n if (exponent === 1024)\r\n exponent = 1023;\r\n mantissa = val * Math.pow(2, -exponent);\r\n writeUint(mantissa * 4503599627370496 >>> 0, buf, pos + off0);\r\n writeUint((sign << 31 | exponent + 1023 << 20 | mantissa * 1048576 & 1048575) >>> 0, buf, pos + off1);\r\n }\r\n }\r\n }\r\n\r\n exports.writeDoubleLE = writeDouble_ieee754.bind(null, writeUintLE, 0, 4);\r\n exports.writeDoubleBE = writeDouble_ieee754.bind(null, writeUintBE, 4, 0);\r\n\r\n function readDouble_ieee754(readUint, off0, off1, buf, pos) {\r\n var lo = readUint(buf, pos + off0),\r\n hi = readUint(buf, pos + off1);\r\n var sign = (hi >> 31) * 2 + 1,\r\n exponent = hi >>> 20 & 2047,\r\n mantissa = 4294967296 * (hi & 1048575) + lo;\r\n return exponent === 2047\r\n ? mantissa\r\n ? NaN\r\n : sign * Infinity\r\n : exponent === 0 // denormal\r\n ? sign * 5e-324 * mantissa\r\n : sign * Math.pow(2, exponent - 1075) * (mantissa + 4503599627370496);\r\n }\r\n\r\n exports.readDoubleLE = readDouble_ieee754.bind(null, readUintLE, 0, 4);\r\n exports.readDoubleBE = readDouble_ieee754.bind(null, readUintBE, 4, 0);\r\n\r\n })();\r\n\r\n return exports;\r\n}\r\n\r\n// uint helpers\r\n\r\nfunction writeUintLE(val, buf, pos) {\r\n buf[pos ] = val & 255;\r\n buf[pos + 1] = val >>> 8 & 255;\r\n buf[pos + 2] = val >>> 16 & 255;\r\n buf[pos + 3] = val >>> 24;\r\n}\r\n\r\nfunction writeUintBE(val, buf, pos) {\r\n buf[pos ] = val >>> 24;\r\n buf[pos + 1] = val >>> 16 & 255;\r\n buf[pos + 2] = val >>> 8 & 255;\r\n buf[pos + 3] = val & 255;\r\n}\r\n\r\nfunction readUintLE(buf, pos) {\r\n return (buf[pos ]\r\n | buf[pos + 1] << 8\r\n | buf[pos + 2] << 16\r\n | buf[pos + 3] << 24) >>> 0;\r\n}\r\n\r\nfunction readUintBE(buf, pos) {\r\n return (buf[pos ] << 24\r\n | buf[pos + 1] << 16\r\n | buf[pos + 2] << 8\r\n | buf[pos + 3]) >>> 0;\r\n}\r\n","\"use strict\";\r\nmodule.exports = inquire;\r\n\r\n/**\r\n * Requires a module only if available.\r\n * @memberof util\r\n * @param {string} moduleName Module to require\r\n * @returns {?Object} Required module if available and not empty, otherwise `null`\r\n */\r\nfunction inquire(moduleName) {\r\n try {\r\n var mod = eval(\"quire\".replace(/^/,\"re\"))(moduleName); // eslint-disable-line no-eval\r\n if (mod && (mod.length || Object.keys(mod).length))\r\n return mod;\r\n } catch (e) {} // eslint-disable-line no-empty\r\n return null;\r\n}\r\n","\"use strict\";\r\n\r\n/**\r\n * A minimal path module to resolve Unix, Windows and URL paths alike.\r\n * @memberof util\r\n * @namespace\r\n */\r\nvar path = exports;\r\n\r\nvar isAbsolute =\r\n/**\r\n * Tests if the specified path is absolute.\r\n * @param {string} path Path to test\r\n * @returns {boolean} `true` if path is absolute\r\n */\r\npath.isAbsolute = function isAbsolute(path) {\r\n return /^(?:\\/|\\w+:)/.test(path);\r\n};\r\n\r\nvar normalize =\r\n/**\r\n * Normalizes the specified path.\r\n * @param {string} path Path to normalize\r\n * @returns {string} Normalized path\r\n */\r\npath.normalize = function normalize(path) {\r\n path = path.replace(/\\\\/g, \"/\")\r\n .replace(/\\/{2,}/g, \"/\");\r\n var parts = path.split(\"/\"),\r\n absolute = isAbsolute(path),\r\n prefix = \"\";\r\n if (absolute)\r\n prefix = parts.shift() + \"/\";\r\n for (var i = 0; i < parts.length;) {\r\n if (parts[i] === \"..\") {\r\n if (i > 0 && parts[i - 1] !== \"..\")\r\n parts.splice(--i, 2);\r\n else if (absolute)\r\n parts.splice(i, 1);\r\n else\r\n ++i;\r\n } else if (parts[i] === \".\")\r\n parts.splice(i, 1);\r\n else\r\n ++i;\r\n }\r\n return prefix + parts.join(\"/\");\r\n};\r\n\r\n/**\r\n * Resolves the specified include path against the specified origin path.\r\n * @param {string} originPath Path to the origin file\r\n * @param {string} includePath Include path relative to origin path\r\n * @param {boolean} [alreadyNormalized=false] `true` if both paths are already known to be normalized\r\n * @returns {string} Path to the include file\r\n */\r\npath.resolve = function resolve(originPath, includePath, alreadyNormalized) {\r\n if (!alreadyNormalized)\r\n includePath = normalize(includePath);\r\n if (isAbsolute(includePath))\r\n return includePath;\r\n if (!alreadyNormalized)\r\n originPath = normalize(originPath);\r\n return (originPath = originPath.replace(/(?:\\/|^)[^/]+$/, \"\")).length ? normalize(originPath + \"/\" + includePath) : includePath;\r\n};\r\n","\"use strict\";\r\nmodule.exports = pool;\r\n\r\n/**\r\n * An allocator as used by {@link util.pool}.\r\n * @typedef PoolAllocator\r\n * @type {function}\r\n * @param {number} size Buffer size\r\n * @returns {Uint8Array} Buffer\r\n */\r\n\r\n/**\r\n * A slicer as used by {@link util.pool}.\r\n * @typedef PoolSlicer\r\n * @type {function}\r\n * @param {number} start Start offset\r\n * @param {number} end End offset\r\n * @returns {Uint8Array} Buffer slice\r\n * @this {Uint8Array}\r\n */\r\n\r\n/**\r\n * A general purpose buffer pool.\r\n * @memberof util\r\n * @function\r\n * @param {PoolAllocator} alloc Allocator\r\n * @param {PoolSlicer} slice Slicer\r\n * @param {number} [size=8192] Slab size\r\n * @returns {PoolAllocator} Pooled allocator\r\n */\r\nfunction pool(alloc, slice, size) {\r\n var SIZE = size || 8192;\r\n var MAX = SIZE >>> 1;\r\n var slab = null;\r\n var offset = SIZE;\r\n return function pool_alloc(size) {\r\n if (size < 1 || size > MAX)\r\n return alloc(size);\r\n if (offset + size > SIZE) {\r\n slab = alloc(SIZE);\r\n offset = 0;\r\n }\r\n var buf = slice.call(slab, offset, offset += size);\r\n if (offset & 7) // align to 32 bit\r\n offset = (offset | 7) + 1;\r\n return buf;\r\n };\r\n}\r\n","\"use strict\";\r\n\r\n/**\r\n * A minimal UTF8 implementation for number arrays.\r\n * @memberof util\r\n * @namespace\r\n */\r\nvar utf8 = exports;\r\n\r\n/**\r\n * Calculates the UTF8 byte length of a string.\r\n * @param {string} string String\r\n * @returns {number} Byte length\r\n */\r\nutf8.length = function utf8_length(string) {\r\n var len = 0,\r\n c = 0;\r\n for (var i = 0; i < string.length; ++i) {\r\n c = string.charCodeAt(i);\r\n if (c < 128)\r\n len += 1;\r\n else if (c < 2048)\r\n len += 2;\r\n else if ((c & 0xFC00) === 0xD800 && (string.charCodeAt(i + 1) & 0xFC00) === 0xDC00) {\r\n ++i;\r\n len += 4;\r\n } else\r\n len += 3;\r\n }\r\n return len;\r\n};\r\n\r\n/**\r\n * Reads UTF8 bytes as a string.\r\n * @param {Uint8Array} buffer Source buffer\r\n * @param {number} start Source start\r\n * @param {number} end Source end\r\n * @returns {string} String read\r\n */\r\nutf8.read = function utf8_read(buffer, start, end) {\r\n var len = end - start;\r\n if (len < 1)\r\n return \"\";\r\n var parts = null,\r\n chunk = [],\r\n i = 0, // char offset\r\n t; // temporary\r\n while (start < end) {\r\n t = buffer[start++];\r\n if (t < 128)\r\n chunk[i++] = t;\r\n else if (t > 191 && t < 224)\r\n chunk[i++] = (t & 31) << 6 | buffer[start++] & 63;\r\n else if (t > 239 && t < 365) {\r\n t = ((t & 7) << 18 | (buffer[start++] & 63) << 12 | (buffer[start++] & 63) << 6 | buffer[start++] & 63) - 0x10000;\r\n chunk[i++] = 0xD800 + (t >> 10);\r\n chunk[i++] = 0xDC00 + (t & 1023);\r\n } else\r\n chunk[i++] = (t & 15) << 12 | (buffer[start++] & 63) << 6 | buffer[start++] & 63;\r\n if (i > 8191) {\r\n (parts || (parts = [])).push(String.fromCharCode.apply(String, chunk));\r\n i = 0;\r\n }\r\n }\r\n if (parts) {\r\n if (i)\r\n parts.push(String.fromCharCode.apply(String, chunk.slice(0, i)));\r\n return parts.join(\"\");\r\n }\r\n return String.fromCharCode.apply(String, chunk.slice(0, i));\r\n};\r\n\r\n/**\r\n * Writes a string as UTF8 bytes.\r\n * @param {string} string Source string\r\n * @param {Uint8Array} buffer Destination buffer\r\n * @param {number} offset Destination offset\r\n * @returns {number} Bytes written\r\n */\r\nutf8.write = function utf8_write(string, buffer, offset) {\r\n var start = offset,\r\n c1, // character 1\r\n c2; // character 2\r\n for (var i = 0; i < string.length; ++i) {\r\n c1 = string.charCodeAt(i);\r\n if (c1 < 128) {\r\n buffer[offset++] = c1;\r\n } else if (c1 < 2048) {\r\n buffer[offset++] = c1 >> 6 | 192;\r\n buffer[offset++] = c1 & 63 | 128;\r\n } else if ((c1 & 0xFC00) === 0xD800 && ((c2 = string.charCodeAt(i + 1)) & 0xFC00) === 0xDC00) {\r\n c1 = 0x10000 + ((c1 & 0x03FF) << 10) + (c2 & 0x03FF);\r\n ++i;\r\n buffer[offset++] = c1 >> 18 | 240;\r\n buffer[offset++] = c1 >> 12 & 63 | 128;\r\n buffer[offset++] = c1 >> 6 & 63 | 128;\r\n buffer[offset++] = c1 & 63 | 128;\r\n } else {\r\n buffer[offset++] = c1 >> 12 | 224;\r\n buffer[offset++] = c1 >> 6 & 63 | 128;\r\n buffer[offset++] = c1 & 63 | 128;\r\n }\r\n }\r\n return offset - start;\r\n};\r\n","\"use strict\";\nmodule.exports = common;\n\nvar commonRe = /\\/|\\./;\n\n/**\n * Provides common type definitions.\n * Can also be used to provide additional google types or your own custom types.\n * @param {string} name Short name as in `google/protobuf/[name].proto` or full file name\n * @param {Object.} json JSON definition within `google.protobuf` if a short name, otherwise the file's root definition\n * @returns {undefined}\n * @property {INamespace} google/protobuf/any.proto Any\n * @property {INamespace} google/protobuf/duration.proto Duration\n * @property {INamespace} google/protobuf/empty.proto Empty\n * @property {INamespace} google/protobuf/field_mask.proto FieldMask\n * @property {INamespace} google/protobuf/struct.proto Struct, Value, NullValue and ListValue\n * @property {INamespace} google/protobuf/timestamp.proto Timestamp\n * @property {INamespace} google/protobuf/wrappers.proto Wrappers\n * @example\n * // manually provides descriptor.proto (assumes google/protobuf/ namespace and .proto extension)\n * protobuf.common(\"descriptor\", descriptorJson);\n *\n * // manually provides a custom definition (uses my.foo namespace)\n * protobuf.common(\"my/foo/bar.proto\", myFooBarJson);\n */\nfunction common(name, json) {\n if (!commonRe.test(name)) {\n name = \"google/protobuf/\" + name + \".proto\";\n json = { nested: { google: { nested: { protobuf: { nested: json } } } } };\n }\n common[name] = json;\n}\n\n// Not provided because of limited use (feel free to discuss or to provide yourself):\n//\n// google/protobuf/descriptor.proto\n// google/protobuf/source_context.proto\n// google/protobuf/type.proto\n//\n// Stripped and pre-parsed versions of these non-bundled files are instead available as part of\n// the repository or package within the google/protobuf directory.\n\ncommon(\"any\", {\n\n /**\n * Properties of a google.protobuf.Any message.\n * @interface IAny\n * @type {Object}\n * @property {string} [typeUrl]\n * @property {Uint8Array} [bytes]\n * @memberof common\n */\n Any: {\n fields: {\n type_url: {\n type: \"string\",\n id: 1\n },\n value: {\n type: \"bytes\",\n id: 2\n }\n }\n }\n});\n\nvar timeType;\n\ncommon(\"duration\", {\n\n /**\n * Properties of a google.protobuf.Duration message.\n * @interface IDuration\n * @type {Object}\n * @property {number|Long} [seconds]\n * @property {number} [nanos]\n * @memberof common\n */\n Duration: timeType = {\n fields: {\n seconds: {\n type: \"int64\",\n id: 1\n },\n nanos: {\n type: \"int32\",\n id: 2\n }\n }\n }\n});\n\ncommon(\"timestamp\", {\n\n /**\n * Properties of a google.protobuf.Timestamp message.\n * @interface ITimestamp\n * @type {Object}\n * @property {number|Long} [seconds]\n * @property {number} [nanos]\n * @memberof common\n */\n Timestamp: timeType\n});\n\ncommon(\"empty\", {\n\n /**\n * Properties of a google.protobuf.Empty message.\n * @interface IEmpty\n * @memberof common\n */\n Empty: {\n fields: {}\n }\n});\n\ncommon(\"struct\", {\n\n /**\n * Properties of a google.protobuf.Struct message.\n * @interface IStruct\n * @type {Object}\n * @property {Object.} [fields]\n * @memberof common\n */\n Struct: {\n fields: {\n fields: {\n keyType: \"string\",\n type: \"Value\",\n id: 1\n }\n }\n },\n\n /**\n * Properties of a google.protobuf.Value message.\n * @interface IValue\n * @type {Object}\n * @property {string} [kind]\n * @property {0} [nullValue]\n * @property {number} [numberValue]\n * @property {string} [stringValue]\n * @property {boolean} [boolValue]\n * @property {IStruct} [structValue]\n * @property {IListValue} [listValue]\n * @memberof common\n */\n Value: {\n oneofs: {\n kind: {\n oneof: [\n \"nullValue\",\n \"numberValue\",\n \"stringValue\",\n \"boolValue\",\n \"structValue\",\n \"listValue\"\n ]\n }\n },\n fields: {\n nullValue: {\n type: \"NullValue\",\n id: 1\n },\n numberValue: {\n type: \"double\",\n id: 2\n },\n stringValue: {\n type: \"string\",\n id: 3\n },\n boolValue: {\n type: \"bool\",\n id: 4\n },\n structValue: {\n type: \"Struct\",\n id: 5\n },\n listValue: {\n type: \"ListValue\",\n id: 6\n }\n }\n },\n\n NullValue: {\n values: {\n NULL_VALUE: 0\n }\n },\n\n /**\n * Properties of a google.protobuf.ListValue message.\n * @interface IListValue\n * @type {Object}\n * @property {Array.} [values]\n * @memberof common\n */\n ListValue: {\n fields: {\n values: {\n rule: \"repeated\",\n type: \"Value\",\n id: 1\n }\n }\n }\n});\n\ncommon(\"wrappers\", {\n\n /**\n * Properties of a google.protobuf.DoubleValue message.\n * @interface IDoubleValue\n * @type {Object}\n * @property {number} [value]\n * @memberof common\n */\n DoubleValue: {\n fields: {\n value: {\n type: \"double\",\n id: 1\n }\n }\n },\n\n /**\n * Properties of a google.protobuf.FloatValue message.\n * @interface IFloatValue\n * @type {Object}\n * @property {number} [value]\n * @memberof common\n */\n FloatValue: {\n fields: {\n value: {\n type: \"float\",\n id: 1\n }\n }\n },\n\n /**\n * Properties of a google.protobuf.Int64Value message.\n * @interface IInt64Value\n * @type {Object}\n * @property {number|Long} [value]\n * @memberof common\n */\n Int64Value: {\n fields: {\n value: {\n type: \"int64\",\n id: 1\n }\n }\n },\n\n /**\n * Properties of a google.protobuf.UInt64Value message.\n * @interface IUInt64Value\n * @type {Object}\n * @property {number|Long} [value]\n * @memberof common\n */\n UInt64Value: {\n fields: {\n value: {\n type: \"uint64\",\n id: 1\n }\n }\n },\n\n /**\n * Properties of a google.protobuf.Int32Value message.\n * @interface IInt32Value\n * @type {Object}\n * @property {number} [value]\n * @memberof common\n */\n Int32Value: {\n fields: {\n value: {\n type: \"int32\",\n id: 1\n }\n }\n },\n\n /**\n * Properties of a google.protobuf.UInt32Value message.\n * @interface IUInt32Value\n * @type {Object}\n * @property {number} [value]\n * @memberof common\n */\n UInt32Value: {\n fields: {\n value: {\n type: \"uint32\",\n id: 1\n }\n }\n },\n\n /**\n * Properties of a google.protobuf.BoolValue message.\n * @interface IBoolValue\n * @type {Object}\n * @property {boolean} [value]\n * @memberof common\n */\n BoolValue: {\n fields: {\n value: {\n type: \"bool\",\n id: 1\n }\n }\n },\n\n /**\n * Properties of a google.protobuf.StringValue message.\n * @interface IStringValue\n * @type {Object}\n * @property {string} [value]\n * @memberof common\n */\n StringValue: {\n fields: {\n value: {\n type: \"string\",\n id: 1\n }\n }\n },\n\n /**\n * Properties of a google.protobuf.BytesValue message.\n * @interface IBytesValue\n * @type {Object}\n * @property {Uint8Array} [value]\n * @memberof common\n */\n BytesValue: {\n fields: {\n value: {\n type: \"bytes\",\n id: 1\n }\n }\n }\n});\n\ncommon(\"field_mask\", {\n\n /**\n * Properties of a google.protobuf.FieldMask message.\n * @interface IDoubleValue\n * @type {Object}\n * @property {number} [value]\n * @memberof common\n */\n FieldMask: {\n fields: {\n paths: {\n rule: \"repeated\",\n type: \"string\",\n id: 1\n }\n }\n }\n});\n\n/**\n * Gets the root definition of the specified common proto file.\n *\n * Bundled definitions are:\n * - google/protobuf/any.proto\n * - google/protobuf/duration.proto\n * - google/protobuf/empty.proto\n * - google/protobuf/field_mask.proto\n * - google/protobuf/struct.proto\n * - google/protobuf/timestamp.proto\n * - google/protobuf/wrappers.proto\n *\n * @param {string} file Proto file name\n * @returns {INamespace|null} Root definition or `null` if not defined\n */\ncommon.get = function get(file) {\n return common[file] || null;\n};\n","\"use strict\";\n/**\n * Runtime message from/to plain object converters.\n * @namespace\n */\nvar converter = exports;\n\nvar Enum = require(15),\n util = require(37);\n\n/**\n * Generates a partial value fromObject conveter.\n * @param {Codegen} gen Codegen instance\n * @param {Field} field Reflected field\n * @param {number} fieldIndex Field index\n * @param {string} prop Property reference\n * @returns {Codegen} Codegen instance\n * @ignore\n */\nfunction genValuePartial_fromObject(gen, field, fieldIndex, prop) {\n var defaultAlreadyEmitted = false;\n /* eslint-disable no-unexpected-multiline, block-scoped-var, no-redeclare */\n if (field.resolvedType) {\n if (field.resolvedType instanceof Enum) { gen\n (\"switch(d%s){\", prop);\n for (var values = field.resolvedType.values, keys = Object.keys(values), i = 0; i < keys.length; ++i) {\n // enum unknown values passthrough\n if (values[keys[i]] === field.typeDefault && !defaultAlreadyEmitted) { gen\n (\"default:\")\n (\"if(typeof(d%s)===\\\"number\\\"){m%s=d%s;break}\", prop, prop, prop);\n if (!field.repeated) gen // fallback to default value only for\n // arrays, to avoid leaving holes.\n (\"break\"); // for non-repeated fields, just ignore\n defaultAlreadyEmitted = true;\n }\n gen\n (\"case%j:\", keys[i])\n (\"case %i:\", values[keys[i]])\n (\"m%s=%j\", prop, values[keys[i]])\n (\"break\");\n } gen\n (\"}\");\n } else gen\n (\"if(typeof d%s!==\\\"object\\\")\", prop)\n (\"throw TypeError(%j)\", field.fullName + \": object expected\")\n (\"m%s=types[%i].fromObject(d%s)\", prop, fieldIndex, prop);\n } else {\n var isUnsigned = false;\n switch (field.type) {\n case \"double\":\n case \"float\": gen\n (\"m%s=Number(d%s)\", prop, prop); // also catches \"NaN\", \"Infinity\"\n break;\n case \"uint32\":\n case \"fixed32\": gen\n (\"m%s=d%s>>>0\", prop, prop);\n break;\n case \"int32\":\n case \"sint32\":\n case \"sfixed32\": gen\n (\"m%s=d%s|0\", prop, prop);\n break;\n case \"uint64\":\n isUnsigned = true;\n // eslint-disable-next-line no-fallthrough\n case \"int64\":\n case \"sint64\":\n case \"fixed64\":\n case \"sfixed64\": gen\n (\"if(util.Long)\")\n (\"(m%s=util.Long.fromValue(d%s)).unsigned=%j\", prop, prop, isUnsigned)\n (\"else if(typeof d%s===\\\"string\\\")\", prop)\n (\"m%s=parseInt(d%s,10)\", prop, prop)\n (\"else if(typeof d%s===\\\"number\\\")\", prop)\n (\"m%s=d%s\", prop, prop)\n (\"else if(typeof d%s===\\\"object\\\")\", prop)\n (\"m%s=new util.LongBits(d%s.low>>>0,d%s.high>>>0).toNumber(%s)\", prop, prop, prop, isUnsigned ? \"true\" : \"\");\n break;\n case \"bytes\": gen\n (\"if(typeof d%s===\\\"string\\\")\", prop)\n (\"util.base64.decode(d%s,m%s=util.newBuffer(util.base64.length(d%s)),0)\", prop, prop, prop)\n (\"else if(d%s.length >= 0)\", prop)\n (\"m%s=d%s\", prop, prop);\n break;\n case \"string\": gen\n (\"m%s=String(d%s)\", prop, prop);\n break;\n case \"bool\": gen\n (\"m%s=Boolean(d%s)\", prop, prop);\n break;\n /* default: gen\n (\"m%s=d%s\", prop, prop);\n break; */\n }\n }\n return gen;\n /* eslint-enable no-unexpected-multiline, block-scoped-var, no-redeclare */\n}\n\n/**\n * Generates a plain object to runtime message converter specific to the specified message type.\n * @param {Type} mtype Message type\n * @returns {Codegen} Codegen instance\n */\nconverter.fromObject = function fromObject(mtype) {\n /* eslint-disable no-unexpected-multiline, block-scoped-var, no-redeclare */\n var fields = mtype.fieldsArray;\n var gen = util.codegen([\"d\"], mtype.name + \"$fromObject\")\n (\"if(d instanceof this.ctor)\")\n (\"return d\");\n if (!fields.length) return gen\n (\"return new this.ctor\");\n gen\n (\"var m=new this.ctor\");\n for (var i = 0; i < fields.length; ++i) {\n var field = fields[i].resolve(),\n prop = util.safeProp(field.name);\n\n // Map fields\n if (field.map) { gen\n (\"if(d%s){\", prop)\n (\"if(typeof d%s!==\\\"object\\\")\", prop)\n (\"throw TypeError(%j)\", field.fullName + \": object expected\")\n (\"m%s={}\", prop)\n (\"for(var ks=Object.keys(d%s),i=0;i>>0,m%s.high>>>0).toNumber(%s):m%s\", prop, prop, prop, prop, isUnsigned ? \"true\": \"\", prop);\n break;\n case \"bytes\": gen\n (\"d%s=o.bytes===String?util.base64.encode(m%s,0,m%s.length):o.bytes===Array?Array.prototype.slice.call(m%s):m%s\", prop, prop, prop, prop, prop);\n break;\n default: gen\n (\"d%s=m%s\", prop, prop);\n break;\n }\n }\n return gen;\n /* eslint-enable no-unexpected-multiline, block-scoped-var, no-redeclare */\n}\n\n/**\n * Generates a runtime message to plain object converter specific to the specified message type.\n * @param {Type} mtype Message type\n * @returns {Codegen} Codegen instance\n */\nconverter.toObject = function toObject(mtype) {\n /* eslint-disable no-unexpected-multiline, block-scoped-var, no-redeclare */\n var fields = mtype.fieldsArray.slice().sort(util.compareFieldsById);\n if (!fields.length)\n return util.codegen()(\"return {}\");\n var gen = util.codegen([\"m\", \"o\"], mtype.name + \"$toObject\")\n (\"if(!o)\")\n (\"o={}\")\n (\"var d={}\");\n\n var repeatedFields = [],\n mapFields = [],\n normalFields = [],\n i = 0;\n for (; i < fields.length; ++i)\n if (!fields[i].partOf)\n ( fields[i].resolve().repeated ? repeatedFields\n : fields[i].map ? mapFields\n : normalFields).push(fields[i]);\n\n if (repeatedFields.length) { gen\n (\"if(o.arrays||o.defaults){\");\n for (i = 0; i < repeatedFields.length; ++i) gen\n (\"d%s=[]\", util.safeProp(repeatedFields[i].name));\n gen\n (\"}\");\n }\n\n if (mapFields.length) { gen\n (\"if(o.objects||o.defaults){\");\n for (i = 0; i < mapFields.length; ++i) gen\n (\"d%s={}\", util.safeProp(mapFields[i].name));\n gen\n (\"}\");\n }\n\n if (normalFields.length) { gen\n (\"if(o.defaults){\");\n for (i = 0; i < normalFields.length; ++i) {\n var field = normalFields[i],\n prop = util.safeProp(field.name);\n if (field.resolvedType instanceof Enum) gen\n (\"d%s=o.enums===String?%j:%j\", prop, field.resolvedType.valuesById[field.typeDefault], field.typeDefault);\n else if (field.long) gen\n (\"if(util.Long){\")\n (\"var n=new util.Long(%i,%i,%j)\", field.typeDefault.low, field.typeDefault.high, field.typeDefault.unsigned)\n (\"d%s=o.longs===String?n.toString():o.longs===Number?n.toNumber():n\", prop)\n (\"}else\")\n (\"d%s=o.longs===String?%j:%i\", prop, field.typeDefault.toString(), field.typeDefault.toNumber());\n else if (field.bytes) {\n var arrayDefault = \"[\" + Array.prototype.slice.call(field.typeDefault).join(\",\") + \"]\";\n gen\n (\"if(o.bytes===String)d%s=%j\", prop, String.fromCharCode.apply(String, field.typeDefault))\n (\"else{\")\n (\"d%s=%s\", prop, arrayDefault)\n (\"if(o.bytes!==Array)d%s=util.newBuffer(d%s)\", prop, prop)\n (\"}\");\n } else gen\n (\"d%s=%j\", prop, field.typeDefault); // also messages (=null)\n } gen\n (\"}\");\n }\n var hasKs2 = false;\n for (i = 0; i < fields.length; ++i) {\n var field = fields[i],\n index = mtype._fieldsArray.indexOf(field),\n prop = util.safeProp(field.name);\n if (field.map) {\n if (!hasKs2) { hasKs2 = true; gen\n (\"var ks2\");\n } gen\n (\"if(m%s&&(ks2=Object.keys(m%s)).length){\", prop, prop)\n (\"d%s={}\", prop)\n (\"for(var j=0;j>>3){\");\n\n var i = 0;\n for (; i < /* initializes */ mtype.fieldsArray.length; ++i) {\n var field = mtype._fieldsArray[i].resolve(),\n type = field.resolvedType instanceof Enum ? \"int32\" : field.type,\n ref = \"m\" + util.safeProp(field.name); gen\n (\"case %i: {\", field.id);\n\n // Map fields\n if (field.map) { gen\n (\"if(%s===util.emptyObject)\", ref)\n (\"%s={}\", ref)\n (\"var c2 = r.uint32()+r.pos\");\n\n if (types.defaults[field.keyType] !== undefined) gen\n (\"k=%j\", types.defaults[field.keyType]);\n else gen\n (\"k=null\");\n\n if (types.defaults[type] !== undefined) gen\n (\"value=%j\", types.defaults[type]);\n else gen\n (\"value=null\");\n\n gen\n (\"while(r.pos>>3){\")\n (\"case 1: k=r.%s(); break\", field.keyType)\n (\"case 2:\");\n\n if (types.basic[type] === undefined) gen\n (\"value=types[%i].decode(r,r.uint32())\", i); // can't be groups\n else gen\n (\"value=r.%s()\", type);\n\n gen\n (\"break\")\n (\"default:\")\n (\"r.skipType(tag2&7)\")\n (\"break\")\n (\"}\")\n (\"}\");\n\n if (types.long[field.keyType] !== undefined) gen\n (\"%s[typeof k===\\\"object\\\"?util.longToHash(k):k]=value\", ref);\n else gen\n (\"%s[k]=value\", ref);\n\n // Repeated fields\n } else if (field.repeated) { gen\n\n (\"if(!(%s&&%s.length))\", ref, ref)\n (\"%s=[]\", ref);\n\n // Packable (always check for forward and backward compatiblity)\n if (types.packed[type] !== undefined) gen\n (\"if((t&7)===2){\")\n (\"var c2=r.uint32()+r.pos\")\n (\"while(r.pos>> 0, (field.id << 3 | 4) >>> 0)\n : gen(\"types[%i].encode(%s,w.uint32(%i).fork()).ldelim()\", fieldIndex, ref, (field.id << 3 | 2) >>> 0);\n}\n\n/**\n * Generates an encoder specific to the specified message type.\n * @param {Type} mtype Message type\n * @returns {Codegen} Codegen instance\n */\nfunction encoder(mtype) {\n /* eslint-disable no-unexpected-multiline, block-scoped-var, no-redeclare */\n var gen = util.codegen([\"m\", \"w\"], mtype.name + \"$encode\")\n (\"if(!w)\")\n (\"w=Writer.create()\");\n\n var i, ref;\n\n // \"when a message is serialized its known fields should be written sequentially by field number\"\n var fields = /* initializes */ mtype.fieldsArray.slice().sort(util.compareFieldsById);\n\n for (var i = 0; i < fields.length; ++i) {\n var field = fields[i].resolve(),\n index = mtype._fieldsArray.indexOf(field),\n type = field.resolvedType instanceof Enum ? \"int32\" : field.type,\n wireType = types.basic[type];\n ref = \"m\" + util.safeProp(field.name);\n\n // Map fields\n if (field.map) {\n gen\n (\"if(%s!=null&&Object.hasOwnProperty.call(m,%j)){\", ref, field.name) // !== undefined && !== null\n (\"for(var ks=Object.keys(%s),i=0;i>> 0, 8 | types.mapKey[field.keyType], field.keyType);\n if (wireType === undefined) gen\n (\"types[%i].encode(%s[ks[i]],w.uint32(18).fork()).ldelim().ldelim()\", index, ref); // can't be groups\n else gen\n (\".uint32(%i).%s(%s[ks[i]]).ldelim()\", 16 | wireType, type, ref);\n gen\n (\"}\")\n (\"}\");\n\n // Repeated fields\n } else if (field.repeated) { gen\n (\"if(%s!=null&&%s.length){\", ref, ref); // !== undefined && !== null\n\n // Packed repeated\n if (field.packed && types.packed[type] !== undefined) { gen\n\n (\"w.uint32(%i).fork()\", (field.id << 3 | 2) >>> 0)\n (\"for(var i=0;i<%s.length;++i)\", ref)\n (\"w.%s(%s[i])\", type, ref)\n (\"w.ldelim()\");\n\n // Non-packed\n } else { gen\n\n (\"for(var i=0;i<%s.length;++i)\", ref);\n if (wireType === undefined)\n genTypePartial(gen, field, index, ref + \"[i]\");\n else gen\n (\"w.uint32(%i).%s(%s[i])\", (field.id << 3 | wireType) >>> 0, type, ref);\n\n } gen\n (\"}\");\n\n // Non-repeated\n } else {\n if (field.optional) gen\n (\"if(%s!=null&&Object.hasOwnProperty.call(m,%j))\", ref, field.name); // !== undefined && !== null\n\n if (wireType === undefined)\n genTypePartial(gen, field, index, ref);\n else gen\n (\"w.uint32(%i).%s(%s)\", (field.id << 3 | wireType) >>> 0, type, ref);\n\n }\n }\n\n return gen\n (\"return w\");\n /* eslint-enable no-unexpected-multiline, block-scoped-var, no-redeclare */\n}\n","\"use strict\";\nmodule.exports = Enum;\n\n// extends ReflectionObject\nvar ReflectionObject = require(24);\n((Enum.prototype = Object.create(ReflectionObject.prototype)).constructor = Enum).className = \"Enum\";\n\nvar Namespace = require(23),\n util = require(37);\n\n/**\n * Constructs a new enum instance.\n * @classdesc Reflected enum.\n * @extends ReflectionObject\n * @constructor\n * @param {string} name Unique name within its namespace\n * @param {Object.} [values] Enum values as an object, by name\n * @param {Object.} [options] Declared options\n * @param {string} [comment] The comment for this enum\n * @param {Object.} [comments] The value comments for this enum\n * @param {Object.>|undefined} [valuesOptions] The value options for this enum\n */\nfunction Enum(name, values, options, comment, comments, valuesOptions) {\n ReflectionObject.call(this, name, options);\n\n if (values && typeof values !== \"object\")\n throw TypeError(\"values must be an object\");\n\n /**\n * Enum values by id.\n * @type {Object.}\n */\n this.valuesById = {};\n\n /**\n * Enum values by name.\n * @type {Object.}\n */\n this.values = Object.create(this.valuesById); // toJSON, marker\n\n /**\n * Enum comment text.\n * @type {string|null}\n */\n this.comment = comment;\n\n /**\n * Value comment texts, if any.\n * @type {Object.}\n */\n this.comments = comments || {};\n\n /**\n * Values options, if any\n * @type {Object>|undefined}\n */\n this.valuesOptions = valuesOptions;\n\n /**\n * Reserved ranges, if any.\n * @type {Array.}\n */\n this.reserved = undefined; // toJSON\n\n // Note that values inherit valuesById on their prototype which makes them a TypeScript-\n // compatible enum. This is used by pbts to write actual enum definitions that work for\n // static and reflection code alike instead of emitting generic object definitions.\n\n if (values)\n for (var keys = Object.keys(values), i = 0; i < keys.length; ++i)\n if (typeof values[keys[i]] === \"number\") // use forward entries only\n this.valuesById[ this.values[keys[i]] = values[keys[i]] ] = keys[i];\n}\n\n/**\n * Enum descriptor.\n * @interface IEnum\n * @property {Object.} values Enum values\n * @property {Object.} [options] Enum options\n */\n\n/**\n * Constructs an enum from an enum descriptor.\n * @param {string} name Enum name\n * @param {IEnum} json Enum descriptor\n * @returns {Enum} Created enum\n * @throws {TypeError} If arguments are invalid\n */\nEnum.fromJSON = function fromJSON(name, json) {\n var enm = new Enum(name, json.values, json.options, json.comment, json.comments);\n enm.reserved = json.reserved;\n return enm;\n};\n\n/**\n * Converts this enum to an enum descriptor.\n * @param {IToJSONOptions} [toJSONOptions] JSON conversion options\n * @returns {IEnum} Enum descriptor\n */\nEnum.prototype.toJSON = function toJSON(toJSONOptions) {\n var keepComments = toJSONOptions ? Boolean(toJSONOptions.keepComments) : false;\n return util.toObject([\n \"options\" , this.options,\n \"valuesOptions\" , this.valuesOptions,\n \"values\" , this.values,\n \"reserved\" , this.reserved && this.reserved.length ? this.reserved : undefined,\n \"comment\" , keepComments ? this.comment : undefined,\n \"comments\" , keepComments ? this.comments : undefined\n ]);\n};\n\n/**\n * Adds a value to this enum.\n * @param {string} name Value name\n * @param {number} id Value id\n * @param {string} [comment] Comment, if any\n * @param {Object.|undefined} [options] Options, if any\n * @returns {Enum} `this`\n * @throws {TypeError} If arguments are invalid\n * @throws {Error} If there is already a value with this name or id\n */\nEnum.prototype.add = function add(name, id, comment, options) {\n // utilized by the parser but not by .fromJSON\n\n if (!util.isString(name))\n throw TypeError(\"name must be a string\");\n\n if (!util.isInteger(id))\n throw TypeError(\"id must be an integer\");\n\n if (this.values[name] !== undefined)\n throw Error(\"duplicate name '\" + name + \"' in \" + this);\n\n if (this.isReservedId(id))\n throw Error(\"id \" + id + \" is reserved in \" + this);\n\n if (this.isReservedName(name))\n throw Error(\"name '\" + name + \"' is reserved in \" + this);\n\n if (this.valuesById[id] !== undefined) {\n if (!(this.options && this.options.allow_alias))\n throw Error(\"duplicate id \" + id + \" in \" + this);\n this.values[name] = id;\n } else\n this.valuesById[this.values[name] = id] = name;\n\n if (options) {\n if (this.valuesOptions === undefined)\n this.valuesOptions = {};\n this.valuesOptions[name] = options || null;\n }\n\n this.comments[name] = comment || null;\n return this;\n};\n\n/**\n * Removes a value from this enum\n * @param {string} name Value name\n * @returns {Enum} `this`\n * @throws {TypeError} If arguments are invalid\n * @throws {Error} If `name` is not a name of this enum\n */\nEnum.prototype.remove = function remove(name) {\n\n if (!util.isString(name))\n throw TypeError(\"name must be a string\");\n\n var val = this.values[name];\n if (val == null)\n throw Error(\"name '\" + name + \"' does not exist in \" + this);\n\n delete this.valuesById[val];\n delete this.values[name];\n delete this.comments[name];\n if (this.valuesOptions)\n delete this.valuesOptions[name];\n\n return this;\n};\n\n/**\n * Tests if the specified id is reserved.\n * @param {number} id Id to test\n * @returns {boolean} `true` if reserved, otherwise `false`\n */\nEnum.prototype.isReservedId = function isReservedId(id) {\n return Namespace.isReservedId(this.reserved, id);\n};\n\n/**\n * Tests if the specified name is reserved.\n * @param {string} name Name to test\n * @returns {boolean} `true` if reserved, otherwise `false`\n */\nEnum.prototype.isReservedName = function isReservedName(name) {\n return Namespace.isReservedName(this.reserved, name);\n};\n","\"use strict\";\nmodule.exports = Field;\n\n// extends ReflectionObject\nvar ReflectionObject = require(24);\n((Field.prototype = Object.create(ReflectionObject.prototype)).constructor = Field).className = \"Field\";\n\nvar Enum = require(15),\n types = require(36),\n util = require(37);\n\nvar Type; // cyclic\n\nvar ruleRe = /^required|optional|repeated$/;\n\n/**\n * Constructs a new message field instance. Note that {@link MapField|map fields} have their own class.\n * @name Field\n * @classdesc Reflected message field.\n * @extends FieldBase\n * @constructor\n * @param {string} name Unique name within its namespace\n * @param {number} id Unique id within its namespace\n * @param {string} type Value type\n * @param {string|Object.} [rule=\"optional\"] Field rule\n * @param {string|Object.} [extend] Extended type if different from parent\n * @param {Object.} [options] Declared options\n */\n\n/**\n * Constructs a field from a field descriptor.\n * @param {string} name Field name\n * @param {IField} json Field descriptor\n * @returns {Field} Created field\n * @throws {TypeError} If arguments are invalid\n */\nField.fromJSON = function fromJSON(name, json) {\n return new Field(name, json.id, json.type, json.rule, json.extend, json.options, json.comment);\n};\n\n/**\n * Not an actual constructor. Use {@link Field} instead.\n * @classdesc Base class of all reflected message fields. This is not an actual class but here for the sake of having consistent type definitions.\n * @exports FieldBase\n * @extends ReflectionObject\n * @constructor\n * @param {string} name Unique name within its namespace\n * @param {number} id Unique id within its namespace\n * @param {string} type Value type\n * @param {string|Object.} [rule=\"optional\"] Field rule\n * @param {string|Object.} [extend] Extended type if different from parent\n * @param {Object.} [options] Declared options\n * @param {string} [comment] Comment associated with this field\n */\nfunction Field(name, id, type, rule, extend, options, comment) {\n\n if (util.isObject(rule)) {\n comment = extend;\n options = rule;\n rule = extend = undefined;\n } else if (util.isObject(extend)) {\n comment = options;\n options = extend;\n extend = undefined;\n }\n\n ReflectionObject.call(this, name, options);\n\n if (!util.isInteger(id) || id < 0)\n throw TypeError(\"id must be a non-negative integer\");\n\n if (!util.isString(type))\n throw TypeError(\"type must be a string\");\n\n if (rule !== undefined && !ruleRe.test(rule = rule.toString().toLowerCase()))\n throw TypeError(\"rule must be a string rule\");\n\n if (extend !== undefined && !util.isString(extend))\n throw TypeError(\"extend must be a string\");\n\n /**\n * Field rule, if any.\n * @type {string|undefined}\n */\n if (rule === \"proto3_optional\") {\n rule = \"optional\";\n }\n this.rule = rule && rule !== \"optional\" ? rule : undefined; // toJSON\n\n /**\n * Field type.\n * @type {string}\n */\n this.type = type; // toJSON\n\n /**\n * Unique field id.\n * @type {number}\n */\n this.id = id; // toJSON, marker\n\n /**\n * Extended type if different from parent.\n * @type {string|undefined}\n */\n this.extend = extend || undefined; // toJSON\n\n /**\n * Whether this field is required.\n * @type {boolean}\n */\n this.required = rule === \"required\";\n\n /**\n * Whether this field is optional.\n * @type {boolean}\n */\n this.optional = !this.required;\n\n /**\n * Whether this field is repeated.\n * @type {boolean}\n */\n this.repeated = rule === \"repeated\";\n\n /**\n * Whether this field is a map or not.\n * @type {boolean}\n */\n this.map = false;\n\n /**\n * Message this field belongs to.\n * @type {Type|null}\n */\n this.message = null;\n\n /**\n * OneOf this field belongs to, if any,\n * @type {OneOf|null}\n */\n this.partOf = null;\n\n /**\n * The field type's default value.\n * @type {*}\n */\n this.typeDefault = null;\n\n /**\n * The field's default value on prototypes.\n * @type {*}\n */\n this.defaultValue = null;\n\n /**\n * Whether this field's value should be treated as a long.\n * @type {boolean}\n */\n this.long = util.Long ? types.long[type] !== undefined : /* istanbul ignore next */ false;\n\n /**\n * Whether this field's value is a buffer.\n * @type {boolean}\n */\n this.bytes = type === \"bytes\";\n\n /**\n * Resolved type if not a basic type.\n * @type {Type|Enum|null}\n */\n this.resolvedType = null;\n\n /**\n * Sister-field within the extended type if a declaring extension field.\n * @type {Field|null}\n */\n this.extensionField = null;\n\n /**\n * Sister-field within the declaring namespace if an extended field.\n * @type {Field|null}\n */\n this.declaringField = null;\n\n /**\n * Internally remembers whether this field is packed.\n * @type {boolean|null}\n * @private\n */\n this._packed = null;\n\n /**\n * Comment for this field.\n * @type {string|null}\n */\n this.comment = comment;\n}\n\n/**\n * Determines whether this field is packed. Only relevant when repeated and working with proto2.\n * @name Field#packed\n * @type {boolean}\n * @readonly\n */\nObject.defineProperty(Field.prototype, \"packed\", {\n get: function() {\n // defaults to packed=true if not explicity set to false\n if (this._packed === null)\n this._packed = this.getOption(\"packed\") !== false;\n return this._packed;\n }\n});\n\n/**\n * @override\n */\nField.prototype.setOption = function setOption(name, value, ifNotSet) {\n if (name === \"packed\") // clear cached before setting\n this._packed = null;\n return ReflectionObject.prototype.setOption.call(this, name, value, ifNotSet);\n};\n\n/**\n * Field descriptor.\n * @interface IField\n * @property {string} [rule=\"optional\"] Field rule\n * @property {string} type Field type\n * @property {number} id Field id\n * @property {Object.} [options] Field options\n */\n\n/**\n * Extension field descriptor.\n * @interface IExtensionField\n * @extends IField\n * @property {string} extend Extended type\n */\n\n/**\n * Converts this field to a field descriptor.\n * @param {IToJSONOptions} [toJSONOptions] JSON conversion options\n * @returns {IField} Field descriptor\n */\nField.prototype.toJSON = function toJSON(toJSONOptions) {\n var keepComments = toJSONOptions ? Boolean(toJSONOptions.keepComments) : false;\n return util.toObject([\n \"rule\" , this.rule !== \"optional\" && this.rule || undefined,\n \"type\" , this.type,\n \"id\" , this.id,\n \"extend\" , this.extend,\n \"options\" , this.options,\n \"comment\" , keepComments ? this.comment : undefined\n ]);\n};\n\n/**\n * Resolves this field's type references.\n * @returns {Field} `this`\n * @throws {Error} If any reference cannot be resolved\n */\nField.prototype.resolve = function resolve() {\n\n if (this.resolved)\n return this;\n\n if ((this.typeDefault = types.defaults[this.type]) === undefined) { // if not a basic type, resolve it\n this.resolvedType = (this.declaringField ? this.declaringField.parent : this.parent).lookupTypeOrEnum(this.type);\n if (this.resolvedType instanceof Type)\n this.typeDefault = null;\n else // instanceof Enum\n this.typeDefault = this.resolvedType.values[Object.keys(this.resolvedType.values)[0]]; // first defined\n } else if (this.options && this.options.proto3_optional) {\n // proto3 scalar value marked optional; should default to null\n this.typeDefault = null;\n }\n\n // use explicitly set default value if present\n if (this.options && this.options[\"default\"] != null) {\n this.typeDefault = this.options[\"default\"];\n if (this.resolvedType instanceof Enum && typeof this.typeDefault === \"string\")\n this.typeDefault = this.resolvedType.values[this.typeDefault];\n }\n\n // remove unnecessary options\n if (this.options) {\n if (this.options.packed === true || this.options.packed !== undefined && this.resolvedType && !(this.resolvedType instanceof Enum))\n delete this.options.packed;\n if (!Object.keys(this.options).length)\n this.options = undefined;\n }\n\n // convert to internal data type if necesssary\n if (this.long) {\n this.typeDefault = util.Long.fromNumber(this.typeDefault, this.type.charAt(0) === \"u\");\n\n /* istanbul ignore else */\n if (Object.freeze)\n Object.freeze(this.typeDefault); // long instances are meant to be immutable anyway (i.e. use small int cache that even requires it)\n\n } else if (this.bytes && typeof this.typeDefault === \"string\") {\n var buf;\n if (util.base64.test(this.typeDefault))\n util.base64.decode(this.typeDefault, buf = util.newBuffer(util.base64.length(this.typeDefault)), 0);\n else\n util.utf8.write(this.typeDefault, buf = util.newBuffer(util.utf8.length(this.typeDefault)), 0);\n this.typeDefault = buf;\n }\n\n // take special care of maps and repeated fields\n if (this.map)\n this.defaultValue = util.emptyObject;\n else if (this.repeated)\n this.defaultValue = util.emptyArray;\n else\n this.defaultValue = this.typeDefault;\n\n // ensure proper value on prototype\n if (this.parent instanceof Type)\n this.parent.ctor.prototype[this.name] = this.defaultValue;\n\n return ReflectionObject.prototype.resolve.call(this);\n};\n\n/**\n * Decorator function as returned by {@link Field.d} and {@link MapField.d} (TypeScript).\n * @typedef FieldDecorator\n * @type {function}\n * @param {Object} prototype Target prototype\n * @param {string} fieldName Field name\n * @returns {undefined}\n */\n\n/**\n * Field decorator (TypeScript).\n * @name Field.d\n * @function\n * @param {number} fieldId Field id\n * @param {\"double\"|\"float\"|\"int32\"|\"uint32\"|\"sint32\"|\"fixed32\"|\"sfixed32\"|\"int64\"|\"uint64\"|\"sint64\"|\"fixed64\"|\"sfixed64\"|\"string\"|\"bool\"|\"bytes\"|Object} fieldType Field type\n * @param {\"optional\"|\"required\"|\"repeated\"} [fieldRule=\"optional\"] Field rule\n * @param {T} [defaultValue] Default value\n * @returns {FieldDecorator} Decorator function\n * @template T extends number | number[] | Long | Long[] | string | string[] | boolean | boolean[] | Uint8Array | Uint8Array[] | Buffer | Buffer[]\n */\nField.d = function decorateField(fieldId, fieldType, fieldRule, defaultValue) {\n\n // submessage: decorate the submessage and use its name as the type\n if (typeof fieldType === \"function\")\n fieldType = util.decorateType(fieldType).name;\n\n // enum reference: create a reflected copy of the enum and keep reuseing it\n else if (fieldType && typeof fieldType === \"object\")\n fieldType = util.decorateEnum(fieldType).name;\n\n return function fieldDecorator(prototype, fieldName) {\n util.decorateType(prototype.constructor)\n .add(new Field(fieldName, fieldId, fieldType, fieldRule, { \"default\": defaultValue }));\n };\n};\n\n/**\n * Field decorator (TypeScript).\n * @name Field.d\n * @function\n * @param {number} fieldId Field id\n * @param {Constructor|string} fieldType Field type\n * @param {\"optional\"|\"required\"|\"repeated\"} [fieldRule=\"optional\"] Field rule\n * @returns {FieldDecorator} Decorator function\n * @template T extends Message\n * @variation 2\n */\n// like Field.d but without a default value\n\n// Sets up cyclic dependencies (called in index-light)\nField._configure = function configure(Type_) {\n Type = Type_;\n};\n","\"use strict\";\nvar protobuf = module.exports = require(18);\n\nprotobuf.build = \"light\";\n\n/**\n * A node-style callback as used by {@link load} and {@link Root#load}.\n * @typedef LoadCallback\n * @type {function}\n * @param {Error|null} error Error, if any, otherwise `null`\n * @param {Root} [root] Root, if there hasn't been an error\n * @returns {undefined}\n */\n\n/**\n * Loads one or multiple .proto or preprocessed .json files into a common root namespace and calls the callback.\n * @param {string|string[]} filename One or multiple files to load\n * @param {Root} root Root namespace, defaults to create a new one if omitted.\n * @param {LoadCallback} callback Callback function\n * @returns {undefined}\n * @see {@link Root#load}\n */\nfunction load(filename, root, callback) {\n if (typeof root === \"function\") {\n callback = root;\n root = new protobuf.Root();\n } else if (!root)\n root = new protobuf.Root();\n return root.load(filename, callback);\n}\n\n/**\n * Loads one or multiple .proto or preprocessed .json files into a common root namespace and calls the callback.\n * @name load\n * @function\n * @param {string|string[]} filename One or multiple files to load\n * @param {LoadCallback} callback Callback function\n * @returns {undefined}\n * @see {@link Root#load}\n * @variation 2\n */\n// function load(filename:string, callback:LoadCallback):undefined\n\n/**\n * Loads one or multiple .proto or preprocessed .json files into a common root namespace and returns a promise.\n * @name load\n * @function\n * @param {string|string[]} filename One or multiple files to load\n * @param {Root} [root] Root namespace, defaults to create a new one if omitted.\n * @returns {Promise} Promise\n * @see {@link Root#load}\n * @variation 3\n */\n// function load(filename:string, [root:Root]):Promise\n\nprotobuf.load = load;\n\n/**\n * Synchronously loads one or multiple .proto or preprocessed .json files into a common root namespace (node only).\n * @param {string|string[]} filename One or multiple files to load\n * @param {Root} [root] Root namespace, defaults to create a new one if omitted.\n * @returns {Root} Root namespace\n * @throws {Error} If synchronous fetching is not supported (i.e. in browsers) or if a file's syntax is invalid\n * @see {@link Root#loadSync}\n */\nfunction loadSync(filename, root) {\n if (!root)\n root = new protobuf.Root();\n return root.loadSync(filename);\n}\n\nprotobuf.loadSync = loadSync;\n\n// Serialization\nprotobuf.encoder = require(14);\nprotobuf.decoder = require(13);\nprotobuf.verifier = require(40);\nprotobuf.converter = require(12);\n\n// Reflection\nprotobuf.ReflectionObject = require(24);\nprotobuf.Namespace = require(23);\nprotobuf.Root = require(29);\nprotobuf.Enum = require(15);\nprotobuf.Type = require(35);\nprotobuf.Field = require(16);\nprotobuf.OneOf = require(25);\nprotobuf.MapField = require(20);\nprotobuf.Service = require(33);\nprotobuf.Method = require(22);\n\n// Runtime\nprotobuf.Message = require(21);\nprotobuf.wrappers = require(41);\n\n// Utility\nprotobuf.types = require(36);\nprotobuf.util = require(37);\n\n// Set up possibly cyclic reflection dependencies\nprotobuf.ReflectionObject._configure(protobuf.Root);\nprotobuf.Namespace._configure(protobuf.Type, protobuf.Service, protobuf.Enum);\nprotobuf.Root._configure(protobuf.Type);\nprotobuf.Field._configure(protobuf.Type);\n","\"use strict\";\nvar protobuf = exports;\n\n/**\n * Build type, one of `\"full\"`, `\"light\"` or `\"minimal\"`.\n * @name build\n * @type {string}\n * @const\n */\nprotobuf.build = \"minimal\";\n\n// Serialization\nprotobuf.Writer = require(42);\nprotobuf.BufferWriter = require(43);\nprotobuf.Reader = require(27);\nprotobuf.BufferReader = require(28);\n\n// Utility\nprotobuf.util = require(39);\nprotobuf.rpc = require(31);\nprotobuf.roots = require(30);\nprotobuf.configure = configure;\n\n/* istanbul ignore next */\n/**\n * Reconfigures the library according to the environment.\n * @returns {undefined}\n */\nfunction configure() {\n protobuf.util._configure();\n protobuf.Writer._configure(protobuf.BufferWriter);\n protobuf.Reader._configure(protobuf.BufferReader);\n}\n\n// Set up buffer utility according to the environment\nconfigure();\n","\"use strict\";\nvar protobuf = module.exports = require(17);\n\nprotobuf.build = \"full\";\n\n// Parser\nprotobuf.tokenize = require(34);\nprotobuf.parse = require(26);\nprotobuf.common = require(11);\n\n// Configure parser\nprotobuf.Root._configure(protobuf.Type, protobuf.parse, protobuf.common);\n","\"use strict\";\nmodule.exports = MapField;\n\n// extends Field\nvar Field = require(16);\n((MapField.prototype = Object.create(Field.prototype)).constructor = MapField).className = \"MapField\";\n\nvar types = require(36),\n util = require(37);\n\n/**\n * Constructs a new map field instance.\n * @classdesc Reflected map field.\n * @extends FieldBase\n * @constructor\n * @param {string} name Unique name within its namespace\n * @param {number} id Unique id within its namespace\n * @param {string} keyType Key type\n * @param {string} type Value type\n * @param {Object.} [options] Declared options\n * @param {string} [comment] Comment associated with this field\n */\nfunction MapField(name, id, keyType, type, options, comment) {\n Field.call(this, name, id, type, undefined, undefined, options, comment);\n\n /* istanbul ignore if */\n if (!util.isString(keyType))\n throw TypeError(\"keyType must be a string\");\n\n /**\n * Key type.\n * @type {string}\n */\n this.keyType = keyType; // toJSON, marker\n\n /**\n * Resolved key type if not a basic type.\n * @type {ReflectionObject|null}\n */\n this.resolvedKeyType = null;\n\n // Overrides Field#map\n this.map = true;\n}\n\n/**\n * Map field descriptor.\n * @interface IMapField\n * @extends {IField}\n * @property {string} keyType Key type\n */\n\n/**\n * Extension map field descriptor.\n * @interface IExtensionMapField\n * @extends IMapField\n * @property {string} extend Extended type\n */\n\n/**\n * Constructs a map field from a map field descriptor.\n * @param {string} name Field name\n * @param {IMapField} json Map field descriptor\n * @returns {MapField} Created map field\n * @throws {TypeError} If arguments are invalid\n */\nMapField.fromJSON = function fromJSON(name, json) {\n return new MapField(name, json.id, json.keyType, json.type, json.options, json.comment);\n};\n\n/**\n * Converts this map field to a map field descriptor.\n * @param {IToJSONOptions} [toJSONOptions] JSON conversion options\n * @returns {IMapField} Map field descriptor\n */\nMapField.prototype.toJSON = function toJSON(toJSONOptions) {\n var keepComments = toJSONOptions ? Boolean(toJSONOptions.keepComments) : false;\n return util.toObject([\n \"keyType\" , this.keyType,\n \"type\" , this.type,\n \"id\" , this.id,\n \"extend\" , this.extend,\n \"options\" , this.options,\n \"comment\" , keepComments ? this.comment : undefined\n ]);\n};\n\n/**\n * @override\n */\nMapField.prototype.resolve = function resolve() {\n if (this.resolved)\n return this;\n\n // Besides a value type, map fields have a key type that may be \"any scalar type except for floating point types and bytes\"\n if (types.mapKey[this.keyType] === undefined)\n throw Error(\"invalid key type: \" + this.keyType);\n\n return Field.prototype.resolve.call(this);\n};\n\n/**\n * Map field decorator (TypeScript).\n * @name MapField.d\n * @function\n * @param {number} fieldId Field id\n * @param {\"int32\"|\"uint32\"|\"sint32\"|\"fixed32\"|\"sfixed32\"|\"int64\"|\"uint64\"|\"sint64\"|\"fixed64\"|\"sfixed64\"|\"bool\"|\"string\"} fieldKeyType Field key type\n * @param {\"double\"|\"float\"|\"int32\"|\"uint32\"|\"sint32\"|\"fixed32\"|\"sfixed32\"|\"int64\"|\"uint64\"|\"sint64\"|\"fixed64\"|\"sfixed64\"|\"bool\"|\"string\"|\"bytes\"|Object|Constructor<{}>} fieldValueType Field value type\n * @returns {FieldDecorator} Decorator function\n * @template T extends { [key: string]: number | Long | string | boolean | Uint8Array | Buffer | number[] | Message<{}> }\n */\nMapField.d = function decorateMapField(fieldId, fieldKeyType, fieldValueType) {\n\n // submessage value: decorate the submessage and use its name as the type\n if (typeof fieldValueType === \"function\")\n fieldValueType = util.decorateType(fieldValueType).name;\n\n // enum reference value: create a reflected copy of the enum and keep reuseing it\n else if (fieldValueType && typeof fieldValueType === \"object\")\n fieldValueType = util.decorateEnum(fieldValueType).name;\n\n return function mapFieldDecorator(prototype, fieldName) {\n util.decorateType(prototype.constructor)\n .add(new MapField(fieldName, fieldId, fieldKeyType, fieldValueType));\n };\n};\n","\"use strict\";\nmodule.exports = Message;\n\nvar util = require(39);\n\n/**\n * Constructs a new message instance.\n * @classdesc Abstract runtime message.\n * @constructor\n * @param {Properties} [properties] Properties to set\n * @template T extends object = object\n */\nfunction Message(properties) {\n // not used internally\n if (properties)\n for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i)\n this[keys[i]] = properties[keys[i]];\n}\n\n/**\n * Reference to the reflected type.\n * @name Message.$type\n * @type {Type}\n * @readonly\n */\n\n/**\n * Reference to the reflected type.\n * @name Message#$type\n * @type {Type}\n * @readonly\n */\n\n/*eslint-disable valid-jsdoc*/\n\n/**\n * Creates a new message of this type using the specified properties.\n * @param {Object.} [properties] Properties to set\n * @returns {Message} Message instance\n * @template T extends Message\n * @this Constructor\n */\nMessage.create = function create(properties) {\n return this.$type.create(properties);\n};\n\n/**\n * Encodes a message of this type.\n * @param {T|Object.} message Message to encode\n * @param {Writer} [writer] Writer to use\n * @returns {Writer} Writer\n * @template T extends Message\n * @this Constructor\n */\nMessage.encode = function encode(message, writer) {\n return this.$type.encode(message, writer);\n};\n\n/**\n * Encodes a message of this type preceeded by its length as a varint.\n * @param {T|Object.} message Message to encode\n * @param {Writer} [writer] Writer to use\n * @returns {Writer} Writer\n * @template T extends Message\n * @this Constructor\n */\nMessage.encodeDelimited = function encodeDelimited(message, writer) {\n return this.$type.encodeDelimited(message, writer);\n};\n\n/**\n * Decodes a message of this type.\n * @name Message.decode\n * @function\n * @param {Reader|Uint8Array} reader Reader or buffer to decode\n * @returns {T} Decoded message\n * @template T extends Message\n * @this Constructor\n */\nMessage.decode = function decode(reader) {\n return this.$type.decode(reader);\n};\n\n/**\n * Decodes a message of this type preceeded by its length as a varint.\n * @name Message.decodeDelimited\n * @function\n * @param {Reader|Uint8Array} reader Reader or buffer to decode\n * @returns {T} Decoded message\n * @template T extends Message\n * @this Constructor\n */\nMessage.decodeDelimited = function decodeDelimited(reader) {\n return this.$type.decodeDelimited(reader);\n};\n\n/**\n * Verifies a message of this type.\n * @name Message.verify\n * @function\n * @param {Object.} message Plain object to verify\n * @returns {string|null} `null` if valid, otherwise the reason why it is not\n */\nMessage.verify = function verify(message) {\n return this.$type.verify(message);\n};\n\n/**\n * Creates a new message of this type from a plain object. Also converts values to their respective internal types.\n * @param {Object.} object Plain object\n * @returns {T} Message instance\n * @template T extends Message\n * @this Constructor\n */\nMessage.fromObject = function fromObject(object) {\n return this.$type.fromObject(object);\n};\n\n/**\n * Creates a plain object from a message of this type. Also converts values to other types if specified.\n * @param {T} message Message instance\n * @param {IConversionOptions} [options] Conversion options\n * @returns {Object.} Plain object\n * @template T extends Message\n * @this Constructor\n */\nMessage.toObject = function toObject(message, options) {\n return this.$type.toObject(message, options);\n};\n\n/**\n * Converts this message to JSON.\n * @returns {Object.} JSON object\n */\nMessage.prototype.toJSON = function toJSON() {\n return this.$type.toObject(this, util.toJSONOptions);\n};\n\n/*eslint-enable valid-jsdoc*/","\"use strict\";\nmodule.exports = Method;\n\n// extends ReflectionObject\nvar ReflectionObject = require(24);\n((Method.prototype = Object.create(ReflectionObject.prototype)).constructor = Method).className = \"Method\";\n\nvar util = require(37);\n\n/**\n * Constructs a new service method instance.\n * @classdesc Reflected service method.\n * @extends ReflectionObject\n * @constructor\n * @param {string} name Method name\n * @param {string|undefined} type Method type, usually `\"rpc\"`\n * @param {string} requestType Request message type\n * @param {string} responseType Response message type\n * @param {boolean|Object.} [requestStream] Whether the request is streamed\n * @param {boolean|Object.} [responseStream] Whether the response is streamed\n * @param {Object.} [options] Declared options\n * @param {string} [comment] The comment for this method\n * @param {Object.} [parsedOptions] Declared options, properly parsed into an object\n */\nfunction Method(name, type, requestType, responseType, requestStream, responseStream, options, comment, parsedOptions) {\n\n /* istanbul ignore next */\n if (util.isObject(requestStream)) {\n options = requestStream;\n requestStream = responseStream = undefined;\n } else if (util.isObject(responseStream)) {\n options = responseStream;\n responseStream = undefined;\n }\n\n /* istanbul ignore if */\n if (!(type === undefined || util.isString(type)))\n throw TypeError(\"type must be a string\");\n\n /* istanbul ignore if */\n if (!util.isString(requestType))\n throw TypeError(\"requestType must be a string\");\n\n /* istanbul ignore if */\n if (!util.isString(responseType))\n throw TypeError(\"responseType must be a string\");\n\n ReflectionObject.call(this, name, options);\n\n /**\n * Method type.\n * @type {string}\n */\n this.type = type || \"rpc\"; // toJSON\n\n /**\n * Request type.\n * @type {string}\n */\n this.requestType = requestType; // toJSON, marker\n\n /**\n * Whether requests are streamed or not.\n * @type {boolean|undefined}\n */\n this.requestStream = requestStream ? true : undefined; // toJSON\n\n /**\n * Response type.\n * @type {string}\n */\n this.responseType = responseType; // toJSON\n\n /**\n * Whether responses are streamed or not.\n * @type {boolean|undefined}\n */\n this.responseStream = responseStream ? true : undefined; // toJSON\n\n /**\n * Resolved request type.\n * @type {Type|null}\n */\n this.resolvedRequestType = null;\n\n /**\n * Resolved response type.\n * @type {Type|null}\n */\n this.resolvedResponseType = null;\n\n /**\n * Comment for this method\n * @type {string|null}\n */\n this.comment = comment;\n\n /**\n * Options properly parsed into an object\n */\n this.parsedOptions = parsedOptions;\n}\n\n/**\n * Method descriptor.\n * @interface IMethod\n * @property {string} [type=\"rpc\"] Method type\n * @property {string} requestType Request type\n * @property {string} responseType Response type\n * @property {boolean} [requestStream=false] Whether requests are streamed\n * @property {boolean} [responseStream=false] Whether responses are streamed\n * @property {Object.} [options] Method options\n * @property {string} comment Method comments\n * @property {Object.} [parsedOptions] Method options properly parsed into an object\n */\n\n/**\n * Constructs a method from a method descriptor.\n * @param {string} name Method name\n * @param {IMethod} json Method descriptor\n * @returns {Method} Created method\n * @throws {TypeError} If arguments are invalid\n */\nMethod.fromJSON = function fromJSON(name, json) {\n return new Method(name, json.type, json.requestType, json.responseType, json.requestStream, json.responseStream, json.options, json.comment, json.parsedOptions);\n};\n\n/**\n * Converts this method to a method descriptor.\n * @param {IToJSONOptions} [toJSONOptions] JSON conversion options\n * @returns {IMethod} Method descriptor\n */\nMethod.prototype.toJSON = function toJSON(toJSONOptions) {\n var keepComments = toJSONOptions ? Boolean(toJSONOptions.keepComments) : false;\n return util.toObject([\n \"type\" , this.type !== \"rpc\" && /* istanbul ignore next */ this.type || undefined,\n \"requestType\" , this.requestType,\n \"requestStream\" , this.requestStream,\n \"responseType\" , this.responseType,\n \"responseStream\" , this.responseStream,\n \"options\" , this.options,\n \"comment\" , keepComments ? this.comment : undefined,\n \"parsedOptions\" , this.parsedOptions,\n ]);\n};\n\n/**\n * @override\n */\nMethod.prototype.resolve = function resolve() {\n\n /* istanbul ignore if */\n if (this.resolved)\n return this;\n\n this.resolvedRequestType = this.parent.lookupType(this.requestType);\n this.resolvedResponseType = this.parent.lookupType(this.responseType);\n\n return ReflectionObject.prototype.resolve.call(this);\n};\n","\"use strict\";\nmodule.exports = Namespace;\n\n// extends ReflectionObject\nvar ReflectionObject = require(24);\n((Namespace.prototype = Object.create(ReflectionObject.prototype)).constructor = Namespace).className = \"Namespace\";\n\nvar Field = require(16),\n util = require(37),\n OneOf = require(25);\n\nvar Type, // cyclic\n Service,\n Enum;\n\n/**\n * Constructs a new namespace instance.\n * @name Namespace\n * @classdesc Reflected namespace.\n * @extends NamespaceBase\n * @constructor\n * @param {string} name Namespace name\n * @param {Object.} [options] Declared options\n */\n\n/**\n * Constructs a namespace from JSON.\n * @memberof Namespace\n * @function\n * @param {string} name Namespace name\n * @param {Object.} json JSON object\n * @returns {Namespace} Created namespace\n * @throws {TypeError} If arguments are invalid\n */\nNamespace.fromJSON = function fromJSON(name, json) {\n return new Namespace(name, json.options).addJSON(json.nested);\n};\n\n/**\n * Converts an array of reflection objects to JSON.\n * @memberof Namespace\n * @param {ReflectionObject[]} array Object array\n * @param {IToJSONOptions} [toJSONOptions] JSON conversion options\n * @returns {Object.|undefined} JSON object or `undefined` when array is empty\n */\nfunction arrayToJSON(array, toJSONOptions) {\n if (!(array && array.length))\n return undefined;\n var obj = {};\n for (var i = 0; i < array.length; ++i)\n obj[array[i].name] = array[i].toJSON(toJSONOptions);\n return obj;\n}\n\nNamespace.arrayToJSON = arrayToJSON;\n\n/**\n * Tests if the specified id is reserved.\n * @param {Array.|undefined} reserved Array of reserved ranges and names\n * @param {number} id Id to test\n * @returns {boolean} `true` if reserved, otherwise `false`\n */\nNamespace.isReservedId = function isReservedId(reserved, id) {\n if (reserved)\n for (var i = 0; i < reserved.length; ++i)\n if (typeof reserved[i] !== \"string\" && reserved[i][0] <= id && reserved[i][1] > id)\n return true;\n return false;\n};\n\n/**\n * Tests if the specified name is reserved.\n * @param {Array.|undefined} reserved Array of reserved ranges and names\n * @param {string} name Name to test\n * @returns {boolean} `true` if reserved, otherwise `false`\n */\nNamespace.isReservedName = function isReservedName(reserved, name) {\n if (reserved)\n for (var i = 0; i < reserved.length; ++i)\n if (reserved[i] === name)\n return true;\n return false;\n};\n\n/**\n * Not an actual constructor. Use {@link Namespace} instead.\n * @classdesc Base class of all reflection objects containing nested objects. This is not an actual class but here for the sake of having consistent type definitions.\n * @exports NamespaceBase\n * @extends ReflectionObject\n * @abstract\n * @constructor\n * @param {string} name Namespace name\n * @param {Object.} [options] Declared options\n * @see {@link Namespace}\n */\nfunction Namespace(name, options) {\n ReflectionObject.call(this, name, options);\n\n /**\n * Nested objects by name.\n * @type {Object.|undefined}\n */\n this.nested = undefined; // toJSON\n\n /**\n * Cached nested objects as an array.\n * @type {ReflectionObject[]|null}\n * @private\n */\n this._nestedArray = null;\n}\n\nfunction clearCache(namespace) {\n namespace._nestedArray = null;\n return namespace;\n}\n\n/**\n * Nested objects of this namespace as an array for iteration.\n * @name NamespaceBase#nestedArray\n * @type {ReflectionObject[]}\n * @readonly\n */\nObject.defineProperty(Namespace.prototype, \"nestedArray\", {\n get: function() {\n return this._nestedArray || (this._nestedArray = util.toArray(this.nested));\n }\n});\n\n/**\n * Namespace descriptor.\n * @interface INamespace\n * @property {Object.} [options] Namespace options\n * @property {Object.} [nested] Nested object descriptors\n */\n\n/**\n * Any extension field descriptor.\n * @typedef AnyExtensionField\n * @type {IExtensionField|IExtensionMapField}\n */\n\n/**\n * Any nested object descriptor.\n * @typedef AnyNestedObject\n * @type {IEnum|IType|IService|AnyExtensionField|INamespace|IOneOf}\n */\n\n/**\n * Converts this namespace to a namespace descriptor.\n * @param {IToJSONOptions} [toJSONOptions] JSON conversion options\n * @returns {INamespace} Namespace descriptor\n */\nNamespace.prototype.toJSON = function toJSON(toJSONOptions) {\n return util.toObject([\n \"options\" , this.options,\n \"nested\" , arrayToJSON(this.nestedArray, toJSONOptions)\n ]);\n};\n\n/**\n * Adds nested objects to this namespace from nested object descriptors.\n * @param {Object.} nestedJson Any nested object descriptors\n * @returns {Namespace} `this`\n */\nNamespace.prototype.addJSON = function addJSON(nestedJson) {\n var ns = this;\n /* istanbul ignore else */\n if (nestedJson) {\n for (var names = Object.keys(nestedJson), i = 0, nested; i < names.length; ++i) {\n nested = nestedJson[names[i]];\n ns.add( // most to least likely\n ( nested.fields !== undefined\n ? Type.fromJSON\n : nested.values !== undefined\n ? Enum.fromJSON\n : nested.methods !== undefined\n ? Service.fromJSON\n : nested.id !== undefined\n ? Field.fromJSON\n : Namespace.fromJSON )(names[i], nested)\n );\n }\n }\n return this;\n};\n\n/**\n * Gets the nested object of the specified name.\n * @param {string} name Nested object name\n * @returns {ReflectionObject|null} The reflection object or `null` if it doesn't exist\n */\nNamespace.prototype.get = function get(name) {\n return this.nested && this.nested[name]\n || null;\n};\n\n/**\n * Gets the values of the nested {@link Enum|enum} of the specified name.\n * This methods differs from {@link Namespace#get|get} in that it returns an enum's values directly and throws instead of returning `null`.\n * @param {string} name Nested enum name\n * @returns {Object.} Enum values\n * @throws {Error} If there is no such enum\n */\nNamespace.prototype.getEnum = function getEnum(name) {\n if (this.nested && this.nested[name] instanceof Enum)\n return this.nested[name].values;\n throw Error(\"no such enum: \" + name);\n};\n\n/**\n * Adds a nested object to this namespace.\n * @param {ReflectionObject} object Nested object to add\n * @returns {Namespace} `this`\n * @throws {TypeError} If arguments are invalid\n * @throws {Error} If there is already a nested object with this name\n */\nNamespace.prototype.add = function add(object) {\n\n if (!(object instanceof Field && object.extend !== undefined || object instanceof Type || object instanceof OneOf || object instanceof Enum || object instanceof Service || object instanceof Namespace))\n throw TypeError(\"object must be a valid nested object\");\n\n if (!this.nested)\n this.nested = {};\n else {\n var prev = this.get(object.name);\n if (prev) {\n if (prev instanceof Namespace && object instanceof Namespace && !(prev instanceof Type || prev instanceof Service)) {\n // replace plain namespace but keep existing nested elements and options\n var nested = prev.nestedArray;\n for (var i = 0; i < nested.length; ++i)\n object.add(nested[i]);\n this.remove(prev);\n if (!this.nested)\n this.nested = {};\n object.setOptions(prev.options, true);\n\n } else\n throw Error(\"duplicate name '\" + object.name + \"' in \" + this);\n }\n }\n this.nested[object.name] = object;\n object.onAdd(this);\n return clearCache(this);\n};\n\n/**\n * Removes a nested object from this namespace.\n * @param {ReflectionObject} object Nested object to remove\n * @returns {Namespace} `this`\n * @throws {TypeError} If arguments are invalid\n * @throws {Error} If `object` is not a member of this namespace\n */\nNamespace.prototype.remove = function remove(object) {\n\n if (!(object instanceof ReflectionObject))\n throw TypeError(\"object must be a ReflectionObject\");\n if (object.parent !== this)\n throw Error(object + \" is not a member of \" + this);\n\n delete this.nested[object.name];\n if (!Object.keys(this.nested).length)\n this.nested = undefined;\n\n object.onRemove(this);\n return clearCache(this);\n};\n\n/**\n * Defines additial namespaces within this one if not yet existing.\n * @param {string|string[]} path Path to create\n * @param {*} [json] Nested types to create from JSON\n * @returns {Namespace} Pointer to the last namespace created or `this` if path is empty\n */\nNamespace.prototype.define = function define(path, json) {\n\n if (util.isString(path))\n path = path.split(\".\");\n else if (!Array.isArray(path))\n throw TypeError(\"illegal path\");\n if (path && path.length && path[0] === \"\")\n throw Error(\"path must be relative\");\n\n var ptr = this;\n while (path.length > 0) {\n var part = path.shift();\n if (ptr.nested && ptr.nested[part]) {\n ptr = ptr.nested[part];\n if (!(ptr instanceof Namespace))\n throw Error(\"path conflicts with non-namespace objects\");\n } else\n ptr.add(ptr = new Namespace(part));\n }\n if (json)\n ptr.addJSON(json);\n return ptr;\n};\n\n/**\n * Resolves this namespace's and all its nested objects' type references. Useful to validate a reflection tree, but comes at a cost.\n * @returns {Namespace} `this`\n */\nNamespace.prototype.resolveAll = function resolveAll() {\n var nested = this.nestedArray, i = 0;\n while (i < nested.length)\n if (nested[i] instanceof Namespace)\n nested[i++].resolveAll();\n else\n nested[i++].resolve();\n return this.resolve();\n};\n\n/**\n * Recursively looks up the reflection object matching the specified path in the scope of this namespace.\n * @param {string|string[]} path Path to look up\n * @param {*|Array.<*>} filterTypes Filter types, any combination of the constructors of `protobuf.Type`, `protobuf.Enum`, `protobuf.Service` etc.\n * @param {boolean} [parentAlreadyChecked=false] If known, whether the parent has already been checked\n * @returns {ReflectionObject|null} Looked up object or `null` if none could be found\n */\nNamespace.prototype.lookup = function lookup(path, filterTypes, parentAlreadyChecked) {\n\n /* istanbul ignore next */\n if (typeof filterTypes === \"boolean\") {\n parentAlreadyChecked = filterTypes;\n filterTypes = undefined;\n } else if (filterTypes && !Array.isArray(filterTypes))\n filterTypes = [ filterTypes ];\n\n if (util.isString(path) && path.length) {\n if (path === \".\")\n return this.root;\n path = path.split(\".\");\n } else if (!path.length)\n return this;\n\n // Start at root if path is absolute\n if (path[0] === \"\")\n return this.root.lookup(path.slice(1), filterTypes);\n\n // Test if the first part matches any nested object, and if so, traverse if path contains more\n var found = this.get(path[0]);\n if (found) {\n if (path.length === 1) {\n if (!filterTypes || filterTypes.indexOf(found.constructor) > -1)\n return found;\n } else if (found instanceof Namespace && (found = found.lookup(path.slice(1), filterTypes, true)))\n return found;\n\n // Otherwise try each nested namespace\n } else\n for (var i = 0; i < this.nestedArray.length; ++i)\n if (this._nestedArray[i] instanceof Namespace && (found = this._nestedArray[i].lookup(path, filterTypes, true)))\n return found;\n\n // If there hasn't been a match, try again at the parent\n if (this.parent === null || parentAlreadyChecked)\n return null;\n return this.parent.lookup(path, filterTypes);\n};\n\n/**\n * Looks up the reflection object at the specified path, relative to this namespace.\n * @name NamespaceBase#lookup\n * @function\n * @param {string|string[]} path Path to look up\n * @param {boolean} [parentAlreadyChecked=false] Whether the parent has already been checked\n * @returns {ReflectionObject|null} Looked up object or `null` if none could be found\n * @variation 2\n */\n// lookup(path: string, [parentAlreadyChecked: boolean])\n\n/**\n * Looks up the {@link Type|type} at the specified path, relative to this namespace.\n * Besides its signature, this methods differs from {@link Namespace#lookup|lookup} in that it throws instead of returning `null`.\n * @param {string|string[]} path Path to look up\n * @returns {Type} Looked up type\n * @throws {Error} If `path` does not point to a type\n */\nNamespace.prototype.lookupType = function lookupType(path) {\n var found = this.lookup(path, [ Type ]);\n if (!found)\n throw Error(\"no such type: \" + path);\n return found;\n};\n\n/**\n * Looks up the values of the {@link Enum|enum} at the specified path, relative to this namespace.\n * Besides its signature, this methods differs from {@link Namespace#lookup|lookup} in that it throws instead of returning `null`.\n * @param {string|string[]} path Path to look up\n * @returns {Enum} Looked up enum\n * @throws {Error} If `path` does not point to an enum\n */\nNamespace.prototype.lookupEnum = function lookupEnum(path) {\n var found = this.lookup(path, [ Enum ]);\n if (!found)\n throw Error(\"no such Enum '\" + path + \"' in \" + this);\n return found;\n};\n\n/**\n * Looks up the {@link Type|type} or {@link Enum|enum} at the specified path, relative to this namespace.\n * Besides its signature, this methods differs from {@link Namespace#lookup|lookup} in that it throws instead of returning `null`.\n * @param {string|string[]} path Path to look up\n * @returns {Type} Looked up type or enum\n * @throws {Error} If `path` does not point to a type or enum\n */\nNamespace.prototype.lookupTypeOrEnum = function lookupTypeOrEnum(path) {\n var found = this.lookup(path, [ Type, Enum ]);\n if (!found)\n throw Error(\"no such Type or Enum '\" + path + \"' in \" + this);\n return found;\n};\n\n/**\n * Looks up the {@link Service|service} at the specified path, relative to this namespace.\n * Besides its signature, this methods differs from {@link Namespace#lookup|lookup} in that it throws instead of returning `null`.\n * @param {string|string[]} path Path to look up\n * @returns {Service} Looked up service\n * @throws {Error} If `path` does not point to a service\n */\nNamespace.prototype.lookupService = function lookupService(path) {\n var found = this.lookup(path, [ Service ]);\n if (!found)\n throw Error(\"no such Service '\" + path + \"' in \" + this);\n return found;\n};\n\n// Sets up cyclic dependencies (called in index-light)\nNamespace._configure = function(Type_, Service_, Enum_) {\n Type = Type_;\n Service = Service_;\n Enum = Enum_;\n};\n","\"use strict\";\nmodule.exports = ReflectionObject;\n\nReflectionObject.className = \"ReflectionObject\";\n\nvar util = require(37);\n\nvar Root; // cyclic\n\n/**\n * Constructs a new reflection object instance.\n * @classdesc Base class of all reflection objects.\n * @constructor\n * @param {string} name Object name\n * @param {Object.} [options] Declared options\n * @abstract\n */\nfunction ReflectionObject(name, options) {\n\n if (!util.isString(name))\n throw TypeError(\"name must be a string\");\n\n if (options && !util.isObject(options))\n throw TypeError(\"options must be an object\");\n\n /**\n * Options.\n * @type {Object.|undefined}\n */\n this.options = options; // toJSON\n\n /**\n * Parsed Options.\n * @type {Array.>|undefined}\n */\n this.parsedOptions = null;\n\n /**\n * Unique name within its namespace.\n * @type {string}\n */\n this.name = name;\n\n /**\n * Parent namespace.\n * @type {Namespace|null}\n */\n this.parent = null;\n\n /**\n * Whether already resolved or not.\n * @type {boolean}\n */\n this.resolved = false;\n\n /**\n * Comment text, if any.\n * @type {string|null}\n */\n this.comment = null;\n\n /**\n * Defining file name.\n * @type {string|null}\n */\n this.filename = null;\n}\n\nObject.defineProperties(ReflectionObject.prototype, {\n\n /**\n * Reference to the root namespace.\n * @name ReflectionObject#root\n * @type {Root}\n * @readonly\n */\n root: {\n get: function() {\n var ptr = this;\n while (ptr.parent !== null)\n ptr = ptr.parent;\n return ptr;\n }\n },\n\n /**\n * Full name including leading dot.\n * @name ReflectionObject#fullName\n * @type {string}\n * @readonly\n */\n fullName: {\n get: function() {\n var path = [ this.name ],\n ptr = this.parent;\n while (ptr) {\n path.unshift(ptr.name);\n ptr = ptr.parent;\n }\n return path.join(\".\");\n }\n }\n});\n\n/**\n * Converts this reflection object to its descriptor representation.\n * @returns {Object.} Descriptor\n * @abstract\n */\nReflectionObject.prototype.toJSON = /* istanbul ignore next */ function toJSON() {\n throw Error(); // not implemented, shouldn't happen\n};\n\n/**\n * Called when this object is added to a parent.\n * @param {ReflectionObject} parent Parent added to\n * @returns {undefined}\n */\nReflectionObject.prototype.onAdd = function onAdd(parent) {\n if (this.parent && this.parent !== parent)\n this.parent.remove(this);\n this.parent = parent;\n this.resolved = false;\n var root = parent.root;\n if (root instanceof Root)\n root._handleAdd(this);\n};\n\n/**\n * Called when this object is removed from a parent.\n * @param {ReflectionObject} parent Parent removed from\n * @returns {undefined}\n */\nReflectionObject.prototype.onRemove = function onRemove(parent) {\n var root = parent.root;\n if (root instanceof Root)\n root._handleRemove(this);\n this.parent = null;\n this.resolved = false;\n};\n\n/**\n * Resolves this objects type references.\n * @returns {ReflectionObject} `this`\n */\nReflectionObject.prototype.resolve = function resolve() {\n if (this.resolved)\n return this;\n if (this.root instanceof Root)\n this.resolved = true; // only if part of a root\n return this;\n};\n\n/**\n * Gets an option value.\n * @param {string} name Option name\n * @returns {*} Option value or `undefined` if not set\n */\nReflectionObject.prototype.getOption = function getOption(name) {\n if (this.options)\n return this.options[name];\n return undefined;\n};\n\n/**\n * Sets an option.\n * @param {string} name Option name\n * @param {*} value Option value\n * @param {boolean} [ifNotSet] Sets the option only if it isn't currently set\n * @returns {ReflectionObject} `this`\n */\nReflectionObject.prototype.setOption = function setOption(name, value, ifNotSet) {\n if (!ifNotSet || !this.options || this.options[name] === undefined)\n (this.options || (this.options = {}))[name] = value;\n return this;\n};\n\n/**\n * Sets a parsed option.\n * @param {string} name parsed Option name\n * @param {*} value Option value\n * @param {string} propName dot '.' delimited full path of property within the option to set. if undefined\\empty, will add a new option with that value\n * @returns {ReflectionObject} `this`\n */\nReflectionObject.prototype.setParsedOption = function setParsedOption(name, value, propName) {\n if (!this.parsedOptions) {\n this.parsedOptions = [];\n }\n var parsedOptions = this.parsedOptions;\n if (propName) {\n // If setting a sub property of an option then try to merge it\n // with an existing option\n var opt = parsedOptions.find(function (opt) {\n return Object.prototype.hasOwnProperty.call(opt, name);\n });\n if (opt) {\n // If we found an existing option - just merge the property value\n var newValue = opt[name];\n util.setProperty(newValue, propName, value);\n } else {\n // otherwise, create a new option, set it's property and add it to the list\n opt = {};\n opt[name] = util.setProperty({}, propName, value);\n parsedOptions.push(opt);\n }\n } else {\n // Always create a new option when setting the value of the option itself\n var newOpt = {};\n newOpt[name] = value;\n parsedOptions.push(newOpt);\n }\n return this;\n};\n\n/**\n * Sets multiple options.\n * @param {Object.} options Options to set\n * @param {boolean} [ifNotSet] Sets an option only if it isn't currently set\n * @returns {ReflectionObject} `this`\n */\nReflectionObject.prototype.setOptions = function setOptions(options, ifNotSet) {\n if (options)\n for (var keys = Object.keys(options), i = 0; i < keys.length; ++i)\n this.setOption(keys[i], options[keys[i]], ifNotSet);\n return this;\n};\n\n/**\n * Converts this instance to its string representation.\n * @returns {string} Class name[, space, full name]\n */\nReflectionObject.prototype.toString = function toString() {\n var className = this.constructor.className,\n fullName = this.fullName;\n if (fullName.length)\n return className + \" \" + fullName;\n return className;\n};\n\n// Sets up cyclic dependencies (called in index-light)\nReflectionObject._configure = function(Root_) {\n Root = Root_;\n};\n","\"use strict\";\nmodule.exports = OneOf;\n\n// extends ReflectionObject\nvar ReflectionObject = require(24);\n((OneOf.prototype = Object.create(ReflectionObject.prototype)).constructor = OneOf).className = \"OneOf\";\n\nvar Field = require(16),\n util = require(37);\n\n/**\n * Constructs a new oneof instance.\n * @classdesc Reflected oneof.\n * @extends ReflectionObject\n * @constructor\n * @param {string} name Oneof name\n * @param {string[]|Object.} [fieldNames] Field names\n * @param {Object.} [options] Declared options\n * @param {string} [comment] Comment associated with this field\n */\nfunction OneOf(name, fieldNames, options, comment) {\n if (!Array.isArray(fieldNames)) {\n options = fieldNames;\n fieldNames = undefined;\n }\n ReflectionObject.call(this, name, options);\n\n /* istanbul ignore if */\n if (!(fieldNames === undefined || Array.isArray(fieldNames)))\n throw TypeError(\"fieldNames must be an Array\");\n\n /**\n * Field names that belong to this oneof.\n * @type {string[]}\n */\n this.oneof = fieldNames || []; // toJSON, marker\n\n /**\n * Fields that belong to this oneof as an array for iteration.\n * @type {Field[]}\n * @readonly\n */\n this.fieldsArray = []; // declared readonly for conformance, possibly not yet added to parent\n\n /**\n * Comment for this field.\n * @type {string|null}\n */\n this.comment = comment;\n}\n\n/**\n * Oneof descriptor.\n * @interface IOneOf\n * @property {Array.} oneof Oneof field names\n * @property {Object.} [options] Oneof options\n */\n\n/**\n * Constructs a oneof from a oneof descriptor.\n * @param {string} name Oneof name\n * @param {IOneOf} json Oneof descriptor\n * @returns {OneOf} Created oneof\n * @throws {TypeError} If arguments are invalid\n */\nOneOf.fromJSON = function fromJSON(name, json) {\n return new OneOf(name, json.oneof, json.options, json.comment);\n};\n\n/**\n * Converts this oneof to a oneof descriptor.\n * @param {IToJSONOptions} [toJSONOptions] JSON conversion options\n * @returns {IOneOf} Oneof descriptor\n */\nOneOf.prototype.toJSON = function toJSON(toJSONOptions) {\n var keepComments = toJSONOptions ? Boolean(toJSONOptions.keepComments) : false;\n return util.toObject([\n \"options\" , this.options,\n \"oneof\" , this.oneof,\n \"comment\" , keepComments ? this.comment : undefined\n ]);\n};\n\n/**\n * Adds the fields of the specified oneof to the parent if not already done so.\n * @param {OneOf} oneof The oneof\n * @returns {undefined}\n * @inner\n * @ignore\n */\nfunction addFieldsToParent(oneof) {\n if (oneof.parent)\n for (var i = 0; i < oneof.fieldsArray.length; ++i)\n if (!oneof.fieldsArray[i].parent)\n oneof.parent.add(oneof.fieldsArray[i]);\n}\n\n/**\n * Adds a field to this oneof and removes it from its current parent, if any.\n * @param {Field} field Field to add\n * @returns {OneOf} `this`\n */\nOneOf.prototype.add = function add(field) {\n\n /* istanbul ignore if */\n if (!(field instanceof Field))\n throw TypeError(\"field must be a Field\");\n\n if (field.parent && field.parent !== this.parent)\n field.parent.remove(field);\n this.oneof.push(field.name);\n this.fieldsArray.push(field);\n field.partOf = this; // field.parent remains null\n addFieldsToParent(this);\n return this;\n};\n\n/**\n * Removes a field from this oneof and puts it back to the oneof's parent.\n * @param {Field} field Field to remove\n * @returns {OneOf} `this`\n */\nOneOf.prototype.remove = function remove(field) {\n\n /* istanbul ignore if */\n if (!(field instanceof Field))\n throw TypeError(\"field must be a Field\");\n\n var index = this.fieldsArray.indexOf(field);\n\n /* istanbul ignore if */\n if (index < 0)\n throw Error(field + \" is not a member of \" + this);\n\n this.fieldsArray.splice(index, 1);\n index = this.oneof.indexOf(field.name);\n\n /* istanbul ignore else */\n if (index > -1) // theoretical\n this.oneof.splice(index, 1);\n\n field.partOf = null;\n return this;\n};\n\n/**\n * @override\n */\nOneOf.prototype.onAdd = function onAdd(parent) {\n ReflectionObject.prototype.onAdd.call(this, parent);\n var self = this;\n // Collect present fields\n for (var i = 0; i < this.oneof.length; ++i) {\n var field = parent.get(this.oneof[i]);\n if (field && !field.partOf) {\n field.partOf = self;\n self.fieldsArray.push(field);\n }\n }\n // Add not yet present fields\n addFieldsToParent(this);\n};\n\n/**\n * @override\n */\nOneOf.prototype.onRemove = function onRemove(parent) {\n for (var i = 0, field; i < this.fieldsArray.length; ++i)\n if ((field = this.fieldsArray[i]).parent)\n field.parent.remove(field);\n ReflectionObject.prototype.onRemove.call(this, parent);\n};\n\n/**\n * Decorator function as returned by {@link OneOf.d} (TypeScript).\n * @typedef OneOfDecorator\n * @type {function}\n * @param {Object} prototype Target prototype\n * @param {string} oneofName OneOf name\n * @returns {undefined}\n */\n\n/**\n * OneOf decorator (TypeScript).\n * @function\n * @param {...string} fieldNames Field names\n * @returns {OneOfDecorator} Decorator function\n * @template T extends string\n */\nOneOf.d = function decorateOneOf() {\n var fieldNames = new Array(arguments.length),\n index = 0;\n while (index < arguments.length)\n fieldNames[index] = arguments[index++];\n return function oneOfDecorator(prototype, oneofName) {\n util.decorateType(prototype.constructor)\n .add(new OneOf(oneofName, fieldNames));\n Object.defineProperty(prototype, oneofName, {\n get: util.oneOfGetter(fieldNames),\n set: util.oneOfSetter(fieldNames)\n });\n };\n};\n","\"use strict\";\nmodule.exports = parse;\n\nparse.filename = null;\nparse.defaults = { keepCase: false };\n\nvar tokenize = require(34),\n Root = require(29),\n Type = require(35),\n Field = require(16),\n MapField = require(20),\n OneOf = require(25),\n Enum = require(15),\n Service = require(33),\n Method = require(22),\n types = require(36),\n util = require(37);\n\nvar base10Re = /^[1-9][0-9]*$/,\n base10NegRe = /^-?[1-9][0-9]*$/,\n base16Re = /^0[x][0-9a-fA-F]+$/,\n base16NegRe = /^-?0[x][0-9a-fA-F]+$/,\n base8Re = /^0[0-7]+$/,\n base8NegRe = /^-?0[0-7]+$/,\n numberRe = /^(?![eE])[0-9]*(?:\\.[0-9]*)?(?:[eE][+-]?[0-9]+)?$/,\n nameRe = /^[a-zA-Z_][a-zA-Z_0-9]*$/,\n typeRefRe = /^(?:\\.?[a-zA-Z_][a-zA-Z_0-9]*)(?:\\.[a-zA-Z_][a-zA-Z_0-9]*)*$/,\n fqTypeRefRe = /^(?:\\.[a-zA-Z_][a-zA-Z_0-9]*)+$/;\n\n/**\n * Result object returned from {@link parse}.\n * @interface IParserResult\n * @property {string|undefined} package Package name, if declared\n * @property {string[]|undefined} imports Imports, if any\n * @property {string[]|undefined} weakImports Weak imports, if any\n * @property {string|undefined} syntax Syntax, if specified (either `\"proto2\"` or `\"proto3\"`)\n * @property {Root} root Populated root instance\n */\n\n/**\n * Options modifying the behavior of {@link parse}.\n * @interface IParseOptions\n * @property {boolean} [keepCase=false] Keeps field casing instead of converting to camel case\n * @property {boolean} [alternateCommentMode=false] Recognize double-slash comments in addition to doc-block comments.\n * @property {boolean} [preferTrailingComment=false] Use trailing comment when both leading comment and trailing comment exist.\n */\n\n/**\n * Options modifying the behavior of JSON serialization.\n * @interface IToJSONOptions\n * @property {boolean} [keepComments=false] Serializes comments.\n */\n\n/**\n * Parses the given .proto source and returns an object with the parsed contents.\n * @param {string} source Source contents\n * @param {Root} root Root to populate\n * @param {IParseOptions} [options] Parse options. Defaults to {@link parse.defaults} when omitted.\n * @returns {IParserResult} Parser result\n * @property {string} filename=null Currently processing file name for error reporting, if known\n * @property {IParseOptions} defaults Default {@link IParseOptions}\n */\nfunction parse(source, root, options) {\n /* eslint-disable callback-return */\n if (!(root instanceof Root)) {\n options = root;\n root = new Root();\n }\n if (!options)\n options = parse.defaults;\n\n var preferTrailingComment = options.preferTrailingComment || false;\n var tn = tokenize(source, options.alternateCommentMode || false),\n next = tn.next,\n push = tn.push,\n peek = tn.peek,\n skip = tn.skip,\n cmnt = tn.cmnt;\n\n var head = true,\n pkg,\n imports,\n weakImports,\n syntax,\n isProto3 = false;\n\n var ptr = root;\n\n var applyCase = options.keepCase ? function(name) { return name; } : util.camelCase;\n\n /* istanbul ignore next */\n function illegal(token, name, insideTryCatch) {\n var filename = parse.filename;\n if (!insideTryCatch)\n parse.filename = null;\n return Error(\"illegal \" + (name || \"token\") + \" '\" + token + \"' (\" + (filename ? filename + \", \" : \"\") + \"line \" + tn.line + \")\");\n }\n\n function readString() {\n var values = [],\n token;\n do {\n /* istanbul ignore if */\n if ((token = next()) !== \"\\\"\" && token !== \"'\")\n throw illegal(token);\n\n values.push(next());\n skip(token);\n token = peek();\n } while (token === \"\\\"\" || token === \"'\");\n return values.join(\"\");\n }\n\n function readValue(acceptTypeRef) {\n var token = next();\n switch (token) {\n case \"'\":\n case \"\\\"\":\n push(token);\n return readString();\n case \"true\": case \"TRUE\":\n return true;\n case \"false\": case \"FALSE\":\n return false;\n }\n try {\n return parseNumber(token, /* insideTryCatch */ true);\n } catch (e) {\n\n /* istanbul ignore else */\n if (acceptTypeRef && typeRefRe.test(token))\n return token;\n\n /* istanbul ignore next */\n throw illegal(token, \"value\");\n }\n }\n\n function readRanges(target, acceptStrings) {\n var token, start;\n do {\n if (acceptStrings && ((token = peek()) === \"\\\"\" || token === \"'\"))\n target.push(readString());\n else\n target.push([ start = parseId(next()), skip(\"to\", true) ? parseId(next()) : start ]);\n } while (skip(\",\", true));\n var dummy = {options: undefined};\n dummy.setOption = function(name, value) {\n if (this.options === undefined) this.options = {};\n this.options[name] = value;\n };\n ifBlock(\n dummy,\n function parseRange_block(token) {\n /* istanbul ignore else */\n if (token === \"option\") {\n parseOption(dummy, token); // skip\n skip(\";\");\n } else\n throw illegal(token);\n },\n function parseRange_line() {\n parseInlineOptions(dummy); // skip\n });\n }\n\n function parseNumber(token, insideTryCatch) {\n var sign = 1;\n if (token.charAt(0) === \"-\") {\n sign = -1;\n token = token.substring(1);\n }\n switch (token) {\n case \"inf\": case \"INF\": case \"Inf\":\n return sign * Infinity;\n case \"nan\": case \"NAN\": case \"Nan\": case \"NaN\":\n return NaN;\n case \"0\":\n return 0;\n }\n if (base10Re.test(token))\n return sign * parseInt(token, 10);\n if (base16Re.test(token))\n return sign * parseInt(token, 16);\n if (base8Re.test(token))\n return sign * parseInt(token, 8);\n\n /* istanbul ignore else */\n if (numberRe.test(token))\n return sign * parseFloat(token);\n\n /* istanbul ignore next */\n throw illegal(token, \"number\", insideTryCatch);\n }\n\n function parseId(token, acceptNegative) {\n switch (token) {\n case \"max\": case \"MAX\": case \"Max\":\n return 536870911;\n case \"0\":\n return 0;\n }\n\n /* istanbul ignore if */\n if (!acceptNegative && token.charAt(0) === \"-\")\n throw illegal(token, \"id\");\n\n if (base10NegRe.test(token))\n return parseInt(token, 10);\n if (base16NegRe.test(token))\n return parseInt(token, 16);\n\n /* istanbul ignore else */\n if (base8NegRe.test(token))\n return parseInt(token, 8);\n\n /* istanbul ignore next */\n throw illegal(token, \"id\");\n }\n\n function parsePackage() {\n\n /* istanbul ignore if */\n if (pkg !== undefined)\n throw illegal(\"package\");\n\n pkg = next();\n\n /* istanbul ignore if */\n if (!typeRefRe.test(pkg))\n throw illegal(pkg, \"name\");\n\n ptr = ptr.define(pkg);\n skip(\";\");\n }\n\n function parseImport() {\n var token = peek();\n var whichImports;\n switch (token) {\n case \"weak\":\n whichImports = weakImports || (weakImports = []);\n next();\n break;\n case \"public\":\n next();\n // eslint-disable-next-line no-fallthrough\n default:\n whichImports = imports || (imports = []);\n break;\n }\n token = readString();\n skip(\";\");\n whichImports.push(token);\n }\n\n function parseSyntax() {\n skip(\"=\");\n syntax = readString();\n isProto3 = syntax === \"proto3\";\n\n /* istanbul ignore if */\n if (!isProto3 && syntax !== \"proto2\")\n throw illegal(syntax, \"syntax\");\n\n skip(\";\");\n }\n\n function parseCommon(parent, token) {\n switch (token) {\n\n case \"option\":\n parseOption(parent, token);\n skip(\";\");\n return true;\n\n case \"message\":\n parseType(parent, token);\n return true;\n\n case \"enum\":\n parseEnum(parent, token);\n return true;\n\n case \"service\":\n parseService(parent, token);\n return true;\n\n case \"extend\":\n parseExtension(parent, token);\n return true;\n }\n return false;\n }\n\n function ifBlock(obj, fnIf, fnElse) {\n var trailingLine = tn.line;\n if (obj) {\n if(typeof obj.comment !== \"string\") {\n obj.comment = cmnt(); // try block-type comment\n }\n obj.filename = parse.filename;\n }\n if (skip(\"{\", true)) {\n var token;\n while ((token = next()) !== \"}\")\n fnIf(token);\n skip(\";\", true);\n } else {\n if (fnElse)\n fnElse();\n skip(\";\");\n if (obj && (typeof obj.comment !== \"string\" || preferTrailingComment))\n obj.comment = cmnt(trailingLine) || obj.comment; // try line-type comment\n }\n }\n\n function parseType(parent, token) {\n\n /* istanbul ignore if */\n if (!nameRe.test(token = next()))\n throw illegal(token, \"type name\");\n\n var type = new Type(token);\n ifBlock(type, function parseType_block(token) {\n if (parseCommon(type, token))\n return;\n\n switch (token) {\n\n case \"map\":\n parseMapField(type, token);\n break;\n\n case \"required\":\n case \"repeated\":\n parseField(type, token);\n break;\n\n case \"optional\":\n /* istanbul ignore if */\n if (isProto3) {\n parseField(type, \"proto3_optional\");\n } else {\n parseField(type, \"optional\");\n }\n break;\n\n case \"oneof\":\n parseOneOf(type, token);\n break;\n\n case \"extensions\":\n readRanges(type.extensions || (type.extensions = []));\n break;\n\n case \"reserved\":\n readRanges(type.reserved || (type.reserved = []), true);\n break;\n\n default:\n /* istanbul ignore if */\n if (!isProto3 || !typeRefRe.test(token))\n throw illegal(token);\n\n push(token);\n parseField(type, \"optional\");\n break;\n }\n });\n parent.add(type);\n }\n\n function parseField(parent, rule, extend) {\n var type = next();\n if (type === \"group\") {\n parseGroup(parent, rule);\n return;\n }\n // Type names can consume multiple tokens, in multiple variants:\n // package.subpackage field tokens: \"package.subpackage\" [TYPE NAME ENDS HERE] \"field\"\n // package . subpackage field tokens: \"package\" \".\" \"subpackage\" [TYPE NAME ENDS HERE] \"field\"\n // package. subpackage field tokens: \"package.\" \"subpackage\" [TYPE NAME ENDS HERE] \"field\"\n // package .subpackage field tokens: \"package\" \".subpackage\" [TYPE NAME ENDS HERE] \"field\"\n // Keep reading tokens until we get a type name with no period at the end,\n // and the next token does not start with a period.\n while (type.endsWith(\".\") || peek().startsWith(\".\")) {\n type += next();\n }\n\n /* istanbul ignore if */\n if (!typeRefRe.test(type))\n throw illegal(type, \"type\");\n\n var name = next();\n\n /* istanbul ignore if */\n if (!nameRe.test(name))\n throw illegal(name, \"name\");\n\n name = applyCase(name);\n skip(\"=\");\n\n var field = new Field(name, parseId(next()), type, rule, extend);\n ifBlock(field, function parseField_block(token) {\n\n /* istanbul ignore else */\n if (token === \"option\") {\n parseOption(field, token);\n skip(\";\");\n } else\n throw illegal(token);\n\n }, function parseField_line() {\n parseInlineOptions(field);\n });\n\n if (rule === \"proto3_optional\") {\n // for proto3 optional fields, we create a single-member Oneof to mimic \"optional\" behavior\n var oneof = new OneOf(\"_\" + name);\n field.setOption(\"proto3_optional\", true);\n oneof.add(field);\n parent.add(oneof);\n } else {\n parent.add(field);\n }\n\n // JSON defaults to packed=true if not set so we have to set packed=false explicity when\n // parsing proto2 descriptors without the option, where applicable. This must be done for\n // all known packable types and anything that could be an enum (= is not a basic type).\n if (!isProto3 && field.repeated && (types.packed[type] !== undefined || types.basic[type] === undefined))\n field.setOption(\"packed\", false, /* ifNotSet */ true);\n }\n\n function parseGroup(parent, rule) {\n var name = next();\n\n /* istanbul ignore if */\n if (!nameRe.test(name))\n throw illegal(name, \"name\");\n\n var fieldName = util.lcFirst(name);\n if (name === fieldName)\n name = util.ucFirst(name);\n skip(\"=\");\n var id = parseId(next());\n var type = new Type(name);\n type.group = true;\n var field = new Field(fieldName, id, name, rule);\n field.filename = parse.filename;\n ifBlock(type, function parseGroup_block(token) {\n switch (token) {\n\n case \"option\":\n parseOption(type, token);\n skip(\";\");\n break;\n\n case \"required\":\n case \"repeated\":\n parseField(type, token);\n break;\n\n case \"optional\":\n /* istanbul ignore if */\n if (isProto3) {\n parseField(type, \"proto3_optional\");\n } else {\n parseField(type, \"optional\");\n }\n break;\n\n case \"message\":\n parseType(type, token);\n break;\n\n case \"enum\":\n parseEnum(type, token);\n break;\n\n /* istanbul ignore next */\n default:\n throw illegal(token); // there are no groups with proto3 semantics\n }\n });\n parent.add(type)\n .add(field);\n }\n\n function parseMapField(parent) {\n skip(\"<\");\n var keyType = next();\n\n /* istanbul ignore if */\n if (types.mapKey[keyType] === undefined)\n throw illegal(keyType, \"type\");\n\n skip(\",\");\n var valueType = next();\n\n /* istanbul ignore if */\n if (!typeRefRe.test(valueType))\n throw illegal(valueType, \"type\");\n\n skip(\">\");\n var name = next();\n\n /* istanbul ignore if */\n if (!nameRe.test(name))\n throw illegal(name, \"name\");\n\n skip(\"=\");\n var field = new MapField(applyCase(name), parseId(next()), keyType, valueType);\n ifBlock(field, function parseMapField_block(token) {\n\n /* istanbul ignore else */\n if (token === \"option\") {\n parseOption(field, token);\n skip(\";\");\n } else\n throw illegal(token);\n\n }, function parseMapField_line() {\n parseInlineOptions(field);\n });\n parent.add(field);\n }\n\n function parseOneOf(parent, token) {\n\n /* istanbul ignore if */\n if (!nameRe.test(token = next()))\n throw illegal(token, \"name\");\n\n var oneof = new OneOf(applyCase(token));\n ifBlock(oneof, function parseOneOf_block(token) {\n if (token === \"option\") {\n parseOption(oneof, token);\n skip(\";\");\n } else {\n push(token);\n parseField(oneof, \"optional\");\n }\n });\n parent.add(oneof);\n }\n\n function parseEnum(parent, token) {\n\n /* istanbul ignore if */\n if (!nameRe.test(token = next()))\n throw illegal(token, \"name\");\n\n var enm = new Enum(token);\n ifBlock(enm, function parseEnum_block(token) {\n switch(token) {\n case \"option\":\n parseOption(enm, token);\n skip(\";\");\n break;\n\n case \"reserved\":\n readRanges(enm.reserved || (enm.reserved = []), true);\n break;\n\n default:\n parseEnumValue(enm, token);\n }\n });\n parent.add(enm);\n }\n\n function parseEnumValue(parent, token) {\n\n /* istanbul ignore if */\n if (!nameRe.test(token))\n throw illegal(token, \"name\");\n\n skip(\"=\");\n var value = parseId(next(), true),\n dummy = {\n options: undefined\n };\n dummy.setOption = function(name, value) {\n if (this.options === undefined)\n this.options = {};\n this.options[name] = value;\n };\n ifBlock(dummy, function parseEnumValue_block(token) {\n\n /* istanbul ignore else */\n if (token === \"option\") {\n parseOption(dummy, token); // skip\n skip(\";\");\n } else\n throw illegal(token);\n\n }, function parseEnumValue_line() {\n parseInlineOptions(dummy); // skip\n });\n parent.add(token, value, dummy.comment, dummy.options);\n }\n\n function parseOption(parent, token) {\n var isCustom = skip(\"(\", true);\n\n /* istanbul ignore if */\n if (!typeRefRe.test(token = next()))\n throw illegal(token, \"name\");\n\n var name = token;\n var option = name;\n var propName;\n\n if (isCustom) {\n skip(\")\");\n name = \"(\" + name + \")\";\n option = name;\n token = peek();\n if (fqTypeRefRe.test(token)) {\n propName = token.slice(1); //remove '.' before property name\n name += token;\n next();\n }\n }\n skip(\"=\");\n var optionValue = parseOptionValue(parent, name);\n setParsedOption(parent, option, optionValue, propName);\n }\n\n function parseOptionValue(parent, name) {\n // { a: \"foo\" b { c: \"bar\" } }\n if (skip(\"{\", true)) {\n var objectResult = {};\n\n while (!skip(\"}\", true)) {\n /* istanbul ignore if */\n if (!nameRe.test(token = next())) {\n throw illegal(token, \"name\");\n }\n if (token === null) {\n throw illegal(token, \"end of input\");\n }\n\n var value;\n var propName = token;\n\n skip(\":\", true);\n\n if (peek() === \"{\")\n value = parseOptionValue(parent, name + \".\" + token);\n else if (peek() === \"[\") {\n // option (my_option) = {\n // repeated_value: [ \"foo\", \"bar\" ]\n // };\n value = [];\n var lastValue;\n if (skip(\"[\", true)) {\n do {\n lastValue = readValue(true);\n value.push(lastValue);\n } while (skip(\",\", true));\n skip(\"]\");\n if (typeof lastValue !== \"undefined\") {\n setOption(parent, name + \".\" + token, lastValue);\n }\n }\n } else {\n value = readValue(true);\n setOption(parent, name + \".\" + token, value);\n }\n\n var prevValue = objectResult[propName];\n\n if (prevValue)\n value = [].concat(prevValue).concat(value);\n\n objectResult[propName] = value;\n\n // Semicolons and commas can be optional\n skip(\",\", true);\n skip(\";\", true);\n }\n\n return objectResult;\n }\n\n var simpleValue = readValue(true);\n setOption(parent, name, simpleValue);\n return simpleValue;\n // Does not enforce a delimiter to be universal\n }\n\n function setOption(parent, name, value) {\n if (parent.setOption)\n parent.setOption(name, value);\n }\n\n function setParsedOption(parent, name, value, propName) {\n if (parent.setParsedOption)\n parent.setParsedOption(name, value, propName);\n }\n\n function parseInlineOptions(parent) {\n if (skip(\"[\", true)) {\n do {\n parseOption(parent, \"option\");\n } while (skip(\",\", true));\n skip(\"]\");\n }\n return parent;\n }\n\n function parseService(parent, token) {\n\n /* istanbul ignore if */\n if (!nameRe.test(token = next()))\n throw illegal(token, \"service name\");\n\n var service = new Service(token);\n ifBlock(service, function parseService_block(token) {\n if (parseCommon(service, token))\n return;\n\n /* istanbul ignore else */\n if (token === \"rpc\")\n parseMethod(service, token);\n else\n throw illegal(token);\n });\n parent.add(service);\n }\n\n function parseMethod(parent, token) {\n // Get the comment of the preceding line now (if one exists) in case the\n // method is defined across multiple lines.\n var commentText = cmnt();\n\n var type = token;\n\n /* istanbul ignore if */\n if (!nameRe.test(token = next()))\n throw illegal(token, \"name\");\n\n var name = token,\n requestType, requestStream,\n responseType, responseStream;\n\n skip(\"(\");\n if (skip(\"stream\", true))\n requestStream = true;\n\n /* istanbul ignore if */\n if (!typeRefRe.test(token = next()))\n throw illegal(token);\n\n requestType = token;\n skip(\")\"); skip(\"returns\"); skip(\"(\");\n if (skip(\"stream\", true))\n responseStream = true;\n\n /* istanbul ignore if */\n if (!typeRefRe.test(token = next()))\n throw illegal(token);\n\n responseType = token;\n skip(\")\");\n\n var method = new Method(name, type, requestType, responseType, requestStream, responseStream);\n method.comment = commentText;\n ifBlock(method, function parseMethod_block(token) {\n\n /* istanbul ignore else */\n if (token === \"option\") {\n parseOption(method, token);\n skip(\";\");\n } else\n throw illegal(token);\n\n });\n parent.add(method);\n }\n\n function parseExtension(parent, token) {\n\n /* istanbul ignore if */\n if (!typeRefRe.test(token = next()))\n throw illegal(token, \"reference\");\n\n var reference = token;\n ifBlock(null, function parseExtension_block(token) {\n switch (token) {\n\n case \"required\":\n case \"repeated\":\n parseField(parent, token, reference);\n break;\n\n case \"optional\":\n /* istanbul ignore if */\n if (isProto3) {\n parseField(parent, \"proto3_optional\", reference);\n } else {\n parseField(parent, \"optional\", reference);\n }\n break;\n\n default:\n /* istanbul ignore if */\n if (!isProto3 || !typeRefRe.test(token))\n throw illegal(token);\n push(token);\n parseField(parent, \"optional\", reference);\n break;\n }\n });\n }\n\n var token;\n while ((token = next()) !== null) {\n switch (token) {\n\n case \"package\":\n\n /* istanbul ignore if */\n if (!head)\n throw illegal(token);\n\n parsePackage();\n break;\n\n case \"import\":\n\n /* istanbul ignore if */\n if (!head)\n throw illegal(token);\n\n parseImport();\n break;\n\n case \"syntax\":\n\n /* istanbul ignore if */\n if (!head)\n throw illegal(token);\n\n parseSyntax();\n break;\n\n case \"option\":\n\n parseOption(ptr, token);\n skip(\";\");\n break;\n\n default:\n\n /* istanbul ignore else */\n if (parseCommon(ptr, token)) {\n head = false;\n continue;\n }\n\n /* istanbul ignore next */\n throw illegal(token);\n }\n }\n\n parse.filename = null;\n return {\n \"package\" : pkg,\n \"imports\" : imports,\n weakImports : weakImports,\n syntax : syntax,\n root : root\n };\n}\n\n/**\n * Parses the given .proto source and returns an object with the parsed contents.\n * @name parse\n * @function\n * @param {string} source Source contents\n * @param {IParseOptions} [options] Parse options. Defaults to {@link parse.defaults} when omitted.\n * @returns {IParserResult} Parser result\n * @property {string} filename=null Currently processing file name for error reporting, if known\n * @property {IParseOptions} defaults Default {@link IParseOptions}\n * @variation 2\n */\n","\"use strict\";\nmodule.exports = Reader;\n\nvar util = require(39);\n\nvar BufferReader; // cyclic\n\nvar LongBits = util.LongBits,\n utf8 = util.utf8;\n\n/* istanbul ignore next */\nfunction indexOutOfRange(reader, writeLength) {\n return RangeError(\"index out of range: \" + reader.pos + \" + \" + (writeLength || 1) + \" > \" + reader.len);\n}\n\n/**\n * Constructs a new reader instance using the specified buffer.\n * @classdesc Wire format reader using `Uint8Array` if available, otherwise `Array`.\n * @constructor\n * @param {Uint8Array} buffer Buffer to read from\n */\nfunction Reader(buffer) {\n\n /**\n * Read buffer.\n * @type {Uint8Array}\n */\n this.buf = buffer;\n\n /**\n * Read buffer position.\n * @type {number}\n */\n this.pos = 0;\n\n /**\n * Read buffer length.\n * @type {number}\n */\n this.len = buffer.length;\n}\n\nvar create_array = typeof Uint8Array !== \"undefined\"\n ? function create_typed_array(buffer) {\n if (buffer instanceof Uint8Array || Array.isArray(buffer))\n return new Reader(buffer);\n throw Error(\"illegal buffer\");\n }\n /* istanbul ignore next */\n : function create_array(buffer) {\n if (Array.isArray(buffer))\n return new Reader(buffer);\n throw Error(\"illegal buffer\");\n };\n\nvar create = function create() {\n return util.Buffer\n ? function create_buffer_setup(buffer) {\n return (Reader.create = function create_buffer(buffer) {\n return util.Buffer.isBuffer(buffer)\n ? new BufferReader(buffer)\n /* istanbul ignore next */\n : create_array(buffer);\n })(buffer);\n }\n /* istanbul ignore next */\n : create_array;\n};\n\n/**\n * Creates a new reader using the specified buffer.\n * @function\n * @param {Uint8Array|Buffer} buffer Buffer to read from\n * @returns {Reader|BufferReader} A {@link BufferReader} if `buffer` is a Buffer, otherwise a {@link Reader}\n * @throws {Error} If `buffer` is not a valid buffer\n */\nReader.create = create();\n\nReader.prototype._slice = util.Array.prototype.subarray || /* istanbul ignore next */ util.Array.prototype.slice;\n\n/**\n * Reads a varint as an unsigned 32 bit value.\n * @function\n * @returns {number} Value read\n */\nReader.prototype.uint32 = (function read_uint32_setup() {\n var value = 4294967295; // optimizer type-hint, tends to deopt otherwise (?!)\n return function read_uint32() {\n value = ( this.buf[this.pos] & 127 ) >>> 0; if (this.buf[this.pos++] < 128) return value;\n value = (value | (this.buf[this.pos] & 127) << 7) >>> 0; if (this.buf[this.pos++] < 128) return value;\n value = (value | (this.buf[this.pos] & 127) << 14) >>> 0; if (this.buf[this.pos++] < 128) return value;\n value = (value | (this.buf[this.pos] & 127) << 21) >>> 0; if (this.buf[this.pos++] < 128) return value;\n value = (value | (this.buf[this.pos] & 15) << 28) >>> 0; if (this.buf[this.pos++] < 128) return value;\n\n /* istanbul ignore if */\n if ((this.pos += 5) > this.len) {\n this.pos = this.len;\n throw indexOutOfRange(this, 10);\n }\n return value;\n };\n})();\n\n/**\n * Reads a varint as a signed 32 bit value.\n * @returns {number} Value read\n */\nReader.prototype.int32 = function read_int32() {\n return this.uint32() | 0;\n};\n\n/**\n * Reads a zig-zag encoded varint as a signed 32 bit value.\n * @returns {number} Value read\n */\nReader.prototype.sint32 = function read_sint32() {\n var value = this.uint32();\n return value >>> 1 ^ -(value & 1) | 0;\n};\n\n/* eslint-disable no-invalid-this */\n\nfunction readLongVarint() {\n // tends to deopt with local vars for octet etc.\n var bits = new LongBits(0, 0);\n var i = 0;\n if (this.len - this.pos > 4) { // fast route (lo)\n for (; i < 4; ++i) {\n // 1st..4th\n bits.lo = (bits.lo | (this.buf[this.pos] & 127) << i * 7) >>> 0;\n if (this.buf[this.pos++] < 128)\n return bits;\n }\n // 5th\n bits.lo = (bits.lo | (this.buf[this.pos] & 127) << 28) >>> 0;\n bits.hi = (bits.hi | (this.buf[this.pos] & 127) >> 4) >>> 0;\n if (this.buf[this.pos++] < 128)\n return bits;\n i = 0;\n } else {\n for (; i < 3; ++i) {\n /* istanbul ignore if */\n if (this.pos >= this.len)\n throw indexOutOfRange(this);\n // 1st..3th\n bits.lo = (bits.lo | (this.buf[this.pos] & 127) << i * 7) >>> 0;\n if (this.buf[this.pos++] < 128)\n return bits;\n }\n // 4th\n bits.lo = (bits.lo | (this.buf[this.pos++] & 127) << i * 7) >>> 0;\n return bits;\n }\n if (this.len - this.pos > 4) { // fast route (hi)\n for (; i < 5; ++i) {\n // 6th..10th\n bits.hi = (bits.hi | (this.buf[this.pos] & 127) << i * 7 + 3) >>> 0;\n if (this.buf[this.pos++] < 128)\n return bits;\n }\n } else {\n for (; i < 5; ++i) {\n /* istanbul ignore if */\n if (this.pos >= this.len)\n throw indexOutOfRange(this);\n // 6th..10th\n bits.hi = (bits.hi | (this.buf[this.pos] & 127) << i * 7 + 3) >>> 0;\n if (this.buf[this.pos++] < 128)\n return bits;\n }\n }\n /* istanbul ignore next */\n throw Error(\"invalid varint encoding\");\n}\n\n/* eslint-enable no-invalid-this */\n\n/**\n * Reads a varint as a signed 64 bit value.\n * @name Reader#int64\n * @function\n * @returns {Long} Value read\n */\n\n/**\n * Reads a varint as an unsigned 64 bit value.\n * @name Reader#uint64\n * @function\n * @returns {Long} Value read\n */\n\n/**\n * Reads a zig-zag encoded varint as a signed 64 bit value.\n * @name Reader#sint64\n * @function\n * @returns {Long} Value read\n */\n\n/**\n * Reads a varint as a boolean.\n * @returns {boolean} Value read\n */\nReader.prototype.bool = function read_bool() {\n return this.uint32() !== 0;\n};\n\nfunction readFixed32_end(buf, end) { // note that this uses `end`, not `pos`\n return (buf[end - 4]\n | buf[end - 3] << 8\n | buf[end - 2] << 16\n | buf[end - 1] << 24) >>> 0;\n}\n\n/**\n * Reads fixed 32 bits as an unsigned 32 bit integer.\n * @returns {number} Value read\n */\nReader.prototype.fixed32 = function read_fixed32() {\n\n /* istanbul ignore if */\n if (this.pos + 4 > this.len)\n throw indexOutOfRange(this, 4);\n\n return readFixed32_end(this.buf, this.pos += 4);\n};\n\n/**\n * Reads fixed 32 bits as a signed 32 bit integer.\n * @returns {number} Value read\n */\nReader.prototype.sfixed32 = function read_sfixed32() {\n\n /* istanbul ignore if */\n if (this.pos + 4 > this.len)\n throw indexOutOfRange(this, 4);\n\n return readFixed32_end(this.buf, this.pos += 4) | 0;\n};\n\n/* eslint-disable no-invalid-this */\n\nfunction readFixed64(/* this: Reader */) {\n\n /* istanbul ignore if */\n if (this.pos + 8 > this.len)\n throw indexOutOfRange(this, 8);\n\n return new LongBits(readFixed32_end(this.buf, this.pos += 4), readFixed32_end(this.buf, this.pos += 4));\n}\n\n/* eslint-enable no-invalid-this */\n\n/**\n * Reads fixed 64 bits.\n * @name Reader#fixed64\n * @function\n * @returns {Long} Value read\n */\n\n/**\n * Reads zig-zag encoded fixed 64 bits.\n * @name Reader#sfixed64\n * @function\n * @returns {Long} Value read\n */\n\n/**\n * Reads a float (32 bit) as a number.\n * @function\n * @returns {number} Value read\n */\nReader.prototype.float = function read_float() {\n\n /* istanbul ignore if */\n if (this.pos + 4 > this.len)\n throw indexOutOfRange(this, 4);\n\n var value = util.float.readFloatLE(this.buf, this.pos);\n this.pos += 4;\n return value;\n};\n\n/**\n * Reads a double (64 bit float) as a number.\n * @function\n * @returns {number} Value read\n */\nReader.prototype.double = function read_double() {\n\n /* istanbul ignore if */\n if (this.pos + 8 > this.len)\n throw indexOutOfRange(this, 4);\n\n var value = util.float.readDoubleLE(this.buf, this.pos);\n this.pos += 8;\n return value;\n};\n\n/**\n * Reads a sequence of bytes preceeded by its length as a varint.\n * @returns {Uint8Array} Value read\n */\nReader.prototype.bytes = function read_bytes() {\n var length = this.uint32(),\n start = this.pos,\n end = this.pos + length;\n\n /* istanbul ignore if */\n if (end > this.len)\n throw indexOutOfRange(this, length);\n\n this.pos += length;\n if (Array.isArray(this.buf)) // plain array\n return this.buf.slice(start, end);\n\n if (start === end) { // fix for IE 10/Win8 and others' subarray returning array of size 1\n var nativeBuffer = util.Buffer;\n return nativeBuffer\n ? nativeBuffer.alloc(0)\n : new this.buf.constructor(0);\n }\n return this._slice.call(this.buf, start, end);\n};\n\n/**\n * Reads a string preceeded by its byte length as a varint.\n * @returns {string} Value read\n */\nReader.prototype.string = function read_string() {\n var bytes = this.bytes();\n return utf8.read(bytes, 0, bytes.length);\n};\n\n/**\n * Skips the specified number of bytes if specified, otherwise skips a varint.\n * @param {number} [length] Length if known, otherwise a varint is assumed\n * @returns {Reader} `this`\n */\nReader.prototype.skip = function skip(length) {\n if (typeof length === \"number\") {\n /* istanbul ignore if */\n if (this.pos + length > this.len)\n throw indexOutOfRange(this, length);\n this.pos += length;\n } else {\n do {\n /* istanbul ignore if */\n if (this.pos >= this.len)\n throw indexOutOfRange(this);\n } while (this.buf[this.pos++] & 128);\n }\n return this;\n};\n\n/**\n * Skips the next element of the specified wire type.\n * @param {number} wireType Wire type received\n * @returns {Reader} `this`\n */\nReader.prototype.skipType = function(wireType) {\n switch (wireType) {\n case 0:\n this.skip();\n break;\n case 1:\n this.skip(8);\n break;\n case 2:\n this.skip(this.uint32());\n break;\n case 3:\n while ((wireType = this.uint32() & 7) !== 4) {\n this.skipType(wireType);\n }\n break;\n case 5:\n this.skip(4);\n break;\n\n /* istanbul ignore next */\n default:\n throw Error(\"invalid wire type \" + wireType + \" at offset \" + this.pos);\n }\n return this;\n};\n\nReader._configure = function(BufferReader_) {\n BufferReader = BufferReader_;\n Reader.create = create();\n BufferReader._configure();\n\n var fn = util.Long ? \"toLong\" : /* istanbul ignore next */ \"toNumber\";\n util.merge(Reader.prototype, {\n\n int64: function read_int64() {\n return readLongVarint.call(this)[fn](false);\n },\n\n uint64: function read_uint64() {\n return readLongVarint.call(this)[fn](true);\n },\n\n sint64: function read_sint64() {\n return readLongVarint.call(this).zzDecode()[fn](false);\n },\n\n fixed64: function read_fixed64() {\n return readFixed64.call(this)[fn](true);\n },\n\n sfixed64: function read_sfixed64() {\n return readFixed64.call(this)[fn](false);\n }\n\n });\n};\n","\"use strict\";\nmodule.exports = BufferReader;\n\n// extends Reader\nvar Reader = require(27);\n(BufferReader.prototype = Object.create(Reader.prototype)).constructor = BufferReader;\n\nvar util = require(39);\n\n/**\n * Constructs a new buffer reader instance.\n * @classdesc Wire format reader using node buffers.\n * @extends Reader\n * @constructor\n * @param {Buffer} buffer Buffer to read from\n */\nfunction BufferReader(buffer) {\n Reader.call(this, buffer);\n\n /**\n * Read buffer.\n * @name BufferReader#buf\n * @type {Buffer}\n */\n}\n\nBufferReader._configure = function () {\n /* istanbul ignore else */\n if (util.Buffer)\n BufferReader.prototype._slice = util.Buffer.prototype.slice;\n};\n\n\n/**\n * @override\n */\nBufferReader.prototype.string = function read_string_buffer() {\n var len = this.uint32(); // modifies pos\n return this.buf.utf8Slice\n ? this.buf.utf8Slice(this.pos, this.pos = Math.min(this.pos + len, this.len))\n : this.buf.toString(\"utf-8\", this.pos, this.pos = Math.min(this.pos + len, this.len));\n};\n\n/**\n * Reads a sequence of bytes preceeded by its length as a varint.\n * @name BufferReader#bytes\n * @function\n * @returns {Buffer} Value read\n */\n\nBufferReader._configure();\n","\"use strict\";\nmodule.exports = Root;\n\n// extends Namespace\nvar Namespace = require(23);\n((Root.prototype = Object.create(Namespace.prototype)).constructor = Root).className = \"Root\";\n\nvar Field = require(16),\n Enum = require(15),\n OneOf = require(25),\n util = require(37);\n\nvar Type, // cyclic\n parse, // might be excluded\n common; // \"\n\n/**\n * Constructs a new root namespace instance.\n * @classdesc Root namespace wrapping all types, enums, services, sub-namespaces etc. that belong together.\n * @extends NamespaceBase\n * @constructor\n * @param {Object.} [options] Top level options\n */\nfunction Root(options) {\n Namespace.call(this, \"\", options);\n\n /**\n * Deferred extension fields.\n * @type {Field[]}\n */\n this.deferred = [];\n\n /**\n * Resolved file names of loaded files.\n * @type {string[]}\n */\n this.files = [];\n}\n\n/**\n * Loads a namespace descriptor into a root namespace.\n * @param {INamespace} json Nameespace descriptor\n * @param {Root} [root] Root namespace, defaults to create a new one if omitted\n * @returns {Root} Root namespace\n */\nRoot.fromJSON = function fromJSON(json, root) {\n if (!root)\n root = new Root();\n if (json.options)\n root.setOptions(json.options);\n return root.addJSON(json.nested);\n};\n\n/**\n * Resolves the path of an imported file, relative to the importing origin.\n * This method exists so you can override it with your own logic in case your imports are scattered over multiple directories.\n * @function\n * @param {string} origin The file name of the importing file\n * @param {string} target The file name being imported\n * @returns {string|null} Resolved path to `target` or `null` to skip the file\n */\nRoot.prototype.resolvePath = util.path.resolve;\n\n/**\n * Fetch content from file path or url\n * This method exists so you can override it with your own logic.\n * @function\n * @param {string} path File path or url\n * @param {FetchCallback} callback Callback function\n * @returns {undefined}\n */\nRoot.prototype.fetch = util.fetch;\n\n// A symbol-like function to safely signal synchronous loading\n/* istanbul ignore next */\nfunction SYNC() {} // eslint-disable-line no-empty-function\n\n/**\n * Loads one or multiple .proto or preprocessed .json files into this root namespace and calls the callback.\n * @param {string|string[]} filename Names of one or multiple files to load\n * @param {IParseOptions} options Parse options\n * @param {LoadCallback} callback Callback function\n * @returns {undefined}\n */\nRoot.prototype.load = function load(filename, options, callback) {\n if (typeof options === \"function\") {\n callback = options;\n options = undefined;\n }\n var self = this;\n if (!callback)\n return util.asPromise(load, self, filename, options);\n\n var sync = callback === SYNC; // undocumented\n\n // Finishes loading by calling the callback (exactly once)\n function finish(err, root) {\n /* istanbul ignore if */\n if (!callback)\n return;\n if (sync)\n throw err;\n var cb = callback;\n callback = null;\n cb(err, root);\n }\n\n // Bundled definition existence checking\n function getBundledFileName(filename) {\n var idx = filename.lastIndexOf(\"google/protobuf/\");\n if (idx > -1) {\n var altname = filename.substring(idx);\n if (altname in common) return altname;\n }\n return null;\n }\n\n // Processes a single file\n function process(filename, source) {\n try {\n if (util.isString(source) && source.charAt(0) === \"{\")\n source = JSON.parse(source);\n if (!util.isString(source))\n self.setOptions(source.options).addJSON(source.nested);\n else {\n parse.filename = filename;\n var parsed = parse(source, self, options),\n resolved,\n i = 0;\n if (parsed.imports)\n for (; i < parsed.imports.length; ++i)\n if (resolved = getBundledFileName(parsed.imports[i]) || self.resolvePath(filename, parsed.imports[i]))\n fetch(resolved);\n if (parsed.weakImports)\n for (i = 0; i < parsed.weakImports.length; ++i)\n if (resolved = getBundledFileName(parsed.weakImports[i]) || self.resolvePath(filename, parsed.weakImports[i]))\n fetch(resolved, true);\n }\n } catch (err) {\n finish(err);\n }\n if (!sync && !queued)\n finish(null, self); // only once anyway\n }\n\n // Fetches a single file\n function fetch(filename, weak) {\n filename = getBundledFileName(filename) || filename;\n\n // Skip if already loaded / attempted\n if (self.files.indexOf(filename) > -1)\n return;\n self.files.push(filename);\n\n // Shortcut bundled definitions\n if (filename in common) {\n if (sync)\n process(filename, common[filename]);\n else {\n ++queued;\n setTimeout(function() {\n --queued;\n process(filename, common[filename]);\n });\n }\n return;\n }\n\n // Otherwise fetch from disk or network\n if (sync) {\n var source;\n try {\n source = util.fs.readFileSync(filename).toString(\"utf8\");\n } catch (err) {\n if (!weak)\n finish(err);\n return;\n }\n process(filename, source);\n } else {\n ++queued;\n self.fetch(filename, function(err, source) {\n --queued;\n /* istanbul ignore if */\n if (!callback)\n return; // terminated meanwhile\n if (err) {\n /* istanbul ignore else */\n if (!weak)\n finish(err);\n else if (!queued) // can't be covered reliably\n finish(null, self);\n return;\n }\n process(filename, source);\n });\n }\n }\n var queued = 0;\n\n // Assembling the root namespace doesn't require working type\n // references anymore, so we can load everything in parallel\n if (util.isString(filename))\n filename = [ filename ];\n for (var i = 0, resolved; i < filename.length; ++i)\n if (resolved = self.resolvePath(\"\", filename[i]))\n fetch(resolved);\n\n if (sync)\n return self;\n if (!queued)\n finish(null, self);\n return undefined;\n};\n// function load(filename:string, options:IParseOptions, callback:LoadCallback):undefined\n\n/**\n * Loads one or multiple .proto or preprocessed .json files into this root namespace and calls the callback.\n * @function Root#load\n * @param {string|string[]} filename Names of one or multiple files to load\n * @param {LoadCallback} callback Callback function\n * @returns {undefined}\n * @variation 2\n */\n// function load(filename:string, callback:LoadCallback):undefined\n\n/**\n * Loads one or multiple .proto or preprocessed .json files into this root namespace and returns a promise.\n * @function Root#load\n * @param {string|string[]} filename Names of one or multiple files to load\n * @param {IParseOptions} [options] Parse options. Defaults to {@link parse.defaults} when omitted.\n * @returns {Promise} Promise\n * @variation 3\n */\n// function load(filename:string, [options:IParseOptions]):Promise\n\n/**\n * Synchronously loads one or multiple .proto or preprocessed .json files into this root namespace (node only).\n * @function Root#loadSync\n * @param {string|string[]} filename Names of one or multiple files to load\n * @param {IParseOptions} [options] Parse options. Defaults to {@link parse.defaults} when omitted.\n * @returns {Root} Root namespace\n * @throws {Error} If synchronous fetching is not supported (i.e. in browsers) or if a file's syntax is invalid\n */\nRoot.prototype.loadSync = function loadSync(filename, options) {\n if (!util.isNode)\n throw Error(\"not supported\");\n return this.load(filename, options, SYNC);\n};\n\n/**\n * @override\n */\nRoot.prototype.resolveAll = function resolveAll() {\n if (this.deferred.length)\n throw Error(\"unresolvable extensions: \" + this.deferred.map(function(field) {\n return \"'extend \" + field.extend + \"' in \" + field.parent.fullName;\n }).join(\", \"));\n return Namespace.prototype.resolveAll.call(this);\n};\n\n// only uppercased (and thus conflict-free) children are exposed, see below\nvar exposeRe = /^[A-Z]/;\n\n/**\n * Handles a deferred declaring extension field by creating a sister field to represent it within its extended type.\n * @param {Root} root Root instance\n * @param {Field} field Declaring extension field witin the declaring type\n * @returns {boolean} `true` if successfully added to the extended type, `false` otherwise\n * @inner\n * @ignore\n */\nfunction tryHandleExtension(root, field) {\n var extendedType = field.parent.lookup(field.extend);\n if (extendedType) {\n var sisterField = new Field(field.fullName, field.id, field.type, field.rule, undefined, field.options);\n //do not allow to extend same field twice to prevent the error\n if (extendedType.get(sisterField.name)) {\n return true;\n }\n sisterField.declaringField = field;\n field.extensionField = sisterField;\n extendedType.add(sisterField);\n return true;\n }\n return false;\n}\n\n/**\n * Called when any object is added to this root or its sub-namespaces.\n * @param {ReflectionObject} object Object added\n * @returns {undefined}\n * @private\n */\nRoot.prototype._handleAdd = function _handleAdd(object) {\n if (object instanceof Field) {\n\n if (/* an extension field (implies not part of a oneof) */ object.extend !== undefined && /* not already handled */ !object.extensionField)\n if (!tryHandleExtension(this, object))\n this.deferred.push(object);\n\n } else if (object instanceof Enum) {\n\n if (exposeRe.test(object.name))\n object.parent[object.name] = object.values; // expose enum values as property of its parent\n\n } else if (!(object instanceof OneOf)) /* everything else is a namespace */ {\n\n if (object instanceof Type) // Try to handle any deferred extensions\n for (var i = 0; i < this.deferred.length;)\n if (tryHandleExtension(this, this.deferred[i]))\n this.deferred.splice(i, 1);\n else\n ++i;\n for (var j = 0; j < /* initializes */ object.nestedArray.length; ++j) // recurse into the namespace\n this._handleAdd(object._nestedArray[j]);\n if (exposeRe.test(object.name))\n object.parent[object.name] = object; // expose namespace as property of its parent\n }\n\n // The above also adds uppercased (and thus conflict-free) nested types, services and enums as\n // properties of namespaces just like static code does. This allows using a .d.ts generated for\n // a static module with reflection-based solutions where the condition is met.\n};\n\n/**\n * Called when any object is removed from this root or its sub-namespaces.\n * @param {ReflectionObject} object Object removed\n * @returns {undefined}\n * @private\n */\nRoot.prototype._handleRemove = function _handleRemove(object) {\n if (object instanceof Field) {\n\n if (/* an extension field */ object.extend !== undefined) {\n if (/* already handled */ object.extensionField) { // remove its sister field\n object.extensionField.parent.remove(object.extensionField);\n object.extensionField = null;\n } else { // cancel the extension\n var index = this.deferred.indexOf(object);\n /* istanbul ignore else */\n if (index > -1)\n this.deferred.splice(index, 1);\n }\n }\n\n } else if (object instanceof Enum) {\n\n if (exposeRe.test(object.name))\n delete object.parent[object.name]; // unexpose enum values\n\n } else if (object instanceof Namespace) {\n\n for (var i = 0; i < /* initializes */ object.nestedArray.length; ++i) // recurse into the namespace\n this._handleRemove(object._nestedArray[i]);\n\n if (exposeRe.test(object.name))\n delete object.parent[object.name]; // unexpose namespaces\n\n }\n};\n\n// Sets up cyclic dependencies (called in index-light)\nRoot._configure = function(Type_, parse_, common_) {\n Type = Type_;\n parse = parse_;\n common = common_;\n};\n","\"use strict\";\nmodule.exports = {};\n\n/**\n * Named roots.\n * This is where pbjs stores generated structures (the option `-r, --root` specifies a name).\n * Can also be used manually to make roots available across modules.\n * @name roots\n * @type {Object.}\n * @example\n * // pbjs -r myroot -o compiled.js ...\n *\n * // in another module:\n * require(\"./compiled.js\");\n *\n * // in any subsequent module:\n * var root = protobuf.roots[\"myroot\"];\n */\n","\"use strict\";\n\n/**\n * Streaming RPC helpers.\n * @namespace\n */\nvar rpc = exports;\n\n/**\n * RPC implementation passed to {@link Service#create} performing a service request on network level, i.e. by utilizing http requests or websockets.\n * @typedef RPCImpl\n * @type {function}\n * @param {Method|rpc.ServiceMethod,Message<{}>>} method Reflected or static method being called\n * @param {Uint8Array} requestData Request data\n * @param {RPCImplCallback} callback Callback function\n * @returns {undefined}\n * @example\n * function rpcImpl(method, requestData, callback) {\n * if (protobuf.util.lcFirst(method.name) !== \"myMethod\") // compatible with static code\n * throw Error(\"no such method\");\n * asynchronouslyObtainAResponse(requestData, function(err, responseData) {\n * callback(err, responseData);\n * });\n * }\n */\n\n/**\n * Node-style callback as used by {@link RPCImpl}.\n * @typedef RPCImplCallback\n * @type {function}\n * @param {Error|null} error Error, if any, otherwise `null`\n * @param {Uint8Array|null} [response] Response data or `null` to signal end of stream, if there hasn't been an error\n * @returns {undefined}\n */\n\nrpc.Service = require(32);\n","\"use strict\";\nmodule.exports = Service;\n\nvar util = require(39);\n\n// Extends EventEmitter\n(Service.prototype = Object.create(util.EventEmitter.prototype)).constructor = Service;\n\n/**\n * A service method callback as used by {@link rpc.ServiceMethod|ServiceMethod}.\n *\n * Differs from {@link RPCImplCallback} in that it is an actual callback of a service method which may not return `response = null`.\n * @typedef rpc.ServiceMethodCallback\n * @template TRes extends Message\n * @type {function}\n * @param {Error|null} error Error, if any\n * @param {TRes} [response] Response message\n * @returns {undefined}\n */\n\n/**\n * A service method part of a {@link rpc.Service} as created by {@link Service.create}.\n * @typedef rpc.ServiceMethod\n * @template TReq extends Message\n * @template TRes extends Message\n * @type {function}\n * @param {TReq|Properties} request Request message or plain object\n * @param {rpc.ServiceMethodCallback} [callback] Node-style callback called with the error, if any, and the response message\n * @returns {Promise>} Promise if `callback` has been omitted, otherwise `undefined`\n */\n\n/**\n * Constructs a new RPC service instance.\n * @classdesc An RPC service as returned by {@link Service#create}.\n * @exports rpc.Service\n * @extends util.EventEmitter\n * @constructor\n * @param {RPCImpl} rpcImpl RPC implementation\n * @param {boolean} [requestDelimited=false] Whether requests are length-delimited\n * @param {boolean} [responseDelimited=false] Whether responses are length-delimited\n */\nfunction Service(rpcImpl, requestDelimited, responseDelimited) {\n\n if (typeof rpcImpl !== \"function\")\n throw TypeError(\"rpcImpl must be a function\");\n\n util.EventEmitter.call(this);\n\n /**\n * RPC implementation. Becomes `null` once the service is ended.\n * @type {RPCImpl|null}\n */\n this.rpcImpl = rpcImpl;\n\n /**\n * Whether requests are length-delimited.\n * @type {boolean}\n */\n this.requestDelimited = Boolean(requestDelimited);\n\n /**\n * Whether responses are length-delimited.\n * @type {boolean}\n */\n this.responseDelimited = Boolean(responseDelimited);\n}\n\n/**\n * Calls a service method through {@link rpc.Service#rpcImpl|rpcImpl}.\n * @param {Method|rpc.ServiceMethod} method Reflected or static method\n * @param {Constructor} requestCtor Request constructor\n * @param {Constructor} responseCtor Response constructor\n * @param {TReq|Properties} request Request message or plain object\n * @param {rpc.ServiceMethodCallback} callback Service callback\n * @returns {undefined}\n * @template TReq extends Message\n * @template TRes extends Message\n */\nService.prototype.rpcCall = function rpcCall(method, requestCtor, responseCtor, request, callback) {\n\n if (!request)\n throw TypeError(\"request must be specified\");\n\n var self = this;\n if (!callback)\n return util.asPromise(rpcCall, self, method, requestCtor, responseCtor, request);\n\n if (!self.rpcImpl) {\n setTimeout(function() { callback(Error(\"already ended\")); }, 0);\n return undefined;\n }\n\n try {\n return self.rpcImpl(\n method,\n requestCtor[self.requestDelimited ? \"encodeDelimited\" : \"encode\"](request).finish(),\n function rpcCallback(err, response) {\n\n if (err) {\n self.emit(\"error\", err, method);\n return callback(err);\n }\n\n if (response === null) {\n self.end(/* endedByRPC */ true);\n return undefined;\n }\n\n if (!(response instanceof responseCtor)) {\n try {\n response = responseCtor[self.responseDelimited ? \"decodeDelimited\" : \"decode\"](response);\n } catch (err) {\n self.emit(\"error\", err, method);\n return callback(err);\n }\n }\n\n self.emit(\"data\", response, method);\n return callback(null, response);\n }\n );\n } catch (err) {\n self.emit(\"error\", err, method);\n setTimeout(function() { callback(err); }, 0);\n return undefined;\n }\n};\n\n/**\n * Ends this service and emits the `end` event.\n * @param {boolean} [endedByRPC=false] Whether the service has been ended by the RPC implementation.\n * @returns {rpc.Service} `this`\n */\nService.prototype.end = function end(endedByRPC) {\n if (this.rpcImpl) {\n if (!endedByRPC) // signal end to rpcImpl\n this.rpcImpl(null, null, null);\n this.rpcImpl = null;\n this.emit(\"end\").off();\n }\n return this;\n};\n","\"use strict\";\nmodule.exports = Service;\n\n// extends Namespace\nvar Namespace = require(23);\n((Service.prototype = Object.create(Namespace.prototype)).constructor = Service).className = \"Service\";\n\nvar Method = require(22),\n util = require(37),\n rpc = require(31);\n\n/**\n * Constructs a new service instance.\n * @classdesc Reflected service.\n * @extends NamespaceBase\n * @constructor\n * @param {string} name Service name\n * @param {Object.} [options] Service options\n * @throws {TypeError} If arguments are invalid\n */\nfunction Service(name, options) {\n Namespace.call(this, name, options);\n\n /**\n * Service methods.\n * @type {Object.}\n */\n this.methods = {}; // toJSON, marker\n\n /**\n * Cached methods as an array.\n * @type {Method[]|null}\n * @private\n */\n this._methodsArray = null;\n}\n\n/**\n * Service descriptor.\n * @interface IService\n * @extends INamespace\n * @property {Object.} methods Method descriptors\n */\n\n/**\n * Constructs a service from a service descriptor.\n * @param {string} name Service name\n * @param {IService} json Service descriptor\n * @returns {Service} Created service\n * @throws {TypeError} If arguments are invalid\n */\nService.fromJSON = function fromJSON(name, json) {\n var service = new Service(name, json.options);\n /* istanbul ignore else */\n if (json.methods)\n for (var names = Object.keys(json.methods), i = 0; i < names.length; ++i)\n service.add(Method.fromJSON(names[i], json.methods[names[i]]));\n if (json.nested)\n service.addJSON(json.nested);\n service.comment = json.comment;\n return service;\n};\n\n/**\n * Converts this service to a service descriptor.\n * @param {IToJSONOptions} [toJSONOptions] JSON conversion options\n * @returns {IService} Service descriptor\n */\nService.prototype.toJSON = function toJSON(toJSONOptions) {\n var inherited = Namespace.prototype.toJSON.call(this, toJSONOptions);\n var keepComments = toJSONOptions ? Boolean(toJSONOptions.keepComments) : false;\n return util.toObject([\n \"options\" , inherited && inherited.options || undefined,\n \"methods\" , Namespace.arrayToJSON(this.methodsArray, toJSONOptions) || /* istanbul ignore next */ {},\n \"nested\" , inherited && inherited.nested || undefined,\n \"comment\" , keepComments ? this.comment : undefined\n ]);\n};\n\n/**\n * Methods of this service as an array for iteration.\n * @name Service#methodsArray\n * @type {Method[]}\n * @readonly\n */\nObject.defineProperty(Service.prototype, \"methodsArray\", {\n get: function() {\n return this._methodsArray || (this._methodsArray = util.toArray(this.methods));\n }\n});\n\nfunction clearCache(service) {\n service._methodsArray = null;\n return service;\n}\n\n/**\n * @override\n */\nService.prototype.get = function get(name) {\n return this.methods[name]\n || Namespace.prototype.get.call(this, name);\n};\n\n/**\n * @override\n */\nService.prototype.resolveAll = function resolveAll() {\n var methods = this.methodsArray;\n for (var i = 0; i < methods.length; ++i)\n methods[i].resolve();\n return Namespace.prototype.resolve.call(this);\n};\n\n/**\n * @override\n */\nService.prototype.add = function add(object) {\n\n /* istanbul ignore if */\n if (this.get(object.name))\n throw Error(\"duplicate name '\" + object.name + \"' in \" + this);\n\n if (object instanceof Method) {\n this.methods[object.name] = object;\n object.parent = this;\n return clearCache(this);\n }\n return Namespace.prototype.add.call(this, object);\n};\n\n/**\n * @override\n */\nService.prototype.remove = function remove(object) {\n if (object instanceof Method) {\n\n /* istanbul ignore if */\n if (this.methods[object.name] !== object)\n throw Error(object + \" is not a member of \" + this);\n\n delete this.methods[object.name];\n object.parent = null;\n return clearCache(this);\n }\n return Namespace.prototype.remove.call(this, object);\n};\n\n/**\n * Creates a runtime service using the specified rpc implementation.\n * @param {RPCImpl} rpcImpl RPC implementation\n * @param {boolean} [requestDelimited=false] Whether requests are length-delimited\n * @param {boolean} [responseDelimited=false] Whether responses are length-delimited\n * @returns {rpc.Service} RPC service. Useful where requests and/or responses are streamed.\n */\nService.prototype.create = function create(rpcImpl, requestDelimited, responseDelimited) {\n var rpcService = new rpc.Service(rpcImpl, requestDelimited, responseDelimited);\n for (var i = 0, method; i < /* initializes */ this.methodsArray.length; ++i) {\n var methodName = util.lcFirst((method = this._methodsArray[i]).resolve().name).replace(/[^$\\w_]/g, \"\");\n rpcService[methodName] = util.codegen([\"r\",\"c\"], util.isReserved(methodName) ? methodName + \"_\" : methodName)(\"return this.rpcCall(m,q,s,r,c)\")({\n m: method,\n q: method.resolvedRequestType.ctor,\n s: method.resolvedResponseType.ctor\n });\n }\n return rpcService;\n};\n","\"use strict\";\nmodule.exports = tokenize;\n\nvar delimRe = /[\\s{}=;:[\\],'\"()<>]/g,\n stringDoubleRe = /(?:\"([^\"\\\\]*(?:\\\\.[^\"\\\\]*)*)\")/g,\n stringSingleRe = /(?:'([^'\\\\]*(?:\\\\.[^'\\\\]*)*)')/g;\n\nvar setCommentRe = /^ *[*/]+ */,\n setCommentAltRe = /^\\s*\\*?\\/*/,\n setCommentSplitRe = /\\n/g,\n whitespaceRe = /\\s/,\n unescapeRe = /\\\\(.?)/g;\n\nvar unescapeMap = {\n \"0\": \"\\0\",\n \"r\": \"\\r\",\n \"n\": \"\\n\",\n \"t\": \"\\t\"\n};\n\n/**\n * Unescapes a string.\n * @param {string} str String to unescape\n * @returns {string} Unescaped string\n * @property {Object.} map Special characters map\n * @memberof tokenize\n */\nfunction unescape(str) {\n return str.replace(unescapeRe, function($0, $1) {\n switch ($1) {\n case \"\\\\\":\n case \"\":\n return $1;\n default:\n return unescapeMap[$1] || \"\";\n }\n });\n}\n\ntokenize.unescape = unescape;\n\n/**\n * Gets the next token and advances.\n * @typedef TokenizerHandleNext\n * @type {function}\n * @returns {string|null} Next token or `null` on eof\n */\n\n/**\n * Peeks for the next token.\n * @typedef TokenizerHandlePeek\n * @type {function}\n * @returns {string|null} Next token or `null` on eof\n */\n\n/**\n * Pushes a token back to the stack.\n * @typedef TokenizerHandlePush\n * @type {function}\n * @param {string} token Token\n * @returns {undefined}\n */\n\n/**\n * Skips the next token.\n * @typedef TokenizerHandleSkip\n * @type {function}\n * @param {string} expected Expected token\n * @param {boolean} [optional=false] If optional\n * @returns {boolean} Whether the token matched\n * @throws {Error} If the token didn't match and is not optional\n */\n\n/**\n * Gets the comment on the previous line or, alternatively, the line comment on the specified line.\n * @typedef TokenizerHandleCmnt\n * @type {function}\n * @param {number} [line] Line number\n * @returns {string|null} Comment text or `null` if none\n */\n\n/**\n * Handle object returned from {@link tokenize}.\n * @interface ITokenizerHandle\n * @property {TokenizerHandleNext} next Gets the next token and advances (`null` on eof)\n * @property {TokenizerHandlePeek} peek Peeks for the next token (`null` on eof)\n * @property {TokenizerHandlePush} push Pushes a token back to the stack\n * @property {TokenizerHandleSkip} skip Skips a token, returns its presence and advances or, if non-optional and not present, throws\n * @property {TokenizerHandleCmnt} cmnt Gets the comment on the previous line or the line comment on the specified line, if any\n * @property {number} line Current line number\n */\n\n/**\n * Tokenizes the given .proto source and returns an object with useful utility functions.\n * @param {string} source Source contents\n * @param {boolean} alternateCommentMode Whether we should activate alternate comment parsing mode.\n * @returns {ITokenizerHandle} Tokenizer handle\n */\nfunction tokenize(source, alternateCommentMode) {\n /* eslint-disable callback-return */\n source = source.toString();\n\n var offset = 0,\n length = source.length,\n line = 1,\n lastCommentLine = 0,\n comments = {};\n\n var stack = [];\n\n var stringDelim = null;\n\n /* istanbul ignore next */\n /**\n * Creates an error for illegal syntax.\n * @param {string} subject Subject\n * @returns {Error} Error created\n * @inner\n */\n function illegal(subject) {\n return Error(\"illegal \" + subject + \" (line \" + line + \")\");\n }\n\n /**\n * Reads a string till its end.\n * @returns {string} String read\n * @inner\n */\n function readString() {\n var re = stringDelim === \"'\" ? stringSingleRe : stringDoubleRe;\n re.lastIndex = offset - 1;\n var match = re.exec(source);\n if (!match)\n throw illegal(\"string\");\n offset = re.lastIndex;\n push(stringDelim);\n stringDelim = null;\n return unescape(match[1]);\n }\n\n /**\n * Gets the character at `pos` within the source.\n * @param {number} pos Position\n * @returns {string} Character\n * @inner\n */\n function charAt(pos) {\n return source.charAt(pos);\n }\n\n /**\n * Sets the current comment text.\n * @param {number} start Start offset\n * @param {number} end End offset\n * @param {boolean} isLeading set if a leading comment\n * @returns {undefined}\n * @inner\n */\n function setComment(start, end, isLeading) {\n var comment = {\n type: source.charAt(start++),\n lineEmpty: false,\n leading: isLeading,\n };\n var lookback;\n if (alternateCommentMode) {\n lookback = 2; // alternate comment parsing: \"//\" or \"/*\"\n } else {\n lookback = 3; // \"///\" or \"/**\"\n }\n var commentOffset = start - lookback,\n c;\n do {\n if (--commentOffset < 0 ||\n (c = source.charAt(commentOffset)) === \"\\n\") {\n comment.lineEmpty = true;\n break;\n }\n } while (c === \" \" || c === \"\\t\");\n var lines = source\n .substring(start, end)\n .split(setCommentSplitRe);\n for (var i = 0; i < lines.length; ++i)\n lines[i] = lines[i]\n .replace(alternateCommentMode ? setCommentAltRe : setCommentRe, \"\")\n .trim();\n comment.text = lines\n .join(\"\\n\")\n .trim();\n\n comments[line] = comment;\n lastCommentLine = line;\n }\n\n function isDoubleSlashCommentLine(startOffset) {\n var endOffset = findEndOfLine(startOffset);\n\n // see if remaining line matches comment pattern\n var lineText = source.substring(startOffset, endOffset);\n var isComment = /^\\s*\\/\\//.test(lineText);\n return isComment;\n }\n\n function findEndOfLine(cursor) {\n // find end of cursor's line\n var endOffset = cursor;\n while (endOffset < length && charAt(endOffset) !== \"\\n\") {\n endOffset++;\n }\n return endOffset;\n }\n\n /**\n * Obtains the next token.\n * @returns {string|null} Next token or `null` on eof\n * @inner\n */\n function next() {\n if (stack.length > 0)\n return stack.shift();\n if (stringDelim)\n return readString();\n var repeat,\n prev,\n curr,\n start,\n isDoc,\n isLeadingComment = offset === 0;\n do {\n if (offset === length)\n return null;\n repeat = false;\n while (whitespaceRe.test(curr = charAt(offset))) {\n if (curr === \"\\n\") {\n isLeadingComment = true;\n ++line;\n }\n if (++offset === length)\n return null;\n }\n\n if (charAt(offset) === \"/\") {\n if (++offset === length) {\n throw illegal(\"comment\");\n }\n if (charAt(offset) === \"/\") { // Line\n if (!alternateCommentMode) {\n // check for triple-slash comment\n isDoc = charAt(start = offset + 1) === \"/\";\n\n while (charAt(++offset) !== \"\\n\") {\n if (offset === length) {\n return null;\n }\n }\n ++offset;\n if (isDoc) {\n setComment(start, offset - 1, isLeadingComment);\n // Trailing comment cannot not be multi-line,\n // so leading comment state should be reset to handle potential next comments\n isLeadingComment = true;\n }\n ++line;\n repeat = true;\n } else {\n // check for double-slash comments, consolidating consecutive lines\n start = offset;\n isDoc = false;\n if (isDoubleSlashCommentLine(offset - 1)) {\n isDoc = true;\n do {\n offset = findEndOfLine(offset);\n if (offset === length) {\n break;\n }\n offset++;\n if (!isLeadingComment) {\n // Trailing comment cannot not be multi-line\n break;\n }\n } while (isDoubleSlashCommentLine(offset));\n } else {\n offset = Math.min(length, findEndOfLine(offset) + 1);\n }\n if (isDoc) {\n setComment(start, offset, isLeadingComment);\n isLeadingComment = true;\n }\n line++;\n repeat = true;\n }\n } else if ((curr = charAt(offset)) === \"*\") { /* Block */\n // check for /** (regular comment mode) or /* (alternate comment mode)\n start = offset + 1;\n isDoc = alternateCommentMode || charAt(start) === \"*\";\n do {\n if (curr === \"\\n\") {\n ++line;\n }\n if (++offset === length) {\n throw illegal(\"comment\");\n }\n prev = curr;\n curr = charAt(offset);\n } while (prev !== \"*\" || curr !== \"/\");\n ++offset;\n if (isDoc) {\n setComment(start, offset - 2, isLeadingComment);\n isLeadingComment = true;\n }\n repeat = true;\n } else {\n return \"/\";\n }\n }\n } while (repeat);\n\n // offset !== length if we got here\n\n var end = offset;\n delimRe.lastIndex = 0;\n var delim = delimRe.test(charAt(end++));\n if (!delim)\n while (end < length && !delimRe.test(charAt(end)))\n ++end;\n var token = source.substring(offset, offset = end);\n if (token === \"\\\"\" || token === \"'\")\n stringDelim = token;\n return token;\n }\n\n /**\n * Pushes a token back to the stack.\n * @param {string} token Token\n * @returns {undefined}\n * @inner\n */\n function push(token) {\n stack.push(token);\n }\n\n /**\n * Peeks for the next token.\n * @returns {string|null} Token or `null` on eof\n * @inner\n */\n function peek() {\n if (!stack.length) {\n var token = next();\n if (token === null)\n return null;\n push(token);\n }\n return stack[0];\n }\n\n /**\n * Skips a token.\n * @param {string} expected Expected token\n * @param {boolean} [optional=false] Whether the token is optional\n * @returns {boolean} `true` when skipped, `false` if not\n * @throws {Error} When a required token is not present\n * @inner\n */\n function skip(expected, optional) {\n var actual = peek(),\n equals = actual === expected;\n if (equals) {\n next();\n return true;\n }\n if (!optional)\n throw illegal(\"token '\" + actual + \"', '\" + expected + \"' expected\");\n return false;\n }\n\n /**\n * Gets a comment.\n * @param {number} [trailingLine] Line number if looking for a trailing comment\n * @returns {string|null} Comment text\n * @inner\n */\n function cmnt(trailingLine) {\n var ret = null;\n var comment;\n if (trailingLine === undefined) {\n comment = comments[line - 1];\n delete comments[line - 1];\n if (comment && (alternateCommentMode || comment.type === \"*\" || comment.lineEmpty)) {\n ret = comment.leading ? comment.text : null;\n }\n } else {\n /* istanbul ignore else */\n if (lastCommentLine < trailingLine) {\n peek();\n }\n comment = comments[trailingLine];\n delete comments[trailingLine];\n if (comment && !comment.lineEmpty && (alternateCommentMode || comment.type === \"/\")) {\n ret = comment.leading ? null : comment.text;\n }\n }\n return ret;\n }\n\n return Object.defineProperty({\n next: next,\n peek: peek,\n push: push,\n skip: skip,\n cmnt: cmnt\n }, \"line\", {\n get: function() { return line; }\n });\n /* eslint-enable callback-return */\n}\n","\"use strict\";\nmodule.exports = Type;\n\n// extends Namespace\nvar Namespace = require(23);\n((Type.prototype = Object.create(Namespace.prototype)).constructor = Type).className = \"Type\";\n\nvar Enum = require(15),\n OneOf = require(25),\n Field = require(16),\n MapField = require(20),\n Service = require(33),\n Message = require(21),\n Reader = require(27),\n Writer = require(42),\n util = require(37),\n encoder = require(14),\n decoder = require(13),\n verifier = require(40),\n converter = require(12),\n wrappers = require(41);\n\n/**\n * Constructs a new reflected message type instance.\n * @classdesc Reflected message type.\n * @extends NamespaceBase\n * @constructor\n * @param {string} name Message name\n * @param {Object.} [options] Declared options\n */\nfunction Type(name, options) {\n Namespace.call(this, name, options);\n\n /**\n * Message fields.\n * @type {Object.}\n */\n this.fields = {}; // toJSON, marker\n\n /**\n * Oneofs declared within this namespace, if any.\n * @type {Object.}\n */\n this.oneofs = undefined; // toJSON\n\n /**\n * Extension ranges, if any.\n * @type {number[][]}\n */\n this.extensions = undefined; // toJSON\n\n /**\n * Reserved ranges, if any.\n * @type {Array.}\n */\n this.reserved = undefined; // toJSON\n\n /*?\n * Whether this type is a legacy group.\n * @type {boolean|undefined}\n */\n this.group = undefined; // toJSON\n\n /**\n * Cached fields by id.\n * @type {Object.|null}\n * @private\n */\n this._fieldsById = null;\n\n /**\n * Cached fields as an array.\n * @type {Field[]|null}\n * @private\n */\n this._fieldsArray = null;\n\n /**\n * Cached oneofs as an array.\n * @type {OneOf[]|null}\n * @private\n */\n this._oneofsArray = null;\n\n /**\n * Cached constructor.\n * @type {Constructor<{}>}\n * @private\n */\n this._ctor = null;\n}\n\nObject.defineProperties(Type.prototype, {\n\n /**\n * Message fields by id.\n * @name Type#fieldsById\n * @type {Object.}\n * @readonly\n */\n fieldsById: {\n get: function() {\n\n /* istanbul ignore if */\n if (this._fieldsById)\n return this._fieldsById;\n\n this._fieldsById = {};\n for (var names = Object.keys(this.fields), i = 0; i < names.length; ++i) {\n var field = this.fields[names[i]],\n id = field.id;\n\n /* istanbul ignore if */\n if (this._fieldsById[id])\n throw Error(\"duplicate id \" + id + \" in \" + this);\n\n this._fieldsById[id] = field;\n }\n return this._fieldsById;\n }\n },\n\n /**\n * Fields of this message as an array for iteration.\n * @name Type#fieldsArray\n * @type {Field[]}\n * @readonly\n */\n fieldsArray: {\n get: function() {\n return this._fieldsArray || (this._fieldsArray = util.toArray(this.fields));\n }\n },\n\n /**\n * Oneofs of this message as an array for iteration.\n * @name Type#oneofsArray\n * @type {OneOf[]}\n * @readonly\n */\n oneofsArray: {\n get: function() {\n return this._oneofsArray || (this._oneofsArray = util.toArray(this.oneofs));\n }\n },\n\n /**\n * The registered constructor, if any registered, otherwise a generic constructor.\n * Assigning a function replaces the internal constructor. If the function does not extend {@link Message} yet, its prototype will be setup accordingly and static methods will be populated. If it already extends {@link Message}, it will just replace the internal constructor.\n * @name Type#ctor\n * @type {Constructor<{}>}\n */\n ctor: {\n get: function() {\n return this._ctor || (this.ctor = Type.generateConstructor(this)());\n },\n set: function(ctor) {\n\n // Ensure proper prototype\n var prototype = ctor.prototype;\n if (!(prototype instanceof Message)) {\n (ctor.prototype = new Message()).constructor = ctor;\n util.merge(ctor.prototype, prototype);\n }\n\n // Classes and messages reference their reflected type\n ctor.$type = ctor.prototype.$type = this;\n\n // Mix in static methods\n util.merge(ctor, Message, true);\n\n this._ctor = ctor;\n\n // Messages have non-enumerable default values on their prototype\n var i = 0;\n for (; i < /* initializes */ this.fieldsArray.length; ++i)\n this._fieldsArray[i].resolve(); // ensures a proper value\n\n // Messages have non-enumerable getters and setters for each virtual oneof field\n var ctorProperties = {};\n for (i = 0; i < /* initializes */ this.oneofsArray.length; ++i)\n ctorProperties[this._oneofsArray[i].resolve().name] = {\n get: util.oneOfGetter(this._oneofsArray[i].oneof),\n set: util.oneOfSetter(this._oneofsArray[i].oneof)\n };\n if (i)\n Object.defineProperties(ctor.prototype, ctorProperties);\n }\n }\n});\n\n/**\n * Generates a constructor function for the specified type.\n * @param {Type} mtype Message type\n * @returns {Codegen} Codegen instance\n */\nType.generateConstructor = function generateConstructor(mtype) {\n /* eslint-disable no-unexpected-multiline */\n var gen = util.codegen([\"p\"], mtype.name);\n // explicitly initialize mutable object/array fields so that these aren't just inherited from the prototype\n for (var i = 0, field; i < mtype.fieldsArray.length; ++i)\n if ((field = mtype._fieldsArray[i]).map) gen\n (\"this%s={}\", util.safeProp(field.name));\n else if (field.repeated) gen\n (\"this%s=[]\", util.safeProp(field.name));\n return gen\n (\"if(p)for(var ks=Object.keys(p),i=0;i} [oneofs] Oneof descriptors\n * @property {Object.} fields Field descriptors\n * @property {number[][]} [extensions] Extension ranges\n * @property {number[][]} [reserved] Reserved ranges\n * @property {boolean} [group=false] Whether a legacy group or not\n */\n\n/**\n * Creates a message type from a message type descriptor.\n * @param {string} name Message name\n * @param {IType} json Message type descriptor\n * @returns {Type} Created message type\n */\nType.fromJSON = function fromJSON(name, json) {\n var type = new Type(name, json.options);\n type.extensions = json.extensions;\n type.reserved = json.reserved;\n var names = Object.keys(json.fields),\n i = 0;\n for (; i < names.length; ++i)\n type.add(\n ( typeof json.fields[names[i]].keyType !== \"undefined\"\n ? MapField.fromJSON\n : Field.fromJSON )(names[i], json.fields[names[i]])\n );\n if (json.oneofs)\n for (names = Object.keys(json.oneofs), i = 0; i < names.length; ++i)\n type.add(OneOf.fromJSON(names[i], json.oneofs[names[i]]));\n if (json.nested)\n for (names = Object.keys(json.nested), i = 0; i < names.length; ++i) {\n var nested = json.nested[names[i]];\n type.add( // most to least likely\n ( nested.id !== undefined\n ? Field.fromJSON\n : nested.fields !== undefined\n ? Type.fromJSON\n : nested.values !== undefined\n ? Enum.fromJSON\n : nested.methods !== undefined\n ? Service.fromJSON\n : Namespace.fromJSON )(names[i], nested)\n );\n }\n if (json.extensions && json.extensions.length)\n type.extensions = json.extensions;\n if (json.reserved && json.reserved.length)\n type.reserved = json.reserved;\n if (json.group)\n type.group = true;\n if (json.comment)\n type.comment = json.comment;\n return type;\n};\n\n/**\n * Converts this message type to a message type descriptor.\n * @param {IToJSONOptions} [toJSONOptions] JSON conversion options\n * @returns {IType} Message type descriptor\n */\nType.prototype.toJSON = function toJSON(toJSONOptions) {\n var inherited = Namespace.prototype.toJSON.call(this, toJSONOptions);\n var keepComments = toJSONOptions ? Boolean(toJSONOptions.keepComments) : false;\n return util.toObject([\n \"options\" , inherited && inherited.options || undefined,\n \"oneofs\" , Namespace.arrayToJSON(this.oneofsArray, toJSONOptions),\n \"fields\" , Namespace.arrayToJSON(this.fieldsArray.filter(function(obj) { return !obj.declaringField; }), toJSONOptions) || {},\n \"extensions\" , this.extensions && this.extensions.length ? this.extensions : undefined,\n \"reserved\" , this.reserved && this.reserved.length ? this.reserved : undefined,\n \"group\" , this.group || undefined,\n \"nested\" , inherited && inherited.nested || undefined,\n \"comment\" , keepComments ? this.comment : undefined\n ]);\n};\n\n/**\n * @override\n */\nType.prototype.resolveAll = function resolveAll() {\n var fields = this.fieldsArray, i = 0;\n while (i < fields.length)\n fields[i++].resolve();\n var oneofs = this.oneofsArray; i = 0;\n while (i < oneofs.length)\n oneofs[i++].resolve();\n return Namespace.prototype.resolveAll.call(this);\n};\n\n/**\n * @override\n */\nType.prototype.get = function get(name) {\n return this.fields[name]\n || this.oneofs && this.oneofs[name]\n || this.nested && this.nested[name]\n || null;\n};\n\n/**\n * Adds a nested object to this type.\n * @param {ReflectionObject} object Nested object to add\n * @returns {Type} `this`\n * @throws {TypeError} If arguments are invalid\n * @throws {Error} If there is already a nested object with this name or, if a field, when there is already a field with this id\n */\nType.prototype.add = function add(object) {\n\n if (this.get(object.name))\n throw Error(\"duplicate name '\" + object.name + \"' in \" + this);\n\n if (object instanceof Field && object.extend === undefined) {\n // NOTE: Extension fields aren't actual fields on the declaring type, but nested objects.\n // The root object takes care of adding distinct sister-fields to the respective extended\n // type instead.\n\n // avoids calling the getter if not absolutely necessary because it's called quite frequently\n if (this._fieldsById ? /* istanbul ignore next */ this._fieldsById[object.id] : this.fieldsById[object.id])\n throw Error(\"duplicate id \" + object.id + \" in \" + this);\n if (this.isReservedId(object.id))\n throw Error(\"id \" + object.id + \" is reserved in \" + this);\n if (this.isReservedName(object.name))\n throw Error(\"name '\" + object.name + \"' is reserved in \" + this);\n\n if (object.parent)\n object.parent.remove(object);\n this.fields[object.name] = object;\n object.message = this;\n object.onAdd(this);\n return clearCache(this);\n }\n if (object instanceof OneOf) {\n if (!this.oneofs)\n this.oneofs = {};\n this.oneofs[object.name] = object;\n object.onAdd(this);\n return clearCache(this);\n }\n return Namespace.prototype.add.call(this, object);\n};\n\n/**\n * Removes a nested object from this type.\n * @param {ReflectionObject} object Nested object to remove\n * @returns {Type} `this`\n * @throws {TypeError} If arguments are invalid\n * @throws {Error} If `object` is not a member of this type\n */\nType.prototype.remove = function remove(object) {\n if (object instanceof Field && object.extend === undefined) {\n // See Type#add for the reason why extension fields are excluded here.\n\n /* istanbul ignore if */\n if (!this.fields || this.fields[object.name] !== object)\n throw Error(object + \" is not a member of \" + this);\n\n delete this.fields[object.name];\n object.parent = null;\n object.onRemove(this);\n return clearCache(this);\n }\n if (object instanceof OneOf) {\n\n /* istanbul ignore if */\n if (!this.oneofs || this.oneofs[object.name] !== object)\n throw Error(object + \" is not a member of \" + this);\n\n delete this.oneofs[object.name];\n object.parent = null;\n object.onRemove(this);\n return clearCache(this);\n }\n return Namespace.prototype.remove.call(this, object);\n};\n\n/**\n * Tests if the specified id is reserved.\n * @param {number} id Id to test\n * @returns {boolean} `true` if reserved, otherwise `false`\n */\nType.prototype.isReservedId = function isReservedId(id) {\n return Namespace.isReservedId(this.reserved, id);\n};\n\n/**\n * Tests if the specified name is reserved.\n * @param {string} name Name to test\n * @returns {boolean} `true` if reserved, otherwise `false`\n */\nType.prototype.isReservedName = function isReservedName(name) {\n return Namespace.isReservedName(this.reserved, name);\n};\n\n/**\n * Creates a new message of this type using the specified properties.\n * @param {Object.} [properties] Properties to set\n * @returns {Message<{}>} Message instance\n */\nType.prototype.create = function create(properties) {\n return new this.ctor(properties);\n};\n\n/**\n * Sets up {@link Type#encode|encode}, {@link Type#decode|decode} and {@link Type#verify|verify}.\n * @returns {Type} `this`\n */\nType.prototype.setup = function setup() {\n // Sets up everything at once so that the prototype chain does not have to be re-evaluated\n // multiple times (V8, soft-deopt prototype-check).\n\n var fullName = this.fullName,\n types = [];\n for (var i = 0; i < /* initializes */ this.fieldsArray.length; ++i)\n types.push(this._fieldsArray[i].resolve().resolvedType);\n\n // Replace setup methods with type-specific generated functions\n this.encode = encoder(this)({\n Writer : Writer,\n types : types,\n util : util\n });\n this.decode = decoder(this)({\n Reader : Reader,\n types : types,\n util : util\n });\n this.verify = verifier(this)({\n types : types,\n util : util\n });\n this.fromObject = converter.fromObject(this)({\n types : types,\n util : util\n });\n this.toObject = converter.toObject(this)({\n types : types,\n util : util\n });\n\n // Inject custom wrappers for common types\n var wrapper = wrappers[fullName];\n if (wrapper) {\n var originalThis = Object.create(this);\n // if (wrapper.fromObject) {\n originalThis.fromObject = this.fromObject;\n this.fromObject = wrapper.fromObject.bind(originalThis);\n // }\n // if (wrapper.toObject) {\n originalThis.toObject = this.toObject;\n this.toObject = wrapper.toObject.bind(originalThis);\n // }\n }\n\n return this;\n};\n\n/**\n * Encodes a message of this type. Does not implicitly {@link Type#verify|verify} messages.\n * @param {Message<{}>|Object.} message Message instance or plain object\n * @param {Writer} [writer] Writer to encode to\n * @returns {Writer} writer\n */\nType.prototype.encode = function encode_setup(message, writer) {\n return this.setup().encode(message, writer); // overrides this method\n};\n\n/**\n * Encodes a message of this type preceeded by its byte length as a varint. Does not implicitly {@link Type#verify|verify} messages.\n * @param {Message<{}>|Object.} message Message instance or plain object\n * @param {Writer} [writer] Writer to encode to\n * @returns {Writer} writer\n */\nType.prototype.encodeDelimited = function encodeDelimited(message, writer) {\n return this.encode(message, writer && writer.len ? writer.fork() : writer).ldelim();\n};\n\n/**\n * Decodes a message of this type.\n * @param {Reader|Uint8Array} reader Reader or buffer to decode from\n * @param {number} [length] Length of the message, if known beforehand\n * @returns {Message<{}>} Decoded message\n * @throws {Error} If the payload is not a reader or valid buffer\n * @throws {util.ProtocolError<{}>} If required fields are missing\n */\nType.prototype.decode = function decode_setup(reader, length) {\n return this.setup().decode(reader, length); // overrides this method\n};\n\n/**\n * Decodes a message of this type preceeded by its byte length as a varint.\n * @param {Reader|Uint8Array} reader Reader or buffer to decode from\n * @returns {Message<{}>} Decoded message\n * @throws {Error} If the payload is not a reader or valid buffer\n * @throws {util.ProtocolError} If required fields are missing\n */\nType.prototype.decodeDelimited = function decodeDelimited(reader) {\n if (!(reader instanceof Reader))\n reader = Reader.create(reader);\n return this.decode(reader, reader.uint32());\n};\n\n/**\n * Verifies that field values are valid and that required fields are present.\n * @param {Object.} message Plain object to verify\n * @returns {null|string} `null` if valid, otherwise the reason why it is not\n */\nType.prototype.verify = function verify_setup(message) {\n return this.setup().verify(message); // overrides this method\n};\n\n/**\n * Creates a new message of this type from a plain object. Also converts values to their respective internal types.\n * @param {Object.} object Plain object to convert\n * @returns {Message<{}>} Message instance\n */\nType.prototype.fromObject = function fromObject(object) {\n return this.setup().fromObject(object);\n};\n\n/**\n * Conversion options as used by {@link Type#toObject} and {@link Message.toObject}.\n * @interface IConversionOptions\n * @property {Function} [longs] Long conversion type.\n * Valid values are `String` and `Number` (the global types).\n * Defaults to copy the present value, which is a possibly unsafe number without and a {@link Long} with a long library.\n * @property {Function} [enums] Enum value conversion type.\n * Only valid value is `String` (the global type).\n * Defaults to copy the present value, which is the numeric id.\n * @property {Function} [bytes] Bytes value conversion type.\n * Valid values are `Array` and (a base64 encoded) `String` (the global types).\n * Defaults to copy the present value, which usually is a Buffer under node and an Uint8Array in the browser.\n * @property {boolean} [defaults=false] Also sets default values on the resulting object\n * @property {boolean} [arrays=false] Sets empty arrays for missing repeated fields even if `defaults=false`\n * @property {boolean} [objects=false] Sets empty objects for missing map fields even if `defaults=false`\n * @property {boolean} [oneofs=false] Includes virtual oneof properties set to the present field's name, if any\n * @property {boolean} [json=false] Performs additional JSON compatibility conversions, i.e. NaN and Infinity to strings\n */\n\n/**\n * Creates a plain object from a message of this type. Also converts values to other types if specified.\n * @param {Message<{}>} message Message instance\n * @param {IConversionOptions} [options] Conversion options\n * @returns {Object.} Plain object\n */\nType.prototype.toObject = function toObject(message, options) {\n return this.setup().toObject(message, options);\n};\n\n/**\n * Decorator function as returned by {@link Type.d} (TypeScript).\n * @typedef TypeDecorator\n * @type {function}\n * @param {Constructor} target Target constructor\n * @returns {undefined}\n * @template T extends Message\n */\n\n/**\n * Type decorator (TypeScript).\n * @param {string} [typeName] Type name, defaults to the constructor's name\n * @returns {TypeDecorator} Decorator function\n * @template T extends Message\n */\nType.d = function decorateType(typeName) {\n return function typeDecorator(target) {\n util.decorateType(target, typeName);\n };\n};\n","\"use strict\";\n\n/**\n * Common type constants.\n * @namespace\n */\nvar types = exports;\n\nvar util = require(37);\n\nvar s = [\n \"double\", // 0\n \"float\", // 1\n \"int32\", // 2\n \"uint32\", // 3\n \"sint32\", // 4\n \"fixed32\", // 5\n \"sfixed32\", // 6\n \"int64\", // 7\n \"uint64\", // 8\n \"sint64\", // 9\n \"fixed64\", // 10\n \"sfixed64\", // 11\n \"bool\", // 12\n \"string\", // 13\n \"bytes\" // 14\n];\n\nfunction bake(values, offset) {\n var i = 0, o = {};\n offset |= 0;\n while (i < values.length) o[s[i + offset]] = values[i++];\n return o;\n}\n\n/**\n * Basic type wire types.\n * @type {Object.}\n * @const\n * @property {number} double=1 Fixed64 wire type\n * @property {number} float=5 Fixed32 wire type\n * @property {number} int32=0 Varint wire type\n * @property {number} uint32=0 Varint wire type\n * @property {number} sint32=0 Varint wire type\n * @property {number} fixed32=5 Fixed32 wire type\n * @property {number} sfixed32=5 Fixed32 wire type\n * @property {number} int64=0 Varint wire type\n * @property {number} uint64=0 Varint wire type\n * @property {number} sint64=0 Varint wire type\n * @property {number} fixed64=1 Fixed64 wire type\n * @property {number} sfixed64=1 Fixed64 wire type\n * @property {number} bool=0 Varint wire type\n * @property {number} string=2 Ldelim wire type\n * @property {number} bytes=2 Ldelim wire type\n */\ntypes.basic = bake([\n /* double */ 1,\n /* float */ 5,\n /* int32 */ 0,\n /* uint32 */ 0,\n /* sint32 */ 0,\n /* fixed32 */ 5,\n /* sfixed32 */ 5,\n /* int64 */ 0,\n /* uint64 */ 0,\n /* sint64 */ 0,\n /* fixed64 */ 1,\n /* sfixed64 */ 1,\n /* bool */ 0,\n /* string */ 2,\n /* bytes */ 2\n]);\n\n/**\n * Basic type defaults.\n * @type {Object.}\n * @const\n * @property {number} double=0 Double default\n * @property {number} float=0 Float default\n * @property {number} int32=0 Int32 default\n * @property {number} uint32=0 Uint32 default\n * @property {number} sint32=0 Sint32 default\n * @property {number} fixed32=0 Fixed32 default\n * @property {number} sfixed32=0 Sfixed32 default\n * @property {number} int64=0 Int64 default\n * @property {number} uint64=0 Uint64 default\n * @property {number} sint64=0 Sint32 default\n * @property {number} fixed64=0 Fixed64 default\n * @property {number} sfixed64=0 Sfixed64 default\n * @property {boolean} bool=false Bool default\n * @property {string} string=\"\" String default\n * @property {Array.} bytes=Array(0) Bytes default\n * @property {null} message=null Message default\n */\ntypes.defaults = bake([\n /* double */ 0,\n /* float */ 0,\n /* int32 */ 0,\n /* uint32 */ 0,\n /* sint32 */ 0,\n /* fixed32 */ 0,\n /* sfixed32 */ 0,\n /* int64 */ 0,\n /* uint64 */ 0,\n /* sint64 */ 0,\n /* fixed64 */ 0,\n /* sfixed64 */ 0,\n /* bool */ false,\n /* string */ \"\",\n /* bytes */ util.emptyArray,\n /* message */ null\n]);\n\n/**\n * Basic long type wire types.\n * @type {Object.}\n * @const\n * @property {number} int64=0 Varint wire type\n * @property {number} uint64=0 Varint wire type\n * @property {number} sint64=0 Varint wire type\n * @property {number} fixed64=1 Fixed64 wire type\n * @property {number} sfixed64=1 Fixed64 wire type\n */\ntypes.long = bake([\n /* int64 */ 0,\n /* uint64 */ 0,\n /* sint64 */ 0,\n /* fixed64 */ 1,\n /* sfixed64 */ 1\n], 7);\n\n/**\n * Allowed types for map keys with their associated wire type.\n * @type {Object.}\n * @const\n * @property {number} int32=0 Varint wire type\n * @property {number} uint32=0 Varint wire type\n * @property {number} sint32=0 Varint wire type\n * @property {number} fixed32=5 Fixed32 wire type\n * @property {number} sfixed32=5 Fixed32 wire type\n * @property {number} int64=0 Varint wire type\n * @property {number} uint64=0 Varint wire type\n * @property {number} sint64=0 Varint wire type\n * @property {number} fixed64=1 Fixed64 wire type\n * @property {number} sfixed64=1 Fixed64 wire type\n * @property {number} bool=0 Varint wire type\n * @property {number} string=2 Ldelim wire type\n */\ntypes.mapKey = bake([\n /* int32 */ 0,\n /* uint32 */ 0,\n /* sint32 */ 0,\n /* fixed32 */ 5,\n /* sfixed32 */ 5,\n /* int64 */ 0,\n /* uint64 */ 0,\n /* sint64 */ 0,\n /* fixed64 */ 1,\n /* sfixed64 */ 1,\n /* bool */ 0,\n /* string */ 2\n], 2);\n\n/**\n * Allowed types for packed repeated fields with their associated wire type.\n * @type {Object.}\n * @const\n * @property {number} double=1 Fixed64 wire type\n * @property {number} float=5 Fixed32 wire type\n * @property {number} int32=0 Varint wire type\n * @property {number} uint32=0 Varint wire type\n * @property {number} sint32=0 Varint wire type\n * @property {number} fixed32=5 Fixed32 wire type\n * @property {number} sfixed32=5 Fixed32 wire type\n * @property {number} int64=0 Varint wire type\n * @property {number} uint64=0 Varint wire type\n * @property {number} sint64=0 Varint wire type\n * @property {number} fixed64=1 Fixed64 wire type\n * @property {number} sfixed64=1 Fixed64 wire type\n * @property {number} bool=0 Varint wire type\n */\ntypes.packed = bake([\n /* double */ 1,\n /* float */ 5,\n /* int32 */ 0,\n /* uint32 */ 0,\n /* sint32 */ 0,\n /* fixed32 */ 5,\n /* sfixed32 */ 5,\n /* int64 */ 0,\n /* uint64 */ 0,\n /* sint64 */ 0,\n /* fixed64 */ 1,\n /* sfixed64 */ 1,\n /* bool */ 0\n]);\n","\"use strict\";\n\n/**\n * Various utility functions.\n * @namespace\n */\nvar util = module.exports = require(39);\n\nvar roots = require(30);\n\nvar Type, // cyclic\n Enum;\n\nutil.codegen = require(3);\nutil.fetch = require(5);\nutil.path = require(8);\n\n/**\n * Node's fs module if available.\n * @type {Object.}\n */\nutil.fs = util.inquire(\"fs\");\n\n/**\n * Converts an object's values to an array.\n * @param {Object.} object Object to convert\n * @returns {Array.<*>} Converted array\n */\nutil.toArray = function toArray(object) {\n if (object) {\n var keys = Object.keys(object),\n array = new Array(keys.length),\n index = 0;\n while (index < keys.length)\n array[index] = object[keys[index++]];\n return array;\n }\n return [];\n};\n\n/**\n * Converts an array of keys immediately followed by their respective value to an object, omitting undefined values.\n * @param {Array.<*>} array Array to convert\n * @returns {Object.} Converted object\n */\nutil.toObject = function toObject(array) {\n var object = {},\n index = 0;\n while (index < array.length) {\n var key = array[index++],\n val = array[index++];\n if (val !== undefined)\n object[key] = val;\n }\n return object;\n};\n\nvar safePropBackslashRe = /\\\\/g,\n safePropQuoteRe = /\"/g;\n\n/**\n * Tests whether the specified name is a reserved word in JS.\n * @param {string} name Name to test\n * @returns {boolean} `true` if reserved, otherwise `false`\n */\nutil.isReserved = function isReserved(name) {\n return /^(?:do|if|in|for|let|new|try|var|case|else|enum|eval|false|null|this|true|void|with|break|catch|class|const|super|throw|while|yield|delete|export|import|public|return|static|switch|typeof|default|extends|finally|package|private|continue|debugger|function|arguments|interface|protected|implements|instanceof)$/.test(name);\n};\n\n/**\n * Returns a safe property accessor for the specified property name.\n * @param {string} prop Property name\n * @returns {string} Safe accessor\n */\nutil.safeProp = function safeProp(prop) {\n if (!/^[$\\w_]+$/.test(prop) || util.isReserved(prop))\n return \"[\\\"\" + prop.replace(safePropBackslashRe, \"\\\\\\\\\").replace(safePropQuoteRe, \"\\\\\\\"\") + \"\\\"]\";\n return \".\" + prop;\n};\n\n/**\n * Converts the first character of a string to upper case.\n * @param {string} str String to convert\n * @returns {string} Converted string\n */\nutil.ucFirst = function ucFirst(str) {\n return str.charAt(0).toUpperCase() + str.substring(1);\n};\n\nvar camelCaseRe = /_([a-z])/g;\n\n/**\n * Converts a string to camel case.\n * @param {string} str String to convert\n * @returns {string} Converted string\n */\nutil.camelCase = function camelCase(str) {\n return str.substring(0, 1)\n + str.substring(1)\n .replace(camelCaseRe, function($0, $1) { return $1.toUpperCase(); });\n};\n\n/**\n * Compares reflected fields by id.\n * @param {Field} a First field\n * @param {Field} b Second field\n * @returns {number} Comparison value\n */\nutil.compareFieldsById = function compareFieldsById(a, b) {\n return a.id - b.id;\n};\n\n/**\n * Decorator helper for types (TypeScript).\n * @param {Constructor} ctor Constructor function\n * @param {string} [typeName] Type name, defaults to the constructor's name\n * @returns {Type} Reflected type\n * @template T extends Message\n * @property {Root} root Decorators root\n */\nutil.decorateType = function decorateType(ctor, typeName) {\n\n /* istanbul ignore if */\n if (ctor.$type) {\n if (typeName && ctor.$type.name !== typeName) {\n util.decorateRoot.remove(ctor.$type);\n ctor.$type.name = typeName;\n util.decorateRoot.add(ctor.$type);\n }\n return ctor.$type;\n }\n\n /* istanbul ignore next */\n if (!Type)\n Type = require(35);\n\n var type = new Type(typeName || ctor.name);\n util.decorateRoot.add(type);\n type.ctor = ctor; // sets up .encode, .decode etc.\n Object.defineProperty(ctor, \"$type\", { value: type, enumerable: false });\n Object.defineProperty(ctor.prototype, \"$type\", { value: type, enumerable: false });\n return type;\n};\n\nvar decorateEnumIndex = 0;\n\n/**\n * Decorator helper for enums (TypeScript).\n * @param {Object} object Enum object\n * @returns {Enum} Reflected enum\n */\nutil.decorateEnum = function decorateEnum(object) {\n\n /* istanbul ignore if */\n if (object.$type)\n return object.$type;\n\n /* istanbul ignore next */\n if (!Enum)\n Enum = require(15);\n\n var enm = new Enum(\"Enum\" + decorateEnumIndex++, object);\n util.decorateRoot.add(enm);\n Object.defineProperty(object, \"$type\", { value: enm, enumerable: false });\n return enm;\n};\n\n\n/**\n * Sets the value of a property by property path. If a value already exists, it is turned to an array\n * @param {Object.} dst Destination object\n * @param {string} path dot '.' delimited path of the property to set\n * @param {Object} value the value to set\n * @returns {Object.} Destination object\n */\nutil.setProperty = function setProperty(dst, path, value) {\n function setProp(dst, path, value) {\n var part = path.shift();\n if (part === \"__proto__\" || part === \"prototype\") {\n return dst;\n }\n if (path.length > 0) {\n dst[part] = setProp(dst[part] || {}, path, value);\n } else {\n var prevValue = dst[part];\n if (prevValue)\n value = [].concat(prevValue).concat(value);\n dst[part] = value;\n }\n return dst;\n }\n\n if (typeof dst !== \"object\")\n throw TypeError(\"dst must be an object\");\n if (!path)\n throw TypeError(\"path must be specified\");\n\n path = path.split(\".\");\n return setProp(dst, path, value);\n};\n\n/**\n * Decorator root (TypeScript).\n * @name util.decorateRoot\n * @type {Root}\n * @readonly\n */\nObject.defineProperty(util, \"decorateRoot\", {\n get: function() {\n return roots[\"decorated\"] || (roots[\"decorated\"] = new (require(29))());\n }\n});\n","\"use strict\";\nmodule.exports = LongBits;\n\nvar util = require(39);\n\n/**\n * Constructs new long bits.\n * @classdesc Helper class for working with the low and high bits of a 64 bit value.\n * @memberof util\n * @constructor\n * @param {number} lo Low 32 bits, unsigned\n * @param {number} hi High 32 bits, unsigned\n */\nfunction LongBits(lo, hi) {\n\n // note that the casts below are theoretically unnecessary as of today, but older statically\n // generated converter code might still call the ctor with signed 32bits. kept for compat.\n\n /**\n * Low bits.\n * @type {number}\n */\n this.lo = lo >>> 0;\n\n /**\n * High bits.\n * @type {number}\n */\n this.hi = hi >>> 0;\n}\n\n/**\n * Zero bits.\n * @memberof util.LongBits\n * @type {util.LongBits}\n */\nvar zero = LongBits.zero = new LongBits(0, 0);\n\nzero.toNumber = function() { return 0; };\nzero.zzEncode = zero.zzDecode = function() { return this; };\nzero.length = function() { return 1; };\n\n/**\n * Zero hash.\n * @memberof util.LongBits\n * @type {string}\n */\nvar zeroHash = LongBits.zeroHash = \"\\0\\0\\0\\0\\0\\0\\0\\0\";\n\n/**\n * Constructs new long bits from the specified number.\n * @param {number} value Value\n * @returns {util.LongBits} Instance\n */\nLongBits.fromNumber = function fromNumber(value) {\n if (value === 0)\n return zero;\n var sign = value < 0;\n if (sign)\n value = -value;\n var lo = value >>> 0,\n hi = (value - lo) / 4294967296 >>> 0;\n if (sign) {\n hi = ~hi >>> 0;\n lo = ~lo >>> 0;\n if (++lo > 4294967295) {\n lo = 0;\n if (++hi > 4294967295)\n hi = 0;\n }\n }\n return new LongBits(lo, hi);\n};\n\n/**\n * Constructs new long bits from a number, long or string.\n * @param {Long|number|string} value Value\n * @returns {util.LongBits} Instance\n */\nLongBits.from = function from(value) {\n if (typeof value === \"number\")\n return LongBits.fromNumber(value);\n if (util.isString(value)) {\n /* istanbul ignore else */\n if (util.Long)\n value = util.Long.fromString(value);\n else\n return LongBits.fromNumber(parseInt(value, 10));\n }\n return value.low || value.high ? new LongBits(value.low >>> 0, value.high >>> 0) : zero;\n};\n\n/**\n * Converts this long bits to a possibly unsafe JavaScript number.\n * @param {boolean} [unsigned=false] Whether unsigned or not\n * @returns {number} Possibly unsafe number\n */\nLongBits.prototype.toNumber = function toNumber(unsigned) {\n if (!unsigned && this.hi >>> 31) {\n var lo = ~this.lo + 1 >>> 0,\n hi = ~this.hi >>> 0;\n if (!lo)\n hi = hi + 1 >>> 0;\n return -(lo + hi * 4294967296);\n }\n return this.lo + this.hi * 4294967296;\n};\n\n/**\n * Converts this long bits to a long.\n * @param {boolean} [unsigned=false] Whether unsigned or not\n * @returns {Long} Long\n */\nLongBits.prototype.toLong = function toLong(unsigned) {\n return util.Long\n ? new util.Long(this.lo | 0, this.hi | 0, Boolean(unsigned))\n /* istanbul ignore next */\n : { low: this.lo | 0, high: this.hi | 0, unsigned: Boolean(unsigned) };\n};\n\nvar charCodeAt = String.prototype.charCodeAt;\n\n/**\n * Constructs new long bits from the specified 8 characters long hash.\n * @param {string} hash Hash\n * @returns {util.LongBits} Bits\n */\nLongBits.fromHash = function fromHash(hash) {\n if (hash === zeroHash)\n return zero;\n return new LongBits(\n ( charCodeAt.call(hash, 0)\n | charCodeAt.call(hash, 1) << 8\n | charCodeAt.call(hash, 2) << 16\n | charCodeAt.call(hash, 3) << 24) >>> 0\n ,\n ( charCodeAt.call(hash, 4)\n | charCodeAt.call(hash, 5) << 8\n | charCodeAt.call(hash, 6) << 16\n | charCodeAt.call(hash, 7) << 24) >>> 0\n );\n};\n\n/**\n * Converts this long bits to a 8 characters long hash.\n * @returns {string} Hash\n */\nLongBits.prototype.toHash = function toHash() {\n return String.fromCharCode(\n this.lo & 255,\n this.lo >>> 8 & 255,\n this.lo >>> 16 & 255,\n this.lo >>> 24 ,\n this.hi & 255,\n this.hi >>> 8 & 255,\n this.hi >>> 16 & 255,\n this.hi >>> 24\n );\n};\n\n/**\n * Zig-zag encodes this long bits.\n * @returns {util.LongBits} `this`\n */\nLongBits.prototype.zzEncode = function zzEncode() {\n var mask = this.hi >> 31;\n this.hi = ((this.hi << 1 | this.lo >>> 31) ^ mask) >>> 0;\n this.lo = ( this.lo << 1 ^ mask) >>> 0;\n return this;\n};\n\n/**\n * Zig-zag decodes this long bits.\n * @returns {util.LongBits} `this`\n */\nLongBits.prototype.zzDecode = function zzDecode() {\n var mask = -(this.lo & 1);\n this.lo = ((this.lo >>> 1 | this.hi << 31) ^ mask) >>> 0;\n this.hi = ( this.hi >>> 1 ^ mask) >>> 0;\n return this;\n};\n\n/**\n * Calculates the length of this longbits when encoded as a varint.\n * @returns {number} Length\n */\nLongBits.prototype.length = function length() {\n var part0 = this.lo,\n part1 = (this.lo >>> 28 | this.hi << 4) >>> 0,\n part2 = this.hi >>> 24;\n return part2 === 0\n ? part1 === 0\n ? part0 < 16384\n ? part0 < 128 ? 1 : 2\n : part0 < 2097152 ? 3 : 4\n : part1 < 16384\n ? part1 < 128 ? 5 : 6\n : part1 < 2097152 ? 7 : 8\n : part2 < 128 ? 9 : 10;\n};\n","\"use strict\";\nvar util = exports;\n\n// used to return a Promise where callback is omitted\nutil.asPromise = require(1);\n\n// converts to / from base64 encoded strings\nutil.base64 = require(2);\n\n// base class of rpc.Service\nutil.EventEmitter = require(4);\n\n// float handling accross browsers\nutil.float = require(6);\n\n// requires modules optionally and hides the call from bundlers\nutil.inquire = require(7);\n\n// converts to / from utf8 encoded strings\nutil.utf8 = require(10);\n\n// provides a node-like buffer pool in the browser\nutil.pool = require(9);\n\n// utility to work with the low and high bits of a 64 bit value\nutil.LongBits = require(38);\n\n/**\n * Whether running within node or not.\n * @memberof util\n * @type {boolean}\n */\nutil.isNode = Boolean(typeof global !== \"undefined\"\n && global\n && global.process\n && global.process.versions\n && global.process.versions.node);\n\n/**\n * Global object reference.\n * @memberof util\n * @type {Object}\n */\nutil.global = util.isNode && global\n || typeof window !== \"undefined\" && window\n || typeof self !== \"undefined\" && self\n || this; // eslint-disable-line no-invalid-this\n\n/**\n * An immuable empty array.\n * @memberof util\n * @type {Array.<*>}\n * @const\n */\nutil.emptyArray = Object.freeze ? Object.freeze([]) : /* istanbul ignore next */ []; // used on prototypes\n\n/**\n * An immutable empty object.\n * @type {Object}\n * @const\n */\nutil.emptyObject = Object.freeze ? Object.freeze({}) : /* istanbul ignore next */ {}; // used on prototypes\n\n/**\n * Tests if the specified value is an integer.\n * @function\n * @param {*} value Value to test\n * @returns {boolean} `true` if the value is an integer\n */\nutil.isInteger = Number.isInteger || /* istanbul ignore next */ function isInteger(value) {\n return typeof value === \"number\" && isFinite(value) && Math.floor(value) === value;\n};\n\n/**\n * Tests if the specified value is a string.\n * @param {*} value Value to test\n * @returns {boolean} `true` if the value is a string\n */\nutil.isString = function isString(value) {\n return typeof value === \"string\" || value instanceof String;\n};\n\n/**\n * Tests if the specified value is a non-null object.\n * @param {*} value Value to test\n * @returns {boolean} `true` if the value is a non-null object\n */\nutil.isObject = function isObject(value) {\n return value && typeof value === \"object\";\n};\n\n/**\n * Checks if a property on a message is considered to be present.\n * This is an alias of {@link util.isSet}.\n * @function\n * @param {Object} obj Plain object or message instance\n * @param {string} prop Property name\n * @returns {boolean} `true` if considered to be present, otherwise `false`\n */\nutil.isset =\n\n/**\n * Checks if a property on a message is considered to be present.\n * @param {Object} obj Plain object or message instance\n * @param {string} prop Property name\n * @returns {boolean} `true` if considered to be present, otherwise `false`\n */\nutil.isSet = function isSet(obj, prop) {\n var value = obj[prop];\n if (value != null && obj.hasOwnProperty(prop)) // eslint-disable-line eqeqeq, no-prototype-builtins\n return typeof value !== \"object\" || (Array.isArray(value) ? value.length : Object.keys(value).length) > 0;\n return false;\n};\n\n/**\n * Any compatible Buffer instance.\n * This is a minimal stand-alone definition of a Buffer instance. The actual type is that exported by node's typings.\n * @interface Buffer\n * @extends Uint8Array\n */\n\n/**\n * Node's Buffer class if available.\n * @type {Constructor}\n */\nutil.Buffer = (function() {\n try {\n var Buffer = util.inquire(\"buffer\").Buffer;\n // refuse to use non-node buffers if not explicitly assigned (perf reasons):\n return Buffer.prototype.utf8Write ? Buffer : /* istanbul ignore next */ null;\n } catch (e) {\n /* istanbul ignore next */\n return null;\n }\n})();\n\n// Internal alias of or polyfull for Buffer.from.\nutil._Buffer_from = null;\n\n// Internal alias of or polyfill for Buffer.allocUnsafe.\nutil._Buffer_allocUnsafe = null;\n\n/**\n * Creates a new buffer of whatever type supported by the environment.\n * @param {number|number[]} [sizeOrArray=0] Buffer size or number array\n * @returns {Uint8Array|Buffer} Buffer\n */\nutil.newBuffer = function newBuffer(sizeOrArray) {\n /* istanbul ignore next */\n return typeof sizeOrArray === \"number\"\n ? util.Buffer\n ? util._Buffer_allocUnsafe(sizeOrArray)\n : new util.Array(sizeOrArray)\n : util.Buffer\n ? util._Buffer_from(sizeOrArray)\n : typeof Uint8Array === \"undefined\"\n ? sizeOrArray\n : new Uint8Array(sizeOrArray);\n};\n\n/**\n * Array implementation used in the browser. `Uint8Array` if supported, otherwise `Array`.\n * @type {Constructor}\n */\nutil.Array = typeof Uint8Array !== \"undefined\" ? Uint8Array /* istanbul ignore next */ : Array;\n\n/**\n * Any compatible Long instance.\n * This is a minimal stand-alone definition of a Long instance. The actual type is that exported by long.js.\n * @interface Long\n * @property {number} low Low bits\n * @property {number} high High bits\n * @property {boolean} unsigned Whether unsigned or not\n */\n\n/**\n * Long.js's Long class if available.\n * @type {Constructor}\n */\nutil.Long = /* istanbul ignore next */ util.global.dcodeIO && /* istanbul ignore next */ util.global.dcodeIO.Long\n || /* istanbul ignore next */ util.global.Long\n || util.inquire(\"long\");\n\n/**\n * Regular expression used to verify 2 bit (`bool`) map keys.\n * @type {RegExp}\n * @const\n */\nutil.key2Re = /^true|false|0|1$/;\n\n/**\n * Regular expression used to verify 32 bit (`int32` etc.) map keys.\n * @type {RegExp}\n * @const\n */\nutil.key32Re = /^-?(?:0|[1-9][0-9]*)$/;\n\n/**\n * Regular expression used to verify 64 bit (`int64` etc.) map keys.\n * @type {RegExp}\n * @const\n */\nutil.key64Re = /^(?:[\\\\x00-\\\\xff]{8}|-?(?:0|[1-9][0-9]*))$/;\n\n/**\n * Converts a number or long to an 8 characters long hash string.\n * @param {Long|number} value Value to convert\n * @returns {string} Hash\n */\nutil.longToHash = function longToHash(value) {\n return value\n ? util.LongBits.from(value).toHash()\n : util.LongBits.zeroHash;\n};\n\n/**\n * Converts an 8 characters long hash string to a long or number.\n * @param {string} hash Hash\n * @param {boolean} [unsigned=false] Whether unsigned or not\n * @returns {Long|number} Original value\n */\nutil.longFromHash = function longFromHash(hash, unsigned) {\n var bits = util.LongBits.fromHash(hash);\n if (util.Long)\n return util.Long.fromBits(bits.lo, bits.hi, unsigned);\n return bits.toNumber(Boolean(unsigned));\n};\n\n/**\n * Merges the properties of the source object into the destination object.\n * @memberof util\n * @param {Object.} dst Destination object\n * @param {Object.} src Source object\n * @param {boolean} [ifNotSet=false] Merges only if the key is not already set\n * @returns {Object.} Destination object\n */\nfunction merge(dst, src, ifNotSet) { // used by converters\n for (var keys = Object.keys(src), i = 0; i < keys.length; ++i)\n if (dst[keys[i]] === undefined || !ifNotSet)\n dst[keys[i]] = src[keys[i]];\n return dst;\n}\n\nutil.merge = merge;\n\n/**\n * Converts the first character of a string to lower case.\n * @param {string} str String to convert\n * @returns {string} Converted string\n */\nutil.lcFirst = function lcFirst(str) {\n return str.charAt(0).toLowerCase() + str.substring(1);\n};\n\n/**\n * Creates a custom error constructor.\n * @memberof util\n * @param {string} name Error name\n * @returns {Constructor} Custom error constructor\n */\nfunction newError(name) {\n\n function CustomError(message, properties) {\n\n if (!(this instanceof CustomError))\n return new CustomError(message, properties);\n\n // Error.call(this, message);\n // ^ just returns a new error instance because the ctor can be called as a function\n\n Object.defineProperty(this, \"message\", { get: function() { return message; } });\n\n /* istanbul ignore next */\n if (Error.captureStackTrace) // node\n Error.captureStackTrace(this, CustomError);\n else\n Object.defineProperty(this, \"stack\", { value: new Error().stack || \"\" });\n\n if (properties)\n merge(this, properties);\n }\n\n CustomError.prototype = Object.create(Error.prototype, {\n constructor: {\n value: CustomError,\n writable: true,\n enumerable: false,\n configurable: true,\n },\n name: {\n get: function get() { return name; },\n set: undefined,\n enumerable: false,\n // configurable: false would accurately preserve the behavior of\n // the original, but I'm guessing that was not intentional.\n // For an actual error subclass, this property would\n // be configurable.\n configurable: true,\n },\n toString: {\n value: function value() { return this.name + \": \" + this.message; },\n writable: true,\n enumerable: false,\n configurable: true,\n },\n });\n\n return CustomError;\n}\n\nutil.newError = newError;\n\n/**\n * Constructs a new protocol error.\n * @classdesc Error subclass indicating a protocol specifc error.\n * @memberof util\n * @extends Error\n * @template T extends Message\n * @constructor\n * @param {string} message Error message\n * @param {Object.} [properties] Additional properties\n * @example\n * try {\n * MyMessage.decode(someBuffer); // throws if required fields are missing\n * } catch (e) {\n * if (e instanceof ProtocolError && e.instance)\n * console.log(\"decoded so far: \" + JSON.stringify(e.instance));\n * }\n */\nutil.ProtocolError = newError(\"ProtocolError\");\n\n/**\n * So far decoded message instance.\n * @name util.ProtocolError#instance\n * @type {Message}\n */\n\n/**\n * A OneOf getter as returned by {@link util.oneOfGetter}.\n * @typedef OneOfGetter\n * @type {function}\n * @returns {string|undefined} Set field name, if any\n */\n\n/**\n * Builds a getter for a oneof's present field name.\n * @param {string[]} fieldNames Field names\n * @returns {OneOfGetter} Unbound getter\n */\nutil.oneOfGetter = function getOneOf(fieldNames) {\n var fieldMap = {};\n for (var i = 0; i < fieldNames.length; ++i)\n fieldMap[fieldNames[i]] = 1;\n\n /**\n * @returns {string|undefined} Set field name, if any\n * @this Object\n * @ignore\n */\n return function() { // eslint-disable-line consistent-return\n for (var keys = Object.keys(this), i = keys.length - 1; i > -1; --i)\n if (fieldMap[keys[i]] === 1 && this[keys[i]] !== undefined && this[keys[i]] !== null)\n return keys[i];\n };\n};\n\n/**\n * A OneOf setter as returned by {@link util.oneOfSetter}.\n * @typedef OneOfSetter\n * @type {function}\n * @param {string|undefined} value Field name\n * @returns {undefined}\n */\n\n/**\n * Builds a setter for a oneof's present field name.\n * @param {string[]} fieldNames Field names\n * @returns {OneOfSetter} Unbound setter\n */\nutil.oneOfSetter = function setOneOf(fieldNames) {\n\n /**\n * @param {string} name Field name\n * @returns {undefined}\n * @this Object\n * @ignore\n */\n return function(name) {\n for (var i = 0; i < fieldNames.length; ++i)\n if (fieldNames[i] !== name)\n delete this[fieldNames[i]];\n };\n};\n\n/**\n * Default conversion options used for {@link Message#toJSON} implementations.\n *\n * These options are close to proto3's JSON mapping with the exception that internal types like Any are handled just like messages. More precisely:\n *\n * - Longs become strings\n * - Enums become string keys\n * - Bytes become base64 encoded strings\n * - (Sub-)Messages become plain objects\n * - Maps become plain objects with all string keys\n * - Repeated fields become arrays\n * - NaN and Infinity for float and double fields become strings\n *\n * @type {IConversionOptions}\n * @see https://developers.google.com/protocol-buffers/docs/proto3?hl=en#json\n */\nutil.toJSONOptions = {\n longs: String,\n enums: String,\n bytes: String,\n json: true\n};\n\n// Sets up buffer utility according to the environment (called in index-minimal)\nutil._configure = function() {\n var Buffer = util.Buffer;\n /* istanbul ignore if */\n if (!Buffer) {\n util._Buffer_from = util._Buffer_allocUnsafe = null;\n return;\n }\n // because node 4.x buffers are incompatible & immutable\n // see: https://github.com/dcodeIO/protobuf.js/pull/665\n util._Buffer_from = Buffer.from !== Uint8Array.from && Buffer.from ||\n /* istanbul ignore next */\n function Buffer_from(value, encoding) {\n return new Buffer(value, encoding);\n };\n util._Buffer_allocUnsafe = Buffer.allocUnsafe ||\n /* istanbul ignore next */\n function Buffer_allocUnsafe(size) {\n return new Buffer(size);\n };\n};\n","\"use strict\";\nmodule.exports = verifier;\n\nvar Enum = require(15),\n util = require(37);\n\nfunction invalid(field, expected) {\n return field.name + \": \" + expected + (field.repeated && expected !== \"array\" ? \"[]\" : field.map && expected !== \"object\" ? \"{k:\"+field.keyType+\"}\" : \"\") + \" expected\";\n}\n\n/**\n * Generates a partial value verifier.\n * @param {Codegen} gen Codegen instance\n * @param {Field} field Reflected field\n * @param {number} fieldIndex Field index\n * @param {string} ref Variable reference\n * @returns {Codegen} Codegen instance\n * @ignore\n */\nfunction genVerifyValue(gen, field, fieldIndex, ref) {\n /* eslint-disable no-unexpected-multiline */\n if (field.resolvedType) {\n if (field.resolvedType instanceof Enum) { gen\n (\"switch(%s){\", ref)\n (\"default:\")\n (\"return%j\", invalid(field, \"enum value\"));\n for (var keys = Object.keys(field.resolvedType.values), j = 0; j < keys.length; ++j) gen\n (\"case %i:\", field.resolvedType.values[keys[j]]);\n gen\n (\"break\")\n (\"}\");\n } else {\n gen\n (\"{\")\n (\"var e=types[%i].verify(%s);\", fieldIndex, ref)\n (\"if(e)\")\n (\"return%j+e\", field.name + \".\")\n (\"}\");\n }\n } else {\n switch (field.type) {\n case \"int32\":\n case \"uint32\":\n case \"sint32\":\n case \"fixed32\":\n case \"sfixed32\": gen\n (\"if(!util.isInteger(%s))\", ref)\n (\"return%j\", invalid(field, \"integer\"));\n break;\n case \"int64\":\n case \"uint64\":\n case \"sint64\":\n case \"fixed64\":\n case \"sfixed64\": gen\n (\"if(!util.isInteger(%s)&&!(%s&&util.isInteger(%s.low)&&util.isInteger(%s.high)))\", ref, ref, ref, ref)\n (\"return%j\", invalid(field, \"integer|Long\"));\n break;\n case \"float\":\n case \"double\": gen\n (\"if(typeof %s!==\\\"number\\\")\", ref)\n (\"return%j\", invalid(field, \"number\"));\n break;\n case \"bool\": gen\n (\"if(typeof %s!==\\\"boolean\\\")\", ref)\n (\"return%j\", invalid(field, \"boolean\"));\n break;\n case \"string\": gen\n (\"if(!util.isString(%s))\", ref)\n (\"return%j\", invalid(field, \"string\"));\n break;\n case \"bytes\": gen\n (\"if(!(%s&&typeof %s.length===\\\"number\\\"||util.isString(%s)))\", ref, ref, ref)\n (\"return%j\", invalid(field, \"buffer\"));\n break;\n }\n }\n return gen;\n /* eslint-enable no-unexpected-multiline */\n}\n\n/**\n * Generates a partial key verifier.\n * @param {Codegen} gen Codegen instance\n * @param {Field} field Reflected field\n * @param {string} ref Variable reference\n * @returns {Codegen} Codegen instance\n * @ignore\n */\nfunction genVerifyKey(gen, field, ref) {\n /* eslint-disable no-unexpected-multiline */\n switch (field.keyType) {\n case \"int32\":\n case \"uint32\":\n case \"sint32\":\n case \"fixed32\":\n case \"sfixed32\": gen\n (\"if(!util.key32Re.test(%s))\", ref)\n (\"return%j\", invalid(field, \"integer key\"));\n break;\n case \"int64\":\n case \"uint64\":\n case \"sint64\":\n case \"fixed64\":\n case \"sfixed64\": gen\n (\"if(!util.key64Re.test(%s))\", ref) // see comment above: x is ok, d is not\n (\"return%j\", invalid(field, \"integer|Long key\"));\n break;\n case \"bool\": gen\n (\"if(!util.key2Re.test(%s))\", ref)\n (\"return%j\", invalid(field, \"boolean key\"));\n break;\n }\n return gen;\n /* eslint-enable no-unexpected-multiline */\n}\n\n/**\n * Generates a verifier specific to the specified message type.\n * @param {Type} mtype Message type\n * @returns {Codegen} Codegen instance\n */\nfunction verifier(mtype) {\n /* eslint-disable no-unexpected-multiline */\n\n var gen = util.codegen([\"m\"], mtype.name + \"$verify\")\n (\"if(typeof m!==\\\"object\\\"||m===null)\")\n (\"return%j\", \"object expected\");\n var oneofs = mtype.oneofsArray,\n seenFirstField = {};\n if (oneofs.length) gen\n (\"var p={}\");\n\n for (var i = 0; i < /* initializes */ mtype.fieldsArray.length; ++i) {\n var field = mtype._fieldsArray[i].resolve(),\n ref = \"m\" + util.safeProp(field.name);\n\n if (field.optional) gen\n (\"if(%s!=null&&m.hasOwnProperty(%j)){\", ref, field.name); // !== undefined && !== null\n\n // map fields\n if (field.map) { gen\n (\"if(!util.isObject(%s))\", ref)\n (\"return%j\", invalid(field, \"object\"))\n (\"var k=Object.keys(%s)\", ref)\n (\"for(var i=0;i}\n * @const\n */\nvar wrappers = exports;\n\nvar Message = require(21);\n\n/**\n * From object converter part of an {@link IWrapper}.\n * @typedef WrapperFromObjectConverter\n * @type {function}\n * @param {Object.} object Plain object\n * @returns {Message<{}>} Message instance\n * @this Type\n */\n\n/**\n * To object converter part of an {@link IWrapper}.\n * @typedef WrapperToObjectConverter\n * @type {function}\n * @param {Message<{}>} message Message instance\n * @param {IConversionOptions} [options] Conversion options\n * @returns {Object.} Plain object\n * @this Type\n */\n\n/**\n * Common type wrapper part of {@link wrappers}.\n * @interface IWrapper\n * @property {WrapperFromObjectConverter} [fromObject] From object converter\n * @property {WrapperToObjectConverter} [toObject] To object converter\n */\n\n// Custom wrapper for Any\nwrappers[\".google.protobuf.Any\"] = {\n\n fromObject: function(object) {\n\n // unwrap value type if mapped\n if (object && object[\"@type\"]) {\n // Only use fully qualified type name after the last '/'\n var name = object[\"@type\"].substring(object[\"@type\"].lastIndexOf(\"/\") + 1);\n var type = this.lookup(name);\n /* istanbul ignore else */\n if (type) {\n // type_url does not accept leading \".\"\n var type_url = object[\"@type\"].charAt(0) === \".\" ?\n object[\"@type\"].slice(1) : object[\"@type\"];\n // type_url prefix is optional, but path seperator is required\n if (type_url.indexOf(\"/\") === -1) {\n type_url = \"/\" + type_url;\n }\n return this.create({\n type_url: type_url,\n value: type.encode(type.fromObject(object)).finish()\n });\n }\n }\n\n return this.fromObject(object);\n },\n\n toObject: function(message, options) {\n\n // Default prefix\n var googleApi = \"type.googleapis.com/\";\n var prefix = \"\";\n var name = \"\";\n\n // decode value if requested and unmapped\n if (options && options.json && message.type_url && message.value) {\n // Only use fully qualified type name after the last '/'\n name = message.type_url.substring(message.type_url.lastIndexOf(\"/\") + 1);\n // Separate the prefix used\n prefix = message.type_url.substring(0, message.type_url.lastIndexOf(\"/\") + 1);\n var type = this.lookup(name);\n /* istanbul ignore else */\n if (type)\n message = type.decode(message.value);\n }\n\n // wrap value if unmapped\n if (!(message instanceof this.ctor) && message instanceof Message) {\n var object = message.$type.toObject(message, options);\n var messageName = message.$type.fullName[0] === \".\" ?\n message.$type.fullName.slice(1) : message.$type.fullName;\n // Default to type.googleapis.com prefix if no prefix is used\n if (prefix === \"\") {\n prefix = googleApi;\n }\n name = prefix + messageName;\n object[\"@type\"] = name;\n return object;\n }\n\n return this.toObject(message, options);\n }\n};\n","\"use strict\";\nmodule.exports = Writer;\n\nvar util = require(39);\n\nvar BufferWriter; // cyclic\n\nvar LongBits = util.LongBits,\n base64 = util.base64,\n utf8 = util.utf8;\n\n/**\n * Constructs a new writer operation instance.\n * @classdesc Scheduled writer operation.\n * @constructor\n * @param {function(*, Uint8Array, number)} fn Function to call\n * @param {number} len Value byte length\n * @param {*} val Value to write\n * @ignore\n */\nfunction Op(fn, len, val) {\n\n /**\n * Function to call.\n * @type {function(Uint8Array, number, *)}\n */\n this.fn = fn;\n\n /**\n * Value byte length.\n * @type {number}\n */\n this.len = len;\n\n /**\n * Next operation.\n * @type {Writer.Op|undefined}\n */\n this.next = undefined;\n\n /**\n * Value to write.\n * @type {*}\n */\n this.val = val; // type varies\n}\n\n/* istanbul ignore next */\nfunction noop() {} // eslint-disable-line no-empty-function\n\n/**\n * Constructs a new writer state instance.\n * @classdesc Copied writer state.\n * @memberof Writer\n * @constructor\n * @param {Writer} writer Writer to copy state from\n * @ignore\n */\nfunction State(writer) {\n\n /**\n * Current head.\n * @type {Writer.Op}\n */\n this.head = writer.head;\n\n /**\n * Current tail.\n * @type {Writer.Op}\n */\n this.tail = writer.tail;\n\n /**\n * Current buffer length.\n * @type {number}\n */\n this.len = writer.len;\n\n /**\n * Next state.\n * @type {State|null}\n */\n this.next = writer.states;\n}\n\n/**\n * Constructs a new writer instance.\n * @classdesc Wire format writer using `Uint8Array` if available, otherwise `Array`.\n * @constructor\n */\nfunction Writer() {\n\n /**\n * Current length.\n * @type {number}\n */\n this.len = 0;\n\n /**\n * Operations head.\n * @type {Object}\n */\n this.head = new Op(noop, 0, 0);\n\n /**\n * Operations tail\n * @type {Object}\n */\n this.tail = this.head;\n\n /**\n * Linked forked states.\n * @type {Object|null}\n */\n this.states = null;\n\n // When a value is written, the writer calculates its byte length and puts it into a linked\n // list of operations to perform when finish() is called. This both allows us to allocate\n // buffers of the exact required size and reduces the amount of work we have to do compared\n // to first calculating over objects and then encoding over objects. In our case, the encoding\n // part is just a linked list walk calling operations with already prepared values.\n}\n\nvar create = function create() {\n return util.Buffer\n ? function create_buffer_setup() {\n return (Writer.create = function create_buffer() {\n return new BufferWriter();\n })();\n }\n /* istanbul ignore next */\n : function create_array() {\n return new Writer();\n };\n};\n\n/**\n * Creates a new writer.\n * @function\n * @returns {BufferWriter|Writer} A {@link BufferWriter} when Buffers are supported, otherwise a {@link Writer}\n */\nWriter.create = create();\n\n/**\n * Allocates a buffer of the specified size.\n * @param {number} size Buffer size\n * @returns {Uint8Array} Buffer\n */\nWriter.alloc = function alloc(size) {\n return new util.Array(size);\n};\n\n// Use Uint8Array buffer pool in the browser, just like node does with buffers\n/* istanbul ignore else */\nif (util.Array !== Array)\n Writer.alloc = util.pool(Writer.alloc, util.Array.prototype.subarray);\n\n/**\n * Pushes a new operation to the queue.\n * @param {function(Uint8Array, number, *)} fn Function to call\n * @param {number} len Value byte length\n * @param {number} val Value to write\n * @returns {Writer} `this`\n * @private\n */\nWriter.prototype._push = function push(fn, len, val) {\n this.tail = this.tail.next = new Op(fn, len, val);\n this.len += len;\n return this;\n};\n\nfunction writeByte(val, buf, pos) {\n buf[pos] = val & 255;\n}\n\nfunction writeVarint32(val, buf, pos) {\n while (val > 127) {\n buf[pos++] = val & 127 | 128;\n val >>>= 7;\n }\n buf[pos] = val;\n}\n\n/**\n * Constructs a new varint writer operation instance.\n * @classdesc Scheduled varint writer operation.\n * @extends Op\n * @constructor\n * @param {number} len Value byte length\n * @param {number} val Value to write\n * @ignore\n */\nfunction VarintOp(len, val) {\n this.len = len;\n this.next = undefined;\n this.val = val;\n}\n\nVarintOp.prototype = Object.create(Op.prototype);\nVarintOp.prototype.fn = writeVarint32;\n\n/**\n * Writes an unsigned 32 bit value as a varint.\n * @param {number} value Value to write\n * @returns {Writer} `this`\n */\nWriter.prototype.uint32 = function write_uint32(value) {\n // here, the call to this.push has been inlined and a varint specific Op subclass is used.\n // uint32 is by far the most frequently used operation and benefits significantly from this.\n this.len += (this.tail = this.tail.next = new VarintOp(\n (value = value >>> 0)\n < 128 ? 1\n : value < 16384 ? 2\n : value < 2097152 ? 3\n : value < 268435456 ? 4\n : 5,\n value)).len;\n return this;\n};\n\n/**\n * Writes a signed 32 bit value as a varint.\n * @function\n * @param {number} value Value to write\n * @returns {Writer} `this`\n */\nWriter.prototype.int32 = function write_int32(value) {\n return value < 0\n ? this._push(writeVarint64, 10, LongBits.fromNumber(value)) // 10 bytes per spec\n : this.uint32(value);\n};\n\n/**\n * Writes a 32 bit value as a varint, zig-zag encoded.\n * @param {number} value Value to write\n * @returns {Writer} `this`\n */\nWriter.prototype.sint32 = function write_sint32(value) {\n return this.uint32((value << 1 ^ value >> 31) >>> 0);\n};\n\nfunction writeVarint64(val, buf, pos) {\n while (val.hi) {\n buf[pos++] = val.lo & 127 | 128;\n val.lo = (val.lo >>> 7 | val.hi << 25) >>> 0;\n val.hi >>>= 7;\n }\n while (val.lo > 127) {\n buf[pos++] = val.lo & 127 | 128;\n val.lo = val.lo >>> 7;\n }\n buf[pos++] = val.lo;\n}\n\n/**\n * Writes an unsigned 64 bit value as a varint.\n * @param {Long|number|string} value Value to write\n * @returns {Writer} `this`\n * @throws {TypeError} If `value` is a string and no long library is present.\n */\nWriter.prototype.uint64 = function write_uint64(value) {\n var bits = LongBits.from(value);\n return this._push(writeVarint64, bits.length(), bits);\n};\n\n/**\n * Writes a signed 64 bit value as a varint.\n * @function\n * @param {Long|number|string} value Value to write\n * @returns {Writer} `this`\n * @throws {TypeError} If `value` is a string and no long library is present.\n */\nWriter.prototype.int64 = Writer.prototype.uint64;\n\n/**\n * Writes a signed 64 bit value as a varint, zig-zag encoded.\n * @param {Long|number|string} value Value to write\n * @returns {Writer} `this`\n * @throws {TypeError} If `value` is a string and no long library is present.\n */\nWriter.prototype.sint64 = function write_sint64(value) {\n var bits = LongBits.from(value).zzEncode();\n return this._push(writeVarint64, bits.length(), bits);\n};\n\n/**\n * Writes a boolish value as a varint.\n * @param {boolean} value Value to write\n * @returns {Writer} `this`\n */\nWriter.prototype.bool = function write_bool(value) {\n return this._push(writeByte, 1, value ? 1 : 0);\n};\n\nfunction writeFixed32(val, buf, pos) {\n buf[pos ] = val & 255;\n buf[pos + 1] = val >>> 8 & 255;\n buf[pos + 2] = val >>> 16 & 255;\n buf[pos + 3] = val >>> 24;\n}\n\n/**\n * Writes an unsigned 32 bit value as fixed 32 bits.\n * @param {number} value Value to write\n * @returns {Writer} `this`\n */\nWriter.prototype.fixed32 = function write_fixed32(value) {\n return this._push(writeFixed32, 4, value >>> 0);\n};\n\n/**\n * Writes a signed 32 bit value as fixed 32 bits.\n * @function\n * @param {number} value Value to write\n * @returns {Writer} `this`\n */\nWriter.prototype.sfixed32 = Writer.prototype.fixed32;\n\n/**\n * Writes an unsigned 64 bit value as fixed 64 bits.\n * @param {Long|number|string} value Value to write\n * @returns {Writer} `this`\n * @throws {TypeError} If `value` is a string and no long library is present.\n */\nWriter.prototype.fixed64 = function write_fixed64(value) {\n var bits = LongBits.from(value);\n return this._push(writeFixed32, 4, bits.lo)._push(writeFixed32, 4, bits.hi);\n};\n\n/**\n * Writes a signed 64 bit value as fixed 64 bits.\n * @function\n * @param {Long|number|string} value Value to write\n * @returns {Writer} `this`\n * @throws {TypeError} If `value` is a string and no long library is present.\n */\nWriter.prototype.sfixed64 = Writer.prototype.fixed64;\n\n/**\n * Writes a float (32 bit).\n * @function\n * @param {number} value Value to write\n * @returns {Writer} `this`\n */\nWriter.prototype.float = function write_float(value) {\n return this._push(util.float.writeFloatLE, 4, value);\n};\n\n/**\n * Writes a double (64 bit float).\n * @function\n * @param {number} value Value to write\n * @returns {Writer} `this`\n */\nWriter.prototype.double = function write_double(value) {\n return this._push(util.float.writeDoubleLE, 8, value);\n};\n\nvar writeBytes = util.Array.prototype.set\n ? function writeBytes_set(val, buf, pos) {\n buf.set(val, pos); // also works for plain array values\n }\n /* istanbul ignore next */\n : function writeBytes_for(val, buf, pos) {\n for (var i = 0; i < val.length; ++i)\n buf[pos + i] = val[i];\n };\n\n/**\n * Writes a sequence of bytes.\n * @param {Uint8Array|string} value Buffer or base64 encoded string to write\n * @returns {Writer} `this`\n */\nWriter.prototype.bytes = function write_bytes(value) {\n var len = value.length >>> 0;\n if (!len)\n return this._push(writeByte, 1, 0);\n if (util.isString(value)) {\n var buf = Writer.alloc(len = base64.length(value));\n base64.decode(value, buf, 0);\n value = buf;\n }\n return this.uint32(len)._push(writeBytes, len, value);\n};\n\n/**\n * Writes a string.\n * @param {string} value Value to write\n * @returns {Writer} `this`\n */\nWriter.prototype.string = function write_string(value) {\n var len = utf8.length(value);\n return len\n ? this.uint32(len)._push(utf8.write, len, value)\n : this._push(writeByte, 1, 0);\n};\n\n/**\n * Forks this writer's state by pushing it to a stack.\n * Calling {@link Writer#reset|reset} or {@link Writer#ldelim|ldelim} resets the writer to the previous state.\n * @returns {Writer} `this`\n */\nWriter.prototype.fork = function fork() {\n this.states = new State(this);\n this.head = this.tail = new Op(noop, 0, 0);\n this.len = 0;\n return this;\n};\n\n/**\n * Resets this instance to the last state.\n * @returns {Writer} `this`\n */\nWriter.prototype.reset = function reset() {\n if (this.states) {\n this.head = this.states.head;\n this.tail = this.states.tail;\n this.len = this.states.len;\n this.states = this.states.next;\n } else {\n this.head = this.tail = new Op(noop, 0, 0);\n this.len = 0;\n }\n return this;\n};\n\n/**\n * Resets to the last state and appends the fork state's current write length as a varint followed by its operations.\n * @returns {Writer} `this`\n */\nWriter.prototype.ldelim = function ldelim() {\n var head = this.head,\n tail = this.tail,\n len = this.len;\n this.reset().uint32(len);\n if (len) {\n this.tail.next = head.next; // skip noop\n this.tail = tail;\n this.len += len;\n }\n return this;\n};\n\n/**\n * Finishes the write operation.\n * @returns {Uint8Array} Finished buffer\n */\nWriter.prototype.finish = function finish() {\n var head = this.head.next, // skip noop\n buf = this.constructor.alloc(this.len),\n pos = 0;\n while (head) {\n head.fn(head.val, buf, pos);\n pos += head.len;\n head = head.next;\n }\n // this.head = this.tail = null;\n return buf;\n};\n\nWriter._configure = function(BufferWriter_) {\n BufferWriter = BufferWriter_;\n Writer.create = create();\n BufferWriter._configure();\n};\n","\"use strict\";\nmodule.exports = BufferWriter;\n\n// extends Writer\nvar Writer = require(42);\n(BufferWriter.prototype = Object.create(Writer.prototype)).constructor = BufferWriter;\n\nvar util = require(39);\n\n/**\n * Constructs a new buffer writer instance.\n * @classdesc Wire format writer using node buffers.\n * @extends Writer\n * @constructor\n */\nfunction BufferWriter() {\n Writer.call(this);\n}\n\nBufferWriter._configure = function () {\n /**\n * Allocates a buffer of the specified size.\n * @function\n * @param {number} size Buffer size\n * @returns {Buffer} Buffer\n */\n BufferWriter.alloc = util._Buffer_allocUnsafe;\n\n BufferWriter.writeBytesBuffer = util.Buffer && util.Buffer.prototype instanceof Uint8Array && util.Buffer.prototype.set.name === \"set\"\n ? function writeBytesBuffer_set(val, buf, pos) {\n buf.set(val, pos); // faster than copy (requires node >= 4 where Buffers extend Uint8Array and set is properly inherited)\n // also works for plain array values\n }\n /* istanbul ignore next */\n : function writeBytesBuffer_copy(val, buf, pos) {\n if (val.copy) // Buffer values\n val.copy(buf, pos, 0, val.length);\n else for (var i = 0; i < val.length;) // plain array values\n buf[pos++] = val[i++];\n };\n};\n\n\n/**\n * @override\n */\nBufferWriter.prototype.bytes = function write_bytes_buffer(value) {\n if (util.isString(value))\n value = util._Buffer_from(value, \"base64\");\n var len = value.length >>> 0;\n this.uint32(len);\n if (len)\n this._push(BufferWriter.writeBytesBuffer, len, value);\n return this;\n};\n\nfunction writeStringBuffer(val, buf, pos) {\n if (val.length < 40) // plain js is faster for short strings (probably due to redundant assertions)\n util.utf8.write(val, buf, pos);\n else if (buf.utf8Write)\n buf.utf8Write(val, pos);\n else\n buf.write(val, pos);\n}\n\n/**\n * @override\n */\nBufferWriter.prototype.string = function write_string_buffer(value) {\n var len = util.Buffer.byteLength(value);\n this.uint32(len);\n if (len)\n this._push(writeStringBuffer, len, value);\n return this;\n};\n\n\n/**\n * Finishes the write operation.\n * @name BufferWriter#finish\n * @function\n * @returns {Buffer} Finished buffer\n */\n\nBufferWriter._configure();\n"],"sourceRoot":"."} \ No newline at end of file diff --git a/node_modules/protobufjs/dist/protobuf.min.js b/node_modules/protobufjs/dist/protobuf.min.js new file mode 100644 index 0000000..2a238fb --- /dev/null +++ b/node_modules/protobufjs/dist/protobuf.min.js @@ -0,0 +1,8 @@ +/*! + * protobuf.js v7.3.0 (c) 2016, daniel wirtz + * compiled fri, 10 may 2024 03:38:35 utc + * licensed under the bsd-3-clause license + * see: https://github.com/dcodeio/protobuf.js for details + */ +!function(nt){"use strict";!function(r,e,t){var i=function t(i){var n=e[i];return n||r[i][0].call(n=e[i]={exports:{}},t,n,n.exports),n.exports}(t[0]);i.util.global.protobuf=i,"function"==typeof define&&define.amd&&define(["long"],function(t){return t&&t.isLong&&(i.util.Long=t,i.configure()),i}),"object"==typeof module&&module&&module.exports&&(module.exports=i)}({1:[function(t,i,n){i.exports=function(t,i){var n=Array(arguments.length-1),s=0,r=2,o=!0;for(;r>2],r=(3&f)<<4,u=1;break;case 1:s[o++]=h[r|f>>4],r=(15&f)<<2,u=2;break;case 2:s[o++]=h[r|f>>6],s[o++]=h[63&f],u=0}8191>4,r=u,s=2;break;case 2:i[n++]=(15&r)<<4|(60&u)>>2,r=u,s=3;break;case 3:i[n++]=(3&r)<<6|u,s=0}}if(1===s)throw Error(a);return n-e},n.test=function(t){return/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(t)}},{}],3:[function(t,i,n){function c(i,n){"string"==typeof i&&(n=i,i=nt);var f=[];function h(t){if("string"!=typeof t){var i=a();if(c.verbose&&console.log("codegen: "+i),i="return "+i,t){for(var n=Object.keys(t),r=Array(n.length+1),e=Array(n.length),s=0;s>>0:i<11754943508222875e-54?(e<<31|Math.round(i/1401298464324817e-60))>>>0:(e<<31|127+(t=Math.floor(Math.log(i)/Math.LN2))<<23|8388607&Math.round(i*Math.pow(2,-t)*8388608))>>>0,n,r)}function n(t,i,n){t=t(i,n),i=2*(t>>31)+1,n=t>>>23&255,t&=8388607;return 255==n?t?NaN:1/0*i:0==n?1401298464324817e-60*i*t:i*Math.pow(2,n-150)*(8388608+t)}function r(t,i,n){u[0]=t,i[n]=f[0],i[n+1]=f[1],i[n+2]=f[2],i[n+3]=f[3]}function e(t,i,n){u[0]=t,i[n]=f[3],i[n+1]=f[2],i[n+2]=f[1],i[n+3]=f[0]}function s(t,i){return f[0]=t[i],f[1]=t[i+1],f[2]=t[i+2],f[3]=t[i+3],u[0]}function o(t,i){return f[3]=t[i],f[2]=t[i+1],f[1]=t[i+2],f[0]=t[i+3],u[0]}var u,f,h,a,c;function l(t,i,n,r,e,s){var o,u=r<0?1:0;0===(r=u?-r:r)?(t(0,e,s+i),t(0<1/r?0:2147483648,e,s+n)):isNaN(r)?(t(0,e,s+i),t(2146959360,e,s+n)):17976931348623157e292>>0,e,s+n)):r<22250738585072014e-324?(t((o=r/5e-324)>>>0,e,s+i),t((u<<31|o/4294967296)>>>0,e,s+n)):(t(4503599627370496*(o=r*Math.pow(2,-(r=1024===(r=Math.floor(Math.log(r)/Math.LN2))?1023:r)))>>>0,e,s+i),t((u<<31|r+1023<<20|1048576*o&1048575)>>>0,e,s+n))}function d(t,i,n,r,e){i=t(r,e+i),t=t(r,e+n),r=2*(t>>31)+1,e=t>>>20&2047,n=4294967296*(1048575&t)+i;return 2047==e?n?NaN:1/0*r:0==e?5e-324*r*n:r*Math.pow(2,e-1075)*(n+4503599627370496)}function p(t,i,n){h[0]=t,i[n]=a[0],i[n+1]=a[1],i[n+2]=a[2],i[n+3]=a[3],i[n+4]=a[4],i[n+5]=a[5],i[n+6]=a[6],i[n+7]=a[7]}function v(t,i,n){h[0]=t,i[n]=a[7],i[n+1]=a[6],i[n+2]=a[5],i[n+3]=a[4],i[n+4]=a[3],i[n+5]=a[2],i[n+6]=a[1],i[n+7]=a[0]}function b(t,i){return a[0]=t[i],a[1]=t[i+1],a[2]=t[i+2],a[3]=t[i+3],a[4]=t[i+4],a[5]=t[i+5],a[6]=t[i+6],a[7]=t[i+7],h[0]}function w(t,i){return a[7]=t[i],a[6]=t[i+1],a[5]=t[i+2],a[4]=t[i+3],a[3]=t[i+4],a[2]=t[i+5],a[1]=t[i+6],a[0]=t[i+7],h[0]}return"undefined"!=typeof Float32Array?(u=new Float32Array([-0]),f=new Uint8Array(u.buffer),c=128===f[3],t.writeFloatLE=c?r:e,t.writeFloatBE=c?e:r,t.readFloatLE=c?s:o,t.readFloatBE=c?o:s):(t.writeFloatLE=i.bind(null,y),t.writeFloatBE=i.bind(null,m),t.readFloatLE=n.bind(null,g),t.readFloatBE=n.bind(null,j)),"undefined"!=typeof Float64Array?(h=new Float64Array([-0]),a=new Uint8Array(h.buffer),c=128===a[7],t.writeDoubleLE=c?p:v,t.writeDoubleBE=c?v:p,t.readDoubleLE=c?b:w,t.readDoubleBE=c?w:b):(t.writeDoubleLE=l.bind(null,y,0,4),t.writeDoubleBE=l.bind(null,m,4,0),t.readDoubleLE=d.bind(null,g,0,4),t.readDoubleBE=d.bind(null,j,4,0)),t}function y(t,i,n){i[n]=255&t,i[n+1]=t>>>8&255,i[n+2]=t>>>16&255,i[n+3]=t>>>24}function m(t,i,n){i[n]=t>>>24,i[n+1]=t>>>16&255,i[n+2]=t>>>8&255,i[n+3]=255&t}function g(t,i){return(t[i]|t[i+1]<<8|t[i+2]<<16|t[i+3]<<24)>>>0}function j(t,i){return(t[i]<<24|t[i+1]<<16|t[i+2]<<8|t[i+3])>>>0}i.exports=r(r)},{}],7:[function(t,i,n){function r(t){try{var i=eval("require")(t);if(i&&(i.length||Object.keys(i).length))return i}catch(t){}return null}i.exports=r},{}],8:[function(t,i,n){var e=n.isAbsolute=function(t){return/^(?:\/|\w+:)/.test(t)},r=n.normalize=function(t){var i=(t=t.replace(/\\/g,"/").replace(/\/{2,}/g,"/")).split("/"),n=e(t),t="";n&&(t=i.shift()+"/");for(var r=0;r>>1,s=null,o=r;return function(t){if(t<1||e>10),s[o++]=56320+(1023&r)):s[o++]=(15&r)<<12|(63&t[i++])<<6|63&t[i++],8191>6|192:(55296==(64512&r)&&56320==(64512&(e=t.charCodeAt(o+1)))?(++o,i[n++]=(r=65536+((1023&r)<<10)+(1023&e))>>18|240,i[n++]=r>>12&63|128):i[n++]=r>>12|224,i[n++]=r>>6&63|128),i[n++]=63&r|128);return n-s}},{}],11:[function(t,i,n){i.exports=e;var r=/\/|\./;function e(t,i){r.test(t)||(t="google/protobuf/"+t+".proto",i={nested:{google:{nested:{protobuf:{nested:i}}}}}),e[t]=i}e("any",{Any:{fields:{type_url:{type:"string",id:1},value:{type:"bytes",id:2}}}}),e("duration",{Duration:i={fields:{seconds:{type:"int64",id:1},nanos:{type:"int32",id:2}}}}),e("timestamp",{Timestamp:i}),e("empty",{Empty:{fields:{}}}),e("struct",{Struct:{fields:{fields:{keyType:"string",type:"Value",id:1}}},Value:{oneofs:{kind:{oneof:["nullValue","numberValue","stringValue","boolValue","structValue","listValue"]}},fields:{nullValue:{type:"NullValue",id:1},numberValue:{type:"double",id:2},stringValue:{type:"string",id:3},boolValue:{type:"bool",id:4},structValue:{type:"Struct",id:5},listValue:{type:"ListValue",id:6}}},NullValue:{values:{NULL_VALUE:0}},ListValue:{fields:{values:{rule:"repeated",type:"Value",id:1}}}}),e("wrappers",{DoubleValue:{fields:{value:{type:"double",id:1}}},FloatValue:{fields:{value:{type:"float",id:1}}},Int64Value:{fields:{value:{type:"int64",id:1}}},UInt64Value:{fields:{value:{type:"uint64",id:1}}},Int32Value:{fields:{value:{type:"int32",id:1}}},UInt32Value:{fields:{value:{type:"uint32",id:1}}},BoolValue:{fields:{value:{type:"bool",id:1}}},StringValue:{fields:{value:{type:"string",id:1}}},BytesValue:{fields:{value:{type:"bytes",id:1}}}}),e("field_mask",{FieldMask:{fields:{paths:{rule:"repeated",type:"string",id:1}}}}),e.get=function(t){return e[t]||null}},{}],12:[function(t,i,n){var l=t(15),d=t(37);function o(t,i,n,r){var e=!1;if(i.resolvedType)if(i.resolvedType instanceof l){t("switch(d%s){",r);for(var s=i.resolvedType.values,o=Object.keys(s),u=0;u>>0",r,r);break;case"int32":case"sint32":case"sfixed32":t("m%s=d%s|0",r,r);break;case"uint64":f=!0;case"int64":case"sint64":case"fixed64":case"sfixed64":t("if(util.Long)")("(m%s=util.Long.fromValue(d%s)).unsigned=%j",r,r,f)('else if(typeof d%s==="string")',r)("m%s=parseInt(d%s,10)",r,r)('else if(typeof d%s==="number")',r)("m%s=d%s",r,r)('else if(typeof d%s==="object")',r)("m%s=new util.LongBits(d%s.low>>>0,d%s.high>>>0).toNumber(%s)",r,r,r,f?"true":"");break;case"bytes":t('if(typeof d%s==="string")',r)("util.base64.decode(d%s,m%s=util.newBuffer(util.base64.length(d%s)),0)",r,r,r)("else if(d%s.length >= 0)",r)("m%s=d%s",r,r);break;case"string":t("m%s=String(d%s)",r,r);break;case"bool":t("m%s=Boolean(d%s)",r,r)}}return t}function p(t,i,n,r){if(i.resolvedType)i.resolvedType instanceof l?t("d%s=o.enums===String?(types[%i].values[m%s]===undefined?m%s:types[%i].values[m%s]):m%s",r,n,r,r,n,r,r):t("d%s=types[%i].toObject(m%s,o)",r,n,r);else{var e=!1;switch(i.type){case"double":case"float":t("d%s=o.json&&!isFinite(m%s)?String(m%s):m%s",r,r,r,r);break;case"uint64":e=!0;case"int64":case"sint64":case"fixed64":case"sfixed64":t('if(typeof m%s==="number")',r)("d%s=o.longs===String?String(m%s):m%s",r,r,r)("else")("d%s=o.longs===String?util.Long.prototype.toString.call(m%s):o.longs===Number?new util.LongBits(m%s.low>>>0,m%s.high>>>0).toNumber(%s):m%s",r,r,r,r,e?"true":"",r);break;case"bytes":t("d%s=o.bytes===String?util.base64.encode(m%s,0,m%s.length):o.bytes===Array?Array.prototype.slice.call(m%s):m%s",r,r,r,r,r);break;default:t("d%s=m%s",r,r)}}return t}n.fromObject=function(t){var i=t.fieldsArray,n=d.codegen(["d"],t.name+"$fromObject")("if(d instanceof this.ctor)")("return d");if(!i.length)return n("return new this.ctor");n("var m=new this.ctor");for(var r=0;r>>3){");for(var n=0;n>>3){")("case 1: k=r.%s(); break",r.keyType)("case 2:"),f.basic[e]===nt?i("value=types[%i].decode(r,r.uint32())",n):i("value=r.%s()",e),i("break")("default:")("r.skipType(tag2&7)")("break")("}")("}"),f.long[r.keyType]!==nt?i('%s[typeof k==="object"?util.longToHash(k):k]=value',s):i("%s[k]=value",s)):r.repeated?(i("if(!(%s&&%s.length))",s,s)("%s=[]",s),f.packed[e]!==nt&&i("if((t&7)===2){")("var c2=r.uint32()+r.pos")("while(r.pos>>0,8|a.mapKey[s.keyType],s.keyType),f===nt?n("types[%i].encode(%s[ks[i]],w.uint32(18).fork()).ldelim().ldelim()",o,i):n(".uint32(%i).%s(%s[ks[i]]).ldelim()",16|f,u,i),n("}")("}")):s.repeated?(n("if(%s!=null&&%s.length){",i,i),s.packed&&a.packed[u]!==nt?n("w.uint32(%i).fork()",(s.id<<3|2)>>>0)("for(var i=0;i<%s.length;++i)",i)("w.%s(%s[i])",u,i)("w.ldelim()"):(n("for(var i=0;i<%s.length;++i)",i),f===nt?l(n,s,o,i+"[i]"):n("w.uint32(%i).%s(%s[i])",(s.id<<3|f)>>>0,u,i)),n("}")):(s.optional&&n("if(%s!=null&&Object.hasOwnProperty.call(m,%j))",i,s.name),f===nt?l(n,s,o,i):n("w.uint32(%i).%s(%s)",(s.id<<3|f)>>>0,u,i))}return n("return w")};var h=t(15),a=t(36),c=t(37);function l(t,i,n,r){i.resolvedType.group?t("types[%i].encode(%s,w.uint32(%i)).uint32(%i)",n,r,(i.id<<3|3)>>>0,(i.id<<3|4)>>>0):t("types[%i].encode(%s,w.uint32(%i).fork()).ldelim()",n,r,(i.id<<3|2)>>>0)}},{15:15,36:36,37:37}],15:[function(t,i,n){i.exports=s;var f=t(24),r=(((s.prototype=Object.create(f.prototype)).constructor=s).className="Enum",t(23)),e=t(37);function s(t,i,n,r,e,s){if(f.call(this,t,n),i&&"object"!=typeof i)throw TypeError("values must be an object");if(this.valuesById={},this.values=Object.create(this.valuesById),this.comment=r,this.comments=e||{},this.valuesOptions=s,this.reserved=nt,i)for(var o=Object.keys(i),u=0;ui)return!0;return!1},c.isReservedName=function(t,i){if(t)for(var n=0;n");var e=l();if(!Q.test(e))throw j(e,"name");v("=");var s=new q(g(e),A(l()),n,r);S(s,function(t){if("option"!==t)throw j(t);$(s,t),v(";")},function(){M(s)}),i.add(s);break;case"required":case"repeated":N(u,t);break;case"optional":N(u,y?"proto3_optional":"optional");break;case"oneof":e=u,n=t;if(!Q.test(n=l()))throw j(n,"name");var o=new R(g(n));S(o,function(t){"option"===t?($(o,t),v(";")):(d(t),N(o,"optional"))}),e.add(o);break;case"extensions":E(u.extensions||(u.extensions=[]));break;case"reserved":E(u.reserved||(u.reserved=[]),!0);break;default:if(!y||!Y.test(t))throw j(t);d(t),N(u,"optional")}}),t.add(u)}function N(t,i,n){var r=l();if("group"===r){var e,s,o=t,u=i,f=l();if(Q.test(f))return s=H.lcFirst(f),f===s&&(f=H.ucFirst(f)),v("="),h=A(l()),(e=new L(f)).group=!0,(s=new U(s,h,f,u)).filename=it.filename,S(e,function(t){switch(t){case"option":$(e,t),v(";");break;case"required":case"repeated":N(e,t);break;case"optional":N(e,y?"proto3_optional":"optional");break;case"message":T(e);break;case"enum":V(e);break;default:throw j(t)}}),void o.add(e).add(s);throw j(f,"name")}for(;r.endsWith(".")||p().startsWith(".");)r+=l();if(!Y.test(r))throw j(r,"type");var h=l();if(!Q.test(h))throw j(h,"name");h=g(h),v("=");var a=new U(h,A(l()),r,i,n);S(a,function(t){if("option"!==t)throw j(t);$(a,t),v(";")},function(){M(a)}),"proto3_optional"===i?(u=new R("_"+h),a.setOption("proto3_optional",!0),u.add(a),t.add(u)):t.add(a),y||!a.repeated||P.packed[r]===nt&&P.basic[r]!==nt||a.setOption("packed",!1,!0)}function V(t,i){if(!Q.test(i=l()))throw j(i,"name");var s=new z(i);S(s,function(t){switch(t){case"option":$(s,t),v(";");break;case"reserved":E(s.reserved||(s.reserved=[]),!0);break;default:var i=s,n=t;if(!Q.test(n))throw j(n,"name");v("=");var r=A(l(),!0),e={options:nt,setOption:function(t,i){this.options===nt&&(this.options={}),this.options[t]=i}};return S(e,function(t){if("option"!==t)throw j(t);$(e,t),v(";")},function(){M(e)}),void i.add(n,r,e.comment,e.options)}}),t.add(s)}function $(t,i){var n=v("(",!0);if(!Y.test(i=l()))throw j(i,"name");var r,e=i,s=e,n=(n&&(v(")"),s=e="("+e+")",i=p(),tt.test(i)&&(r=i.slice(1),e+=i,l())),v("="),function t(i,n){if(v("{",!0)){for(var r={};!v("}",!0);){if(!Q.test(h=l()))throw j(h,"name");if(null===h)throw j(h,"end of input");var e,s,o=h;if(v(":",!0),"{"===p())e=t(i,n+"."+h);else if("["===p()){if(e=[],v("[",!0)){for(;s=O(!0),e.push(s),v(",",!0););v("]"),void 0!==s&&_(i,n+"."+h,s)}}else e=O(!0),_(i,n+"."+h,e);var u=r[o];u&&(e=[].concat(u).concat(e)),r[o]=e,v(",",!0),v(";",!0)}return r}var f=O(!0);_(i,n,f);return f}(t,e));i=s,e=n,s=r,(n=t).setParsedOption&&n.setParsedOption(i,e,s)}function _(t,i,n){t.setOption&&t.setOption(i,n)}function M(t){if(v("[",!0)){for(;$(t,"option"),v(",",!0););v("]")}}for(;null!==(h=l());)switch(h){case"package":if(!w)throw j(h);if(r!==nt)throw j("package");if(r=l(),!Y.test(r))throw j(r,"name");m=m.define(r),v(";");break;case"import":if(!w)throw j(h);switch(f=u=void 0,p()){case"weak":f=s=s||[],l();break;case"public":l();default:f=e=e||[]}u=k(),v(";"),f.push(u);break;case"syntax":if(!w)throw j(h);if(v("="),o=k(),!(y="proto3"===o)&&"proto2"!==o)throw j(o,"syntax");v(";");break;case"option":$(m,h),v(";");break;default:if(x(m,h)){w=!1;continue}throw j(h)}return it.filename=null,{package:r,imports:e,weakImports:s,syntax:o,root:i}}},{15:15,16:16,20:20,22:22,25:25,29:29,33:33,34:34,35:35,36:36,37:37}],27:[function(t,i,n){i.exports=f;var r,e=t(39),s=e.LongBits,o=e.utf8;function u(t,i){return RangeError("index out of range: "+t.pos+" + "+(i||1)+" > "+t.len)}function f(t){this.buf=t,this.pos=0,this.len=t.length}function h(){return e.Buffer?function(t){return(f.create=function(t){return e.Buffer.isBuffer(t)?new r(t):c(t)})(t)}:c}var a,c="undefined"!=typeof Uint8Array?function(t){if(t instanceof Uint8Array||Array.isArray(t))return new f(t);throw Error("illegal buffer")}:function(t){if(Array.isArray(t))return new f(t);throw Error("illegal buffer")};function l(){var t=new s(0,0),i=0;if(!(4=this.len)throw u(this);if(t.lo=(t.lo|(127&this.buf[this.pos])<<7*i)>>>0,this.buf[this.pos++]<128)return t}return t.lo=(t.lo|(127&this.buf[this.pos++])<<7*i)>>>0,t}for(;i<4;++i)if(t.lo=(t.lo|(127&this.buf[this.pos])<<7*i)>>>0,this.buf[this.pos++]<128)return t;if(t.lo=(t.lo|(127&this.buf[this.pos])<<28)>>>0,t.hi=(t.hi|(127&this.buf[this.pos])>>4)>>>0,this.buf[this.pos++]<128)return t;if(i=0,4>>0,this.buf[this.pos++]<128)return t}else for(;i<5;++i){if(this.pos>=this.len)throw u(this);if(t.hi=(t.hi|(127&this.buf[this.pos])<<7*i+3)>>>0,this.buf[this.pos++]<128)return t}throw Error("invalid varint encoding")}function d(t,i){return(t[i-4]|t[i-3]<<8|t[i-2]<<16|t[i-1]<<24)>>>0}function p(){if(this.pos+8>this.len)throw u(this,8);return new s(d(this.buf,this.pos+=4),d(this.buf,this.pos+=4))}f.create=h(),f.prototype.c=e.Array.prototype.subarray||e.Array.prototype.slice,f.prototype.uint32=(a=4294967295,function(){if(a=(127&this.buf[this.pos])>>>0,this.buf[this.pos++]<128||(a=(a|(127&this.buf[this.pos])<<7)>>>0,this.buf[this.pos++]<128||(a=(a|(127&this.buf[this.pos])<<14)>>>0,this.buf[this.pos++]<128||(a=(a|(127&this.buf[this.pos])<<21)>>>0,this.buf[this.pos++]<128||(a=(a|(15&this.buf[this.pos])<<28)>>>0,this.buf[this.pos++]<128||!((this.pos+=5)>this.len))))))return a;throw this.pos=this.len,u(this,10)}),f.prototype.int32=function(){return 0|this.uint32()},f.prototype.sint32=function(){var t=this.uint32();return t>>>1^-(1&t)|0},f.prototype.bool=function(){return 0!==this.uint32()},f.prototype.fixed32=function(){if(this.pos+4>this.len)throw u(this,4);return d(this.buf,this.pos+=4)},f.prototype.sfixed32=function(){if(this.pos+4>this.len)throw u(this,4);return 0|d(this.buf,this.pos+=4)},f.prototype.float=function(){if(this.pos+4>this.len)throw u(this,4);var t=e.float.readFloatLE(this.buf,this.pos);return this.pos+=4,t},f.prototype.double=function(){if(this.pos+8>this.len)throw u(this,4);var t=e.float.readDoubleLE(this.buf,this.pos);return this.pos+=8,t},f.prototype.bytes=function(){var t=this.uint32(),i=this.pos,n=this.pos+t;if(n>this.len)throw u(this,t);return this.pos+=t,Array.isArray(this.buf)?this.buf.slice(i,n):i===n?(t=e.Buffer)?t.alloc(0):new this.buf.constructor(0):this.c.call(this.buf,i,n)},f.prototype.string=function(){var t=this.bytes();return o.read(t,0,t.length)},f.prototype.skip=function(t){if("number"==typeof t){if(this.pos+t>this.len)throw u(this,t);this.pos+=t}else do{if(this.pos>=this.len)throw u(this)}while(128&this.buf[this.pos++]);return this},f.prototype.skipType=function(t){switch(t){case 0:this.skip();break;case 1:this.skip(8);break;case 2:this.skip(this.uint32());break;case 3:for(;4!=(t=7&this.uint32());)this.skipType(t);break;case 5:this.skip(4);break;default:throw Error("invalid wire type "+t+" at offset "+this.pos)}return this},f.u=function(t){r=t,f.create=h(),r.u();var i=e.Long?"toLong":"toNumber";e.merge(f.prototype,{int64:function(){return l.call(this)[i](!1)},uint64:function(){return l.call(this)[i](!0)},sint64:function(){return l.call(this).zzDecode()[i](!1)},fixed64:function(){return p.call(this)[i](!0)},sfixed64:function(){return p.call(this)[i](!1)}})}},{39:39}],28:[function(t,i,n){i.exports=s;var r=t(27),e=((s.prototype=Object.create(r.prototype)).constructor=s,t(39));function s(t){r.call(this,t)}s.u=function(){e.Buffer&&(s.prototype.c=e.Buffer.prototype.slice)},s.prototype.string=function(){var t=this.uint32();return this.buf.utf8Slice?this.buf.utf8Slice(this.pos,this.pos=Math.min(this.pos+t,this.len)):this.buf.toString("utf-8",this.pos,this.pos=Math.min(this.pos+t,this.len))},s.u()},{27:27,39:39}],29:[function(t,i,n){i.exports=f;var r,d,p,e=t(23),s=(((f.prototype=Object.create(e.prototype)).constructor=f).className="Root",t(16)),o=t(15),u=t(25),v=t(37);function f(t){e.call(this,"",t),this.deferred=[],this.files=[]}function b(){}f.fromJSON=function(t,i){return i=i||new f,t.options&&i.setOptions(t.options),i.addJSON(t.nested)},f.prototype.resolvePath=v.path.resolve,f.prototype.fetch=v.fetch,f.prototype.load=function t(i,s,e){"function"==typeof s&&(e=s,s=nt);var o=this;if(!e)return v.asPromise(t,o,i,s);var u=e===b;function f(t,i){if(e){if(u)throw t;var n=e;e=null,n(t,i)}}function h(t){var i=t.lastIndexOf("google/protobuf/");if(-1]/g,E=/(?:"([^"\\]*(?:\\.[^"\\]*)*)")/g,A=/(?:'([^'\\]*(?:\\.[^'\\]*)*)')/g,x=/^ *[*/]+ */,S=/^\s*\*?\/*/,T=/\n/g,N=/\s/,r=/\\(.?)/g,e={0:"\0",r:"\r",n:"\n",t:"\t"};function V(t){return t.replace(r,function(t,i){switch(i){case"\\":case"":return i;default:return e[i]||""}})}function s(h,a){h=h.toString();var c=0,l=h.length,d=1,f=0,p={},v=[],b=null;function w(t){return Error("illegal "+t+" (line "+d+")")}function y(t){return h[0|t]||""}function m(t,i,n){var r,e={type:h[0|t++]||"",lineEmpty:!1,leading:n},n=a?2:3,s=t-n;do{if(--s<0||"\n"==(r=h[0|s]||"")){e.lineEmpty=!0;break}}while(" "===r||"\t"===r);for(var o=h.substring(t,i).split(T),u=0;u>>0,this.hi=i>>>0}var s=e.zero=new e(0,0),o=(s.toNumber=function(){return 0},s.zzEncode=s.zzDecode=function(){return this},s.length=function(){return 1},e.zeroHash="\0\0\0\0\0\0\0\0",e.fromNumber=function(t){var i,n;return 0===t?s:(n=(t=(i=t<0)?-t:t)>>>0,t=(t-n)/4294967296>>>0,i&&(t=~t>>>0,n=~n>>>0,4294967295<++n&&(n=0,4294967295<++t&&(t=0))),new e(n,t))},e.from=function(t){if("number"==typeof t)return e.fromNumber(t);if(r.isString(t)){if(!r.Long)return e.fromNumber(parseInt(t,10));t=r.Long.fromString(t)}return t.low||t.high?new e(t.low>>>0,t.high>>>0):s},e.prototype.toNumber=function(t){var i;return!t&&this.hi>>>31?(t=1+~this.lo>>>0,i=~this.hi>>>0,-(t+4294967296*(i=t?i:i+1>>>0))):this.lo+4294967296*this.hi},e.prototype.toLong=function(t){return r.Long?new r.Long(0|this.lo,0|this.hi,!!t):{low:0|this.lo,high:0|this.hi,unsigned:!!t}},String.prototype.charCodeAt);e.fromHash=function(t){return"\0\0\0\0\0\0\0\0"===t?s:new e((o.call(t,0)|o.call(t,1)<<8|o.call(t,2)<<16|o.call(t,3)<<24)>>>0,(o.call(t,4)|o.call(t,5)<<8|o.call(t,6)<<16|o.call(t,7)<<24)>>>0)},e.prototype.toHash=function(){return String.fromCharCode(255&this.lo,this.lo>>>8&255,this.lo>>>16&255,this.lo>>>24,255&this.hi,this.hi>>>8&255,this.hi>>>16&255,this.hi>>>24)},e.prototype.zzEncode=function(){var t=this.hi>>31;return this.hi=((this.hi<<1|this.lo>>>31)^t)>>>0,this.lo=(this.lo<<1^t)>>>0,this},e.prototype.zzDecode=function(){var t=-(1&this.lo);return this.lo=((this.lo>>>1|this.hi<<31)^t)>>>0,this.hi=(this.hi>>>1^t)>>>0,this},e.prototype.length=function(){var t=this.lo,i=(this.lo>>>28|this.hi<<4)>>>0,n=this.hi>>>24;return 0==n?0==i?t<16384?t<128?1:2:t<2097152?3:4:i<16384?i<128?5:6:i<2097152?7:8:n<128?9:10}},{39:39}],39:[function(t,i,n){var r=n;function e(t,i,n){for(var r=Object.keys(i),e=0;e>>7|t.hi<<25)>>>0,t.hi>>>=7;for(;127>>7;i[n++]=t.lo}function b(t,i,n){i[n]=255&t,i[n+1]=t>>>8&255,i[n+2]=t>>>16&255,i[n+3]=t>>>24}c.create=l(),c.alloc=function(t){return new e.Array(t)},e.Array!==Array&&(c.alloc=e.pool(c.alloc,e.Array.prototype.subarray)),c.prototype.g=function(t,i,n){return this.tail=this.tail.next=new f(t,i,n),this.len+=i,this},(p.prototype=Object.create(f.prototype)).fn=function(t,i,n){for(;127>>=7;i[n]=t},c.prototype.uint32=function(t){return this.len+=(this.tail=this.tail.next=new p((t>>>=0)<128?1:t<16384?2:t<2097152?3:t<268435456?4:5,t)).len,this},c.prototype.int32=function(t){return t<0?this.g(v,10,s.fromNumber(t)):this.uint32(t)},c.prototype.sint32=function(t){return this.uint32((t<<1^t>>31)>>>0)},c.prototype.int64=c.prototype.uint64=function(t){t=s.from(t);return this.g(v,t.length(),t)},c.prototype.sint64=function(t){t=s.from(t).zzEncode();return this.g(v,t.length(),t)},c.prototype.bool=function(t){return this.g(d,1,t?1:0)},c.prototype.sfixed32=c.prototype.fixed32=function(t){return this.g(b,4,t>>>0)},c.prototype.sfixed64=c.prototype.fixed64=function(t){t=s.from(t);return this.g(b,4,t.lo).g(b,4,t.hi)},c.prototype.float=function(t){return this.g(e.float.writeFloatLE,4,t)},c.prototype.double=function(t){return this.g(e.float.writeDoubleLE,8,t)};var w=e.Array.prototype.set?function(t,i,n){i.set(t,n)}:function(t,i,n){for(var r=0;r>>0;return n?(e.isString(t)&&(i=c.alloc(n=o.length(t)),o.decode(t,i,0),t=i),this.uint32(n).g(w,n,t)):this.g(d,1,0)},c.prototype.string=function(t){var i=u.length(t);return i?this.uint32(i).g(u.write,i,t):this.g(d,1,0)},c.prototype.fork=function(){return this.states=new a(this),this.head=this.tail=new f(h,0,0),this.len=0,this},c.prototype.reset=function(){return this.states?(this.head=this.states.head,this.tail=this.states.tail,this.len=this.states.len,this.states=this.states.next):(this.head=this.tail=new f(h,0,0),this.len=0),this},c.prototype.ldelim=function(){var t=this.head,i=this.tail,n=this.len;return this.reset().uint32(n),n&&(this.tail.next=t.next,this.tail=i,this.len+=n),this},c.prototype.finish=function(){for(var t=this.head.next,i=this.constructor.alloc(this.len),n=0;t;)t.fn(t.val,i,n),n+=t.len,t=t.next;return i},c.u=function(t){r=t,c.create=l(),r.u()}},{39:39}],43:[function(t,i,n){i.exports=s;var r=t(42),e=((s.prototype=Object.create(r.prototype)).constructor=s,t(39));function s(){r.call(this)}function o(t,i,n){t.length<40?e.utf8.write(t,i,n):i.utf8Write?i.utf8Write(t,n):i.write(t,n)}s.u=function(){s.alloc=e.y,s.writeBytesBuffer=e.Buffer&&e.Buffer.prototype instanceof Uint8Array&&"set"===e.Buffer.prototype.set.name?function(t,i,n){i.set(t,n)}:function(t,i,n){if(t.copy)t.copy(i,n,0,t.length);else for(var r=0;r>>0;return this.uint32(i),i&&this.g(s.writeBytesBuffer,i,t),this},s.prototype.string=function(t){var i=e.Buffer.byteLength(t);return this.uint32(i),i&&this.g(o,i,t),this},s.u()},{39:39,42:42}]},{},[19])}(); +//# sourceMappingURL=protobuf.min.js.map diff --git a/node_modules/protobufjs/dist/protobuf.min.js.map b/node_modules/protobufjs/dist/protobuf.min.js.map new file mode 100644 index 0000000..97f18d4 --- /dev/null +++ b/node_modules/protobufjs/dist/protobuf.min.js.map @@ -0,0 +1 @@ +{"version":3,"sources":["lib/prelude.js","../node_modules/@protobufjs/aspromise/index.js","../node_modules/@protobufjs/base64/index.js","../node_modules/@protobufjs/codegen/index.js","../node_modules/@protobufjs/eventemitter/index.js","../node_modules/@protobufjs/fetch/index.js","../node_modules/@protobufjs/float/index.js","../node_modules/@protobufjs/inquire/index.js","../node_modules/@protobufjs/path/index.js","../node_modules/@protobufjs/pool/index.js","../node_modules/@protobufjs/utf8/index.js","../src/common.js","../src/converter.js","../src/decoder.js","../src/encoder.js","../src/enum.js","../src/field.js","../src/index-light.js","../src/index-minimal.js","../src/index","../src/mapfield.js","../src/message.js","../src/method.js","../src/namespace.js","../src/object.js","../src/oneof.js","../src/parse.js","../src/reader.js","../src/reader_buffer.js","../src/root.js","../src/roots.js","../src/rpc.js","../src/rpc/service.js","../src/service.js","../src/tokenize.js","../src/type.js","../src/types.js","../src/util.js","../src/util/longbits.js","../src/util/minimal.js","../src/verifier.js","../src/wrappers.js","../src/writer.js","../src/writer_buffer.js"],"names":["undefined","modules","cache","entries","protobuf","$require","name","$module","call","exports","util","global","define","amd","Long","isLong","configure","module","1","require","fn","ctx","params","Array","arguments","length","offset","index","pending","Promise","resolve","reject","err","apply","base64","string","p","n","Math","ceil","b64","s64","i","encode","buffer","start","end","t","parts","chunk","j","b","push","String","fromCharCode","slice","join","invalidEncoding","decode","c","charCodeAt","Error","test","codegen","functionParams","functionName","body","Codegen","formatStringOrScope","source","toString","verbose","console","log","scopeKeys","Object","keys","scopeParams","scopeValues","scopeOffset","Function","formatParams","formatOffset","replace","$0","$1","value","Number","floor","JSON","stringify","functionNameOverride","EventEmitter","this","_listeners","prototype","on","evt","off","listeners","splice","emit","args","fetch","asPromise","fs","filename","options","callback","xhr","readFile","contents","XMLHttpRequest","binary","onreadystatechange","readyState","status","response","responseText","Uint8Array","overrideMimeType","responseType","open","send","factory","writeFloat_ieee754","writeUint","val","buf","pos","sign","isNaN","round","exponent","LN2","pow","readFloat_ieee754","readUint","uint","mantissa","NaN","Infinity","writeFloat_f32_cpy","f32","f8b","writeFloat_f32_rev","readFloat_f32_cpy","readFloat_f32_rev","f64","le","writeDouble_ieee754","off0","off1","readDouble_ieee754","lo","hi","writeDouble_f64_cpy","writeDouble_f64_rev","readDouble_f64_cpy","readDouble_f64_rev","Float32Array","writeFloatLE","writeFloatBE","readFloatLE","readFloatBE","bind","writeUintLE","writeUintBE","readUintLE","readUintBE","Float64Array","writeDoubleLE","writeDoubleBE","readDoubleLE","readDoubleBE","inquire","moduleName","mod","eval","e","isAbsolute","path","normalize","split","absolute","prefix","shift","originPath","includePath","alreadyNormalized","alloc","size","SIZE","MAX","slab","utf8","len","read","write","c1","c2","common","commonRe","json","nested","google","Any","fields","type_url","type","id","Duration","timeType","seconds","nanos","Timestamp","Empty","Struct","keyType","Value","oneofs","kind","oneof","nullValue","numberValue","stringValue","boolValue","structValue","listValue","NullValue","values","NULL_VALUE","ListValue","rule","DoubleValue","FloatValue","Int64Value","UInt64Value","Int32Value","UInt32Value","BoolValue","StringValue","BytesValue","FieldMask","paths","get","file","Enum","genValuePartial_fromObject","gen","field","fieldIndex","prop","defaultAlreadyEmitted","resolvedType","typeDefault","repeated","fullName","isUnsigned","genValuePartial_toObject","converter","fromObject","mtype","fieldsArray","safeProp","map","toObject","sort","compareFieldsById","repeatedFields","mapFields","normalFields","partOf","arrayDefault","valuesById","long","low","high","unsigned","toNumber","bytes","hasKs2","_fieldsArray","indexOf","filter","group","ref","types","defaults","basic","packed","rfield","required","wireType","mapKey","genTypePartial","optional","ReflectionObject","Namespace","create","constructor","className","comment","comments","valuesOptions","TypeError","reserved","fromJSON","enm","toJSON","toJSONOptions","keepComments","Boolean","add","isString","isInteger","isReservedId","isReservedName","allow_alias","remove","Field","Type","ruleRe","extend","isObject","toLowerCase","message","defaultValue","extensionField","declaringField","_packed","defineProperty","getOption","setOption","ifNotSet","resolved","parent","lookupTypeOrEnum","proto3_optional","fromNumber","freeze","newBuffer","emptyObject","emptyArray","ctor","d","fieldId","fieldType","fieldRule","decorateType","decorateEnum","fieldName","default","_configure","Type_","build","load","root","Root","loadSync","encoder","decoder","verifier","OneOf","MapField","Service","Method","Message","wrappers","Writer","BufferWriter","Reader","BufferReader","rpc","roots","tokenize","parse","resolvedKeyType","fieldKeyType","fieldValueType","properties","$type","writer","encodeDelimited","reader","decodeDelimited","verify","object","requestType","requestStream","responseStream","parsedOptions","resolvedRequestType","resolvedResponseType","lookupType","arrayToJSON","array","obj","_nestedArray","clearCache","namespace","addJSON","toArray","nestedArray","nestedJson","names","methods","getEnum","prev","setOptions","onAdd","onRemove","isArray","ptr","part","resolveAll","lookup","filterTypes","parentAlreadyChecked","found","lookupEnum","lookupService","Service_","Enum_","defineProperties","unshift","_handleAdd","_handleRemove","setParsedOption","propName","opt","newOpt","find","hasOwnProperty","newValue","setProperty","Root_","fieldNames","addFieldsToParent","oneofName","oneOfGetter","set","oneOfSetter","keepCase","base10Re","base10NegRe","base16Re","base16NegRe","base8Re","base8NegRe","numberRe","nameRe","typeRefRe","fqTypeRefRe","pkg","imports","weakImports","syntax","token","whichImports","preferTrailingComment","tn","alternateCommentMode","next","peek","skip","cmnt","head","isProto3","applyCase","camelCase","illegal","insideTryCatch","line","readString","readValue","acceptTypeRef","parseNumber","substring","parseInt","parseFloat","readRanges","target","acceptStrings","parseId","dummy","ifBlock","parseOption","parseInlineOptions","acceptNegative","parseCommon","parseType","parseEnum","parseService","service","parseMethod","commentText","method","parseExtension","reference","parseField","fnIf","fnElse","trailingLine","parseMapField","valueType","extensions","parseGroup","lcFirst","ucFirst","endsWith","startsWith","parseEnumValue","isCustom","option","optionValue","parseOptionValue","objectResult","lastValue","prevValue","concat","simpleValue","package","LongBits","indexOutOfRange","writeLength","RangeError","Buffer","isBuffer","create_array","readLongVarint","bits","readFixed32_end","readFixed64","_slice","subarray","uint32","int32","sint32","bool","fixed32","sfixed32","float","double","nativeBuffer","skipType","BufferReader_","merge","int64","uint64","sint64","zzDecode","fixed64","sfixed64","utf8Slice","min","deferred","files","SYNC","resolvePath","self","sync","finish","cb","getBundledFileName","idx","lastIndexOf","altname","process","parsed","queued","weak","setTimeout","readFileSync","isNode","exposeRe","tryHandleExtension","sisterField","extendedType","parse_","common_","rpcImpl","requestDelimited","responseDelimited","rpcCall","requestCtor","responseCtor","request","endedByRPC","_methodsArray","inherited","methodsArray","rpcService","methodName","isReserved","m","q","s","delimRe","stringDoubleRe","stringSingleRe","setCommentRe","setCommentAltRe","setCommentSplitRe","whitespaceRe","unescapeRe","unescapeMap","0","r","unescape","str","lastCommentLine","stack","stringDelim","subject","charAt","setComment","isLeading","lineEmpty","leading","lookback","commentOffset","lines","trim","text","isDoubleSlashCommentLine","startOffset","endOffset","findEndOfLine","lineText","cursor","re","match","lastIndex","exec","repeat","curr","isDoc","isLeadingComment","expected","actual","ret","_fieldsById","_oneofsArray","_ctor","fieldsById","oneofsArray","generateConstructor","ctorProperties","setup","originalThis","wrapper","fork","ldelim","typeName","bake","o","safePropBackslashRe","key","safePropQuoteRe","camelCaseRe","toUpperCase","decorateEnumIndex","a","decorateRoot","enumerable","dst","setProp","zero","zzEncode","zeroHash","from","fromString","toLong","fromHash","hash","toHash","mask","part0","part1","part2","src","newError","CustomError","captureStackTrace","writable","configurable","pool","versions","node","window","isFinite","isset","isSet","utf8Write","_Buffer_from","_Buffer_allocUnsafe","sizeOrArray","dcodeIO","key2Re","key32Re","key64Re","longToHash","longFromHash","fromBits","ProtocolError","fieldMap","longs","enums","encoding","allocUnsafe","seenFirstField","oneofProp","invalid","genVerifyValue","messageName","Op","noop","State","tail","states","writeByte","VarintOp","writeVarint64","writeFixed32","_push","writeBytes","reset","BufferWriter_","writeStringBuffer","writeBytesBuffer","copy","byteLength"],"mappings":";;;;;;AAAA,CAAA,SAAAA,IAAA,aAAA,CAAA,SAAAC,EAAAC,EAAAC,GAcA,IAAAC,EAPA,SAAAC,EAAAC,GACA,IAAAC,EAAAL,EAAAI,GAGA,OAFAC,GACAN,EAAAK,GAAA,GAAAE,KAAAD,EAAAL,EAAAI,GAAA,CAAAG,QAAA,EAAA,EAAAJ,EAAAE,EAAAA,EAAAE,OAAA,EACAF,EAAAE,OACA,EAEAN,EAAA,EAAA,EAGAC,EAAAM,KAAAC,OAAAP,SAAAA,EAGA,YAAA,OAAAQ,QAAAA,OAAAC,KACAD,OAAA,CAAA,QAAA,SAAAE,GAKA,OAJAA,GAAAA,EAAAC,SACAX,EAAAM,KAAAI,KAAAA,EACAV,EAAAY,UAAA,GAEAZ,CACA,CAAA,EAGA,UAAA,OAAAa,QAAAA,QAAAA,OAAAR,UACAQ,OAAAR,QAAAL,EAEA,EAAA,CAAAc,EAAA,CAAA,SAAAC,EAAAF,EAAAR,GChCAQ,EAAAR,QAmBA,SAAAW,EAAAC,GACA,IAAAC,EAAAC,MAAAC,UAAAC,OAAA,CAAA,EACAC,EAAA,EACAC,EAAA,EACAC,EAAA,CAAA,EACA,KAAAD,EAAAH,UAAAC,QACAH,EAAAI,CAAA,IAAAF,UAAAG,CAAA,IACA,OAAA,IAAAE,QAAA,SAAAC,EAAAC,GACAT,EAAAI,GAAA,SAAAM,GACA,GAAAJ,EAEA,GADAA,EAAA,CAAA,EACAI,EACAD,EAAAC,CAAA,MACA,CAGA,IAFA,IAAAV,EAAAC,MAAAC,UAAAC,OAAA,CAAA,EACAC,EAAA,EACAA,EAAAJ,EAAAG,QACAH,EAAAI,CAAA,IAAAF,UAAAE,G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,CACAC,OAAA,CACAC,KAAA,CACAC,MAAA,CACA,YACA,cACA,cACA,YACA,cACA,YAEA,CACA,EACAf,OAAA,CACAgB,UAAA,CACAd,KAAA,YACAC,GAAA,CACA,EACAc,YAAA,CACAf,KAAA,SACAC,GAAA,CACA,EACAe,YAAA,CACAhB,KAAA,SACAC,GAAA,CACA,EACAgB,UAAA,CACAjB,KAAA,OACAC,GAAA,CACA,EACAiB,YAAA,CACAlB,KAAA,SACAC,GAAA,CACA,EACAkB,UAAA,CACAnB,KAAA,YACAC,GAAA,CACA,CACA,CACA,EAEAmB,UAAA,CACAC,OAAA,CACAC,WAAA,CACA,CACA,EASAC,UAAA,CACAzB,OAAA,CACAuB,OAAA,CACAG,KAAA,WACAxB,KAAA,QACAC,GAAA,CACA,CACA,CACA,CACA,CAAA,EAEAT,EAAA,WAAA,CASAiC,YAAA,CACA3B,OAAA,CACAzH,MAAA,CACA2H,KAAA,SACAC,GAAA,CACA,CACA,CACA,EASAyB,WAAA,CACA5B,OAAA,CACAzH,MAAA,CACA2H,KAAA,QACAC,GAAA,CACA,CACA,CACA,EASA0B,WAAA,CACA7B,OAAA,CACAzH,MAAA,CACA2H,KAAA,QACAC,GAAA,CACA,CACA,CACA,EASA2B,YAAA,CACA9B,OAAA,CACAzH,MAAA,CACA2H,KAAA,SACAC,GAAA,CACA,CACA,CACA,EASA4B,WAAA,CACA/B,OAAA,CACAzH,MAAA,CACA2H,KAAA,QACAC,GAAA,CACA,CACA,CACA,EASA6B,YAAA,CACAhC,OAAA,CACAzH,MAAA,CACA2H,KAAA,SACAC,GAAA,CACA,CACA,CACA,EASA8B,UAAA,CACAjC,OAAA,CACAzH,MAAA,CACA2H,KAAA,OACAC,GAAA,CACA,CACA,CACA,EASA+B,YAAA,CACAlC,OAAA,CACAzH,MAAA,CACA2H,KAAA,SACAC,GAAA,CACA,CACA,CACA,EASAgC,WAAA,CACAnC,OAAA,CACAzH,MAAA,CACA2H,KAAA,QACAC,GAAA,CACA,CACA,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,CAAA,EACAO,IACA,EAUAqR,EAAAjB,EAAA","file":"protobuf.min.js","sourcesContent":["(function prelude(modules, cache, entries) {\n\n // This is the prelude used to bundle protobuf.js for the browser. Wraps up the CommonJS\n // sources through a conflict-free require shim and is again wrapped within an iife that\n // provides a minification-friendly `undefined` var plus a global \"use strict\" directive\n // so that minification can remove the directives of each module.\n\n function $require(name) {\n var $module = cache[name];\n if (!$module)\n modules[name][0].call($module = cache[name] = { exports: {} }, $require, $module, $module.exports);\n return $module.exports;\n }\n\n var protobuf = $require(entries[0]);\n\n // Expose globally\n protobuf.util.global.protobuf = protobuf;\n\n // Be nice to AMD\n if (typeof define === \"function\" && define.amd)\n define([\"long\"], function(Long) {\n if (Long && Long.isLong) {\n protobuf.util.Long = Long;\n protobuf.configure();\n }\n return protobuf;\n });\n\n // Be nice to CommonJS\n if (typeof module === \"object\" && module && module.exports)\n module.exports = protobuf;\n\n})/* end of prelude */","\"use strict\";\r\nmodule.exports = asPromise;\r\n\r\n/**\r\n * Callback as used by {@link util.asPromise}.\r\n * @typedef asPromiseCallback\r\n * @type {function}\r\n * @param {Error|null} error Error, if any\r\n * @param {...*} params Additional arguments\r\n * @returns {undefined}\r\n */\r\n\r\n/**\r\n * Returns a promise from a node-style callback function.\r\n * @memberof util\r\n * @param {asPromiseCallback} fn Function to call\r\n * @param {*} ctx Function context\r\n * @param {...*} params Function arguments\r\n * @returns {Promise<*>} Promisified function\r\n */\r\nfunction asPromise(fn, ctx/*, varargs */) {\r\n var params = new Array(arguments.length - 1),\r\n offset = 0,\r\n index = 2,\r\n pending = true;\r\n while (index < arguments.length)\r\n params[offset++] = arguments[index++];\r\n return new Promise(function executor(resolve, reject) {\r\n params[offset] = function callback(err/*, varargs */) {\r\n if (pending) {\r\n pending = false;\r\n if (err)\r\n reject(err);\r\n else {\r\n var params = new Array(arguments.length - 1),\r\n offset = 0;\r\n while (offset < params.length)\r\n params[offset++] = arguments[offset];\r\n resolve.apply(null, params);\r\n }\r\n }\r\n };\r\n try {\r\n fn.apply(ctx || null, params);\r\n } catch (err) {\r\n if (pending) {\r\n pending = false;\r\n reject(err);\r\n }\r\n }\r\n });\r\n}\r\n","\"use strict\";\r\n\r\n/**\r\n * A minimal base64 implementation for number arrays.\r\n * @memberof util\r\n * @namespace\r\n */\r\nvar base64 = exports;\r\n\r\n/**\r\n * Calculates the byte length of a base64 encoded string.\r\n * @param {string} string Base64 encoded string\r\n * @returns {number} Byte length\r\n */\r\nbase64.length = function length(string) {\r\n var p = string.length;\r\n if (!p)\r\n return 0;\r\n var n = 0;\r\n while (--p % 4 > 1 && string.charAt(p) === \"=\")\r\n ++n;\r\n return Math.ceil(string.length * 3) / 4 - n;\r\n};\r\n\r\n// Base64 encoding table\r\nvar b64 = new Array(64);\r\n\r\n// Base64 decoding table\r\nvar s64 = new Array(123);\r\n\r\n// 65..90, 97..122, 48..57, 43, 47\r\nfor (var i = 0; i < 64;)\r\n s64[b64[i] = i < 26 ? i + 65 : i < 52 ? i + 71 : i < 62 ? i - 4 : i - 59 | 43] = i++;\r\n\r\n/**\r\n * Encodes a buffer to a base64 encoded string.\r\n * @param {Uint8Array} buffer Source buffer\r\n * @param {number} start Source start\r\n * @param {number} end Source end\r\n * @returns {string} Base64 encoded string\r\n */\r\nbase64.encode = function encode(buffer, start, end) {\r\n var parts = null,\r\n chunk = [];\r\n var i = 0, // output index\r\n j = 0, // goto index\r\n t; // temporary\r\n while (start < end) {\r\n var b = buffer[start++];\r\n switch (j) {\r\n case 0:\r\n chunk[i++] = b64[b >> 2];\r\n t = (b & 3) << 4;\r\n j = 1;\r\n break;\r\n case 1:\r\n chunk[i++] = b64[t | b >> 4];\r\n t = (b & 15) << 2;\r\n j = 2;\r\n break;\r\n case 2:\r\n chunk[i++] = b64[t | b >> 6];\r\n chunk[i++] = b64[b & 63];\r\n j = 0;\r\n break;\r\n }\r\n if (i > 8191) {\r\n (parts || (parts = [])).push(String.fromCharCode.apply(String, chunk));\r\n i = 0;\r\n }\r\n }\r\n if (j) {\r\n chunk[i++] = b64[t];\r\n chunk[i++] = 61;\r\n if (j === 1)\r\n chunk[i++] = 61;\r\n }\r\n if (parts) {\r\n if (i)\r\n parts.push(String.fromCharCode.apply(String, chunk.slice(0, i)));\r\n return parts.join(\"\");\r\n }\r\n return String.fromCharCode.apply(String, chunk.slice(0, i));\r\n};\r\n\r\nvar invalidEncoding = \"invalid encoding\";\r\n\r\n/**\r\n * Decodes a base64 encoded string to a buffer.\r\n * @param {string} string Source string\r\n * @param {Uint8Array} buffer Destination buffer\r\n * @param {number} offset Destination offset\r\n * @returns {number} Number of bytes written\r\n * @throws {Error} If encoding is invalid\r\n */\r\nbase64.decode = function decode(string, buffer, offset) {\r\n var start = offset;\r\n var j = 0, // goto index\r\n t; // temporary\r\n for (var i = 0; i < string.length;) {\r\n var c = string.charCodeAt(i++);\r\n if (c === 61 && j > 1)\r\n break;\r\n if ((c = s64[c]) === undefined)\r\n throw Error(invalidEncoding);\r\n switch (j) {\r\n case 0:\r\n t = c;\r\n j = 1;\r\n break;\r\n case 1:\r\n buffer[offset++] = t << 2 | (c & 48) >> 4;\r\n t = c;\r\n j = 2;\r\n break;\r\n case 2:\r\n buffer[offset++] = (t & 15) << 4 | (c & 60) >> 2;\r\n t = c;\r\n j = 3;\r\n break;\r\n case 3:\r\n buffer[offset++] = (t & 3) << 6 | c;\r\n j = 0;\r\n break;\r\n }\r\n }\r\n if (j === 1)\r\n throw Error(invalidEncoding);\r\n return offset - start;\r\n};\r\n\r\n/**\r\n * Tests if the specified string appears to be base64 encoded.\r\n * @param {string} string String to test\r\n * @returns {boolean} `true` if probably base64 encoded, otherwise false\r\n */\r\nbase64.test = function test(string) {\r\n return /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(string);\r\n};\r\n","\"use strict\";\r\nmodule.exports = codegen;\r\n\r\n/**\r\n * Begins generating a function.\r\n * @memberof util\r\n * @param {string[]} functionParams Function parameter names\r\n * @param {string} [functionName] Function name if not anonymous\r\n * @returns {Codegen} Appender that appends code to the function's body\r\n */\r\nfunction codegen(functionParams, functionName) {\r\n\r\n /* istanbul ignore if */\r\n if (typeof functionParams === \"string\") {\r\n functionName = functionParams;\r\n functionParams = undefined;\r\n }\r\n\r\n var body = [];\r\n\r\n /**\r\n * Appends code to the function's body or finishes generation.\r\n * @typedef Codegen\r\n * @type {function}\r\n * @param {string|Object.} [formatStringOrScope] Format string or, to finish the function, an object of additional scope variables, if any\r\n * @param {...*} [formatParams] Format parameters\r\n * @returns {Codegen|Function} Itself or the generated function if finished\r\n * @throws {Error} If format parameter counts do not match\r\n */\r\n\r\n function Codegen(formatStringOrScope) {\r\n // note that explicit array handling below makes this ~50% faster\r\n\r\n // finish the function\r\n if (typeof formatStringOrScope !== \"string\") {\r\n var source = toString();\r\n if (codegen.verbose)\r\n console.log(\"codegen: \" + source); // eslint-disable-line no-console\r\n source = \"return \" + source;\r\n if (formatStringOrScope) {\r\n var scopeKeys = Object.keys(formatStringOrScope),\r\n scopeParams = new Array(scopeKeys.length + 1),\r\n scopeValues = new Array(scopeKeys.length),\r\n scopeOffset = 0;\r\n while (scopeOffset < scopeKeys.length) {\r\n scopeParams[scopeOffset] = scopeKeys[scopeOffset];\r\n scopeValues[scopeOffset] = formatStringOrScope[scopeKeys[scopeOffset++]];\r\n }\r\n scopeParams[scopeOffset] = source;\r\n return Function.apply(null, scopeParams).apply(null, scopeValues); // eslint-disable-line no-new-func\r\n }\r\n return Function(source)(); // eslint-disable-line no-new-func\r\n }\r\n\r\n // otherwise append to body\r\n var formatParams = new Array(arguments.length - 1),\r\n formatOffset = 0;\r\n while (formatOffset < formatParams.length)\r\n formatParams[formatOffset] = arguments[++formatOffset];\r\n formatOffset = 0;\r\n formatStringOrScope = formatStringOrScope.replace(/%([%dfijs])/g, function replace($0, $1) {\r\n var value = formatParams[formatOffset++];\r\n switch ($1) {\r\n case \"d\": case \"f\": return String(Number(value));\r\n case \"i\": return String(Math.floor(value));\r\n case \"j\": return JSON.stringify(value);\r\n case \"s\": return String(value);\r\n }\r\n return \"%\";\r\n });\r\n if (formatOffset !== formatParams.length)\r\n throw Error(\"parameter count mismatch\");\r\n body.push(formatStringOrScope);\r\n return Codegen;\r\n }\r\n\r\n function toString(functionNameOverride) {\r\n return \"function \" + (functionNameOverride || functionName || \"\") + \"(\" + (functionParams && functionParams.join(\",\") || \"\") + \"){\\n \" + body.join(\"\\n \") + \"\\n}\";\r\n }\r\n\r\n Codegen.toString = toString;\r\n return Codegen;\r\n}\r\n\r\n/**\r\n * Begins generating a function.\r\n * @memberof util\r\n * @function codegen\r\n * @param {string} [functionName] Function name if not anonymous\r\n * @returns {Codegen} Appender that appends code to the function's body\r\n * @variation 2\r\n */\r\n\r\n/**\r\n * When set to `true`, codegen will log generated code to console. Useful for debugging.\r\n * @name util.codegen.verbose\r\n * @type {boolean}\r\n */\r\ncodegen.verbose = false;\r\n","\"use strict\";\r\nmodule.exports = EventEmitter;\r\n\r\n/**\r\n * Constructs a new event emitter instance.\r\n * @classdesc A minimal event emitter.\r\n * @memberof util\r\n * @constructor\r\n */\r\nfunction EventEmitter() {\r\n\r\n /**\r\n * Registered listeners.\r\n * @type {Object.}\r\n * @private\r\n */\r\n this._listeners = {};\r\n}\r\n\r\n/**\r\n * Registers an event listener.\r\n * @param {string} evt Event name\r\n * @param {function} fn Listener\r\n * @param {*} [ctx] Listener context\r\n * @returns {util.EventEmitter} `this`\r\n */\r\nEventEmitter.prototype.on = function on(evt, fn, ctx) {\r\n (this._listeners[evt] || (this._listeners[evt] = [])).push({\r\n fn : fn,\r\n ctx : ctx || this\r\n });\r\n return this;\r\n};\r\n\r\n/**\r\n * Removes an event listener or any matching listeners if arguments are omitted.\r\n * @param {string} [evt] Event name. Removes all listeners if omitted.\r\n * @param {function} [fn] Listener to remove. Removes all listeners of `evt` if omitted.\r\n * @returns {util.EventEmitter} `this`\r\n */\r\nEventEmitter.prototype.off = function off(evt, fn) {\r\n if (evt === undefined)\r\n this._listeners = {};\r\n else {\r\n if (fn === undefined)\r\n this._listeners[evt] = [];\r\n else {\r\n var listeners = this._listeners[evt];\r\n for (var i = 0; i < listeners.length;)\r\n if (listeners[i].fn === fn)\r\n listeners.splice(i, 1);\r\n else\r\n ++i;\r\n }\r\n }\r\n return this;\r\n};\r\n\r\n/**\r\n * Emits an event by calling its listeners with the specified arguments.\r\n * @param {string} evt Event name\r\n * @param {...*} args Arguments\r\n * @returns {util.EventEmitter} `this`\r\n */\r\nEventEmitter.prototype.emit = function emit(evt) {\r\n var listeners = this._listeners[evt];\r\n if (listeners) {\r\n var args = [],\r\n i = 1;\r\n for (; i < arguments.length;)\r\n args.push(arguments[i++]);\r\n for (i = 0; i < listeners.length;)\r\n listeners[i].fn.apply(listeners[i++].ctx, args);\r\n }\r\n return this;\r\n};\r\n","\"use strict\";\r\nmodule.exports = fetch;\r\n\r\nvar asPromise = require(1),\r\n inquire = require(7);\r\n\r\nvar fs = inquire(\"fs\");\r\n\r\n/**\r\n * Node-style callback as used by {@link util.fetch}.\r\n * @typedef FetchCallback\r\n * @type {function}\r\n * @param {?Error} error Error, if any, otherwise `null`\r\n * @param {string} [contents] File contents, if there hasn't been an error\r\n * @returns {undefined}\r\n */\r\n\r\n/**\r\n * Options as used by {@link util.fetch}.\r\n * @typedef FetchOptions\r\n * @type {Object}\r\n * @property {boolean} [binary=false] Whether expecting a binary response\r\n * @property {boolean} [xhr=false] If `true`, forces the use of XMLHttpRequest\r\n */\r\n\r\n/**\r\n * Fetches the contents of a file.\r\n * @memberof util\r\n * @param {string} filename File path or url\r\n * @param {FetchOptions} options Fetch options\r\n * @param {FetchCallback} callback Callback function\r\n * @returns {undefined}\r\n */\r\nfunction fetch(filename, options, callback) {\r\n if (typeof options === \"function\") {\r\n callback = options;\r\n options = {};\r\n } else if (!options)\r\n options = {};\r\n\r\n if (!callback)\r\n return asPromise(fetch, this, filename, options); // eslint-disable-line no-invalid-this\r\n\r\n // if a node-like filesystem is present, try it first but fall back to XHR if nothing is found.\r\n if (!options.xhr && fs && fs.readFile)\r\n return fs.readFile(filename, function fetchReadFileCallback(err, contents) {\r\n return err && typeof XMLHttpRequest !== \"undefined\"\r\n ? fetch.xhr(filename, options, callback)\r\n : err\r\n ? callback(err)\r\n : callback(null, options.binary ? contents : contents.toString(\"utf8\"));\r\n });\r\n\r\n // use the XHR version otherwise.\r\n return fetch.xhr(filename, options, callback);\r\n}\r\n\r\n/**\r\n * Fetches the contents of a file.\r\n * @name util.fetch\r\n * @function\r\n * @param {string} path File path or url\r\n * @param {FetchCallback} callback Callback function\r\n * @returns {undefined}\r\n * @variation 2\r\n */\r\n\r\n/**\r\n * Fetches the contents of a file.\r\n * @name util.fetch\r\n * @function\r\n * @param {string} path File path or url\r\n * @param {FetchOptions} [options] Fetch options\r\n * @returns {Promise} Promise\r\n * @variation 3\r\n */\r\n\r\n/**/\r\nfetch.xhr = function fetch_xhr(filename, options, callback) {\r\n var xhr = new XMLHttpRequest();\r\n xhr.onreadystatechange /* works everywhere */ = function fetchOnReadyStateChange() {\r\n\r\n if (xhr.readyState !== 4)\r\n return undefined;\r\n\r\n // local cors security errors return status 0 / empty string, too. afaik this cannot be\r\n // reliably distinguished from an actually empty file for security reasons. feel free\r\n // to send a pull request if you are aware of a solution.\r\n if (xhr.status !== 0 && xhr.status !== 200)\r\n return callback(Error(\"status \" + xhr.status));\r\n\r\n // if binary data is expected, make sure that some sort of array is returned, even if\r\n // ArrayBuffers are not supported. the binary string fallback, however, is unsafe.\r\n if (options.binary) {\r\n var buffer = xhr.response;\r\n if (!buffer) {\r\n buffer = [];\r\n for (var i = 0; i < xhr.responseText.length; ++i)\r\n buffer.push(xhr.responseText.charCodeAt(i) & 255);\r\n }\r\n return callback(null, typeof Uint8Array !== \"undefined\" ? new Uint8Array(buffer) : buffer);\r\n }\r\n return callback(null, xhr.responseText);\r\n };\r\n\r\n if (options.binary) {\r\n // ref: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Sending_and_Receiving_Binary_Data#Receiving_binary_data_in_older_browsers\r\n if (\"overrideMimeType\" in xhr)\r\n xhr.overrideMimeType(\"text/plain; charset=x-user-defined\");\r\n xhr.responseType = \"arraybuffer\";\r\n }\r\n\r\n xhr.open(\"GET\", filename);\r\n xhr.send();\r\n};\r\n","\"use strict\";\r\n\r\nmodule.exports = factory(factory);\r\n\r\n/**\r\n * Reads / writes floats / doubles from / to buffers.\r\n * @name util.float\r\n * @namespace\r\n */\r\n\r\n/**\r\n * Writes a 32 bit float to a buffer using little endian byte order.\r\n * @name util.float.writeFloatLE\r\n * @function\r\n * @param {number} val Value to write\r\n * @param {Uint8Array} buf Target buffer\r\n * @param {number} pos Target buffer offset\r\n * @returns {undefined}\r\n */\r\n\r\n/**\r\n * Writes a 32 bit float to a buffer using big endian byte order.\r\n * @name util.float.writeFloatBE\r\n * @function\r\n * @param {number} val Value to write\r\n * @param {Uint8Array} buf Target buffer\r\n * @param {number} pos Target buffer offset\r\n * @returns {undefined}\r\n */\r\n\r\n/**\r\n * Reads a 32 bit float from a buffer using little endian byte order.\r\n * @name util.float.readFloatLE\r\n * @function\r\n * @param {Uint8Array} buf Source buffer\r\n * @param {number} pos Source buffer offset\r\n * @returns {number} Value read\r\n */\r\n\r\n/**\r\n * Reads a 32 bit float from a buffer using big endian byte order.\r\n * @name util.float.readFloatBE\r\n * @function\r\n * @param {Uint8Array} buf Source buffer\r\n * @param {number} pos Source buffer offset\r\n * @returns {number} Value read\r\n */\r\n\r\n/**\r\n * Writes a 64 bit double to a buffer using little endian byte order.\r\n * @name util.float.writeDoubleLE\r\n * @function\r\n * @param {number} val Value to write\r\n * @param {Uint8Array} buf Target buffer\r\n * @param {number} pos Target buffer offset\r\n * @returns {undefined}\r\n */\r\n\r\n/**\r\n * Writes a 64 bit double to a buffer using big endian byte order.\r\n * @name util.float.writeDoubleBE\r\n * @function\r\n * @param {number} val Value to write\r\n * @param {Uint8Array} buf Target buffer\r\n * @param {number} pos Target buffer offset\r\n * @returns {undefined}\r\n */\r\n\r\n/**\r\n * Reads a 64 bit double from a buffer using little endian byte order.\r\n * @name util.float.readDoubleLE\r\n * @function\r\n * @param {Uint8Array} buf Source buffer\r\n * @param {number} pos Source buffer offset\r\n * @returns {number} Value read\r\n */\r\n\r\n/**\r\n * Reads a 64 bit double from a buffer using big endian byte order.\r\n * @name util.float.readDoubleBE\r\n * @function\r\n * @param {Uint8Array} buf Source buffer\r\n * @param {number} pos Source buffer offset\r\n * @returns {number} Value read\r\n */\r\n\r\n// Factory function for the purpose of node-based testing in modified global environments\r\nfunction factory(exports) {\r\n\r\n // float: typed array\r\n if (typeof Float32Array !== \"undefined\") (function() {\r\n\r\n var f32 = new Float32Array([ -0 ]),\r\n f8b = new Uint8Array(f32.buffer),\r\n le = f8b[3] === 128;\r\n\r\n function writeFloat_f32_cpy(val, buf, pos) {\r\n f32[0] = val;\r\n buf[pos ] = f8b[0];\r\n buf[pos + 1] = f8b[1];\r\n buf[pos + 2] = f8b[2];\r\n buf[pos + 3] = f8b[3];\r\n }\r\n\r\n function writeFloat_f32_rev(val, buf, pos) {\r\n f32[0] = val;\r\n buf[pos ] = f8b[3];\r\n buf[pos + 1] = f8b[2];\r\n buf[pos + 2] = f8b[1];\r\n buf[pos + 3] = f8b[0];\r\n }\r\n\r\n /* istanbul ignore next */\r\n exports.writeFloatLE = le ? writeFloat_f32_cpy : writeFloat_f32_rev;\r\n /* istanbul ignore next */\r\n exports.writeFloatBE = le ? writeFloat_f32_rev : writeFloat_f32_cpy;\r\n\r\n function readFloat_f32_cpy(buf, pos) {\r\n f8b[0] = buf[pos ];\r\n f8b[1] = buf[pos + 1];\r\n f8b[2] = buf[pos + 2];\r\n f8b[3] = buf[pos + 3];\r\n return f32[0];\r\n }\r\n\r\n function readFloat_f32_rev(buf, pos) {\r\n f8b[3] = buf[pos ];\r\n f8b[2] = buf[pos + 1];\r\n f8b[1] = buf[pos + 2];\r\n f8b[0] = buf[pos + 3];\r\n return f32[0];\r\n }\r\n\r\n /* istanbul ignore next */\r\n exports.readFloatLE = le ? readFloat_f32_cpy : readFloat_f32_rev;\r\n /* istanbul ignore next */\r\n exports.readFloatBE = le ? readFloat_f32_rev : readFloat_f32_cpy;\r\n\r\n // float: ieee754\r\n })(); else (function() {\r\n\r\n function writeFloat_ieee754(writeUint, val, buf, pos) {\r\n var sign = val < 0 ? 1 : 0;\r\n if (sign)\r\n val = -val;\r\n if (val === 0)\r\n writeUint(1 / val > 0 ? /* positive */ 0 : /* negative 0 */ 2147483648, buf, pos);\r\n else if (isNaN(val))\r\n writeUint(2143289344, buf, pos);\r\n else if (val > 3.4028234663852886e+38) // +-Infinity\r\n writeUint((sign << 31 | 2139095040) >>> 0, buf, pos);\r\n else if (val < 1.1754943508222875e-38) // denormal\r\n writeUint((sign << 31 | Math.round(val / 1.401298464324817e-45)) >>> 0, buf, pos);\r\n else {\r\n var exponent = Math.floor(Math.log(val) / Math.LN2),\r\n mantissa = Math.round(val * Math.pow(2, -exponent) * 8388608) & 8388607;\r\n writeUint((sign << 31 | exponent + 127 << 23 | mantissa) >>> 0, buf, pos);\r\n }\r\n }\r\n\r\n exports.writeFloatLE = writeFloat_ieee754.bind(null, writeUintLE);\r\n exports.writeFloatBE = writeFloat_ieee754.bind(null, writeUintBE);\r\n\r\n function readFloat_ieee754(readUint, buf, pos) {\r\n var uint = readUint(buf, pos),\r\n sign = (uint >> 31) * 2 + 1,\r\n exponent = uint >>> 23 & 255,\r\n mantissa = uint & 8388607;\r\n return exponent === 255\r\n ? mantissa\r\n ? NaN\r\n : sign * Infinity\r\n : exponent === 0 // denormal\r\n ? sign * 1.401298464324817e-45 * mantissa\r\n : sign * Math.pow(2, exponent - 150) * (mantissa + 8388608);\r\n }\r\n\r\n exports.readFloatLE = readFloat_ieee754.bind(null, readUintLE);\r\n exports.readFloatBE = readFloat_ieee754.bind(null, readUintBE);\r\n\r\n })();\r\n\r\n // double: typed array\r\n if (typeof Float64Array !== \"undefined\") (function() {\r\n\r\n var f64 = new Float64Array([-0]),\r\n f8b = new Uint8Array(f64.buffer),\r\n le = f8b[7] === 128;\r\n\r\n function writeDouble_f64_cpy(val, buf, pos) {\r\n f64[0] = val;\r\n buf[pos ] = f8b[0];\r\n buf[pos + 1] = f8b[1];\r\n buf[pos + 2] = f8b[2];\r\n buf[pos + 3] = f8b[3];\r\n buf[pos + 4] = f8b[4];\r\n buf[pos + 5] = f8b[5];\r\n buf[pos + 6] = f8b[6];\r\n buf[pos + 7] = f8b[7];\r\n }\r\n\r\n function writeDouble_f64_rev(val, buf, pos) {\r\n f64[0] = val;\r\n buf[pos ] = f8b[7];\r\n buf[pos + 1] = f8b[6];\r\n buf[pos + 2] = f8b[5];\r\n buf[pos + 3] = f8b[4];\r\n buf[pos + 4] = f8b[3];\r\n buf[pos + 5] = f8b[2];\r\n buf[pos + 6] = f8b[1];\r\n buf[pos + 7] = f8b[0];\r\n }\r\n\r\n /* istanbul ignore next */\r\n exports.writeDoubleLE = le ? writeDouble_f64_cpy : writeDouble_f64_rev;\r\n /* istanbul ignore next */\r\n exports.writeDoubleBE = le ? writeDouble_f64_rev : writeDouble_f64_cpy;\r\n\r\n function readDouble_f64_cpy(buf, pos) {\r\n f8b[0] = buf[pos ];\r\n f8b[1] = buf[pos + 1];\r\n f8b[2] = buf[pos + 2];\r\n f8b[3] = buf[pos + 3];\r\n f8b[4] = buf[pos + 4];\r\n f8b[5] = buf[pos + 5];\r\n f8b[6] = buf[pos + 6];\r\n f8b[7] = buf[pos + 7];\r\n return f64[0];\r\n }\r\n\r\n function readDouble_f64_rev(buf, pos) {\r\n f8b[7] = buf[pos ];\r\n f8b[6] = buf[pos + 1];\r\n f8b[5] = buf[pos + 2];\r\n f8b[4] = buf[pos + 3];\r\n f8b[3] = buf[pos + 4];\r\n f8b[2] = buf[pos + 5];\r\n f8b[1] = buf[pos + 6];\r\n f8b[0] = buf[pos + 7];\r\n return f64[0];\r\n }\r\n\r\n /* istanbul ignore next */\r\n exports.readDoubleLE = le ? readDouble_f64_cpy : readDouble_f64_rev;\r\n /* istanbul ignore next */\r\n exports.readDoubleBE = le ? readDouble_f64_rev : readDouble_f64_cpy;\r\n\r\n // double: ieee754\r\n })(); else (function() {\r\n\r\n function writeDouble_ieee754(writeUint, off0, off1, val, buf, pos) {\r\n var sign = val < 0 ? 1 : 0;\r\n if (sign)\r\n val = -val;\r\n if (val === 0) {\r\n writeUint(0, buf, pos + off0);\r\n writeUint(1 / val > 0 ? /* positive */ 0 : /* negative 0 */ 2147483648, buf, pos + off1);\r\n } else if (isNaN(val)) {\r\n writeUint(0, buf, pos + off0);\r\n writeUint(2146959360, buf, pos + off1);\r\n } else if (val > 1.7976931348623157e+308) { // +-Infinity\r\n writeUint(0, buf, pos + off0);\r\n writeUint((sign << 31 | 2146435072) >>> 0, buf, pos + off1);\r\n } else {\r\n var mantissa;\r\n if (val < 2.2250738585072014e-308) { // denormal\r\n mantissa = val / 5e-324;\r\n writeUint(mantissa >>> 0, buf, pos + off0);\r\n writeUint((sign << 31 | mantissa / 4294967296) >>> 0, buf, pos + off1);\r\n } else {\r\n var exponent = Math.floor(Math.log(val) / Math.LN2);\r\n if (exponent === 1024)\r\n exponent = 1023;\r\n mantissa = val * Math.pow(2, -exponent);\r\n writeUint(mantissa * 4503599627370496 >>> 0, buf, pos + off0);\r\n writeUint((sign << 31 | exponent + 1023 << 20 | mantissa * 1048576 & 1048575) >>> 0, buf, pos + off1);\r\n }\r\n }\r\n }\r\n\r\n exports.writeDoubleLE = writeDouble_ieee754.bind(null, writeUintLE, 0, 4);\r\n exports.writeDoubleBE = writeDouble_ieee754.bind(null, writeUintBE, 4, 0);\r\n\r\n function readDouble_ieee754(readUint, off0, off1, buf, pos) {\r\n var lo = readUint(buf, pos + off0),\r\n hi = readUint(buf, pos + off1);\r\n var sign = (hi >> 31) * 2 + 1,\r\n exponent = hi >>> 20 & 2047,\r\n mantissa = 4294967296 * (hi & 1048575) + lo;\r\n return exponent === 2047\r\n ? mantissa\r\n ? NaN\r\n : sign * Infinity\r\n : exponent === 0 // denormal\r\n ? sign * 5e-324 * mantissa\r\n : sign * Math.pow(2, exponent - 1075) * (mantissa + 4503599627370496);\r\n }\r\n\r\n exports.readDoubleLE = readDouble_ieee754.bind(null, readUintLE, 0, 4);\r\n exports.readDoubleBE = readDouble_ieee754.bind(null, readUintBE, 4, 0);\r\n\r\n })();\r\n\r\n return exports;\r\n}\r\n\r\n// uint helpers\r\n\r\nfunction writeUintLE(val, buf, pos) {\r\n buf[pos ] = val & 255;\r\n buf[pos + 1] = val >>> 8 & 255;\r\n buf[pos + 2] = val >>> 16 & 255;\r\n buf[pos + 3] = val >>> 24;\r\n}\r\n\r\nfunction writeUintBE(val, buf, pos) {\r\n buf[pos ] = val >>> 24;\r\n buf[pos + 1] = val >>> 16 & 255;\r\n buf[pos + 2] = val >>> 8 & 255;\r\n buf[pos + 3] = val & 255;\r\n}\r\n\r\nfunction readUintLE(buf, pos) {\r\n return (buf[pos ]\r\n | buf[pos + 1] << 8\r\n | buf[pos + 2] << 16\r\n | buf[pos + 3] << 24) >>> 0;\r\n}\r\n\r\nfunction readUintBE(buf, pos) {\r\n return (buf[pos ] << 24\r\n | buf[pos + 1] << 16\r\n | buf[pos + 2] << 8\r\n | buf[pos + 3]) >>> 0;\r\n}\r\n","\"use strict\";\r\nmodule.exports = inquire;\r\n\r\n/**\r\n * Requires a module only if available.\r\n * @memberof util\r\n * @param {string} moduleName Module to require\r\n * @returns {?Object} Required module if available and not empty, otherwise `null`\r\n */\r\nfunction inquire(moduleName) {\r\n try {\r\n var mod = eval(\"quire\".replace(/^/,\"re\"))(moduleName); // eslint-disable-line no-eval\r\n if (mod && (mod.length || Object.keys(mod).length))\r\n return mod;\r\n } catch (e) {} // eslint-disable-line no-empty\r\n return null;\r\n}\r\n","\"use strict\";\r\n\r\n/**\r\n * A minimal path module to resolve Unix, Windows and URL paths alike.\r\n * @memberof util\r\n * @namespace\r\n */\r\nvar path = exports;\r\n\r\nvar isAbsolute =\r\n/**\r\n * Tests if the specified path is absolute.\r\n * @param {string} path Path to test\r\n * @returns {boolean} `true` if path is absolute\r\n */\r\npath.isAbsolute = function isAbsolute(path) {\r\n return /^(?:\\/|\\w+:)/.test(path);\r\n};\r\n\r\nvar normalize =\r\n/**\r\n * Normalizes the specified path.\r\n * @param {string} path Path to normalize\r\n * @returns {string} Normalized path\r\n */\r\npath.normalize = function normalize(path) {\r\n path = path.replace(/\\\\/g, \"/\")\r\n .replace(/\\/{2,}/g, \"/\");\r\n var parts = path.split(\"/\"),\r\n absolute = isAbsolute(path),\r\n prefix = \"\";\r\n if (absolute)\r\n prefix = parts.shift() + \"/\";\r\n for (var i = 0; i < parts.length;) {\r\n if (parts[i] === \"..\") {\r\n if (i > 0 && parts[i - 1] !== \"..\")\r\n parts.splice(--i, 2);\r\n else if (absolute)\r\n parts.splice(i, 1);\r\n else\r\n ++i;\r\n } else if (parts[i] === \".\")\r\n parts.splice(i, 1);\r\n else\r\n ++i;\r\n }\r\n return prefix + parts.join(\"/\");\r\n};\r\n\r\n/**\r\n * Resolves the specified include path against the specified origin path.\r\n * @param {string} originPath Path to the origin file\r\n * @param {string} includePath Include path relative to origin path\r\n * @param {boolean} [alreadyNormalized=false] `true` if both paths are already known to be normalized\r\n * @returns {string} Path to the include file\r\n */\r\npath.resolve = function resolve(originPath, includePath, alreadyNormalized) {\r\n if (!alreadyNormalized)\r\n includePath = normalize(includePath);\r\n if (isAbsolute(includePath))\r\n return includePath;\r\n if (!alreadyNormalized)\r\n originPath = normalize(originPath);\r\n return (originPath = originPath.replace(/(?:\\/|^)[^/]+$/, \"\")).length ? normalize(originPath + \"/\" + includePath) : includePath;\r\n};\r\n","\"use strict\";\r\nmodule.exports = pool;\r\n\r\n/**\r\n * An allocator as used by {@link util.pool}.\r\n * @typedef PoolAllocator\r\n * @type {function}\r\n * @param {number} size Buffer size\r\n * @returns {Uint8Array} Buffer\r\n */\r\n\r\n/**\r\n * A slicer as used by {@link util.pool}.\r\n * @typedef PoolSlicer\r\n * @type {function}\r\n * @param {number} start Start offset\r\n * @param {number} end End offset\r\n * @returns {Uint8Array} Buffer slice\r\n * @this {Uint8Array}\r\n */\r\n\r\n/**\r\n * A general purpose buffer pool.\r\n * @memberof util\r\n * @function\r\n * @param {PoolAllocator} alloc Allocator\r\n * @param {PoolSlicer} slice Slicer\r\n * @param {number} [size=8192] Slab size\r\n * @returns {PoolAllocator} Pooled allocator\r\n */\r\nfunction pool(alloc, slice, size) {\r\n var SIZE = size || 8192;\r\n var MAX = SIZE >>> 1;\r\n var slab = null;\r\n var offset = SIZE;\r\n return function pool_alloc(size) {\r\n if (size < 1 || size > MAX)\r\n return alloc(size);\r\n if (offset + size > SIZE) {\r\n slab = alloc(SIZE);\r\n offset = 0;\r\n }\r\n var buf = slice.call(slab, offset, offset += size);\r\n if (offset & 7) // align to 32 bit\r\n offset = (offset | 7) + 1;\r\n return buf;\r\n };\r\n}\r\n","\"use strict\";\r\n\r\n/**\r\n * A minimal UTF8 implementation for number arrays.\r\n * @memberof util\r\n * @namespace\r\n */\r\nvar utf8 = exports;\r\n\r\n/**\r\n * Calculates the UTF8 byte length of a string.\r\n * @param {string} string String\r\n * @returns {number} Byte length\r\n */\r\nutf8.length = function utf8_length(string) {\r\n var len = 0,\r\n c = 0;\r\n for (var i = 0; i < string.length; ++i) {\r\n c = string.charCodeAt(i);\r\n if (c < 128)\r\n len += 1;\r\n else if (c < 2048)\r\n len += 2;\r\n else if ((c & 0xFC00) === 0xD800 && (string.charCodeAt(i + 1) & 0xFC00) === 0xDC00) {\r\n ++i;\r\n len += 4;\r\n } else\r\n len += 3;\r\n }\r\n return len;\r\n};\r\n\r\n/**\r\n * Reads UTF8 bytes as a string.\r\n * @param {Uint8Array} buffer Source buffer\r\n * @param {number} start Source start\r\n * @param {number} end Source end\r\n * @returns {string} String read\r\n */\r\nutf8.read = function utf8_read(buffer, start, end) {\r\n var len = end - start;\r\n if (len < 1)\r\n return \"\";\r\n var parts = null,\r\n chunk = [],\r\n i = 0, // char offset\r\n t; // temporary\r\n while (start < end) {\r\n t = buffer[start++];\r\n if (t < 128)\r\n chunk[i++] = t;\r\n else if (t > 191 && t < 224)\r\n chunk[i++] = (t & 31) << 6 | buffer[start++] & 63;\r\n else if (t > 239 && t < 365) {\r\n t = ((t & 7) << 18 | (buffer[start++] & 63) << 12 | (buffer[start++] & 63) << 6 | buffer[start++] & 63) - 0x10000;\r\n chunk[i++] = 0xD800 + (t >> 10);\r\n chunk[i++] = 0xDC00 + (t & 1023);\r\n } else\r\n chunk[i++] = (t & 15) << 12 | (buffer[start++] & 63) << 6 | buffer[start++] & 63;\r\n if (i > 8191) {\r\n (parts || (parts = [])).push(String.fromCharCode.apply(String, chunk));\r\n i = 0;\r\n }\r\n }\r\n if (parts) {\r\n if (i)\r\n parts.push(String.fromCharCode.apply(String, chunk.slice(0, i)));\r\n return parts.join(\"\");\r\n }\r\n return String.fromCharCode.apply(String, chunk.slice(0, i));\r\n};\r\n\r\n/**\r\n * Writes a string as UTF8 bytes.\r\n * @param {string} string Source string\r\n * @param {Uint8Array} buffer Destination buffer\r\n * @param {number} offset Destination offset\r\n * @returns {number} Bytes written\r\n */\r\nutf8.write = function utf8_write(string, buffer, offset) {\r\n var start = offset,\r\n c1, // character 1\r\n c2; // character 2\r\n for (var i = 0; i < string.length; ++i) {\r\n c1 = string.charCodeAt(i);\r\n if (c1 < 128) {\r\n buffer[offset++] = c1;\r\n } else if (c1 < 2048) {\r\n buffer[offset++] = c1 >> 6 | 192;\r\n buffer[offset++] = c1 & 63 | 128;\r\n } else if ((c1 & 0xFC00) === 0xD800 && ((c2 = string.charCodeAt(i + 1)) & 0xFC00) === 0xDC00) {\r\n c1 = 0x10000 + ((c1 & 0x03FF) << 10) + (c2 & 0x03FF);\r\n ++i;\r\n buffer[offset++] = c1 >> 18 | 240;\r\n buffer[offset++] = c1 >> 12 & 63 | 128;\r\n buffer[offset++] = c1 >> 6 & 63 | 128;\r\n buffer[offset++] = c1 & 63 | 128;\r\n } else {\r\n buffer[offset++] = c1 >> 12 | 224;\r\n buffer[offset++] = c1 >> 6 & 63 | 128;\r\n buffer[offset++] = c1 & 63 | 128;\r\n }\r\n }\r\n return offset - start;\r\n};\r\n","\"use strict\";\nmodule.exports = common;\n\nvar commonRe = /\\/|\\./;\n\n/**\n * Provides common type definitions.\n * Can also be used to provide additional google types or your own custom types.\n * @param {string} name Short name as in `google/protobuf/[name].proto` or full file name\n * @param {Object.} json JSON definition within `google.protobuf` if a short name, otherwise the file's root definition\n * @returns {undefined}\n * @property {INamespace} google/protobuf/any.proto Any\n * @property {INamespace} google/protobuf/duration.proto Duration\n * @property {INamespace} google/protobuf/empty.proto Empty\n * @property {INamespace} google/protobuf/field_mask.proto FieldMask\n * @property {INamespace} google/protobuf/struct.proto Struct, Value, NullValue and ListValue\n * @property {INamespace} google/protobuf/timestamp.proto Timestamp\n * @property {INamespace} google/protobuf/wrappers.proto Wrappers\n * @example\n * // manually provides descriptor.proto (assumes google/protobuf/ namespace and .proto extension)\n * protobuf.common(\"descriptor\", descriptorJson);\n *\n * // manually provides a custom definition (uses my.foo namespace)\n * protobuf.common(\"my/foo/bar.proto\", myFooBarJson);\n */\nfunction common(name, json) {\n if (!commonRe.test(name)) {\n name = \"google/protobuf/\" + name + \".proto\";\n json = { nested: { google: { nested: { protobuf: { nested: json } } } } };\n }\n common[name] = json;\n}\n\n// Not provided because of limited use (feel free to discuss or to provide yourself):\n//\n// google/protobuf/descriptor.proto\n// google/protobuf/source_context.proto\n// google/protobuf/type.proto\n//\n// Stripped and pre-parsed versions of these non-bundled files are instead available as part of\n// the repository or package within the google/protobuf directory.\n\ncommon(\"any\", {\n\n /**\n * Properties of a google.protobuf.Any message.\n * @interface IAny\n * @type {Object}\n * @property {string} [typeUrl]\n * @property {Uint8Array} [bytes]\n * @memberof common\n */\n Any: {\n fields: {\n type_url: {\n type: \"string\",\n id: 1\n },\n value: {\n type: \"bytes\",\n id: 2\n }\n }\n }\n});\n\nvar timeType;\n\ncommon(\"duration\", {\n\n /**\n * Properties of a google.protobuf.Duration message.\n * @interface IDuration\n * @type {Object}\n * @property {number|Long} [seconds]\n * @property {number} [nanos]\n * @memberof common\n */\n Duration: timeType = {\n fields: {\n seconds: {\n type: \"int64\",\n id: 1\n },\n nanos: {\n type: \"int32\",\n id: 2\n }\n }\n }\n});\n\ncommon(\"timestamp\", {\n\n /**\n * Properties of a google.protobuf.Timestamp message.\n * @interface ITimestamp\n * @type {Object}\n * @property {number|Long} [seconds]\n * @property {number} [nanos]\n * @memberof common\n */\n Timestamp: timeType\n});\n\ncommon(\"empty\", {\n\n /**\n * Properties of a google.protobuf.Empty message.\n * @interface IEmpty\n * @memberof common\n */\n Empty: {\n fields: {}\n }\n});\n\ncommon(\"struct\", {\n\n /**\n * Properties of a google.protobuf.Struct message.\n * @interface IStruct\n * @type {Object}\n * @property {Object.} [fields]\n * @memberof common\n */\n Struct: {\n fields: {\n fields: {\n keyType: \"string\",\n type: \"Value\",\n id: 1\n }\n }\n },\n\n /**\n * Properties of a google.protobuf.Value message.\n * @interface IValue\n * @type {Object}\n * @property {string} [kind]\n * @property {0} [nullValue]\n * @property {number} [numberValue]\n * @property {string} [stringValue]\n * @property {boolean} [boolValue]\n * @property {IStruct} [structValue]\n * @property {IListValue} [listValue]\n * @memberof common\n */\n Value: {\n oneofs: {\n kind: {\n oneof: [\n \"nullValue\",\n \"numberValue\",\n \"stringValue\",\n \"boolValue\",\n \"structValue\",\n \"listValue\"\n ]\n }\n },\n fields: {\n nullValue: {\n type: \"NullValue\",\n id: 1\n },\n numberValue: {\n type: \"double\",\n id: 2\n },\n stringValue: {\n type: \"string\",\n id: 3\n },\n boolValue: {\n type: \"bool\",\n id: 4\n },\n structValue: {\n type: \"Struct\",\n id: 5\n },\n listValue: {\n type: \"ListValue\",\n id: 6\n }\n }\n },\n\n NullValue: {\n values: {\n NULL_VALUE: 0\n }\n },\n\n /**\n * Properties of a google.protobuf.ListValue message.\n * @interface IListValue\n * @type {Object}\n * @property {Array.} [values]\n * @memberof common\n */\n ListValue: {\n fields: {\n values: {\n rule: \"repeated\",\n type: \"Value\",\n id: 1\n }\n }\n }\n});\n\ncommon(\"wrappers\", {\n\n /**\n * Properties of a google.protobuf.DoubleValue message.\n * @interface IDoubleValue\n * @type {Object}\n * @property {number} [value]\n * @memberof common\n */\n DoubleValue: {\n fields: {\n value: {\n type: \"double\",\n id: 1\n }\n }\n },\n\n /**\n * Properties of a google.protobuf.FloatValue message.\n * @interface IFloatValue\n * @type {Object}\n * @property {number} [value]\n * @memberof common\n */\n FloatValue: {\n fields: {\n value: {\n type: \"float\",\n id: 1\n }\n }\n },\n\n /**\n * Properties of a google.protobuf.Int64Value message.\n * @interface IInt64Value\n * @type {Object}\n * @property {number|Long} [value]\n * @memberof common\n */\n Int64Value: {\n fields: {\n value: {\n type: \"int64\",\n id: 1\n }\n }\n },\n\n /**\n * Properties of a google.protobuf.UInt64Value message.\n * @interface IUInt64Value\n * @type {Object}\n * @property {number|Long} [value]\n * @memberof common\n */\n UInt64Value: {\n fields: {\n value: {\n type: \"uint64\",\n id: 1\n }\n }\n },\n\n /**\n * Properties of a google.protobuf.Int32Value message.\n * @interface IInt32Value\n * @type {Object}\n * @property {number} [value]\n * @memberof common\n */\n Int32Value: {\n fields: {\n value: {\n type: \"int32\",\n id: 1\n }\n }\n },\n\n /**\n * Properties of a google.protobuf.UInt32Value message.\n * @interface IUInt32Value\n * @type {Object}\n * @property {number} [value]\n * @memberof common\n */\n UInt32Value: {\n fields: {\n value: {\n type: \"uint32\",\n id: 1\n }\n }\n },\n\n /**\n * Properties of a google.protobuf.BoolValue message.\n * @interface IBoolValue\n * @type {Object}\n * @property {boolean} [value]\n * @memberof common\n */\n BoolValue: {\n fields: {\n value: {\n type: \"bool\",\n id: 1\n }\n }\n },\n\n /**\n * Properties of a google.protobuf.StringValue message.\n * @interface IStringValue\n * @type {Object}\n * @property {string} [value]\n * @memberof common\n */\n StringValue: {\n fields: {\n value: {\n type: \"string\",\n id: 1\n }\n }\n },\n\n /**\n * Properties of a google.protobuf.BytesValue message.\n * @interface IBytesValue\n * @type {Object}\n * @property {Uint8Array} [value]\n * @memberof common\n */\n BytesValue: {\n fields: {\n value: {\n type: \"bytes\",\n id: 1\n }\n }\n }\n});\n\ncommon(\"field_mask\", {\n\n /**\n * Properties of a google.protobuf.FieldMask message.\n * @interface IDoubleValue\n * @type {Object}\n * @property {number} [value]\n * @memberof common\n */\n FieldMask: {\n fields: {\n paths: {\n rule: \"repeated\",\n type: \"string\",\n id: 1\n }\n }\n }\n});\n\n/**\n * Gets the root definition of the specified common proto file.\n *\n * Bundled definitions are:\n * - google/protobuf/any.proto\n * - google/protobuf/duration.proto\n * - google/protobuf/empty.proto\n * - google/protobuf/field_mask.proto\n * - google/protobuf/struct.proto\n * - google/protobuf/timestamp.proto\n * - google/protobuf/wrappers.proto\n *\n * @param {string} file Proto file name\n * @returns {INamespace|null} Root definition or `null` if not defined\n */\ncommon.get = function get(file) {\n return common[file] || null;\n};\n","\"use strict\";\n/**\n * Runtime message from/to plain object converters.\n * @namespace\n */\nvar converter = exports;\n\nvar Enum = require(15),\n util = require(37);\n\n/**\n * Generates a partial value fromObject conveter.\n * @param {Codegen} gen Codegen instance\n * @param {Field} field Reflected field\n * @param {number} fieldIndex Field index\n * @param {string} prop Property reference\n * @returns {Codegen} Codegen instance\n * @ignore\n */\nfunction genValuePartial_fromObject(gen, field, fieldIndex, prop) {\n var defaultAlreadyEmitted = false;\n /* eslint-disable no-unexpected-multiline, block-scoped-var, no-redeclare */\n if (field.resolvedType) {\n if (field.resolvedType instanceof Enum) { gen\n (\"switch(d%s){\", prop);\n for (var values = field.resolvedType.values, keys = Object.keys(values), i = 0; i < keys.length; ++i) {\n // enum unknown values passthrough\n if (values[keys[i]] === field.typeDefault && !defaultAlreadyEmitted) { gen\n (\"default:\")\n (\"if(typeof(d%s)===\\\"number\\\"){m%s=d%s;break}\", prop, prop, prop);\n if (!field.repeated) gen // fallback to default value only for\n // arrays, to avoid leaving holes.\n (\"break\"); // for non-repeated fields, just ignore\n defaultAlreadyEmitted = true;\n }\n gen\n (\"case%j:\", keys[i])\n (\"case %i:\", values[keys[i]])\n (\"m%s=%j\", prop, values[keys[i]])\n (\"break\");\n } gen\n (\"}\");\n } else gen\n (\"if(typeof d%s!==\\\"object\\\")\", prop)\n (\"throw TypeError(%j)\", field.fullName + \": object expected\")\n (\"m%s=types[%i].fromObject(d%s)\", prop, fieldIndex, prop);\n } else {\n var isUnsigned = false;\n switch (field.type) {\n case \"double\":\n case \"float\": gen\n (\"m%s=Number(d%s)\", prop, prop); // also catches \"NaN\", \"Infinity\"\n break;\n case \"uint32\":\n case \"fixed32\": gen\n (\"m%s=d%s>>>0\", prop, prop);\n break;\n case \"int32\":\n case \"sint32\":\n case \"sfixed32\": gen\n (\"m%s=d%s|0\", prop, prop);\n break;\n case \"uint64\":\n isUnsigned = true;\n // eslint-disable-next-line no-fallthrough\n case \"int64\":\n case \"sint64\":\n case \"fixed64\":\n case \"sfixed64\": gen\n (\"if(util.Long)\")\n (\"(m%s=util.Long.fromValue(d%s)).unsigned=%j\", prop, prop, isUnsigned)\n (\"else if(typeof d%s===\\\"string\\\")\", prop)\n (\"m%s=parseInt(d%s,10)\", prop, prop)\n (\"else if(typeof d%s===\\\"number\\\")\", prop)\n (\"m%s=d%s\", prop, prop)\n (\"else if(typeof d%s===\\\"object\\\")\", prop)\n (\"m%s=new util.LongBits(d%s.low>>>0,d%s.high>>>0).toNumber(%s)\", prop, prop, prop, isUnsigned ? \"true\" : \"\");\n break;\n case \"bytes\": gen\n (\"if(typeof d%s===\\\"string\\\")\", prop)\n (\"util.base64.decode(d%s,m%s=util.newBuffer(util.base64.length(d%s)),0)\", prop, prop, prop)\n (\"else if(d%s.length >= 0)\", prop)\n (\"m%s=d%s\", prop, prop);\n break;\n case \"string\": gen\n (\"m%s=String(d%s)\", prop, prop);\n break;\n case \"bool\": gen\n (\"m%s=Boolean(d%s)\", prop, prop);\n break;\n /* default: gen\n (\"m%s=d%s\", prop, prop);\n break; */\n }\n }\n return gen;\n /* eslint-enable no-unexpected-multiline, block-scoped-var, no-redeclare */\n}\n\n/**\n * Generates a plain object to runtime message converter specific to the specified message type.\n * @param {Type} mtype Message type\n * @returns {Codegen} Codegen instance\n */\nconverter.fromObject = function fromObject(mtype) {\n /* eslint-disable no-unexpected-multiline, block-scoped-var, no-redeclare */\n var fields = mtype.fieldsArray;\n var gen = util.codegen([\"d\"], mtype.name + \"$fromObject\")\n (\"if(d instanceof this.ctor)\")\n (\"return d\");\n if (!fields.length) return gen\n (\"return new this.ctor\");\n gen\n (\"var m=new this.ctor\");\n for (var i = 0; i < fields.length; ++i) {\n var field = fields[i].resolve(),\n prop = util.safeProp(field.name);\n\n // Map fields\n if (field.map) { gen\n (\"if(d%s){\", prop)\n (\"if(typeof d%s!==\\\"object\\\")\", prop)\n (\"throw TypeError(%j)\", field.fullName + \": object expected\")\n (\"m%s={}\", prop)\n (\"for(var ks=Object.keys(d%s),i=0;i>>0,m%s.high>>>0).toNumber(%s):m%s\", prop, prop, prop, prop, isUnsigned ? \"true\": \"\", prop);\n break;\n case \"bytes\": gen\n (\"d%s=o.bytes===String?util.base64.encode(m%s,0,m%s.length):o.bytes===Array?Array.prototype.slice.call(m%s):m%s\", prop, prop, prop, prop, prop);\n break;\n default: gen\n (\"d%s=m%s\", prop, prop);\n break;\n }\n }\n return gen;\n /* eslint-enable no-unexpected-multiline, block-scoped-var, no-redeclare */\n}\n\n/**\n * Generates a runtime message to plain object converter specific to the specified message type.\n * @param {Type} mtype Message type\n * @returns {Codegen} Codegen instance\n */\nconverter.toObject = function toObject(mtype) {\n /* eslint-disable no-unexpected-multiline, block-scoped-var, no-redeclare */\n var fields = mtype.fieldsArray.slice().sort(util.compareFieldsById);\n if (!fields.length)\n return util.codegen()(\"return {}\");\n var gen = util.codegen([\"m\", \"o\"], mtype.name + \"$toObject\")\n (\"if(!o)\")\n (\"o={}\")\n (\"var d={}\");\n\n var repeatedFields = [],\n mapFields = [],\n normalFields = [],\n i = 0;\n for (; i < fields.length; ++i)\n if (!fields[i].partOf)\n ( fields[i].resolve().repeated ? repeatedFields\n : fields[i].map ? mapFields\n : normalFields).push(fields[i]);\n\n if (repeatedFields.length) { gen\n (\"if(o.arrays||o.defaults){\");\n for (i = 0; i < repeatedFields.length; ++i) gen\n (\"d%s=[]\", util.safeProp(repeatedFields[i].name));\n gen\n (\"}\");\n }\n\n if (mapFields.length) { gen\n (\"if(o.objects||o.defaults){\");\n for (i = 0; i < mapFields.length; ++i) gen\n (\"d%s={}\", util.safeProp(mapFields[i].name));\n gen\n (\"}\");\n }\n\n if (normalFields.length) { gen\n (\"if(o.defaults){\");\n for (i = 0; i < normalFields.length; ++i) {\n var field = normalFields[i],\n prop = util.safeProp(field.name);\n if (field.resolvedType instanceof Enum) gen\n (\"d%s=o.enums===String?%j:%j\", prop, field.resolvedType.valuesById[field.typeDefault], field.typeDefault);\n else if (field.long) gen\n (\"if(util.Long){\")\n (\"var n=new util.Long(%i,%i,%j)\", field.typeDefault.low, field.typeDefault.high, field.typeDefault.unsigned)\n (\"d%s=o.longs===String?n.toString():o.longs===Number?n.toNumber():n\", prop)\n (\"}else\")\n (\"d%s=o.longs===String?%j:%i\", prop, field.typeDefault.toString(), field.typeDefault.toNumber());\n else if (field.bytes) {\n var arrayDefault = \"[\" + Array.prototype.slice.call(field.typeDefault).join(\",\") + \"]\";\n gen\n (\"if(o.bytes===String)d%s=%j\", prop, String.fromCharCode.apply(String, field.typeDefault))\n (\"else{\")\n (\"d%s=%s\", prop, arrayDefault)\n (\"if(o.bytes!==Array)d%s=util.newBuffer(d%s)\", prop, prop)\n (\"}\");\n } else gen\n (\"d%s=%j\", prop, field.typeDefault); // also messages (=null)\n } gen\n (\"}\");\n }\n var hasKs2 = false;\n for (i = 0; i < fields.length; ++i) {\n var field = fields[i],\n index = mtype._fieldsArray.indexOf(field),\n prop = util.safeProp(field.name);\n if (field.map) {\n if (!hasKs2) { hasKs2 = true; gen\n (\"var ks2\");\n } gen\n (\"if(m%s&&(ks2=Object.keys(m%s)).length){\", prop, prop)\n (\"d%s={}\", prop)\n (\"for(var j=0;j>>3){\");\n\n var i = 0;\n for (; i < /* initializes */ mtype.fieldsArray.length; ++i) {\n var field = mtype._fieldsArray[i].resolve(),\n type = field.resolvedType instanceof Enum ? \"int32\" : field.type,\n ref = \"m\" + util.safeProp(field.name); gen\n (\"case %i: {\", field.id);\n\n // Map fields\n if (field.map) { gen\n (\"if(%s===util.emptyObject)\", ref)\n (\"%s={}\", ref)\n (\"var c2 = r.uint32()+r.pos\");\n\n if (types.defaults[field.keyType] !== undefined) gen\n (\"k=%j\", types.defaults[field.keyType]);\n else gen\n (\"k=null\");\n\n if (types.defaults[type] !== undefined) gen\n (\"value=%j\", types.defaults[type]);\n else gen\n (\"value=null\");\n\n gen\n (\"while(r.pos>>3){\")\n (\"case 1: k=r.%s(); break\", field.keyType)\n (\"case 2:\");\n\n if (types.basic[type] === undefined) gen\n (\"value=types[%i].decode(r,r.uint32())\", i); // can't be groups\n else gen\n (\"value=r.%s()\", type);\n\n gen\n (\"break\")\n (\"default:\")\n (\"r.skipType(tag2&7)\")\n (\"break\")\n (\"}\")\n (\"}\");\n\n if (types.long[field.keyType] !== undefined) gen\n (\"%s[typeof k===\\\"object\\\"?util.longToHash(k):k]=value\", ref);\n else gen\n (\"%s[k]=value\", ref);\n\n // Repeated fields\n } else if (field.repeated) { gen\n\n (\"if(!(%s&&%s.length))\", ref, ref)\n (\"%s=[]\", ref);\n\n // Packable (always check for forward and backward compatiblity)\n if (types.packed[type] !== undefined) gen\n (\"if((t&7)===2){\")\n (\"var c2=r.uint32()+r.pos\")\n (\"while(r.pos>> 0, (field.id << 3 | 4) >>> 0)\n : gen(\"types[%i].encode(%s,w.uint32(%i).fork()).ldelim()\", fieldIndex, ref, (field.id << 3 | 2) >>> 0);\n}\n\n/**\n * Generates an encoder specific to the specified message type.\n * @param {Type} mtype Message type\n * @returns {Codegen} Codegen instance\n */\nfunction encoder(mtype) {\n /* eslint-disable no-unexpected-multiline, block-scoped-var, no-redeclare */\n var gen = util.codegen([\"m\", \"w\"], mtype.name + \"$encode\")\n (\"if(!w)\")\n (\"w=Writer.create()\");\n\n var i, ref;\n\n // \"when a message is serialized its known fields should be written sequentially by field number\"\n var fields = /* initializes */ mtype.fieldsArray.slice().sort(util.compareFieldsById);\n\n for (var i = 0; i < fields.length; ++i) {\n var field = fields[i].resolve(),\n index = mtype._fieldsArray.indexOf(field),\n type = field.resolvedType instanceof Enum ? \"int32\" : field.type,\n wireType = types.basic[type];\n ref = \"m\" + util.safeProp(field.name);\n\n // Map fields\n if (field.map) {\n gen\n (\"if(%s!=null&&Object.hasOwnProperty.call(m,%j)){\", ref, field.name) // !== undefined && !== null\n (\"for(var ks=Object.keys(%s),i=0;i>> 0, 8 | types.mapKey[field.keyType], field.keyType);\n if (wireType === undefined) gen\n (\"types[%i].encode(%s[ks[i]],w.uint32(18).fork()).ldelim().ldelim()\", index, ref); // can't be groups\n else gen\n (\".uint32(%i).%s(%s[ks[i]]).ldelim()\", 16 | wireType, type, ref);\n gen\n (\"}\")\n (\"}\");\n\n // Repeated fields\n } else if (field.repeated) { gen\n (\"if(%s!=null&&%s.length){\", ref, ref); // !== undefined && !== null\n\n // Packed repeated\n if (field.packed && types.packed[type] !== undefined) { gen\n\n (\"w.uint32(%i).fork()\", (field.id << 3 | 2) >>> 0)\n (\"for(var i=0;i<%s.length;++i)\", ref)\n (\"w.%s(%s[i])\", type, ref)\n (\"w.ldelim()\");\n\n // Non-packed\n } else { gen\n\n (\"for(var i=0;i<%s.length;++i)\", ref);\n if (wireType === undefined)\n genTypePartial(gen, field, index, ref + \"[i]\");\n else gen\n (\"w.uint32(%i).%s(%s[i])\", (field.id << 3 | wireType) >>> 0, type, ref);\n\n } gen\n (\"}\");\n\n // Non-repeated\n } else {\n if (field.optional) gen\n (\"if(%s!=null&&Object.hasOwnProperty.call(m,%j))\", ref, field.name); // !== undefined && !== null\n\n if (wireType === undefined)\n genTypePartial(gen, field, index, ref);\n else gen\n (\"w.uint32(%i).%s(%s)\", (field.id << 3 | wireType) >>> 0, type, ref);\n\n }\n }\n\n return gen\n (\"return w\");\n /* eslint-enable no-unexpected-multiline, block-scoped-var, no-redeclare */\n}\n","\"use strict\";\nmodule.exports = Enum;\n\n// extends ReflectionObject\nvar ReflectionObject = require(24);\n((Enum.prototype = Object.create(ReflectionObject.prototype)).constructor = Enum).className = \"Enum\";\n\nvar Namespace = require(23),\n util = require(37);\n\n/**\n * Constructs a new enum instance.\n * @classdesc Reflected enum.\n * @extends ReflectionObject\n * @constructor\n * @param {string} name Unique name within its namespace\n * @param {Object.} [values] Enum values as an object, by name\n * @param {Object.} [options] Declared options\n * @param {string} [comment] The comment for this enum\n * @param {Object.} [comments] The value comments for this enum\n * @param {Object.>|undefined} [valuesOptions] The value options for this enum\n */\nfunction Enum(name, values, options, comment, comments, valuesOptions) {\n ReflectionObject.call(this, name, options);\n\n if (values && typeof values !== \"object\")\n throw TypeError(\"values must be an object\");\n\n /**\n * Enum values by id.\n * @type {Object.}\n */\n this.valuesById = {};\n\n /**\n * Enum values by name.\n * @type {Object.}\n */\n this.values = Object.create(this.valuesById); // toJSON, marker\n\n /**\n * Enum comment text.\n * @type {string|null}\n */\n this.comment = comment;\n\n /**\n * Value comment texts, if any.\n * @type {Object.}\n */\n this.comments = comments || {};\n\n /**\n * Values options, if any\n * @type {Object>|undefined}\n */\n this.valuesOptions = valuesOptions;\n\n /**\n * Reserved ranges, if any.\n * @type {Array.}\n */\n this.reserved = undefined; // toJSON\n\n // Note that values inherit valuesById on their prototype which makes them a TypeScript-\n // compatible enum. This is used by pbts to write actual enum definitions that work for\n // static and reflection code alike instead of emitting generic object definitions.\n\n if (values)\n for (var keys = Object.keys(values), i = 0; i < keys.length; ++i)\n if (typeof values[keys[i]] === \"number\") // use forward entries only\n this.valuesById[ this.values[keys[i]] = values[keys[i]] ] = keys[i];\n}\n\n/**\n * Enum descriptor.\n * @interface IEnum\n * @property {Object.} values Enum values\n * @property {Object.} [options] Enum options\n */\n\n/**\n * Constructs an enum from an enum descriptor.\n * @param {string} name Enum name\n * @param {IEnum} json Enum descriptor\n * @returns {Enum} Created enum\n * @throws {TypeError} If arguments are invalid\n */\nEnum.fromJSON = function fromJSON(name, json) {\n var enm = new Enum(name, json.values, json.options, json.comment, json.comments);\n enm.reserved = json.reserved;\n return enm;\n};\n\n/**\n * Converts this enum to an enum descriptor.\n * @param {IToJSONOptions} [toJSONOptions] JSON conversion options\n * @returns {IEnum} Enum descriptor\n */\nEnum.prototype.toJSON = function toJSON(toJSONOptions) {\n var keepComments = toJSONOptions ? Boolean(toJSONOptions.keepComments) : false;\n return util.toObject([\n \"options\" , this.options,\n \"valuesOptions\" , this.valuesOptions,\n \"values\" , this.values,\n \"reserved\" , this.reserved && this.reserved.length ? this.reserved : undefined,\n \"comment\" , keepComments ? this.comment : undefined,\n \"comments\" , keepComments ? this.comments : undefined\n ]);\n};\n\n/**\n * Adds a value to this enum.\n * @param {string} name Value name\n * @param {number} id Value id\n * @param {string} [comment] Comment, if any\n * @param {Object.|undefined} [options] Options, if any\n * @returns {Enum} `this`\n * @throws {TypeError} If arguments are invalid\n * @throws {Error} If there is already a value with this name or id\n */\nEnum.prototype.add = function add(name, id, comment, options) {\n // utilized by the parser but not by .fromJSON\n\n if (!util.isString(name))\n throw TypeError(\"name must be a string\");\n\n if (!util.isInteger(id))\n throw TypeError(\"id must be an integer\");\n\n if (this.values[name] !== undefined)\n throw Error(\"duplicate name '\" + name + \"' in \" + this);\n\n if (this.isReservedId(id))\n throw Error(\"id \" + id + \" is reserved in \" + this);\n\n if (this.isReservedName(name))\n throw Error(\"name '\" + name + \"' is reserved in \" + this);\n\n if (this.valuesById[id] !== undefined) {\n if (!(this.options && this.options.allow_alias))\n throw Error(\"duplicate id \" + id + \" in \" + this);\n this.values[name] = id;\n } else\n this.valuesById[this.values[name] = id] = name;\n\n if (options) {\n if (this.valuesOptions === undefined)\n this.valuesOptions = {};\n this.valuesOptions[name] = options || null;\n }\n\n this.comments[name] = comment || null;\n return this;\n};\n\n/**\n * Removes a value from this enum\n * @param {string} name Value name\n * @returns {Enum} `this`\n * @throws {TypeError} If arguments are invalid\n * @throws {Error} If `name` is not a name of this enum\n */\nEnum.prototype.remove = function remove(name) {\n\n if (!util.isString(name))\n throw TypeError(\"name must be a string\");\n\n var val = this.values[name];\n if (val == null)\n throw Error(\"name '\" + name + \"' does not exist in \" + this);\n\n delete this.valuesById[val];\n delete this.values[name];\n delete this.comments[name];\n if (this.valuesOptions)\n delete this.valuesOptions[name];\n\n return this;\n};\n\n/**\n * Tests if the specified id is reserved.\n * @param {number} id Id to test\n * @returns {boolean} `true` if reserved, otherwise `false`\n */\nEnum.prototype.isReservedId = function isReservedId(id) {\n return Namespace.isReservedId(this.reserved, id);\n};\n\n/**\n * Tests if the specified name is reserved.\n * @param {string} name Name to test\n * @returns {boolean} `true` if reserved, otherwise `false`\n */\nEnum.prototype.isReservedName = function isReservedName(name) {\n return Namespace.isReservedName(this.reserved, name);\n};\n","\"use strict\";\nmodule.exports = Field;\n\n// extends ReflectionObject\nvar ReflectionObject = require(24);\n((Field.prototype = Object.create(ReflectionObject.prototype)).constructor = Field).className = \"Field\";\n\nvar Enum = require(15),\n types = require(36),\n util = require(37);\n\nvar Type; // cyclic\n\nvar ruleRe = /^required|optional|repeated$/;\n\n/**\n * Constructs a new message field instance. Note that {@link MapField|map fields} have their own class.\n * @name Field\n * @classdesc Reflected message field.\n * @extends FieldBase\n * @constructor\n * @param {string} name Unique name within its namespace\n * @param {number} id Unique id within its namespace\n * @param {string} type Value type\n * @param {string|Object.} [rule=\"optional\"] Field rule\n * @param {string|Object.} [extend] Extended type if different from parent\n * @param {Object.} [options] Declared options\n */\n\n/**\n * Constructs a field from a field descriptor.\n * @param {string} name Field name\n * @param {IField} json Field descriptor\n * @returns {Field} Created field\n * @throws {TypeError} If arguments are invalid\n */\nField.fromJSON = function fromJSON(name, json) {\n return new Field(name, json.id, json.type, json.rule, json.extend, json.options, json.comment);\n};\n\n/**\n * Not an actual constructor. Use {@link Field} instead.\n * @classdesc Base class of all reflected message fields. This is not an actual class but here for the sake of having consistent type definitions.\n * @exports FieldBase\n * @extends ReflectionObject\n * @constructor\n * @param {string} name Unique name within its namespace\n * @param {number} id Unique id within its namespace\n * @param {string} type Value type\n * @param {string|Object.} [rule=\"optional\"] Field rule\n * @param {string|Object.} [extend] Extended type if different from parent\n * @param {Object.} [options] Declared options\n * @param {string} [comment] Comment associated with this field\n */\nfunction Field(name, id, type, rule, extend, options, comment) {\n\n if (util.isObject(rule)) {\n comment = extend;\n options = rule;\n rule = extend = undefined;\n } else if (util.isObject(extend)) {\n comment = options;\n options = extend;\n extend = undefined;\n }\n\n ReflectionObject.call(this, name, options);\n\n if (!util.isInteger(id) || id < 0)\n throw TypeError(\"id must be a non-negative integer\");\n\n if (!util.isString(type))\n throw TypeError(\"type must be a string\");\n\n if (rule !== undefined && !ruleRe.test(rule = rule.toString().toLowerCase()))\n throw TypeError(\"rule must be a string rule\");\n\n if (extend !== undefined && !util.isString(extend))\n throw TypeError(\"extend must be a string\");\n\n /**\n * Field rule, if any.\n * @type {string|undefined}\n */\n if (rule === \"proto3_optional\") {\n rule = \"optional\";\n }\n this.rule = rule && rule !== \"optional\" ? rule : undefined; // toJSON\n\n /**\n * Field type.\n * @type {string}\n */\n this.type = type; // toJSON\n\n /**\n * Unique field id.\n * @type {number}\n */\n this.id = id; // toJSON, marker\n\n /**\n * Extended type if different from parent.\n * @type {string|undefined}\n */\n this.extend = extend || undefined; // toJSON\n\n /**\n * Whether this field is required.\n * @type {boolean}\n */\n this.required = rule === \"required\";\n\n /**\n * Whether this field is optional.\n * @type {boolean}\n */\n this.optional = !this.required;\n\n /**\n * Whether this field is repeated.\n * @type {boolean}\n */\n this.repeated = rule === \"repeated\";\n\n /**\n * Whether this field is a map or not.\n * @type {boolean}\n */\n this.map = false;\n\n /**\n * Message this field belongs to.\n * @type {Type|null}\n */\n this.message = null;\n\n /**\n * OneOf this field belongs to, if any,\n * @type {OneOf|null}\n */\n this.partOf = null;\n\n /**\n * The field type's default value.\n * @type {*}\n */\n this.typeDefault = null;\n\n /**\n * The field's default value on prototypes.\n * @type {*}\n */\n this.defaultValue = null;\n\n /**\n * Whether this field's value should be treated as a long.\n * @type {boolean}\n */\n this.long = util.Long ? types.long[type] !== undefined : /* istanbul ignore next */ false;\n\n /**\n * Whether this field's value is a buffer.\n * @type {boolean}\n */\n this.bytes = type === \"bytes\";\n\n /**\n * Resolved type if not a basic type.\n * @type {Type|Enum|null}\n */\n this.resolvedType = null;\n\n /**\n * Sister-field within the extended type if a declaring extension field.\n * @type {Field|null}\n */\n this.extensionField = null;\n\n /**\n * Sister-field within the declaring namespace if an extended field.\n * @type {Field|null}\n */\n this.declaringField = null;\n\n /**\n * Internally remembers whether this field is packed.\n * @type {boolean|null}\n * @private\n */\n this._packed = null;\n\n /**\n * Comment for this field.\n * @type {string|null}\n */\n this.comment = comment;\n}\n\n/**\n * Determines whether this field is packed. Only relevant when repeated and working with proto2.\n * @name Field#packed\n * @type {boolean}\n * @readonly\n */\nObject.defineProperty(Field.prototype, \"packed\", {\n get: function() {\n // defaults to packed=true if not explicity set to false\n if (this._packed === null)\n this._packed = this.getOption(\"packed\") !== false;\n return this._packed;\n }\n});\n\n/**\n * @override\n */\nField.prototype.setOption = function setOption(name, value, ifNotSet) {\n if (name === \"packed\") // clear cached before setting\n this._packed = null;\n return ReflectionObject.prototype.setOption.call(this, name, value, ifNotSet);\n};\n\n/**\n * Field descriptor.\n * @interface IField\n * @property {string} [rule=\"optional\"] Field rule\n * @property {string} type Field type\n * @property {number} id Field id\n * @property {Object.} [options] Field options\n */\n\n/**\n * Extension field descriptor.\n * @interface IExtensionField\n * @extends IField\n * @property {string} extend Extended type\n */\n\n/**\n * Converts this field to a field descriptor.\n * @param {IToJSONOptions} [toJSONOptions] JSON conversion options\n * @returns {IField} Field descriptor\n */\nField.prototype.toJSON = function toJSON(toJSONOptions) {\n var keepComments = toJSONOptions ? Boolean(toJSONOptions.keepComments) : false;\n return util.toObject([\n \"rule\" , this.rule !== \"optional\" && this.rule || undefined,\n \"type\" , this.type,\n \"id\" , this.id,\n \"extend\" , this.extend,\n \"options\" , this.options,\n \"comment\" , keepComments ? this.comment : undefined\n ]);\n};\n\n/**\n * Resolves this field's type references.\n * @returns {Field} `this`\n * @throws {Error} If any reference cannot be resolved\n */\nField.prototype.resolve = function resolve() {\n\n if (this.resolved)\n return this;\n\n if ((this.typeDefault = types.defaults[this.type]) === undefined) { // if not a basic type, resolve it\n this.resolvedType = (this.declaringField ? this.declaringField.parent : this.parent).lookupTypeOrEnum(this.type);\n if (this.resolvedType instanceof Type)\n this.typeDefault = null;\n else // instanceof Enum\n this.typeDefault = this.resolvedType.values[Object.keys(this.resolvedType.values)[0]]; // first defined\n } else if (this.options && this.options.proto3_optional) {\n // proto3 scalar value marked optional; should default to null\n this.typeDefault = null;\n }\n\n // use explicitly set default value if present\n if (this.options && this.options[\"default\"] != null) {\n this.typeDefault = this.options[\"default\"];\n if (this.resolvedType instanceof Enum && typeof this.typeDefault === \"string\")\n this.typeDefault = this.resolvedType.values[this.typeDefault];\n }\n\n // remove unnecessary options\n if (this.options) {\n if (this.options.packed === true || this.options.packed !== undefined && this.resolvedType && !(this.resolvedType instanceof Enum))\n delete this.options.packed;\n if (!Object.keys(this.options).length)\n this.options = undefined;\n }\n\n // convert to internal data type if necesssary\n if (this.long) {\n this.typeDefault = util.Long.fromNumber(this.typeDefault, this.type.charAt(0) === \"u\");\n\n /* istanbul ignore else */\n if (Object.freeze)\n Object.freeze(this.typeDefault); // long instances are meant to be immutable anyway (i.e. use small int cache that even requires it)\n\n } else if (this.bytes && typeof this.typeDefault === \"string\") {\n var buf;\n if (util.base64.test(this.typeDefault))\n util.base64.decode(this.typeDefault, buf = util.newBuffer(util.base64.length(this.typeDefault)), 0);\n else\n util.utf8.write(this.typeDefault, buf = util.newBuffer(util.utf8.length(this.typeDefault)), 0);\n this.typeDefault = buf;\n }\n\n // take special care of maps and repeated fields\n if (this.map)\n this.defaultValue = util.emptyObject;\n else if (this.repeated)\n this.defaultValue = util.emptyArray;\n else\n this.defaultValue = this.typeDefault;\n\n // ensure proper value on prototype\n if (this.parent instanceof Type)\n this.parent.ctor.prototype[this.name] = this.defaultValue;\n\n return ReflectionObject.prototype.resolve.call(this);\n};\n\n/**\n * Decorator function as returned by {@link Field.d} and {@link MapField.d} (TypeScript).\n * @typedef FieldDecorator\n * @type {function}\n * @param {Object} prototype Target prototype\n * @param {string} fieldName Field name\n * @returns {undefined}\n */\n\n/**\n * Field decorator (TypeScript).\n * @name Field.d\n * @function\n * @param {number} fieldId Field id\n * @param {\"double\"|\"float\"|\"int32\"|\"uint32\"|\"sint32\"|\"fixed32\"|\"sfixed32\"|\"int64\"|\"uint64\"|\"sint64\"|\"fixed64\"|\"sfixed64\"|\"string\"|\"bool\"|\"bytes\"|Object} fieldType Field type\n * @param {\"optional\"|\"required\"|\"repeated\"} [fieldRule=\"optional\"] Field rule\n * @param {T} [defaultValue] Default value\n * @returns {FieldDecorator} Decorator function\n * @template T extends number | number[] | Long | Long[] | string | string[] | boolean | boolean[] | Uint8Array | Uint8Array[] | Buffer | Buffer[]\n */\nField.d = function decorateField(fieldId, fieldType, fieldRule, defaultValue) {\n\n // submessage: decorate the submessage and use its name as the type\n if (typeof fieldType === \"function\")\n fieldType = util.decorateType(fieldType).name;\n\n // enum reference: create a reflected copy of the enum and keep reuseing it\n else if (fieldType && typeof fieldType === \"object\")\n fieldType = util.decorateEnum(fieldType).name;\n\n return function fieldDecorator(prototype, fieldName) {\n util.decorateType(prototype.constructor)\n .add(new Field(fieldName, fieldId, fieldType, fieldRule, { \"default\": defaultValue }));\n };\n};\n\n/**\n * Field decorator (TypeScript).\n * @name Field.d\n * @function\n * @param {number} fieldId Field id\n * @param {Constructor|string} fieldType Field type\n * @param {\"optional\"|\"required\"|\"repeated\"} [fieldRule=\"optional\"] Field rule\n * @returns {FieldDecorator} Decorator function\n * @template T extends Message\n * @variation 2\n */\n// like Field.d but without a default value\n\n// Sets up cyclic dependencies (called in index-light)\nField._configure = function configure(Type_) {\n Type = Type_;\n};\n","\"use strict\";\nvar protobuf = module.exports = require(18);\n\nprotobuf.build = \"light\";\n\n/**\n * A node-style callback as used by {@link load} and {@link Root#load}.\n * @typedef LoadCallback\n * @type {function}\n * @param {Error|null} error Error, if any, otherwise `null`\n * @param {Root} [root] Root, if there hasn't been an error\n * @returns {undefined}\n */\n\n/**\n * Loads one or multiple .proto or preprocessed .json files into a common root namespace and calls the callback.\n * @param {string|string[]} filename One or multiple files to load\n * @param {Root} root Root namespace, defaults to create a new one if omitted.\n * @param {LoadCallback} callback Callback function\n * @returns {undefined}\n * @see {@link Root#load}\n */\nfunction load(filename, root, callback) {\n if (typeof root === \"function\") {\n callback = root;\n root = new protobuf.Root();\n } else if (!root)\n root = new protobuf.Root();\n return root.load(filename, callback);\n}\n\n/**\n * Loads one or multiple .proto or preprocessed .json files into a common root namespace and calls the callback.\n * @name load\n * @function\n * @param {string|string[]} filename One or multiple files to load\n * @param {LoadCallback} callback Callback function\n * @returns {undefined}\n * @see {@link Root#load}\n * @variation 2\n */\n// function load(filename:string, callback:LoadCallback):undefined\n\n/**\n * Loads one or multiple .proto or preprocessed .json files into a common root namespace and returns a promise.\n * @name load\n * @function\n * @param {string|string[]} filename One or multiple files to load\n * @param {Root} [root] Root namespace, defaults to create a new one if omitted.\n * @returns {Promise} Promise\n * @see {@link Root#load}\n * @variation 3\n */\n// function load(filename:string, [root:Root]):Promise\n\nprotobuf.load = load;\n\n/**\n * Synchronously loads one or multiple .proto or preprocessed .json files into a common root namespace (node only).\n * @param {string|string[]} filename One or multiple files to load\n * @param {Root} [root] Root namespace, defaults to create a new one if omitted.\n * @returns {Root} Root namespace\n * @throws {Error} If synchronous fetching is not supported (i.e. in browsers) or if a file's syntax is invalid\n * @see {@link Root#loadSync}\n */\nfunction loadSync(filename, root) {\n if (!root)\n root = new protobuf.Root();\n return root.loadSync(filename);\n}\n\nprotobuf.loadSync = loadSync;\n\n// Serialization\nprotobuf.encoder = require(14);\nprotobuf.decoder = require(13);\nprotobuf.verifier = require(40);\nprotobuf.converter = require(12);\n\n// Reflection\nprotobuf.ReflectionObject = require(24);\nprotobuf.Namespace = require(23);\nprotobuf.Root = require(29);\nprotobuf.Enum = require(15);\nprotobuf.Type = require(35);\nprotobuf.Field = require(16);\nprotobuf.OneOf = require(25);\nprotobuf.MapField = require(20);\nprotobuf.Service = require(33);\nprotobuf.Method = require(22);\n\n// Runtime\nprotobuf.Message = require(21);\nprotobuf.wrappers = require(41);\n\n// Utility\nprotobuf.types = require(36);\nprotobuf.util = require(37);\n\n// Set up possibly cyclic reflection dependencies\nprotobuf.ReflectionObject._configure(protobuf.Root);\nprotobuf.Namespace._configure(protobuf.Type, protobuf.Service, protobuf.Enum);\nprotobuf.Root._configure(protobuf.Type);\nprotobuf.Field._configure(protobuf.Type);\n","\"use strict\";\nvar protobuf = exports;\n\n/**\n * Build type, one of `\"full\"`, `\"light\"` or `\"minimal\"`.\n * @name build\n * @type {string}\n * @const\n */\nprotobuf.build = \"minimal\";\n\n// Serialization\nprotobuf.Writer = require(42);\nprotobuf.BufferWriter = require(43);\nprotobuf.Reader = require(27);\nprotobuf.BufferReader = require(28);\n\n// Utility\nprotobuf.util = require(39);\nprotobuf.rpc = require(31);\nprotobuf.roots = require(30);\nprotobuf.configure = configure;\n\n/* istanbul ignore next */\n/**\n * Reconfigures the library according to the environment.\n * @returns {undefined}\n */\nfunction configure() {\n protobuf.util._configure();\n protobuf.Writer._configure(protobuf.BufferWriter);\n protobuf.Reader._configure(protobuf.BufferReader);\n}\n\n// Set up buffer utility according to the environment\nconfigure();\n","\"use strict\";\nvar protobuf = module.exports = require(17);\n\nprotobuf.build = \"full\";\n\n// Parser\nprotobuf.tokenize = require(34);\nprotobuf.parse = require(26);\nprotobuf.common = require(11);\n\n// Configure parser\nprotobuf.Root._configure(protobuf.Type, protobuf.parse, protobuf.common);\n","\"use strict\";\nmodule.exports = MapField;\n\n// extends Field\nvar Field = require(16);\n((MapField.prototype = Object.create(Field.prototype)).constructor = MapField).className = \"MapField\";\n\nvar types = require(36),\n util = require(37);\n\n/**\n * Constructs a new map field instance.\n * @classdesc Reflected map field.\n * @extends FieldBase\n * @constructor\n * @param {string} name Unique name within its namespace\n * @param {number} id Unique id within its namespace\n * @param {string} keyType Key type\n * @param {string} type Value type\n * @param {Object.} [options] Declared options\n * @param {string} [comment] Comment associated with this field\n */\nfunction MapField(name, id, keyType, type, options, comment) {\n Field.call(this, name, id, type, undefined, undefined, options, comment);\n\n /* istanbul ignore if */\n if (!util.isString(keyType))\n throw TypeError(\"keyType must be a string\");\n\n /**\n * Key type.\n * @type {string}\n */\n this.keyType = keyType; // toJSON, marker\n\n /**\n * Resolved key type if not a basic type.\n * @type {ReflectionObject|null}\n */\n this.resolvedKeyType = null;\n\n // Overrides Field#map\n this.map = true;\n}\n\n/**\n * Map field descriptor.\n * @interface IMapField\n * @extends {IField}\n * @property {string} keyType Key type\n */\n\n/**\n * Extension map field descriptor.\n * @interface IExtensionMapField\n * @extends IMapField\n * @property {string} extend Extended type\n */\n\n/**\n * Constructs a map field from a map field descriptor.\n * @param {string} name Field name\n * @param {IMapField} json Map field descriptor\n * @returns {MapField} Created map field\n * @throws {TypeError} If arguments are invalid\n */\nMapField.fromJSON = function fromJSON(name, json) {\n return new MapField(name, json.id, json.keyType, json.type, json.options, json.comment);\n};\n\n/**\n * Converts this map field to a map field descriptor.\n * @param {IToJSONOptions} [toJSONOptions] JSON conversion options\n * @returns {IMapField} Map field descriptor\n */\nMapField.prototype.toJSON = function toJSON(toJSONOptions) {\n var keepComments = toJSONOptions ? Boolean(toJSONOptions.keepComments) : false;\n return util.toObject([\n \"keyType\" , this.keyType,\n \"type\" , this.type,\n \"id\" , this.id,\n \"extend\" , this.extend,\n \"options\" , this.options,\n \"comment\" , keepComments ? this.comment : undefined\n ]);\n};\n\n/**\n * @override\n */\nMapField.prototype.resolve = function resolve() {\n if (this.resolved)\n return this;\n\n // Besides a value type, map fields have a key type that may be \"any scalar type except for floating point types and bytes\"\n if (types.mapKey[this.keyType] === undefined)\n throw Error(\"invalid key type: \" + this.keyType);\n\n return Field.prototype.resolve.call(this);\n};\n\n/**\n * Map field decorator (TypeScript).\n * @name MapField.d\n * @function\n * @param {number} fieldId Field id\n * @param {\"int32\"|\"uint32\"|\"sint32\"|\"fixed32\"|\"sfixed32\"|\"int64\"|\"uint64\"|\"sint64\"|\"fixed64\"|\"sfixed64\"|\"bool\"|\"string\"} fieldKeyType Field key type\n * @param {\"double\"|\"float\"|\"int32\"|\"uint32\"|\"sint32\"|\"fixed32\"|\"sfixed32\"|\"int64\"|\"uint64\"|\"sint64\"|\"fixed64\"|\"sfixed64\"|\"bool\"|\"string\"|\"bytes\"|Object|Constructor<{}>} fieldValueType Field value type\n * @returns {FieldDecorator} Decorator function\n * @template T extends { [key: string]: number | Long | string | boolean | Uint8Array | Buffer | number[] | Message<{}> }\n */\nMapField.d = function decorateMapField(fieldId, fieldKeyType, fieldValueType) {\n\n // submessage value: decorate the submessage and use its name as the type\n if (typeof fieldValueType === \"function\")\n fieldValueType = util.decorateType(fieldValueType).name;\n\n // enum reference value: create a reflected copy of the enum and keep reuseing it\n else if (fieldValueType && typeof fieldValueType === \"object\")\n fieldValueType = util.decorateEnum(fieldValueType).name;\n\n return function mapFieldDecorator(prototype, fieldName) {\n util.decorateType(prototype.constructor)\n .add(new MapField(fieldName, fieldId, fieldKeyType, fieldValueType));\n };\n};\n","\"use strict\";\nmodule.exports = Message;\n\nvar util = require(39);\n\n/**\n * Constructs a new message instance.\n * @classdesc Abstract runtime message.\n * @constructor\n * @param {Properties} [properties] Properties to set\n * @template T extends object = object\n */\nfunction Message(properties) {\n // not used internally\n if (properties)\n for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i)\n this[keys[i]] = properties[keys[i]];\n}\n\n/**\n * Reference to the reflected type.\n * @name Message.$type\n * @type {Type}\n * @readonly\n */\n\n/**\n * Reference to the reflected type.\n * @name Message#$type\n * @type {Type}\n * @readonly\n */\n\n/*eslint-disable valid-jsdoc*/\n\n/**\n * Creates a new message of this type using the specified properties.\n * @param {Object.} [properties] Properties to set\n * @returns {Message} Message instance\n * @template T extends Message\n * @this Constructor\n */\nMessage.create = function create(properties) {\n return this.$type.create(properties);\n};\n\n/**\n * Encodes a message of this type.\n * @param {T|Object.} message Message to encode\n * @param {Writer} [writer] Writer to use\n * @returns {Writer} Writer\n * @template T extends Message\n * @this Constructor\n */\nMessage.encode = function encode(message, writer) {\n return this.$type.encode(message, writer);\n};\n\n/**\n * Encodes a message of this type preceeded by its length as a varint.\n * @param {T|Object.} message Message to encode\n * @param {Writer} [writer] Writer to use\n * @returns {Writer} Writer\n * @template T extends Message\n * @this Constructor\n */\nMessage.encodeDelimited = function encodeDelimited(message, writer) {\n return this.$type.encodeDelimited(message, writer);\n};\n\n/**\n * Decodes a message of this type.\n * @name Message.decode\n * @function\n * @param {Reader|Uint8Array} reader Reader or buffer to decode\n * @returns {T} Decoded message\n * @template T extends Message\n * @this Constructor\n */\nMessage.decode = function decode(reader) {\n return this.$type.decode(reader);\n};\n\n/**\n * Decodes a message of this type preceeded by its length as a varint.\n * @name Message.decodeDelimited\n * @function\n * @param {Reader|Uint8Array} reader Reader or buffer to decode\n * @returns {T} Decoded message\n * @template T extends Message\n * @this Constructor\n */\nMessage.decodeDelimited = function decodeDelimited(reader) {\n return this.$type.decodeDelimited(reader);\n};\n\n/**\n * Verifies a message of this type.\n * @name Message.verify\n * @function\n * @param {Object.} message Plain object to verify\n * @returns {string|null} `null` if valid, otherwise the reason why it is not\n */\nMessage.verify = function verify(message) {\n return this.$type.verify(message);\n};\n\n/**\n * Creates a new message of this type from a plain object. Also converts values to their respective internal types.\n * @param {Object.} object Plain object\n * @returns {T} Message instance\n * @template T extends Message\n * @this Constructor\n */\nMessage.fromObject = function fromObject(object) {\n return this.$type.fromObject(object);\n};\n\n/**\n * Creates a plain object from a message of this type. Also converts values to other types if specified.\n * @param {T} message Message instance\n * @param {IConversionOptions} [options] Conversion options\n * @returns {Object.} Plain object\n * @template T extends Message\n * @this Constructor\n */\nMessage.toObject = function toObject(message, options) {\n return this.$type.toObject(message, options);\n};\n\n/**\n * Converts this message to JSON.\n * @returns {Object.} JSON object\n */\nMessage.prototype.toJSON = function toJSON() {\n return this.$type.toObject(this, util.toJSONOptions);\n};\n\n/*eslint-enable valid-jsdoc*/","\"use strict\";\nmodule.exports = Method;\n\n// extends ReflectionObject\nvar ReflectionObject = require(24);\n((Method.prototype = Object.create(ReflectionObject.prototype)).constructor = Method).className = \"Method\";\n\nvar util = require(37);\n\n/**\n * Constructs a new service method instance.\n * @classdesc Reflected service method.\n * @extends ReflectionObject\n * @constructor\n * @param {string} name Method name\n * @param {string|undefined} type Method type, usually `\"rpc\"`\n * @param {string} requestType Request message type\n * @param {string} responseType Response message type\n * @param {boolean|Object.} [requestStream] Whether the request is streamed\n * @param {boolean|Object.} [responseStream] Whether the response is streamed\n * @param {Object.} [options] Declared options\n * @param {string} [comment] The comment for this method\n * @param {Object.} [parsedOptions] Declared options, properly parsed into an object\n */\nfunction Method(name, type, requestType, responseType, requestStream, responseStream, options, comment, parsedOptions) {\n\n /* istanbul ignore next */\n if (util.isObject(requestStream)) {\n options = requestStream;\n requestStream = responseStream = undefined;\n } else if (util.isObject(responseStream)) {\n options = responseStream;\n responseStream = undefined;\n }\n\n /* istanbul ignore if */\n if (!(type === undefined || util.isString(type)))\n throw TypeError(\"type must be a string\");\n\n /* istanbul ignore if */\n if (!util.isString(requestType))\n throw TypeError(\"requestType must be a string\");\n\n /* istanbul ignore if */\n if (!util.isString(responseType))\n throw TypeError(\"responseType must be a string\");\n\n ReflectionObject.call(this, name, options);\n\n /**\n * Method type.\n * @type {string}\n */\n this.type = type || \"rpc\"; // toJSON\n\n /**\n * Request type.\n * @type {string}\n */\n this.requestType = requestType; // toJSON, marker\n\n /**\n * Whether requests are streamed or not.\n * @type {boolean|undefined}\n */\n this.requestStream = requestStream ? true : undefined; // toJSON\n\n /**\n * Response type.\n * @type {string}\n */\n this.responseType = responseType; // toJSON\n\n /**\n * Whether responses are streamed or not.\n * @type {boolean|undefined}\n */\n this.responseStream = responseStream ? true : undefined; // toJSON\n\n /**\n * Resolved request type.\n * @type {Type|null}\n */\n this.resolvedRequestType = null;\n\n /**\n * Resolved response type.\n * @type {Type|null}\n */\n this.resolvedResponseType = null;\n\n /**\n * Comment for this method\n * @type {string|null}\n */\n this.comment = comment;\n\n /**\n * Options properly parsed into an object\n */\n this.parsedOptions = parsedOptions;\n}\n\n/**\n * Method descriptor.\n * @interface IMethod\n * @property {string} [type=\"rpc\"] Method type\n * @property {string} requestType Request type\n * @property {string} responseType Response type\n * @property {boolean} [requestStream=false] Whether requests are streamed\n * @property {boolean} [responseStream=false] Whether responses are streamed\n * @property {Object.} [options] Method options\n * @property {string} comment Method comments\n * @property {Object.} [parsedOptions] Method options properly parsed into an object\n */\n\n/**\n * Constructs a method from a method descriptor.\n * @param {string} name Method name\n * @param {IMethod} json Method descriptor\n * @returns {Method} Created method\n * @throws {TypeError} If arguments are invalid\n */\nMethod.fromJSON = function fromJSON(name, json) {\n return new Method(name, json.type, json.requestType, json.responseType, json.requestStream, json.responseStream, json.options, json.comment, json.parsedOptions);\n};\n\n/**\n * Converts this method to a method descriptor.\n * @param {IToJSONOptions} [toJSONOptions] JSON conversion options\n * @returns {IMethod} Method descriptor\n */\nMethod.prototype.toJSON = function toJSON(toJSONOptions) {\n var keepComments = toJSONOptions ? Boolean(toJSONOptions.keepComments) : false;\n return util.toObject([\n \"type\" , this.type !== \"rpc\" && /* istanbul ignore next */ this.type || undefined,\n \"requestType\" , this.requestType,\n \"requestStream\" , this.requestStream,\n \"responseType\" , this.responseType,\n \"responseStream\" , this.responseStream,\n \"options\" , this.options,\n \"comment\" , keepComments ? this.comment : undefined,\n \"parsedOptions\" , this.parsedOptions,\n ]);\n};\n\n/**\n * @override\n */\nMethod.prototype.resolve = function resolve() {\n\n /* istanbul ignore if */\n if (this.resolved)\n return this;\n\n this.resolvedRequestType = this.parent.lookupType(this.requestType);\n this.resolvedResponseType = this.parent.lookupType(this.responseType);\n\n return ReflectionObject.prototype.resolve.call(this);\n};\n","\"use strict\";\nmodule.exports = Namespace;\n\n// extends ReflectionObject\nvar ReflectionObject = require(24);\n((Namespace.prototype = Object.create(ReflectionObject.prototype)).constructor = Namespace).className = \"Namespace\";\n\nvar Field = require(16),\n util = require(37),\n OneOf = require(25);\n\nvar Type, // cyclic\n Service,\n Enum;\n\n/**\n * Constructs a new namespace instance.\n * @name Namespace\n * @classdesc Reflected namespace.\n * @extends NamespaceBase\n * @constructor\n * @param {string} name Namespace name\n * @param {Object.} [options] Declared options\n */\n\n/**\n * Constructs a namespace from JSON.\n * @memberof Namespace\n * @function\n * @param {string} name Namespace name\n * @param {Object.} json JSON object\n * @returns {Namespace} Created namespace\n * @throws {TypeError} If arguments are invalid\n */\nNamespace.fromJSON = function fromJSON(name, json) {\n return new Namespace(name, json.options).addJSON(json.nested);\n};\n\n/**\n * Converts an array of reflection objects to JSON.\n * @memberof Namespace\n * @param {ReflectionObject[]} array Object array\n * @param {IToJSONOptions} [toJSONOptions] JSON conversion options\n * @returns {Object.|undefined} JSON object or `undefined` when array is empty\n */\nfunction arrayToJSON(array, toJSONOptions) {\n if (!(array && array.length))\n return undefined;\n var obj = {};\n for (var i = 0; i < array.length; ++i)\n obj[array[i].name] = array[i].toJSON(toJSONOptions);\n return obj;\n}\n\nNamespace.arrayToJSON = arrayToJSON;\n\n/**\n * Tests if the specified id is reserved.\n * @param {Array.|undefined} reserved Array of reserved ranges and names\n * @param {number} id Id to test\n * @returns {boolean} `true` if reserved, otherwise `false`\n */\nNamespace.isReservedId = function isReservedId(reserved, id) {\n if (reserved)\n for (var i = 0; i < reserved.length; ++i)\n if (typeof reserved[i] !== \"string\" && reserved[i][0] <= id && reserved[i][1] > id)\n return true;\n return false;\n};\n\n/**\n * Tests if the specified name is reserved.\n * @param {Array.|undefined} reserved Array of reserved ranges and names\n * @param {string} name Name to test\n * @returns {boolean} `true` if reserved, otherwise `false`\n */\nNamespace.isReservedName = function isReservedName(reserved, name) {\n if (reserved)\n for (var i = 0; i < reserved.length; ++i)\n if (reserved[i] === name)\n return true;\n return false;\n};\n\n/**\n * Not an actual constructor. Use {@link Namespace} instead.\n * @classdesc Base class of all reflection objects containing nested objects. This is not an actual class but here for the sake of having consistent type definitions.\n * @exports NamespaceBase\n * @extends ReflectionObject\n * @abstract\n * @constructor\n * @param {string} name Namespace name\n * @param {Object.} [options] Declared options\n * @see {@link Namespace}\n */\nfunction Namespace(name, options) {\n ReflectionObject.call(this, name, options);\n\n /**\n * Nested objects by name.\n * @type {Object.|undefined}\n */\n this.nested = undefined; // toJSON\n\n /**\n * Cached nested objects as an array.\n * @type {ReflectionObject[]|null}\n * @private\n */\n this._nestedArray = null;\n}\n\nfunction clearCache(namespace) {\n namespace._nestedArray = null;\n return namespace;\n}\n\n/**\n * Nested objects of this namespace as an array for iteration.\n * @name NamespaceBase#nestedArray\n * @type {ReflectionObject[]}\n * @readonly\n */\nObject.defineProperty(Namespace.prototype, \"nestedArray\", {\n get: function() {\n return this._nestedArray || (this._nestedArray = util.toArray(this.nested));\n }\n});\n\n/**\n * Namespace descriptor.\n * @interface INamespace\n * @property {Object.} [options] Namespace options\n * @property {Object.} [nested] Nested object descriptors\n */\n\n/**\n * Any extension field descriptor.\n * @typedef AnyExtensionField\n * @type {IExtensionField|IExtensionMapField}\n */\n\n/**\n * Any nested object descriptor.\n * @typedef AnyNestedObject\n * @type {IEnum|IType|IService|AnyExtensionField|INamespace|IOneOf}\n */\n\n/**\n * Converts this namespace to a namespace descriptor.\n * @param {IToJSONOptions} [toJSONOptions] JSON conversion options\n * @returns {INamespace} Namespace descriptor\n */\nNamespace.prototype.toJSON = function toJSON(toJSONOptions) {\n return util.toObject([\n \"options\" , this.options,\n \"nested\" , arrayToJSON(this.nestedArray, toJSONOptions)\n ]);\n};\n\n/**\n * Adds nested objects to this namespace from nested object descriptors.\n * @param {Object.} nestedJson Any nested object descriptors\n * @returns {Namespace} `this`\n */\nNamespace.prototype.addJSON = function addJSON(nestedJson) {\n var ns = this;\n /* istanbul ignore else */\n if (nestedJson) {\n for (var names = Object.keys(nestedJson), i = 0, nested; i < names.length; ++i) {\n nested = nestedJson[names[i]];\n ns.add( // most to least likely\n ( nested.fields !== undefined\n ? Type.fromJSON\n : nested.values !== undefined\n ? Enum.fromJSON\n : nested.methods !== undefined\n ? Service.fromJSON\n : nested.id !== undefined\n ? Field.fromJSON\n : Namespace.fromJSON )(names[i], nested)\n );\n }\n }\n return this;\n};\n\n/**\n * Gets the nested object of the specified name.\n * @param {string} name Nested object name\n * @returns {ReflectionObject|null} The reflection object or `null` if it doesn't exist\n */\nNamespace.prototype.get = function get(name) {\n return this.nested && this.nested[name]\n || null;\n};\n\n/**\n * Gets the values of the nested {@link Enum|enum} of the specified name.\n * This methods differs from {@link Namespace#get|get} in that it returns an enum's values directly and throws instead of returning `null`.\n * @param {string} name Nested enum name\n * @returns {Object.} Enum values\n * @throws {Error} If there is no such enum\n */\nNamespace.prototype.getEnum = function getEnum(name) {\n if (this.nested && this.nested[name] instanceof Enum)\n return this.nested[name].values;\n throw Error(\"no such enum: \" + name);\n};\n\n/**\n * Adds a nested object to this namespace.\n * @param {ReflectionObject} object Nested object to add\n * @returns {Namespace} `this`\n * @throws {TypeError} If arguments are invalid\n * @throws {Error} If there is already a nested object with this name\n */\nNamespace.prototype.add = function add(object) {\n\n if (!(object instanceof Field && object.extend !== undefined || object instanceof Type || object instanceof OneOf || object instanceof Enum || object instanceof Service || object instanceof Namespace))\n throw TypeError(\"object must be a valid nested object\");\n\n if (!this.nested)\n this.nested = {};\n else {\n var prev = this.get(object.name);\n if (prev) {\n if (prev instanceof Namespace && object instanceof Namespace && !(prev instanceof Type || prev instanceof Service)) {\n // replace plain namespace but keep existing nested elements and options\n var nested = prev.nestedArray;\n for (var i = 0; i < nested.length; ++i)\n object.add(nested[i]);\n this.remove(prev);\n if (!this.nested)\n this.nested = {};\n object.setOptions(prev.options, true);\n\n } else\n throw Error(\"duplicate name '\" + object.name + \"' in \" + this);\n }\n }\n this.nested[object.name] = object;\n object.onAdd(this);\n return clearCache(this);\n};\n\n/**\n * Removes a nested object from this namespace.\n * @param {ReflectionObject} object Nested object to remove\n * @returns {Namespace} `this`\n * @throws {TypeError} If arguments are invalid\n * @throws {Error} If `object` is not a member of this namespace\n */\nNamespace.prototype.remove = function remove(object) {\n\n if (!(object instanceof ReflectionObject))\n throw TypeError(\"object must be a ReflectionObject\");\n if (object.parent !== this)\n throw Error(object + \" is not a member of \" + this);\n\n delete this.nested[object.name];\n if (!Object.keys(this.nested).length)\n this.nested = undefined;\n\n object.onRemove(this);\n return clearCache(this);\n};\n\n/**\n * Defines additial namespaces within this one if not yet existing.\n * @param {string|string[]} path Path to create\n * @param {*} [json] Nested types to create from JSON\n * @returns {Namespace} Pointer to the last namespace created or `this` if path is empty\n */\nNamespace.prototype.define = function define(path, json) {\n\n if (util.isString(path))\n path = path.split(\".\");\n else if (!Array.isArray(path))\n throw TypeError(\"illegal path\");\n if (path && path.length && path[0] === \"\")\n throw Error(\"path must be relative\");\n\n var ptr = this;\n while (path.length > 0) {\n var part = path.shift();\n if (ptr.nested && ptr.nested[part]) {\n ptr = ptr.nested[part];\n if (!(ptr instanceof Namespace))\n throw Error(\"path conflicts with non-namespace objects\");\n } else\n ptr.add(ptr = new Namespace(part));\n }\n if (json)\n ptr.addJSON(json);\n return ptr;\n};\n\n/**\n * Resolves this namespace's and all its nested objects' type references. Useful to validate a reflection tree, but comes at a cost.\n * @returns {Namespace} `this`\n */\nNamespace.prototype.resolveAll = function resolveAll() {\n var nested = this.nestedArray, i = 0;\n while (i < nested.length)\n if (nested[i] instanceof Namespace)\n nested[i++].resolveAll();\n else\n nested[i++].resolve();\n return this.resolve();\n};\n\n/**\n * Recursively looks up the reflection object matching the specified path in the scope of this namespace.\n * @param {string|string[]} path Path to look up\n * @param {*|Array.<*>} filterTypes Filter types, any combination of the constructors of `protobuf.Type`, `protobuf.Enum`, `protobuf.Service` etc.\n * @param {boolean} [parentAlreadyChecked=false] If known, whether the parent has already been checked\n * @returns {ReflectionObject|null} Looked up object or `null` if none could be found\n */\nNamespace.prototype.lookup = function lookup(path, filterTypes, parentAlreadyChecked) {\n\n /* istanbul ignore next */\n if (typeof filterTypes === \"boolean\") {\n parentAlreadyChecked = filterTypes;\n filterTypes = undefined;\n } else if (filterTypes && !Array.isArray(filterTypes))\n filterTypes = [ filterTypes ];\n\n if (util.isString(path) && path.length) {\n if (path === \".\")\n return this.root;\n path = path.split(\".\");\n } else if (!path.length)\n return this;\n\n // Start at root if path is absolute\n if (path[0] === \"\")\n return this.root.lookup(path.slice(1), filterTypes);\n\n // Test if the first part matches any nested object, and if so, traverse if path contains more\n var found = this.get(path[0]);\n if (found) {\n if (path.length === 1) {\n if (!filterTypes || filterTypes.indexOf(found.constructor) > -1)\n return found;\n } else if (found instanceof Namespace && (found = found.lookup(path.slice(1), filterTypes, true)))\n return found;\n\n // Otherwise try each nested namespace\n } else\n for (var i = 0; i < this.nestedArray.length; ++i)\n if (this._nestedArray[i] instanceof Namespace && (found = this._nestedArray[i].lookup(path, filterTypes, true)))\n return found;\n\n // If there hasn't been a match, try again at the parent\n if (this.parent === null || parentAlreadyChecked)\n return null;\n return this.parent.lookup(path, filterTypes);\n};\n\n/**\n * Looks up the reflection object at the specified path, relative to this namespace.\n * @name NamespaceBase#lookup\n * @function\n * @param {string|string[]} path Path to look up\n * @param {boolean} [parentAlreadyChecked=false] Whether the parent has already been checked\n * @returns {ReflectionObject|null} Looked up object or `null` if none could be found\n * @variation 2\n */\n// lookup(path: string, [parentAlreadyChecked: boolean])\n\n/**\n * Looks up the {@link Type|type} at the specified path, relative to this namespace.\n * Besides its signature, this methods differs from {@link Namespace#lookup|lookup} in that it throws instead of returning `null`.\n * @param {string|string[]} path Path to look up\n * @returns {Type} Looked up type\n * @throws {Error} If `path` does not point to a type\n */\nNamespace.prototype.lookupType = function lookupType(path) {\n var found = this.lookup(path, [ Type ]);\n if (!found)\n throw Error(\"no such type: \" + path);\n return found;\n};\n\n/**\n * Looks up the values of the {@link Enum|enum} at the specified path, relative to this namespace.\n * Besides its signature, this methods differs from {@link Namespace#lookup|lookup} in that it throws instead of returning `null`.\n * @param {string|string[]} path Path to look up\n * @returns {Enum} Looked up enum\n * @throws {Error} If `path` does not point to an enum\n */\nNamespace.prototype.lookupEnum = function lookupEnum(path) {\n var found = this.lookup(path, [ Enum ]);\n if (!found)\n throw Error(\"no such Enum '\" + path + \"' in \" + this);\n return found;\n};\n\n/**\n * Looks up the {@link Type|type} or {@link Enum|enum} at the specified path, relative to this namespace.\n * Besides its signature, this methods differs from {@link Namespace#lookup|lookup} in that it throws instead of returning `null`.\n * @param {string|string[]} path Path to look up\n * @returns {Type} Looked up type or enum\n * @throws {Error} If `path` does not point to a type or enum\n */\nNamespace.prototype.lookupTypeOrEnum = function lookupTypeOrEnum(path) {\n var found = this.lookup(path, [ Type, Enum ]);\n if (!found)\n throw Error(\"no such Type or Enum '\" + path + \"' in \" + this);\n return found;\n};\n\n/**\n * Looks up the {@link Service|service} at the specified path, relative to this namespace.\n * Besides its signature, this methods differs from {@link Namespace#lookup|lookup} in that it throws instead of returning `null`.\n * @param {string|string[]} path Path to look up\n * @returns {Service} Looked up service\n * @throws {Error} If `path` does not point to a service\n */\nNamespace.prototype.lookupService = function lookupService(path) {\n var found = this.lookup(path, [ Service ]);\n if (!found)\n throw Error(\"no such Service '\" + path + \"' in \" + this);\n return found;\n};\n\n// Sets up cyclic dependencies (called in index-light)\nNamespace._configure = function(Type_, Service_, Enum_) {\n Type = Type_;\n Service = Service_;\n Enum = Enum_;\n};\n","\"use strict\";\nmodule.exports = ReflectionObject;\n\nReflectionObject.className = \"ReflectionObject\";\n\nvar util = require(37);\n\nvar Root; // cyclic\n\n/**\n * Constructs a new reflection object instance.\n * @classdesc Base class of all reflection objects.\n * @constructor\n * @param {string} name Object name\n * @param {Object.} [options] Declared options\n * @abstract\n */\nfunction ReflectionObject(name, options) {\n\n if (!util.isString(name))\n throw TypeError(\"name must be a string\");\n\n if (options && !util.isObject(options))\n throw TypeError(\"options must be an object\");\n\n /**\n * Options.\n * @type {Object.|undefined}\n */\n this.options = options; // toJSON\n\n /**\n * Parsed Options.\n * @type {Array.>|undefined}\n */\n this.parsedOptions = null;\n\n /**\n * Unique name within its namespace.\n * @type {string}\n */\n this.name = name;\n\n /**\n * Parent namespace.\n * @type {Namespace|null}\n */\n this.parent = null;\n\n /**\n * Whether already resolved or not.\n * @type {boolean}\n */\n this.resolved = false;\n\n /**\n * Comment text, if any.\n * @type {string|null}\n */\n this.comment = null;\n\n /**\n * Defining file name.\n * @type {string|null}\n */\n this.filename = null;\n}\n\nObject.defineProperties(ReflectionObject.prototype, {\n\n /**\n * Reference to the root namespace.\n * @name ReflectionObject#root\n * @type {Root}\n * @readonly\n */\n root: {\n get: function() {\n var ptr = this;\n while (ptr.parent !== null)\n ptr = ptr.parent;\n return ptr;\n }\n },\n\n /**\n * Full name including leading dot.\n * @name ReflectionObject#fullName\n * @type {string}\n * @readonly\n */\n fullName: {\n get: function() {\n var path = [ this.name ],\n ptr = this.parent;\n while (ptr) {\n path.unshift(ptr.name);\n ptr = ptr.parent;\n }\n return path.join(\".\");\n }\n }\n});\n\n/**\n * Converts this reflection object to its descriptor representation.\n * @returns {Object.} Descriptor\n * @abstract\n */\nReflectionObject.prototype.toJSON = /* istanbul ignore next */ function toJSON() {\n throw Error(); // not implemented, shouldn't happen\n};\n\n/**\n * Called when this object is added to a parent.\n * @param {ReflectionObject} parent Parent added to\n * @returns {undefined}\n */\nReflectionObject.prototype.onAdd = function onAdd(parent) {\n if (this.parent && this.parent !== parent)\n this.parent.remove(this);\n this.parent = parent;\n this.resolved = false;\n var root = parent.root;\n if (root instanceof Root)\n root._handleAdd(this);\n};\n\n/**\n * Called when this object is removed from a parent.\n * @param {ReflectionObject} parent Parent removed from\n * @returns {undefined}\n */\nReflectionObject.prototype.onRemove = function onRemove(parent) {\n var root = parent.root;\n if (root instanceof Root)\n root._handleRemove(this);\n this.parent = null;\n this.resolved = false;\n};\n\n/**\n * Resolves this objects type references.\n * @returns {ReflectionObject} `this`\n */\nReflectionObject.prototype.resolve = function resolve() {\n if (this.resolved)\n return this;\n if (this.root instanceof Root)\n this.resolved = true; // only if part of a root\n return this;\n};\n\n/**\n * Gets an option value.\n * @param {string} name Option name\n * @returns {*} Option value or `undefined` if not set\n */\nReflectionObject.prototype.getOption = function getOption(name) {\n if (this.options)\n return this.options[name];\n return undefined;\n};\n\n/**\n * Sets an option.\n * @param {string} name Option name\n * @param {*} value Option value\n * @param {boolean} [ifNotSet] Sets the option only if it isn't currently set\n * @returns {ReflectionObject} `this`\n */\nReflectionObject.prototype.setOption = function setOption(name, value, ifNotSet) {\n if (!ifNotSet || !this.options || this.options[name] === undefined)\n (this.options || (this.options = {}))[name] = value;\n return this;\n};\n\n/**\n * Sets a parsed option.\n * @param {string} name parsed Option name\n * @param {*} value Option value\n * @param {string} propName dot '.' delimited full path of property within the option to set. if undefined\\empty, will add a new option with that value\n * @returns {ReflectionObject} `this`\n */\nReflectionObject.prototype.setParsedOption = function setParsedOption(name, value, propName) {\n if (!this.parsedOptions) {\n this.parsedOptions = [];\n }\n var parsedOptions = this.parsedOptions;\n if (propName) {\n // If setting a sub property of an option then try to merge it\n // with an existing option\n var opt = parsedOptions.find(function (opt) {\n return Object.prototype.hasOwnProperty.call(opt, name);\n });\n if (opt) {\n // If we found an existing option - just merge the property value\n var newValue = opt[name];\n util.setProperty(newValue, propName, value);\n } else {\n // otherwise, create a new option, set it's property and add it to the list\n opt = {};\n opt[name] = util.setProperty({}, propName, value);\n parsedOptions.push(opt);\n }\n } else {\n // Always create a new option when setting the value of the option itself\n var newOpt = {};\n newOpt[name] = value;\n parsedOptions.push(newOpt);\n }\n return this;\n};\n\n/**\n * Sets multiple options.\n * @param {Object.} options Options to set\n * @param {boolean} [ifNotSet] Sets an option only if it isn't currently set\n * @returns {ReflectionObject} `this`\n */\nReflectionObject.prototype.setOptions = function setOptions(options, ifNotSet) {\n if (options)\n for (var keys = Object.keys(options), i = 0; i < keys.length; ++i)\n this.setOption(keys[i], options[keys[i]], ifNotSet);\n return this;\n};\n\n/**\n * Converts this instance to its string representation.\n * @returns {string} Class name[, space, full name]\n */\nReflectionObject.prototype.toString = function toString() {\n var className = this.constructor.className,\n fullName = this.fullName;\n if (fullName.length)\n return className + \" \" + fullName;\n return className;\n};\n\n// Sets up cyclic dependencies (called in index-light)\nReflectionObject._configure = function(Root_) {\n Root = Root_;\n};\n","\"use strict\";\nmodule.exports = OneOf;\n\n// extends ReflectionObject\nvar ReflectionObject = require(24);\n((OneOf.prototype = Object.create(ReflectionObject.prototype)).constructor = OneOf).className = \"OneOf\";\n\nvar Field = require(16),\n util = require(37);\n\n/**\n * Constructs a new oneof instance.\n * @classdesc Reflected oneof.\n * @extends ReflectionObject\n * @constructor\n * @param {string} name Oneof name\n * @param {string[]|Object.} [fieldNames] Field names\n * @param {Object.} [options] Declared options\n * @param {string} [comment] Comment associated with this field\n */\nfunction OneOf(name, fieldNames, options, comment) {\n if (!Array.isArray(fieldNames)) {\n options = fieldNames;\n fieldNames = undefined;\n }\n ReflectionObject.call(this, name, options);\n\n /* istanbul ignore if */\n if (!(fieldNames === undefined || Array.isArray(fieldNames)))\n throw TypeError(\"fieldNames must be an Array\");\n\n /**\n * Field names that belong to this oneof.\n * @type {string[]}\n */\n this.oneof = fieldNames || []; // toJSON, marker\n\n /**\n * Fields that belong to this oneof as an array for iteration.\n * @type {Field[]}\n * @readonly\n */\n this.fieldsArray = []; // declared readonly for conformance, possibly not yet added to parent\n\n /**\n * Comment for this field.\n * @type {string|null}\n */\n this.comment = comment;\n}\n\n/**\n * Oneof descriptor.\n * @interface IOneOf\n * @property {Array.} oneof Oneof field names\n * @property {Object.} [options] Oneof options\n */\n\n/**\n * Constructs a oneof from a oneof descriptor.\n * @param {string} name Oneof name\n * @param {IOneOf} json Oneof descriptor\n * @returns {OneOf} Created oneof\n * @throws {TypeError} If arguments are invalid\n */\nOneOf.fromJSON = function fromJSON(name, json) {\n return new OneOf(name, json.oneof, json.options, json.comment);\n};\n\n/**\n * Converts this oneof to a oneof descriptor.\n * @param {IToJSONOptions} [toJSONOptions] JSON conversion options\n * @returns {IOneOf} Oneof descriptor\n */\nOneOf.prototype.toJSON = function toJSON(toJSONOptions) {\n var keepComments = toJSONOptions ? Boolean(toJSONOptions.keepComments) : false;\n return util.toObject([\n \"options\" , this.options,\n \"oneof\" , this.oneof,\n \"comment\" , keepComments ? this.comment : undefined\n ]);\n};\n\n/**\n * Adds the fields of the specified oneof to the parent if not already done so.\n * @param {OneOf} oneof The oneof\n * @returns {undefined}\n * @inner\n * @ignore\n */\nfunction addFieldsToParent(oneof) {\n if (oneof.parent)\n for (var i = 0; i < oneof.fieldsArray.length; ++i)\n if (!oneof.fieldsArray[i].parent)\n oneof.parent.add(oneof.fieldsArray[i]);\n}\n\n/**\n * Adds a field to this oneof and removes it from its current parent, if any.\n * @param {Field} field Field to add\n * @returns {OneOf} `this`\n */\nOneOf.prototype.add = function add(field) {\n\n /* istanbul ignore if */\n if (!(field instanceof Field))\n throw TypeError(\"field must be a Field\");\n\n if (field.parent && field.parent !== this.parent)\n field.parent.remove(field);\n this.oneof.push(field.name);\n this.fieldsArray.push(field);\n field.partOf = this; // field.parent remains null\n addFieldsToParent(this);\n return this;\n};\n\n/**\n * Removes a field from this oneof and puts it back to the oneof's parent.\n * @param {Field} field Field to remove\n * @returns {OneOf} `this`\n */\nOneOf.prototype.remove = function remove(field) {\n\n /* istanbul ignore if */\n if (!(field instanceof Field))\n throw TypeError(\"field must be a Field\");\n\n var index = this.fieldsArray.indexOf(field);\n\n /* istanbul ignore if */\n if (index < 0)\n throw Error(field + \" is not a member of \" + this);\n\n this.fieldsArray.splice(index, 1);\n index = this.oneof.indexOf(field.name);\n\n /* istanbul ignore else */\n if (index > -1) // theoretical\n this.oneof.splice(index, 1);\n\n field.partOf = null;\n return this;\n};\n\n/**\n * @override\n */\nOneOf.prototype.onAdd = function onAdd(parent) {\n ReflectionObject.prototype.onAdd.call(this, parent);\n var self = this;\n // Collect present fields\n for (var i = 0; i < this.oneof.length; ++i) {\n var field = parent.get(this.oneof[i]);\n if (field && !field.partOf) {\n field.partOf = self;\n self.fieldsArray.push(field);\n }\n }\n // Add not yet present fields\n addFieldsToParent(this);\n};\n\n/**\n * @override\n */\nOneOf.prototype.onRemove = function onRemove(parent) {\n for (var i = 0, field; i < this.fieldsArray.length; ++i)\n if ((field = this.fieldsArray[i]).parent)\n field.parent.remove(field);\n ReflectionObject.prototype.onRemove.call(this, parent);\n};\n\n/**\n * Decorator function as returned by {@link OneOf.d} (TypeScript).\n * @typedef OneOfDecorator\n * @type {function}\n * @param {Object} prototype Target prototype\n * @param {string} oneofName OneOf name\n * @returns {undefined}\n */\n\n/**\n * OneOf decorator (TypeScript).\n * @function\n * @param {...string} fieldNames Field names\n * @returns {OneOfDecorator} Decorator function\n * @template T extends string\n */\nOneOf.d = function decorateOneOf() {\n var fieldNames = new Array(arguments.length),\n index = 0;\n while (index < arguments.length)\n fieldNames[index] = arguments[index++];\n return function oneOfDecorator(prototype, oneofName) {\n util.decorateType(prototype.constructor)\n .add(new OneOf(oneofName, fieldNames));\n Object.defineProperty(prototype, oneofName, {\n get: util.oneOfGetter(fieldNames),\n set: util.oneOfSetter(fieldNames)\n });\n };\n};\n","\"use strict\";\nmodule.exports = parse;\n\nparse.filename = null;\nparse.defaults = { keepCase: false };\n\nvar tokenize = require(34),\n Root = require(29),\n Type = require(35),\n Field = require(16),\n MapField = require(20),\n OneOf = require(25),\n Enum = require(15),\n Service = require(33),\n Method = require(22),\n types = require(36),\n util = require(37);\n\nvar base10Re = /^[1-9][0-9]*$/,\n base10NegRe = /^-?[1-9][0-9]*$/,\n base16Re = /^0[x][0-9a-fA-F]+$/,\n base16NegRe = /^-?0[x][0-9a-fA-F]+$/,\n base8Re = /^0[0-7]+$/,\n base8NegRe = /^-?0[0-7]+$/,\n numberRe = /^(?![eE])[0-9]*(?:\\.[0-9]*)?(?:[eE][+-]?[0-9]+)?$/,\n nameRe = /^[a-zA-Z_][a-zA-Z_0-9]*$/,\n typeRefRe = /^(?:\\.?[a-zA-Z_][a-zA-Z_0-9]*)(?:\\.[a-zA-Z_][a-zA-Z_0-9]*)*$/,\n fqTypeRefRe = /^(?:\\.[a-zA-Z_][a-zA-Z_0-9]*)+$/;\n\n/**\n * Result object returned from {@link parse}.\n * @interface IParserResult\n * @property {string|undefined} package Package name, if declared\n * @property {string[]|undefined} imports Imports, if any\n * @property {string[]|undefined} weakImports Weak imports, if any\n * @property {string|undefined} syntax Syntax, if specified (either `\"proto2\"` or `\"proto3\"`)\n * @property {Root} root Populated root instance\n */\n\n/**\n * Options modifying the behavior of {@link parse}.\n * @interface IParseOptions\n * @property {boolean} [keepCase=false] Keeps field casing instead of converting to camel case\n * @property {boolean} [alternateCommentMode=false] Recognize double-slash comments in addition to doc-block comments.\n * @property {boolean} [preferTrailingComment=false] Use trailing comment when both leading comment and trailing comment exist.\n */\n\n/**\n * Options modifying the behavior of JSON serialization.\n * @interface IToJSONOptions\n * @property {boolean} [keepComments=false] Serializes comments.\n */\n\n/**\n * Parses the given .proto source and returns an object with the parsed contents.\n * @param {string} source Source contents\n * @param {Root} root Root to populate\n * @param {IParseOptions} [options] Parse options. Defaults to {@link parse.defaults} when omitted.\n * @returns {IParserResult} Parser result\n * @property {string} filename=null Currently processing file name for error reporting, if known\n * @property {IParseOptions} defaults Default {@link IParseOptions}\n */\nfunction parse(source, root, options) {\n /* eslint-disable callback-return */\n if (!(root instanceof Root)) {\n options = root;\n root = new Root();\n }\n if (!options)\n options = parse.defaults;\n\n var preferTrailingComment = options.preferTrailingComment || false;\n var tn = tokenize(source, options.alternateCommentMode || false),\n next = tn.next,\n push = tn.push,\n peek = tn.peek,\n skip = tn.skip,\n cmnt = tn.cmnt;\n\n var head = true,\n pkg,\n imports,\n weakImports,\n syntax,\n isProto3 = false;\n\n var ptr = root;\n\n var applyCase = options.keepCase ? function(name) { return name; } : util.camelCase;\n\n /* istanbul ignore next */\n function illegal(token, name, insideTryCatch) {\n var filename = parse.filename;\n if (!insideTryCatch)\n parse.filename = null;\n return Error(\"illegal \" + (name || \"token\") + \" '\" + token + \"' (\" + (filename ? filename + \", \" : \"\") + \"line \" + tn.line + \")\");\n }\n\n function readString() {\n var values = [],\n token;\n do {\n /* istanbul ignore if */\n if ((token = next()) !== \"\\\"\" && token !== \"'\")\n throw illegal(token);\n\n values.push(next());\n skip(token);\n token = peek();\n } while (token === \"\\\"\" || token === \"'\");\n return values.join(\"\");\n }\n\n function readValue(acceptTypeRef) {\n var token = next();\n switch (token) {\n case \"'\":\n case \"\\\"\":\n push(token);\n return readString();\n case \"true\": case \"TRUE\":\n return true;\n case \"false\": case \"FALSE\":\n return false;\n }\n try {\n return parseNumber(token, /* insideTryCatch */ true);\n } catch (e) {\n\n /* istanbul ignore else */\n if (acceptTypeRef && typeRefRe.test(token))\n return token;\n\n /* istanbul ignore next */\n throw illegal(token, \"value\");\n }\n }\n\n function readRanges(target, acceptStrings) {\n var token, start;\n do {\n if (acceptStrings && ((token = peek()) === \"\\\"\" || token === \"'\"))\n target.push(readString());\n else\n target.push([ start = parseId(next()), skip(\"to\", true) ? parseId(next()) : start ]);\n } while (skip(\",\", true));\n var dummy = {options: undefined};\n dummy.setOption = function(name, value) {\n if (this.options === undefined) this.options = {};\n this.options[name] = value;\n };\n ifBlock(\n dummy,\n function parseRange_block(token) {\n /* istanbul ignore else */\n if (token === \"option\") {\n parseOption(dummy, token); // skip\n skip(\";\");\n } else\n throw illegal(token);\n },\n function parseRange_line() {\n parseInlineOptions(dummy); // skip\n });\n }\n\n function parseNumber(token, insideTryCatch) {\n var sign = 1;\n if (token.charAt(0) === \"-\") {\n sign = -1;\n token = token.substring(1);\n }\n switch (token) {\n case \"inf\": case \"INF\": case \"Inf\":\n return sign * Infinity;\n case \"nan\": case \"NAN\": case \"Nan\": case \"NaN\":\n return NaN;\n case \"0\":\n return 0;\n }\n if (base10Re.test(token))\n return sign * parseInt(token, 10);\n if (base16Re.test(token))\n return sign * parseInt(token, 16);\n if (base8Re.test(token))\n return sign * parseInt(token, 8);\n\n /* istanbul ignore else */\n if (numberRe.test(token))\n return sign * parseFloat(token);\n\n /* istanbul ignore next */\n throw illegal(token, \"number\", insideTryCatch);\n }\n\n function parseId(token, acceptNegative) {\n switch (token) {\n case \"max\": case \"MAX\": case \"Max\":\n return 536870911;\n case \"0\":\n return 0;\n }\n\n /* istanbul ignore if */\n if (!acceptNegative && token.charAt(0) === \"-\")\n throw illegal(token, \"id\");\n\n if (base10NegRe.test(token))\n return parseInt(token, 10);\n if (base16NegRe.test(token))\n return parseInt(token, 16);\n\n /* istanbul ignore else */\n if (base8NegRe.test(token))\n return parseInt(token, 8);\n\n /* istanbul ignore next */\n throw illegal(token, \"id\");\n }\n\n function parsePackage() {\n\n /* istanbul ignore if */\n if (pkg !== undefined)\n throw illegal(\"package\");\n\n pkg = next();\n\n /* istanbul ignore if */\n if (!typeRefRe.test(pkg))\n throw illegal(pkg, \"name\");\n\n ptr = ptr.define(pkg);\n skip(\";\");\n }\n\n function parseImport() {\n var token = peek();\n var whichImports;\n switch (token) {\n case \"weak\":\n whichImports = weakImports || (weakImports = []);\n next();\n break;\n case \"public\":\n next();\n // eslint-disable-next-line no-fallthrough\n default:\n whichImports = imports || (imports = []);\n break;\n }\n token = readString();\n skip(\";\");\n whichImports.push(token);\n }\n\n function parseSyntax() {\n skip(\"=\");\n syntax = readString();\n isProto3 = syntax === \"proto3\";\n\n /* istanbul ignore if */\n if (!isProto3 && syntax !== \"proto2\")\n throw illegal(syntax, \"syntax\");\n\n skip(\";\");\n }\n\n function parseCommon(parent, token) {\n switch (token) {\n\n case \"option\":\n parseOption(parent, token);\n skip(\";\");\n return true;\n\n case \"message\":\n parseType(parent, token);\n return true;\n\n case \"enum\":\n parseEnum(parent, token);\n return true;\n\n case \"service\":\n parseService(parent, token);\n return true;\n\n case \"extend\":\n parseExtension(parent, token);\n return true;\n }\n return false;\n }\n\n function ifBlock(obj, fnIf, fnElse) {\n var trailingLine = tn.line;\n if (obj) {\n if(typeof obj.comment !== \"string\") {\n obj.comment = cmnt(); // try block-type comment\n }\n obj.filename = parse.filename;\n }\n if (skip(\"{\", true)) {\n var token;\n while ((token = next()) !== \"}\")\n fnIf(token);\n skip(\";\", true);\n } else {\n if (fnElse)\n fnElse();\n skip(\";\");\n if (obj && (typeof obj.comment !== \"string\" || preferTrailingComment))\n obj.comment = cmnt(trailingLine) || obj.comment; // try line-type comment\n }\n }\n\n function parseType(parent, token) {\n\n /* istanbul ignore if */\n if (!nameRe.test(token = next()))\n throw illegal(token, \"type name\");\n\n var type = new Type(token);\n ifBlock(type, function parseType_block(token) {\n if (parseCommon(type, token))\n return;\n\n switch (token) {\n\n case \"map\":\n parseMapField(type, token);\n break;\n\n case \"required\":\n case \"repeated\":\n parseField(type, token);\n break;\n\n case \"optional\":\n /* istanbul ignore if */\n if (isProto3) {\n parseField(type, \"proto3_optional\");\n } else {\n parseField(type, \"optional\");\n }\n break;\n\n case \"oneof\":\n parseOneOf(type, token);\n break;\n\n case \"extensions\":\n readRanges(type.extensions || (type.extensions = []));\n break;\n\n case \"reserved\":\n readRanges(type.reserved || (type.reserved = []), true);\n break;\n\n default:\n /* istanbul ignore if */\n if (!isProto3 || !typeRefRe.test(token))\n throw illegal(token);\n\n push(token);\n parseField(type, \"optional\");\n break;\n }\n });\n parent.add(type);\n }\n\n function parseField(parent, rule, extend) {\n var type = next();\n if (type === \"group\") {\n parseGroup(parent, rule);\n return;\n }\n // Type names can consume multiple tokens, in multiple variants:\n // package.subpackage field tokens: \"package.subpackage\" [TYPE NAME ENDS HERE] \"field\"\n // package . subpackage field tokens: \"package\" \".\" \"subpackage\" [TYPE NAME ENDS HERE] \"field\"\n // package. subpackage field tokens: \"package.\" \"subpackage\" [TYPE NAME ENDS HERE] \"field\"\n // package .subpackage field tokens: \"package\" \".subpackage\" [TYPE NAME ENDS HERE] \"field\"\n // Keep reading tokens until we get a type name with no period at the end,\n // and the next token does not start with a period.\n while (type.endsWith(\".\") || peek().startsWith(\".\")) {\n type += next();\n }\n\n /* istanbul ignore if */\n if (!typeRefRe.test(type))\n throw illegal(type, \"type\");\n\n var name = next();\n\n /* istanbul ignore if */\n if (!nameRe.test(name))\n throw illegal(name, \"name\");\n\n name = applyCase(name);\n skip(\"=\");\n\n var field = new Field(name, parseId(next()), type, rule, extend);\n ifBlock(field, function parseField_block(token) {\n\n /* istanbul ignore else */\n if (token === \"option\") {\n parseOption(field, token);\n skip(\";\");\n } else\n throw illegal(token);\n\n }, function parseField_line() {\n parseInlineOptions(field);\n });\n\n if (rule === \"proto3_optional\") {\n // for proto3 optional fields, we create a single-member Oneof to mimic \"optional\" behavior\n var oneof = new OneOf(\"_\" + name);\n field.setOption(\"proto3_optional\", true);\n oneof.add(field);\n parent.add(oneof);\n } else {\n parent.add(field);\n }\n\n // JSON defaults to packed=true if not set so we have to set packed=false explicity when\n // parsing proto2 descriptors without the option, where applicable. This must be done for\n // all known packable types and anything that could be an enum (= is not a basic type).\n if (!isProto3 && field.repeated && (types.packed[type] !== undefined || types.basic[type] === undefined))\n field.setOption(\"packed\", false, /* ifNotSet */ true);\n }\n\n function parseGroup(parent, rule) {\n var name = next();\n\n /* istanbul ignore if */\n if (!nameRe.test(name))\n throw illegal(name, \"name\");\n\n var fieldName = util.lcFirst(name);\n if (name === fieldName)\n name = util.ucFirst(name);\n skip(\"=\");\n var id = parseId(next());\n var type = new Type(name);\n type.group = true;\n var field = new Field(fieldName, id, name, rule);\n field.filename = parse.filename;\n ifBlock(type, function parseGroup_block(token) {\n switch (token) {\n\n case \"option\":\n parseOption(type, token);\n skip(\";\");\n break;\n\n case \"required\":\n case \"repeated\":\n parseField(type, token);\n break;\n\n case \"optional\":\n /* istanbul ignore if */\n if (isProto3) {\n parseField(type, \"proto3_optional\");\n } else {\n parseField(type, \"optional\");\n }\n break;\n\n case \"message\":\n parseType(type, token);\n break;\n\n case \"enum\":\n parseEnum(type, token);\n break;\n\n /* istanbul ignore next */\n default:\n throw illegal(token); // there are no groups with proto3 semantics\n }\n });\n parent.add(type)\n .add(field);\n }\n\n function parseMapField(parent) {\n skip(\"<\");\n var keyType = next();\n\n /* istanbul ignore if */\n if (types.mapKey[keyType] === undefined)\n throw illegal(keyType, \"type\");\n\n skip(\",\");\n var valueType = next();\n\n /* istanbul ignore if */\n if (!typeRefRe.test(valueType))\n throw illegal(valueType, \"type\");\n\n skip(\">\");\n var name = next();\n\n /* istanbul ignore if */\n if (!nameRe.test(name))\n throw illegal(name, \"name\");\n\n skip(\"=\");\n var field = new MapField(applyCase(name), parseId(next()), keyType, valueType);\n ifBlock(field, function parseMapField_block(token) {\n\n /* istanbul ignore else */\n if (token === \"option\") {\n parseOption(field, token);\n skip(\";\");\n } else\n throw illegal(token);\n\n }, function parseMapField_line() {\n parseInlineOptions(field);\n });\n parent.add(field);\n }\n\n function parseOneOf(parent, token) {\n\n /* istanbul ignore if */\n if (!nameRe.test(token = next()))\n throw illegal(token, \"name\");\n\n var oneof = new OneOf(applyCase(token));\n ifBlock(oneof, function parseOneOf_block(token) {\n if (token === \"option\") {\n parseOption(oneof, token);\n skip(\";\");\n } else {\n push(token);\n parseField(oneof, \"optional\");\n }\n });\n parent.add(oneof);\n }\n\n function parseEnum(parent, token) {\n\n /* istanbul ignore if */\n if (!nameRe.test(token = next()))\n throw illegal(token, \"name\");\n\n var enm = new Enum(token);\n ifBlock(enm, function parseEnum_block(token) {\n switch(token) {\n case \"option\":\n parseOption(enm, token);\n skip(\";\");\n break;\n\n case \"reserved\":\n readRanges(enm.reserved || (enm.reserved = []), true);\n break;\n\n default:\n parseEnumValue(enm, token);\n }\n });\n parent.add(enm);\n }\n\n function parseEnumValue(parent, token) {\n\n /* istanbul ignore if */\n if (!nameRe.test(token))\n throw illegal(token, \"name\");\n\n skip(\"=\");\n var value = parseId(next(), true),\n dummy = {\n options: undefined\n };\n dummy.setOption = function(name, value) {\n if (this.options === undefined)\n this.options = {};\n this.options[name] = value;\n };\n ifBlock(dummy, function parseEnumValue_block(token) {\n\n /* istanbul ignore else */\n if (token === \"option\") {\n parseOption(dummy, token); // skip\n skip(\";\");\n } else\n throw illegal(token);\n\n }, function parseEnumValue_line() {\n parseInlineOptions(dummy); // skip\n });\n parent.add(token, value, dummy.comment, dummy.options);\n }\n\n function parseOption(parent, token) {\n var isCustom = skip(\"(\", true);\n\n /* istanbul ignore if */\n if (!typeRefRe.test(token = next()))\n throw illegal(token, \"name\");\n\n var name = token;\n var option = name;\n var propName;\n\n if (isCustom) {\n skip(\")\");\n name = \"(\" + name + \")\";\n option = name;\n token = peek();\n if (fqTypeRefRe.test(token)) {\n propName = token.slice(1); //remove '.' before property name\n name += token;\n next();\n }\n }\n skip(\"=\");\n var optionValue = parseOptionValue(parent, name);\n setParsedOption(parent, option, optionValue, propName);\n }\n\n function parseOptionValue(parent, name) {\n // { a: \"foo\" b { c: \"bar\" } }\n if (skip(\"{\", true)) {\n var objectResult = {};\n\n while (!skip(\"}\", true)) {\n /* istanbul ignore if */\n if (!nameRe.test(token = next())) {\n throw illegal(token, \"name\");\n }\n if (token === null) {\n throw illegal(token, \"end of input\");\n }\n\n var value;\n var propName = token;\n\n skip(\":\", true);\n\n if (peek() === \"{\")\n value = parseOptionValue(parent, name + \".\" + token);\n else if (peek() === \"[\") {\n // option (my_option) = {\n // repeated_value: [ \"foo\", \"bar\" ]\n // };\n value = [];\n var lastValue;\n if (skip(\"[\", true)) {\n do {\n lastValue = readValue(true);\n value.push(lastValue);\n } while (skip(\",\", true));\n skip(\"]\");\n if (typeof lastValue !== \"undefined\") {\n setOption(parent, name + \".\" + token, lastValue);\n }\n }\n } else {\n value = readValue(true);\n setOption(parent, name + \".\" + token, value);\n }\n\n var prevValue = objectResult[propName];\n\n if (prevValue)\n value = [].concat(prevValue).concat(value);\n\n objectResult[propName] = value;\n\n // Semicolons and commas can be optional\n skip(\",\", true);\n skip(\";\", true);\n }\n\n return objectResult;\n }\n\n var simpleValue = readValue(true);\n setOption(parent, name, simpleValue);\n return simpleValue;\n // Does not enforce a delimiter to be universal\n }\n\n function setOption(parent, name, value) {\n if (parent.setOption)\n parent.setOption(name, value);\n }\n\n function setParsedOption(parent, name, value, propName) {\n if (parent.setParsedOption)\n parent.setParsedOption(name, value, propName);\n }\n\n function parseInlineOptions(parent) {\n if (skip(\"[\", true)) {\n do {\n parseOption(parent, \"option\");\n } while (skip(\",\", true));\n skip(\"]\");\n }\n return parent;\n }\n\n function parseService(parent, token) {\n\n /* istanbul ignore if */\n if (!nameRe.test(token = next()))\n throw illegal(token, \"service name\");\n\n var service = new Service(token);\n ifBlock(service, function parseService_block(token) {\n if (parseCommon(service, token))\n return;\n\n /* istanbul ignore else */\n if (token === \"rpc\")\n parseMethod(service, token);\n else\n throw illegal(token);\n });\n parent.add(service);\n }\n\n function parseMethod(parent, token) {\n // Get the comment of the preceding line now (if one exists) in case the\n // method is defined across multiple lines.\n var commentText = cmnt();\n\n var type = token;\n\n /* istanbul ignore if */\n if (!nameRe.test(token = next()))\n throw illegal(token, \"name\");\n\n var name = token,\n requestType, requestStream,\n responseType, responseStream;\n\n skip(\"(\");\n if (skip(\"stream\", true))\n requestStream = true;\n\n /* istanbul ignore if */\n if (!typeRefRe.test(token = next()))\n throw illegal(token);\n\n requestType = token;\n skip(\")\"); skip(\"returns\"); skip(\"(\");\n if (skip(\"stream\", true))\n responseStream = true;\n\n /* istanbul ignore if */\n if (!typeRefRe.test(token = next()))\n throw illegal(token);\n\n responseType = token;\n skip(\")\");\n\n var method = new Method(name, type, requestType, responseType, requestStream, responseStream);\n method.comment = commentText;\n ifBlock(method, function parseMethod_block(token) {\n\n /* istanbul ignore else */\n if (token === \"option\") {\n parseOption(method, token);\n skip(\";\");\n } else\n throw illegal(token);\n\n });\n parent.add(method);\n }\n\n function parseExtension(parent, token) {\n\n /* istanbul ignore if */\n if (!typeRefRe.test(token = next()))\n throw illegal(token, \"reference\");\n\n var reference = token;\n ifBlock(null, function parseExtension_block(token) {\n switch (token) {\n\n case \"required\":\n case \"repeated\":\n parseField(parent, token, reference);\n break;\n\n case \"optional\":\n /* istanbul ignore if */\n if (isProto3) {\n parseField(parent, \"proto3_optional\", reference);\n } else {\n parseField(parent, \"optional\", reference);\n }\n break;\n\n default:\n /* istanbul ignore if */\n if (!isProto3 || !typeRefRe.test(token))\n throw illegal(token);\n push(token);\n parseField(parent, \"optional\", reference);\n break;\n }\n });\n }\n\n var token;\n while ((token = next()) !== null) {\n switch (token) {\n\n case \"package\":\n\n /* istanbul ignore if */\n if (!head)\n throw illegal(token);\n\n parsePackage();\n break;\n\n case \"import\":\n\n /* istanbul ignore if */\n if (!head)\n throw illegal(token);\n\n parseImport();\n break;\n\n case \"syntax\":\n\n /* istanbul ignore if */\n if (!head)\n throw illegal(token);\n\n parseSyntax();\n break;\n\n case \"option\":\n\n parseOption(ptr, token);\n skip(\";\");\n break;\n\n default:\n\n /* istanbul ignore else */\n if (parseCommon(ptr, token)) {\n head = false;\n continue;\n }\n\n /* istanbul ignore next */\n throw illegal(token);\n }\n }\n\n parse.filename = null;\n return {\n \"package\" : pkg,\n \"imports\" : imports,\n weakImports : weakImports,\n syntax : syntax,\n root : root\n };\n}\n\n/**\n * Parses the given .proto source and returns an object with the parsed contents.\n * @name parse\n * @function\n * @param {string} source Source contents\n * @param {IParseOptions} [options] Parse options. Defaults to {@link parse.defaults} when omitted.\n * @returns {IParserResult} Parser result\n * @property {string} filename=null Currently processing file name for error reporting, if known\n * @property {IParseOptions} defaults Default {@link IParseOptions}\n * @variation 2\n */\n","\"use strict\";\nmodule.exports = Reader;\n\nvar util = require(39);\n\nvar BufferReader; // cyclic\n\nvar LongBits = util.LongBits,\n utf8 = util.utf8;\n\n/* istanbul ignore next */\nfunction indexOutOfRange(reader, writeLength) {\n return RangeError(\"index out of range: \" + reader.pos + \" + \" + (writeLength || 1) + \" > \" + reader.len);\n}\n\n/**\n * Constructs a new reader instance using the specified buffer.\n * @classdesc Wire format reader using `Uint8Array` if available, otherwise `Array`.\n * @constructor\n * @param {Uint8Array} buffer Buffer to read from\n */\nfunction Reader(buffer) {\n\n /**\n * Read buffer.\n * @type {Uint8Array}\n */\n this.buf = buffer;\n\n /**\n * Read buffer position.\n * @type {number}\n */\n this.pos = 0;\n\n /**\n * Read buffer length.\n * @type {number}\n */\n this.len = buffer.length;\n}\n\nvar create_array = typeof Uint8Array !== \"undefined\"\n ? function create_typed_array(buffer) {\n if (buffer instanceof Uint8Array || Array.isArray(buffer))\n return new Reader(buffer);\n throw Error(\"illegal buffer\");\n }\n /* istanbul ignore next */\n : function create_array(buffer) {\n if (Array.isArray(buffer))\n return new Reader(buffer);\n throw Error(\"illegal buffer\");\n };\n\nvar create = function create() {\n return util.Buffer\n ? function create_buffer_setup(buffer) {\n return (Reader.create = function create_buffer(buffer) {\n return util.Buffer.isBuffer(buffer)\n ? new BufferReader(buffer)\n /* istanbul ignore next */\n : create_array(buffer);\n })(buffer);\n }\n /* istanbul ignore next */\n : create_array;\n};\n\n/**\n * Creates a new reader using the specified buffer.\n * @function\n * @param {Uint8Array|Buffer} buffer Buffer to read from\n * @returns {Reader|BufferReader} A {@link BufferReader} if `buffer` is a Buffer, otherwise a {@link Reader}\n * @throws {Error} If `buffer` is not a valid buffer\n */\nReader.create = create();\n\nReader.prototype._slice = util.Array.prototype.subarray || /* istanbul ignore next */ util.Array.prototype.slice;\n\n/**\n * Reads a varint as an unsigned 32 bit value.\n * @function\n * @returns {number} Value read\n */\nReader.prototype.uint32 = (function read_uint32_setup() {\n var value = 4294967295; // optimizer type-hint, tends to deopt otherwise (?!)\n return function read_uint32() {\n value = ( this.buf[this.pos] & 127 ) >>> 0; if (this.buf[this.pos++] < 128) return value;\n value = (value | (this.buf[this.pos] & 127) << 7) >>> 0; if (this.buf[this.pos++] < 128) return value;\n value = (value | (this.buf[this.pos] & 127) << 14) >>> 0; if (this.buf[this.pos++] < 128) return value;\n value = (value | (this.buf[this.pos] & 127) << 21) >>> 0; if (this.buf[this.pos++] < 128) return value;\n value = (value | (this.buf[this.pos] & 15) << 28) >>> 0; if (this.buf[this.pos++] < 128) return value;\n\n /* istanbul ignore if */\n if ((this.pos += 5) > this.len) {\n this.pos = this.len;\n throw indexOutOfRange(this, 10);\n }\n return value;\n };\n})();\n\n/**\n * Reads a varint as a signed 32 bit value.\n * @returns {number} Value read\n */\nReader.prototype.int32 = function read_int32() {\n return this.uint32() | 0;\n};\n\n/**\n * Reads a zig-zag encoded varint as a signed 32 bit value.\n * @returns {number} Value read\n */\nReader.prototype.sint32 = function read_sint32() {\n var value = this.uint32();\n return value >>> 1 ^ -(value & 1) | 0;\n};\n\n/* eslint-disable no-invalid-this */\n\nfunction readLongVarint() {\n // tends to deopt with local vars for octet etc.\n var bits = new LongBits(0, 0);\n var i = 0;\n if (this.len - this.pos > 4) { // fast route (lo)\n for (; i < 4; ++i) {\n // 1st..4th\n bits.lo = (bits.lo | (this.buf[this.pos] & 127) << i * 7) >>> 0;\n if (this.buf[this.pos++] < 128)\n return bits;\n }\n // 5th\n bits.lo = (bits.lo | (this.buf[this.pos] & 127) << 28) >>> 0;\n bits.hi = (bits.hi | (this.buf[this.pos] & 127) >> 4) >>> 0;\n if (this.buf[this.pos++] < 128)\n return bits;\n i = 0;\n } else {\n for (; i < 3; ++i) {\n /* istanbul ignore if */\n if (this.pos >= this.len)\n throw indexOutOfRange(this);\n // 1st..3th\n bits.lo = (bits.lo | (this.buf[this.pos] & 127) << i * 7) >>> 0;\n if (this.buf[this.pos++] < 128)\n return bits;\n }\n // 4th\n bits.lo = (bits.lo | (this.buf[this.pos++] & 127) << i * 7) >>> 0;\n return bits;\n }\n if (this.len - this.pos > 4) { // fast route (hi)\n for (; i < 5; ++i) {\n // 6th..10th\n bits.hi = (bits.hi | (this.buf[this.pos] & 127) << i * 7 + 3) >>> 0;\n if (this.buf[this.pos++] < 128)\n return bits;\n }\n } else {\n for (; i < 5; ++i) {\n /* istanbul ignore if */\n if (this.pos >= this.len)\n throw indexOutOfRange(this);\n // 6th..10th\n bits.hi = (bits.hi | (this.buf[this.pos] & 127) << i * 7 + 3) >>> 0;\n if (this.buf[this.pos++] < 128)\n return bits;\n }\n }\n /* istanbul ignore next */\n throw Error(\"invalid varint encoding\");\n}\n\n/* eslint-enable no-invalid-this */\n\n/**\n * Reads a varint as a signed 64 bit value.\n * @name Reader#int64\n * @function\n * @returns {Long} Value read\n */\n\n/**\n * Reads a varint as an unsigned 64 bit value.\n * @name Reader#uint64\n * @function\n * @returns {Long} Value read\n */\n\n/**\n * Reads a zig-zag encoded varint as a signed 64 bit value.\n * @name Reader#sint64\n * @function\n * @returns {Long} Value read\n */\n\n/**\n * Reads a varint as a boolean.\n * @returns {boolean} Value read\n */\nReader.prototype.bool = function read_bool() {\n return this.uint32() !== 0;\n};\n\nfunction readFixed32_end(buf, end) { // note that this uses `end`, not `pos`\n return (buf[end - 4]\n | buf[end - 3] << 8\n | buf[end - 2] << 16\n | buf[end - 1] << 24) >>> 0;\n}\n\n/**\n * Reads fixed 32 bits as an unsigned 32 bit integer.\n * @returns {number} Value read\n */\nReader.prototype.fixed32 = function read_fixed32() {\n\n /* istanbul ignore if */\n if (this.pos + 4 > this.len)\n throw indexOutOfRange(this, 4);\n\n return readFixed32_end(this.buf, this.pos += 4);\n};\n\n/**\n * Reads fixed 32 bits as a signed 32 bit integer.\n * @returns {number} Value read\n */\nReader.prototype.sfixed32 = function read_sfixed32() {\n\n /* istanbul ignore if */\n if (this.pos + 4 > this.len)\n throw indexOutOfRange(this, 4);\n\n return readFixed32_end(this.buf, this.pos += 4) | 0;\n};\n\n/* eslint-disable no-invalid-this */\n\nfunction readFixed64(/* this: Reader */) {\n\n /* istanbul ignore if */\n if (this.pos + 8 > this.len)\n throw indexOutOfRange(this, 8);\n\n return new LongBits(readFixed32_end(this.buf, this.pos += 4), readFixed32_end(this.buf, this.pos += 4));\n}\n\n/* eslint-enable no-invalid-this */\n\n/**\n * Reads fixed 64 bits.\n * @name Reader#fixed64\n * @function\n * @returns {Long} Value read\n */\n\n/**\n * Reads zig-zag encoded fixed 64 bits.\n * @name Reader#sfixed64\n * @function\n * @returns {Long} Value read\n */\n\n/**\n * Reads a float (32 bit) as a number.\n * @function\n * @returns {number} Value read\n */\nReader.prototype.float = function read_float() {\n\n /* istanbul ignore if */\n if (this.pos + 4 > this.len)\n throw indexOutOfRange(this, 4);\n\n var value = util.float.readFloatLE(this.buf, this.pos);\n this.pos += 4;\n return value;\n};\n\n/**\n * Reads a double (64 bit float) as a number.\n * @function\n * @returns {number} Value read\n */\nReader.prototype.double = function read_double() {\n\n /* istanbul ignore if */\n if (this.pos + 8 > this.len)\n throw indexOutOfRange(this, 4);\n\n var value = util.float.readDoubleLE(this.buf, this.pos);\n this.pos += 8;\n return value;\n};\n\n/**\n * Reads a sequence of bytes preceeded by its length as a varint.\n * @returns {Uint8Array} Value read\n */\nReader.prototype.bytes = function read_bytes() {\n var length = this.uint32(),\n start = this.pos,\n end = this.pos + length;\n\n /* istanbul ignore if */\n if (end > this.len)\n throw indexOutOfRange(this, length);\n\n this.pos += length;\n if (Array.isArray(this.buf)) // plain array\n return this.buf.slice(start, end);\n\n if (start === end) { // fix for IE 10/Win8 and others' subarray returning array of size 1\n var nativeBuffer = util.Buffer;\n return nativeBuffer\n ? nativeBuffer.alloc(0)\n : new this.buf.constructor(0);\n }\n return this._slice.call(this.buf, start, end);\n};\n\n/**\n * Reads a string preceeded by its byte length as a varint.\n * @returns {string} Value read\n */\nReader.prototype.string = function read_string() {\n var bytes = this.bytes();\n return utf8.read(bytes, 0, bytes.length);\n};\n\n/**\n * Skips the specified number of bytes if specified, otherwise skips a varint.\n * @param {number} [length] Length if known, otherwise a varint is assumed\n * @returns {Reader} `this`\n */\nReader.prototype.skip = function skip(length) {\n if (typeof length === \"number\") {\n /* istanbul ignore if */\n if (this.pos + length > this.len)\n throw indexOutOfRange(this, length);\n this.pos += length;\n } else {\n do {\n /* istanbul ignore if */\n if (this.pos >= this.len)\n throw indexOutOfRange(this);\n } while (this.buf[this.pos++] & 128);\n }\n return this;\n};\n\n/**\n * Skips the next element of the specified wire type.\n * @param {number} wireType Wire type received\n * @returns {Reader} `this`\n */\nReader.prototype.skipType = function(wireType) {\n switch (wireType) {\n case 0:\n this.skip();\n break;\n case 1:\n this.skip(8);\n break;\n case 2:\n this.skip(this.uint32());\n break;\n case 3:\n while ((wireType = this.uint32() & 7) !== 4) {\n this.skipType(wireType);\n }\n break;\n case 5:\n this.skip(4);\n break;\n\n /* istanbul ignore next */\n default:\n throw Error(\"invalid wire type \" + wireType + \" at offset \" + this.pos);\n }\n return this;\n};\n\nReader._configure = function(BufferReader_) {\n BufferReader = BufferReader_;\n Reader.create = create();\n BufferReader._configure();\n\n var fn = util.Long ? \"toLong\" : /* istanbul ignore next */ \"toNumber\";\n util.merge(Reader.prototype, {\n\n int64: function read_int64() {\n return readLongVarint.call(this)[fn](false);\n },\n\n uint64: function read_uint64() {\n return readLongVarint.call(this)[fn](true);\n },\n\n sint64: function read_sint64() {\n return readLongVarint.call(this).zzDecode()[fn](false);\n },\n\n fixed64: function read_fixed64() {\n return readFixed64.call(this)[fn](true);\n },\n\n sfixed64: function read_sfixed64() {\n return readFixed64.call(this)[fn](false);\n }\n\n });\n};\n","\"use strict\";\nmodule.exports = BufferReader;\n\n// extends Reader\nvar Reader = require(27);\n(BufferReader.prototype = Object.create(Reader.prototype)).constructor = BufferReader;\n\nvar util = require(39);\n\n/**\n * Constructs a new buffer reader instance.\n * @classdesc Wire format reader using node buffers.\n * @extends Reader\n * @constructor\n * @param {Buffer} buffer Buffer to read from\n */\nfunction BufferReader(buffer) {\n Reader.call(this, buffer);\n\n /**\n * Read buffer.\n * @name BufferReader#buf\n * @type {Buffer}\n */\n}\n\nBufferReader._configure = function () {\n /* istanbul ignore else */\n if (util.Buffer)\n BufferReader.prototype._slice = util.Buffer.prototype.slice;\n};\n\n\n/**\n * @override\n */\nBufferReader.prototype.string = function read_string_buffer() {\n var len = this.uint32(); // modifies pos\n return this.buf.utf8Slice\n ? this.buf.utf8Slice(this.pos, this.pos = Math.min(this.pos + len, this.len))\n : this.buf.toString(\"utf-8\", this.pos, this.pos = Math.min(this.pos + len, this.len));\n};\n\n/**\n * Reads a sequence of bytes preceeded by its length as a varint.\n * @name BufferReader#bytes\n * @function\n * @returns {Buffer} Value read\n */\n\nBufferReader._configure();\n","\"use strict\";\nmodule.exports = Root;\n\n// extends Namespace\nvar Namespace = require(23);\n((Root.prototype = Object.create(Namespace.prototype)).constructor = Root).className = \"Root\";\n\nvar Field = require(16),\n Enum = require(15),\n OneOf = require(25),\n util = require(37);\n\nvar Type, // cyclic\n parse, // might be excluded\n common; // \"\n\n/**\n * Constructs a new root namespace instance.\n * @classdesc Root namespace wrapping all types, enums, services, sub-namespaces etc. that belong together.\n * @extends NamespaceBase\n * @constructor\n * @param {Object.} [options] Top level options\n */\nfunction Root(options) {\n Namespace.call(this, \"\", options);\n\n /**\n * Deferred extension fields.\n * @type {Field[]}\n */\n this.deferred = [];\n\n /**\n * Resolved file names of loaded files.\n * @type {string[]}\n */\n this.files = [];\n}\n\n/**\n * Loads a namespace descriptor into a root namespace.\n * @param {INamespace} json Nameespace descriptor\n * @param {Root} [root] Root namespace, defaults to create a new one if omitted\n * @returns {Root} Root namespace\n */\nRoot.fromJSON = function fromJSON(json, root) {\n if (!root)\n root = new Root();\n if (json.options)\n root.setOptions(json.options);\n return root.addJSON(json.nested);\n};\n\n/**\n * Resolves the path of an imported file, relative to the importing origin.\n * This method exists so you can override it with your own logic in case your imports are scattered over multiple directories.\n * @function\n * @param {string} origin The file name of the importing file\n * @param {string} target The file name being imported\n * @returns {string|null} Resolved path to `target` or `null` to skip the file\n */\nRoot.prototype.resolvePath = util.path.resolve;\n\n/**\n * Fetch content from file path or url\n * This method exists so you can override it with your own logic.\n * @function\n * @param {string} path File path or url\n * @param {FetchCallback} callback Callback function\n * @returns {undefined}\n */\nRoot.prototype.fetch = util.fetch;\n\n// A symbol-like function to safely signal synchronous loading\n/* istanbul ignore next */\nfunction SYNC() {} // eslint-disable-line no-empty-function\n\n/**\n * Loads one or multiple .proto or preprocessed .json files into this root namespace and calls the callback.\n * @param {string|string[]} filename Names of one or multiple files to load\n * @param {IParseOptions} options Parse options\n * @param {LoadCallback} callback Callback function\n * @returns {undefined}\n */\nRoot.prototype.load = function load(filename, options, callback) {\n if (typeof options === \"function\") {\n callback = options;\n options = undefined;\n }\n var self = this;\n if (!callback)\n return util.asPromise(load, self, filename, options);\n\n var sync = callback === SYNC; // undocumented\n\n // Finishes loading by calling the callback (exactly once)\n function finish(err, root) {\n /* istanbul ignore if */\n if (!callback)\n return;\n if (sync)\n throw err;\n var cb = callback;\n callback = null;\n cb(err, root);\n }\n\n // Bundled definition existence checking\n function getBundledFileName(filename) {\n var idx = filename.lastIndexOf(\"google/protobuf/\");\n if (idx > -1) {\n var altname = filename.substring(idx);\n if (altname in common) return altname;\n }\n return null;\n }\n\n // Processes a single file\n function process(filename, source) {\n try {\n if (util.isString(source) && source.charAt(0) === \"{\")\n source = JSON.parse(source);\n if (!util.isString(source))\n self.setOptions(source.options).addJSON(source.nested);\n else {\n parse.filename = filename;\n var parsed = parse(source, self, options),\n resolved,\n i = 0;\n if (parsed.imports)\n for (; i < parsed.imports.length; ++i)\n if (resolved = getBundledFileName(parsed.imports[i]) || self.resolvePath(filename, parsed.imports[i]))\n fetch(resolved);\n if (parsed.weakImports)\n for (i = 0; i < parsed.weakImports.length; ++i)\n if (resolved = getBundledFileName(parsed.weakImports[i]) || self.resolvePath(filename, parsed.weakImports[i]))\n fetch(resolved, true);\n }\n } catch (err) {\n finish(err);\n }\n if (!sync && !queued)\n finish(null, self); // only once anyway\n }\n\n // Fetches a single file\n function fetch(filename, weak) {\n filename = getBundledFileName(filename) || filename;\n\n // Skip if already loaded / attempted\n if (self.files.indexOf(filename) > -1)\n return;\n self.files.push(filename);\n\n // Shortcut bundled definitions\n if (filename in common) {\n if (sync)\n process(filename, common[filename]);\n else {\n ++queued;\n setTimeout(function() {\n --queued;\n process(filename, common[filename]);\n });\n }\n return;\n }\n\n // Otherwise fetch from disk or network\n if (sync) {\n var source;\n try {\n source = util.fs.readFileSync(filename).toString(\"utf8\");\n } catch (err) {\n if (!weak)\n finish(err);\n return;\n }\n process(filename, source);\n } else {\n ++queued;\n self.fetch(filename, function(err, source) {\n --queued;\n /* istanbul ignore if */\n if (!callback)\n return; // terminated meanwhile\n if (err) {\n /* istanbul ignore else */\n if (!weak)\n finish(err);\n else if (!queued) // can't be covered reliably\n finish(null, self);\n return;\n }\n process(filename, source);\n });\n }\n }\n var queued = 0;\n\n // Assembling the root namespace doesn't require working type\n // references anymore, so we can load everything in parallel\n if (util.isString(filename))\n filename = [ filename ];\n for (var i = 0, resolved; i < filename.length; ++i)\n if (resolved = self.resolvePath(\"\", filename[i]))\n fetch(resolved);\n\n if (sync)\n return self;\n if (!queued)\n finish(null, self);\n return undefined;\n};\n// function load(filename:string, options:IParseOptions, callback:LoadCallback):undefined\n\n/**\n * Loads one or multiple .proto or preprocessed .json files into this root namespace and calls the callback.\n * @function Root#load\n * @param {string|string[]} filename Names of one or multiple files to load\n * @param {LoadCallback} callback Callback function\n * @returns {undefined}\n * @variation 2\n */\n// function load(filename:string, callback:LoadCallback):undefined\n\n/**\n * Loads one or multiple .proto or preprocessed .json files into this root namespace and returns a promise.\n * @function Root#load\n * @param {string|string[]} filename Names of one or multiple files to load\n * @param {IParseOptions} [options] Parse options. Defaults to {@link parse.defaults} when omitted.\n * @returns {Promise} Promise\n * @variation 3\n */\n// function load(filename:string, [options:IParseOptions]):Promise\n\n/**\n * Synchronously loads one or multiple .proto or preprocessed .json files into this root namespace (node only).\n * @function Root#loadSync\n * @param {string|string[]} filename Names of one or multiple files to load\n * @param {IParseOptions} [options] Parse options. Defaults to {@link parse.defaults} when omitted.\n * @returns {Root} Root namespace\n * @throws {Error} If synchronous fetching is not supported (i.e. in browsers) or if a file's syntax is invalid\n */\nRoot.prototype.loadSync = function loadSync(filename, options) {\n if (!util.isNode)\n throw Error(\"not supported\");\n return this.load(filename, options, SYNC);\n};\n\n/**\n * @override\n */\nRoot.prototype.resolveAll = function resolveAll() {\n if (this.deferred.length)\n throw Error(\"unresolvable extensions: \" + this.deferred.map(function(field) {\n return \"'extend \" + field.extend + \"' in \" + field.parent.fullName;\n }).join(\", \"));\n return Namespace.prototype.resolveAll.call(this);\n};\n\n// only uppercased (and thus conflict-free) children are exposed, see below\nvar exposeRe = /^[A-Z]/;\n\n/**\n * Handles a deferred declaring extension field by creating a sister field to represent it within its extended type.\n * @param {Root} root Root instance\n * @param {Field} field Declaring extension field witin the declaring type\n * @returns {boolean} `true` if successfully added to the extended type, `false` otherwise\n * @inner\n * @ignore\n */\nfunction tryHandleExtension(root, field) {\n var extendedType = field.parent.lookup(field.extend);\n if (extendedType) {\n var sisterField = new Field(field.fullName, field.id, field.type, field.rule, undefined, field.options);\n //do not allow to extend same field twice to prevent the error\n if (extendedType.get(sisterField.name)) {\n return true;\n }\n sisterField.declaringField = field;\n field.extensionField = sisterField;\n extendedType.add(sisterField);\n return true;\n }\n return false;\n}\n\n/**\n * Called when any object is added to this root or its sub-namespaces.\n * @param {ReflectionObject} object Object added\n * @returns {undefined}\n * @private\n */\nRoot.prototype._handleAdd = function _handleAdd(object) {\n if (object instanceof Field) {\n\n if (/* an extension field (implies not part of a oneof) */ object.extend !== undefined && /* not already handled */ !object.extensionField)\n if (!tryHandleExtension(this, object))\n this.deferred.push(object);\n\n } else if (object instanceof Enum) {\n\n if (exposeRe.test(object.name))\n object.parent[object.name] = object.values; // expose enum values as property of its parent\n\n } else if (!(object instanceof OneOf)) /* everything else is a namespace */ {\n\n if (object instanceof Type) // Try to handle any deferred extensions\n for (var i = 0; i < this.deferred.length;)\n if (tryHandleExtension(this, this.deferred[i]))\n this.deferred.splice(i, 1);\n else\n ++i;\n for (var j = 0; j < /* initializes */ object.nestedArray.length; ++j) // recurse into the namespace\n this._handleAdd(object._nestedArray[j]);\n if (exposeRe.test(object.name))\n object.parent[object.name] = object; // expose namespace as property of its parent\n }\n\n // The above also adds uppercased (and thus conflict-free) nested types, services and enums as\n // properties of namespaces just like static code does. This allows using a .d.ts generated for\n // a static module with reflection-based solutions where the condition is met.\n};\n\n/**\n * Called when any object is removed from this root or its sub-namespaces.\n * @param {ReflectionObject} object Object removed\n * @returns {undefined}\n * @private\n */\nRoot.prototype._handleRemove = function _handleRemove(object) {\n if (object instanceof Field) {\n\n if (/* an extension field */ object.extend !== undefined) {\n if (/* already handled */ object.extensionField) { // remove its sister field\n object.extensionField.parent.remove(object.extensionField);\n object.extensionField = null;\n } else { // cancel the extension\n var index = this.deferred.indexOf(object);\n /* istanbul ignore else */\n if (index > -1)\n this.deferred.splice(index, 1);\n }\n }\n\n } else if (object instanceof Enum) {\n\n if (exposeRe.test(object.name))\n delete object.parent[object.name]; // unexpose enum values\n\n } else if (object instanceof Namespace) {\n\n for (var i = 0; i < /* initializes */ object.nestedArray.length; ++i) // recurse into the namespace\n this._handleRemove(object._nestedArray[i]);\n\n if (exposeRe.test(object.name))\n delete object.parent[object.name]; // unexpose namespaces\n\n }\n};\n\n// Sets up cyclic dependencies (called in index-light)\nRoot._configure = function(Type_, parse_, common_) {\n Type = Type_;\n parse = parse_;\n common = common_;\n};\n","\"use strict\";\nmodule.exports = {};\n\n/**\n * Named roots.\n * This is where pbjs stores generated structures (the option `-r, --root` specifies a name).\n * Can also be used manually to make roots available across modules.\n * @name roots\n * @type {Object.}\n * @example\n * // pbjs -r myroot -o compiled.js ...\n *\n * // in another module:\n * require(\"./compiled.js\");\n *\n * // in any subsequent module:\n * var root = protobuf.roots[\"myroot\"];\n */\n","\"use strict\";\n\n/**\n * Streaming RPC helpers.\n * @namespace\n */\nvar rpc = exports;\n\n/**\n * RPC implementation passed to {@link Service#create} performing a service request on network level, i.e. by utilizing http requests or websockets.\n * @typedef RPCImpl\n * @type {function}\n * @param {Method|rpc.ServiceMethod,Message<{}>>} method Reflected or static method being called\n * @param {Uint8Array} requestData Request data\n * @param {RPCImplCallback} callback Callback function\n * @returns {undefined}\n * @example\n * function rpcImpl(method, requestData, callback) {\n * if (protobuf.util.lcFirst(method.name) !== \"myMethod\") // compatible with static code\n * throw Error(\"no such method\");\n * asynchronouslyObtainAResponse(requestData, function(err, responseData) {\n * callback(err, responseData);\n * });\n * }\n */\n\n/**\n * Node-style callback as used by {@link RPCImpl}.\n * @typedef RPCImplCallback\n * @type {function}\n * @param {Error|null} error Error, if any, otherwise `null`\n * @param {Uint8Array|null} [response] Response data or `null` to signal end of stream, if there hasn't been an error\n * @returns {undefined}\n */\n\nrpc.Service = require(32);\n","\"use strict\";\nmodule.exports = Service;\n\nvar util = require(39);\n\n// Extends EventEmitter\n(Service.prototype = Object.create(util.EventEmitter.prototype)).constructor = Service;\n\n/**\n * A service method callback as used by {@link rpc.ServiceMethod|ServiceMethod}.\n *\n * Differs from {@link RPCImplCallback} in that it is an actual callback of a service method which may not return `response = null`.\n * @typedef rpc.ServiceMethodCallback\n * @template TRes extends Message\n * @type {function}\n * @param {Error|null} error Error, if any\n * @param {TRes} [response] Response message\n * @returns {undefined}\n */\n\n/**\n * A service method part of a {@link rpc.Service} as created by {@link Service.create}.\n * @typedef rpc.ServiceMethod\n * @template TReq extends Message\n * @template TRes extends Message\n * @type {function}\n * @param {TReq|Properties} request Request message or plain object\n * @param {rpc.ServiceMethodCallback} [callback] Node-style callback called with the error, if any, and the response message\n * @returns {Promise>} Promise if `callback` has been omitted, otherwise `undefined`\n */\n\n/**\n * Constructs a new RPC service instance.\n * @classdesc An RPC service as returned by {@link Service#create}.\n * @exports rpc.Service\n * @extends util.EventEmitter\n * @constructor\n * @param {RPCImpl} rpcImpl RPC implementation\n * @param {boolean} [requestDelimited=false] Whether requests are length-delimited\n * @param {boolean} [responseDelimited=false] Whether responses are length-delimited\n */\nfunction Service(rpcImpl, requestDelimited, responseDelimited) {\n\n if (typeof rpcImpl !== \"function\")\n throw TypeError(\"rpcImpl must be a function\");\n\n util.EventEmitter.call(this);\n\n /**\n * RPC implementation. Becomes `null` once the service is ended.\n * @type {RPCImpl|null}\n */\n this.rpcImpl = rpcImpl;\n\n /**\n * Whether requests are length-delimited.\n * @type {boolean}\n */\n this.requestDelimited = Boolean(requestDelimited);\n\n /**\n * Whether responses are length-delimited.\n * @type {boolean}\n */\n this.responseDelimited = Boolean(responseDelimited);\n}\n\n/**\n * Calls a service method through {@link rpc.Service#rpcImpl|rpcImpl}.\n * @param {Method|rpc.ServiceMethod} method Reflected or static method\n * @param {Constructor} requestCtor Request constructor\n * @param {Constructor} responseCtor Response constructor\n * @param {TReq|Properties} request Request message or plain object\n * @param {rpc.ServiceMethodCallback} callback Service callback\n * @returns {undefined}\n * @template TReq extends Message\n * @template TRes extends Message\n */\nService.prototype.rpcCall = function rpcCall(method, requestCtor, responseCtor, request, callback) {\n\n if (!request)\n throw TypeError(\"request must be specified\");\n\n var self = this;\n if (!callback)\n return util.asPromise(rpcCall, self, method, requestCtor, responseCtor, request);\n\n if (!self.rpcImpl) {\n setTimeout(function() { callback(Error(\"already ended\")); }, 0);\n return undefined;\n }\n\n try {\n return self.rpcImpl(\n method,\n requestCtor[self.requestDelimited ? \"encodeDelimited\" : \"encode\"](request).finish(),\n function rpcCallback(err, response) {\n\n if (err) {\n self.emit(\"error\", err, method);\n return callback(err);\n }\n\n if (response === null) {\n self.end(/* endedByRPC */ true);\n return undefined;\n }\n\n if (!(response instanceof responseCtor)) {\n try {\n response = responseCtor[self.responseDelimited ? \"decodeDelimited\" : \"decode\"](response);\n } catch (err) {\n self.emit(\"error\", err, method);\n return callback(err);\n }\n }\n\n self.emit(\"data\", response, method);\n return callback(null, response);\n }\n );\n } catch (err) {\n self.emit(\"error\", err, method);\n setTimeout(function() { callback(err); }, 0);\n return undefined;\n }\n};\n\n/**\n * Ends this service and emits the `end` event.\n * @param {boolean} [endedByRPC=false] Whether the service has been ended by the RPC implementation.\n * @returns {rpc.Service} `this`\n */\nService.prototype.end = function end(endedByRPC) {\n if (this.rpcImpl) {\n if (!endedByRPC) // signal end to rpcImpl\n this.rpcImpl(null, null, null);\n this.rpcImpl = null;\n this.emit(\"end\").off();\n }\n return this;\n};\n","\"use strict\";\nmodule.exports = Service;\n\n// extends Namespace\nvar Namespace = require(23);\n((Service.prototype = Object.create(Namespace.prototype)).constructor = Service).className = \"Service\";\n\nvar Method = require(22),\n util = require(37),\n rpc = require(31);\n\n/**\n * Constructs a new service instance.\n * @classdesc Reflected service.\n * @extends NamespaceBase\n * @constructor\n * @param {string} name Service name\n * @param {Object.} [options] Service options\n * @throws {TypeError} If arguments are invalid\n */\nfunction Service(name, options) {\n Namespace.call(this, name, options);\n\n /**\n * Service methods.\n * @type {Object.}\n */\n this.methods = {}; // toJSON, marker\n\n /**\n * Cached methods as an array.\n * @type {Method[]|null}\n * @private\n */\n this._methodsArray = null;\n}\n\n/**\n * Service descriptor.\n * @interface IService\n * @extends INamespace\n * @property {Object.} methods Method descriptors\n */\n\n/**\n * Constructs a service from a service descriptor.\n * @param {string} name Service name\n * @param {IService} json Service descriptor\n * @returns {Service} Created service\n * @throws {TypeError} If arguments are invalid\n */\nService.fromJSON = function fromJSON(name, json) {\n var service = new Service(name, json.options);\n /* istanbul ignore else */\n if (json.methods)\n for (var names = Object.keys(json.methods), i = 0; i < names.length; ++i)\n service.add(Method.fromJSON(names[i], json.methods[names[i]]));\n if (json.nested)\n service.addJSON(json.nested);\n service.comment = json.comment;\n return service;\n};\n\n/**\n * Converts this service to a service descriptor.\n * @param {IToJSONOptions} [toJSONOptions] JSON conversion options\n * @returns {IService} Service descriptor\n */\nService.prototype.toJSON = function toJSON(toJSONOptions) {\n var inherited = Namespace.prototype.toJSON.call(this, toJSONOptions);\n var keepComments = toJSONOptions ? Boolean(toJSONOptions.keepComments) : false;\n return util.toObject([\n \"options\" , inherited && inherited.options || undefined,\n \"methods\" , Namespace.arrayToJSON(this.methodsArray, toJSONOptions) || /* istanbul ignore next */ {},\n \"nested\" , inherited && inherited.nested || undefined,\n \"comment\" , keepComments ? this.comment : undefined\n ]);\n};\n\n/**\n * Methods of this service as an array for iteration.\n * @name Service#methodsArray\n * @type {Method[]}\n * @readonly\n */\nObject.defineProperty(Service.prototype, \"methodsArray\", {\n get: function() {\n return this._methodsArray || (this._methodsArray = util.toArray(this.methods));\n }\n});\n\nfunction clearCache(service) {\n service._methodsArray = null;\n return service;\n}\n\n/**\n * @override\n */\nService.prototype.get = function get(name) {\n return this.methods[name]\n || Namespace.prototype.get.call(this, name);\n};\n\n/**\n * @override\n */\nService.prototype.resolveAll = function resolveAll() {\n var methods = this.methodsArray;\n for (var i = 0; i < methods.length; ++i)\n methods[i].resolve();\n return Namespace.prototype.resolve.call(this);\n};\n\n/**\n * @override\n */\nService.prototype.add = function add(object) {\n\n /* istanbul ignore if */\n if (this.get(object.name))\n throw Error(\"duplicate name '\" + object.name + \"' in \" + this);\n\n if (object instanceof Method) {\n this.methods[object.name] = object;\n object.parent = this;\n return clearCache(this);\n }\n return Namespace.prototype.add.call(this, object);\n};\n\n/**\n * @override\n */\nService.prototype.remove = function remove(object) {\n if (object instanceof Method) {\n\n /* istanbul ignore if */\n if (this.methods[object.name] !== object)\n throw Error(object + \" is not a member of \" + this);\n\n delete this.methods[object.name];\n object.parent = null;\n return clearCache(this);\n }\n return Namespace.prototype.remove.call(this, object);\n};\n\n/**\n * Creates a runtime service using the specified rpc implementation.\n * @param {RPCImpl} rpcImpl RPC implementation\n * @param {boolean} [requestDelimited=false] Whether requests are length-delimited\n * @param {boolean} [responseDelimited=false] Whether responses are length-delimited\n * @returns {rpc.Service} RPC service. Useful where requests and/or responses are streamed.\n */\nService.prototype.create = function create(rpcImpl, requestDelimited, responseDelimited) {\n var rpcService = new rpc.Service(rpcImpl, requestDelimited, responseDelimited);\n for (var i = 0, method; i < /* initializes */ this.methodsArray.length; ++i) {\n var methodName = util.lcFirst((method = this._methodsArray[i]).resolve().name).replace(/[^$\\w_]/g, \"\");\n rpcService[methodName] = util.codegen([\"r\",\"c\"], util.isReserved(methodName) ? methodName + \"_\" : methodName)(\"return this.rpcCall(m,q,s,r,c)\")({\n m: method,\n q: method.resolvedRequestType.ctor,\n s: method.resolvedResponseType.ctor\n });\n }\n return rpcService;\n};\n","\"use strict\";\nmodule.exports = tokenize;\n\nvar delimRe = /[\\s{}=;:[\\],'\"()<>]/g,\n stringDoubleRe = /(?:\"([^\"\\\\]*(?:\\\\.[^\"\\\\]*)*)\")/g,\n stringSingleRe = /(?:'([^'\\\\]*(?:\\\\.[^'\\\\]*)*)')/g;\n\nvar setCommentRe = /^ *[*/]+ */,\n setCommentAltRe = /^\\s*\\*?\\/*/,\n setCommentSplitRe = /\\n/g,\n whitespaceRe = /\\s/,\n unescapeRe = /\\\\(.?)/g;\n\nvar unescapeMap = {\n \"0\": \"\\0\",\n \"r\": \"\\r\",\n \"n\": \"\\n\",\n \"t\": \"\\t\"\n};\n\n/**\n * Unescapes a string.\n * @param {string} str String to unescape\n * @returns {string} Unescaped string\n * @property {Object.} map Special characters map\n * @memberof tokenize\n */\nfunction unescape(str) {\n return str.replace(unescapeRe, function($0, $1) {\n switch ($1) {\n case \"\\\\\":\n case \"\":\n return $1;\n default:\n return unescapeMap[$1] || \"\";\n }\n });\n}\n\ntokenize.unescape = unescape;\n\n/**\n * Gets the next token and advances.\n * @typedef TokenizerHandleNext\n * @type {function}\n * @returns {string|null} Next token or `null` on eof\n */\n\n/**\n * Peeks for the next token.\n * @typedef TokenizerHandlePeek\n * @type {function}\n * @returns {string|null} Next token or `null` on eof\n */\n\n/**\n * Pushes a token back to the stack.\n * @typedef TokenizerHandlePush\n * @type {function}\n * @param {string} token Token\n * @returns {undefined}\n */\n\n/**\n * Skips the next token.\n * @typedef TokenizerHandleSkip\n * @type {function}\n * @param {string} expected Expected token\n * @param {boolean} [optional=false] If optional\n * @returns {boolean} Whether the token matched\n * @throws {Error} If the token didn't match and is not optional\n */\n\n/**\n * Gets the comment on the previous line or, alternatively, the line comment on the specified line.\n * @typedef TokenizerHandleCmnt\n * @type {function}\n * @param {number} [line] Line number\n * @returns {string|null} Comment text or `null` if none\n */\n\n/**\n * Handle object returned from {@link tokenize}.\n * @interface ITokenizerHandle\n * @property {TokenizerHandleNext} next Gets the next token and advances (`null` on eof)\n * @property {TokenizerHandlePeek} peek Peeks for the next token (`null` on eof)\n * @property {TokenizerHandlePush} push Pushes a token back to the stack\n * @property {TokenizerHandleSkip} skip Skips a token, returns its presence and advances or, if non-optional and not present, throws\n * @property {TokenizerHandleCmnt} cmnt Gets the comment on the previous line or the line comment on the specified line, if any\n * @property {number} line Current line number\n */\n\n/**\n * Tokenizes the given .proto source and returns an object with useful utility functions.\n * @param {string} source Source contents\n * @param {boolean} alternateCommentMode Whether we should activate alternate comment parsing mode.\n * @returns {ITokenizerHandle} Tokenizer handle\n */\nfunction tokenize(source, alternateCommentMode) {\n /* eslint-disable callback-return */\n source = source.toString();\n\n var offset = 0,\n length = source.length,\n line = 1,\n lastCommentLine = 0,\n comments = {};\n\n var stack = [];\n\n var stringDelim = null;\n\n /* istanbul ignore next */\n /**\n * Creates an error for illegal syntax.\n * @param {string} subject Subject\n * @returns {Error} Error created\n * @inner\n */\n function illegal(subject) {\n return Error(\"illegal \" + subject + \" (line \" + line + \")\");\n }\n\n /**\n * Reads a string till its end.\n * @returns {string} String read\n * @inner\n */\n function readString() {\n var re = stringDelim === \"'\" ? stringSingleRe : stringDoubleRe;\n re.lastIndex = offset - 1;\n var match = re.exec(source);\n if (!match)\n throw illegal(\"string\");\n offset = re.lastIndex;\n push(stringDelim);\n stringDelim = null;\n return unescape(match[1]);\n }\n\n /**\n * Gets the character at `pos` within the source.\n * @param {number} pos Position\n * @returns {string} Character\n * @inner\n */\n function charAt(pos) {\n return source.charAt(pos);\n }\n\n /**\n * Sets the current comment text.\n * @param {number} start Start offset\n * @param {number} end End offset\n * @param {boolean} isLeading set if a leading comment\n * @returns {undefined}\n * @inner\n */\n function setComment(start, end, isLeading) {\n var comment = {\n type: source.charAt(start++),\n lineEmpty: false,\n leading: isLeading,\n };\n var lookback;\n if (alternateCommentMode) {\n lookback = 2; // alternate comment parsing: \"//\" or \"/*\"\n } else {\n lookback = 3; // \"///\" or \"/**\"\n }\n var commentOffset = start - lookback,\n c;\n do {\n if (--commentOffset < 0 ||\n (c = source.charAt(commentOffset)) === \"\\n\") {\n comment.lineEmpty = true;\n break;\n }\n } while (c === \" \" || c === \"\\t\");\n var lines = source\n .substring(start, end)\n .split(setCommentSplitRe);\n for (var i = 0; i < lines.length; ++i)\n lines[i] = lines[i]\n .replace(alternateCommentMode ? setCommentAltRe : setCommentRe, \"\")\n .trim();\n comment.text = lines\n .join(\"\\n\")\n .trim();\n\n comments[line] = comment;\n lastCommentLine = line;\n }\n\n function isDoubleSlashCommentLine(startOffset) {\n var endOffset = findEndOfLine(startOffset);\n\n // see if remaining line matches comment pattern\n var lineText = source.substring(startOffset, endOffset);\n var isComment = /^\\s*\\/\\//.test(lineText);\n return isComment;\n }\n\n function findEndOfLine(cursor) {\n // find end of cursor's line\n var endOffset = cursor;\n while (endOffset < length && charAt(endOffset) !== \"\\n\") {\n endOffset++;\n }\n return endOffset;\n }\n\n /**\n * Obtains the next token.\n * @returns {string|null} Next token or `null` on eof\n * @inner\n */\n function next() {\n if (stack.length > 0)\n return stack.shift();\n if (stringDelim)\n return readString();\n var repeat,\n prev,\n curr,\n start,\n isDoc,\n isLeadingComment = offset === 0;\n do {\n if (offset === length)\n return null;\n repeat = false;\n while (whitespaceRe.test(curr = charAt(offset))) {\n if (curr === \"\\n\") {\n isLeadingComment = true;\n ++line;\n }\n if (++offset === length)\n return null;\n }\n\n if (charAt(offset) === \"/\") {\n if (++offset === length) {\n throw illegal(\"comment\");\n }\n if (charAt(offset) === \"/\") { // Line\n if (!alternateCommentMode) {\n // check for triple-slash comment\n isDoc = charAt(start = offset + 1) === \"/\";\n\n while (charAt(++offset) !== \"\\n\") {\n if (offset === length) {\n return null;\n }\n }\n ++offset;\n if (isDoc) {\n setComment(start, offset - 1, isLeadingComment);\n // Trailing comment cannot not be multi-line,\n // so leading comment state should be reset to handle potential next comments\n isLeadingComment = true;\n }\n ++line;\n repeat = true;\n } else {\n // check for double-slash comments, consolidating consecutive lines\n start = offset;\n isDoc = false;\n if (isDoubleSlashCommentLine(offset - 1)) {\n isDoc = true;\n do {\n offset = findEndOfLine(offset);\n if (offset === length) {\n break;\n }\n offset++;\n if (!isLeadingComment) {\n // Trailing comment cannot not be multi-line\n break;\n }\n } while (isDoubleSlashCommentLine(offset));\n } else {\n offset = Math.min(length, findEndOfLine(offset) + 1);\n }\n if (isDoc) {\n setComment(start, offset, isLeadingComment);\n isLeadingComment = true;\n }\n line++;\n repeat = true;\n }\n } else if ((curr = charAt(offset)) === \"*\") { /* Block */\n // check for /** (regular comment mode) or /* (alternate comment mode)\n start = offset + 1;\n isDoc = alternateCommentMode || charAt(start) === \"*\";\n do {\n if (curr === \"\\n\") {\n ++line;\n }\n if (++offset === length) {\n throw illegal(\"comment\");\n }\n prev = curr;\n curr = charAt(offset);\n } while (prev !== \"*\" || curr !== \"/\");\n ++offset;\n if (isDoc) {\n setComment(start, offset - 2, isLeadingComment);\n isLeadingComment = true;\n }\n repeat = true;\n } else {\n return \"/\";\n }\n }\n } while (repeat);\n\n // offset !== length if we got here\n\n var end = offset;\n delimRe.lastIndex = 0;\n var delim = delimRe.test(charAt(end++));\n if (!delim)\n while (end < length && !delimRe.test(charAt(end)))\n ++end;\n var token = source.substring(offset, offset = end);\n if (token === \"\\\"\" || token === \"'\")\n stringDelim = token;\n return token;\n }\n\n /**\n * Pushes a token back to the stack.\n * @param {string} token Token\n * @returns {undefined}\n * @inner\n */\n function push(token) {\n stack.push(token);\n }\n\n /**\n * Peeks for the next token.\n * @returns {string|null} Token or `null` on eof\n * @inner\n */\n function peek() {\n if (!stack.length) {\n var token = next();\n if (token === null)\n return null;\n push(token);\n }\n return stack[0];\n }\n\n /**\n * Skips a token.\n * @param {string} expected Expected token\n * @param {boolean} [optional=false] Whether the token is optional\n * @returns {boolean} `true` when skipped, `false` if not\n * @throws {Error} When a required token is not present\n * @inner\n */\n function skip(expected, optional) {\n var actual = peek(),\n equals = actual === expected;\n if (equals) {\n next();\n return true;\n }\n if (!optional)\n throw illegal(\"token '\" + actual + \"', '\" + expected + \"' expected\");\n return false;\n }\n\n /**\n * Gets a comment.\n * @param {number} [trailingLine] Line number if looking for a trailing comment\n * @returns {string|null} Comment text\n * @inner\n */\n function cmnt(trailingLine) {\n var ret = null;\n var comment;\n if (trailingLine === undefined) {\n comment = comments[line - 1];\n delete comments[line - 1];\n if (comment && (alternateCommentMode || comment.type === \"*\" || comment.lineEmpty)) {\n ret = comment.leading ? comment.text : null;\n }\n } else {\n /* istanbul ignore else */\n if (lastCommentLine < trailingLine) {\n peek();\n }\n comment = comments[trailingLine];\n delete comments[trailingLine];\n if (comment && !comment.lineEmpty && (alternateCommentMode || comment.type === \"/\")) {\n ret = comment.leading ? null : comment.text;\n }\n }\n return ret;\n }\n\n return Object.defineProperty({\n next: next,\n peek: peek,\n push: push,\n skip: skip,\n cmnt: cmnt\n }, \"line\", {\n get: function() { return line; }\n });\n /* eslint-enable callback-return */\n}\n","\"use strict\";\nmodule.exports = Type;\n\n// extends Namespace\nvar Namespace = require(23);\n((Type.prototype = Object.create(Namespace.prototype)).constructor = Type).className = \"Type\";\n\nvar Enum = require(15),\n OneOf = require(25),\n Field = require(16),\n MapField = require(20),\n Service = require(33),\n Message = require(21),\n Reader = require(27),\n Writer = require(42),\n util = require(37),\n encoder = require(14),\n decoder = require(13),\n verifier = require(40),\n converter = require(12),\n wrappers = require(41);\n\n/**\n * Constructs a new reflected message type instance.\n * @classdesc Reflected message type.\n * @extends NamespaceBase\n * @constructor\n * @param {string} name Message name\n * @param {Object.} [options] Declared options\n */\nfunction Type(name, options) {\n Namespace.call(this, name, options);\n\n /**\n * Message fields.\n * @type {Object.}\n */\n this.fields = {}; // toJSON, marker\n\n /**\n * Oneofs declared within this namespace, if any.\n * @type {Object.}\n */\n this.oneofs = undefined; // toJSON\n\n /**\n * Extension ranges, if any.\n * @type {number[][]}\n */\n this.extensions = undefined; // toJSON\n\n /**\n * Reserved ranges, if any.\n * @type {Array.}\n */\n this.reserved = undefined; // toJSON\n\n /*?\n * Whether this type is a legacy group.\n * @type {boolean|undefined}\n */\n this.group = undefined; // toJSON\n\n /**\n * Cached fields by id.\n * @type {Object.|null}\n * @private\n */\n this._fieldsById = null;\n\n /**\n * Cached fields as an array.\n * @type {Field[]|null}\n * @private\n */\n this._fieldsArray = null;\n\n /**\n * Cached oneofs as an array.\n * @type {OneOf[]|null}\n * @private\n */\n this._oneofsArray = null;\n\n /**\n * Cached constructor.\n * @type {Constructor<{}>}\n * @private\n */\n this._ctor = null;\n}\n\nObject.defineProperties(Type.prototype, {\n\n /**\n * Message fields by id.\n * @name Type#fieldsById\n * @type {Object.}\n * @readonly\n */\n fieldsById: {\n get: function() {\n\n /* istanbul ignore if */\n if (this._fieldsById)\n return this._fieldsById;\n\n this._fieldsById = {};\n for (var names = Object.keys(this.fields), i = 0; i < names.length; ++i) {\n var field = this.fields[names[i]],\n id = field.id;\n\n /* istanbul ignore if */\n if (this._fieldsById[id])\n throw Error(\"duplicate id \" + id + \" in \" + this);\n\n this._fieldsById[id] = field;\n }\n return this._fieldsById;\n }\n },\n\n /**\n * Fields of this message as an array for iteration.\n * @name Type#fieldsArray\n * @type {Field[]}\n * @readonly\n */\n fieldsArray: {\n get: function() {\n return this._fieldsArray || (this._fieldsArray = util.toArray(this.fields));\n }\n },\n\n /**\n * Oneofs of this message as an array for iteration.\n * @name Type#oneofsArray\n * @type {OneOf[]}\n * @readonly\n */\n oneofsArray: {\n get: function() {\n return this._oneofsArray || (this._oneofsArray = util.toArray(this.oneofs));\n }\n },\n\n /**\n * The registered constructor, if any registered, otherwise a generic constructor.\n * Assigning a function replaces the internal constructor. If the function does not extend {@link Message} yet, its prototype will be setup accordingly and static methods will be populated. If it already extends {@link Message}, it will just replace the internal constructor.\n * @name Type#ctor\n * @type {Constructor<{}>}\n */\n ctor: {\n get: function() {\n return this._ctor || (this.ctor = Type.generateConstructor(this)());\n },\n set: function(ctor) {\n\n // Ensure proper prototype\n var prototype = ctor.prototype;\n if (!(prototype instanceof Message)) {\n (ctor.prototype = new Message()).constructor = ctor;\n util.merge(ctor.prototype, prototype);\n }\n\n // Classes and messages reference their reflected type\n ctor.$type = ctor.prototype.$type = this;\n\n // Mix in static methods\n util.merge(ctor, Message, true);\n\n this._ctor = ctor;\n\n // Messages have non-enumerable default values on their prototype\n var i = 0;\n for (; i < /* initializes */ this.fieldsArray.length; ++i)\n this._fieldsArray[i].resolve(); // ensures a proper value\n\n // Messages have non-enumerable getters and setters for each virtual oneof field\n var ctorProperties = {};\n for (i = 0; i < /* initializes */ this.oneofsArray.length; ++i)\n ctorProperties[this._oneofsArray[i].resolve().name] = {\n get: util.oneOfGetter(this._oneofsArray[i].oneof),\n set: util.oneOfSetter(this._oneofsArray[i].oneof)\n };\n if (i)\n Object.defineProperties(ctor.prototype, ctorProperties);\n }\n }\n});\n\n/**\n * Generates a constructor function for the specified type.\n * @param {Type} mtype Message type\n * @returns {Codegen} Codegen instance\n */\nType.generateConstructor = function generateConstructor(mtype) {\n /* eslint-disable no-unexpected-multiline */\n var gen = util.codegen([\"p\"], mtype.name);\n // explicitly initialize mutable object/array fields so that these aren't just inherited from the prototype\n for (var i = 0, field; i < mtype.fieldsArray.length; ++i)\n if ((field = mtype._fieldsArray[i]).map) gen\n (\"this%s={}\", util.safeProp(field.name));\n else if (field.repeated) gen\n (\"this%s=[]\", util.safeProp(field.name));\n return gen\n (\"if(p)for(var ks=Object.keys(p),i=0;i} [oneofs] Oneof descriptors\n * @property {Object.} fields Field descriptors\n * @property {number[][]} [extensions] Extension ranges\n * @property {number[][]} [reserved] Reserved ranges\n * @property {boolean} [group=false] Whether a legacy group or not\n */\n\n/**\n * Creates a message type from a message type descriptor.\n * @param {string} name Message name\n * @param {IType} json Message type descriptor\n * @returns {Type} Created message type\n */\nType.fromJSON = function fromJSON(name, json) {\n var type = new Type(name, json.options);\n type.extensions = json.extensions;\n type.reserved = json.reserved;\n var names = Object.keys(json.fields),\n i = 0;\n for (; i < names.length; ++i)\n type.add(\n ( typeof json.fields[names[i]].keyType !== \"undefined\"\n ? MapField.fromJSON\n : Field.fromJSON )(names[i], json.fields[names[i]])\n );\n if (json.oneofs)\n for (names = Object.keys(json.oneofs), i = 0; i < names.length; ++i)\n type.add(OneOf.fromJSON(names[i], json.oneofs[names[i]]));\n if (json.nested)\n for (names = Object.keys(json.nested), i = 0; i < names.length; ++i) {\n var nested = json.nested[names[i]];\n type.add( // most to least likely\n ( nested.id !== undefined\n ? Field.fromJSON\n : nested.fields !== undefined\n ? Type.fromJSON\n : nested.values !== undefined\n ? Enum.fromJSON\n : nested.methods !== undefined\n ? Service.fromJSON\n : Namespace.fromJSON )(names[i], nested)\n );\n }\n if (json.extensions && json.extensions.length)\n type.extensions = json.extensions;\n if (json.reserved && json.reserved.length)\n type.reserved = json.reserved;\n if (json.group)\n type.group = true;\n if (json.comment)\n type.comment = json.comment;\n return type;\n};\n\n/**\n * Converts this message type to a message type descriptor.\n * @param {IToJSONOptions} [toJSONOptions] JSON conversion options\n * @returns {IType} Message type descriptor\n */\nType.prototype.toJSON = function toJSON(toJSONOptions) {\n var inherited = Namespace.prototype.toJSON.call(this, toJSONOptions);\n var keepComments = toJSONOptions ? Boolean(toJSONOptions.keepComments) : false;\n return util.toObject([\n \"options\" , inherited && inherited.options || undefined,\n \"oneofs\" , Namespace.arrayToJSON(this.oneofsArray, toJSONOptions),\n \"fields\" , Namespace.arrayToJSON(this.fieldsArray.filter(function(obj) { return !obj.declaringField; }), toJSONOptions) || {},\n \"extensions\" , this.extensions && this.extensions.length ? this.extensions : undefined,\n \"reserved\" , this.reserved && this.reserved.length ? this.reserved : undefined,\n \"group\" , this.group || undefined,\n \"nested\" , inherited && inherited.nested || undefined,\n \"comment\" , keepComments ? this.comment : undefined\n ]);\n};\n\n/**\n * @override\n */\nType.prototype.resolveAll = function resolveAll() {\n var fields = this.fieldsArray, i = 0;\n while (i < fields.length)\n fields[i++].resolve();\n var oneofs = this.oneofsArray; i = 0;\n while (i < oneofs.length)\n oneofs[i++].resolve();\n return Namespace.prototype.resolveAll.call(this);\n};\n\n/**\n * @override\n */\nType.prototype.get = function get(name) {\n return this.fields[name]\n || this.oneofs && this.oneofs[name]\n || this.nested && this.nested[name]\n || null;\n};\n\n/**\n * Adds a nested object to this type.\n * @param {ReflectionObject} object Nested object to add\n * @returns {Type} `this`\n * @throws {TypeError} If arguments are invalid\n * @throws {Error} If there is already a nested object with this name or, if a field, when there is already a field with this id\n */\nType.prototype.add = function add(object) {\n\n if (this.get(object.name))\n throw Error(\"duplicate name '\" + object.name + \"' in \" + this);\n\n if (object instanceof Field && object.extend === undefined) {\n // NOTE: Extension fields aren't actual fields on the declaring type, but nested objects.\n // The root object takes care of adding distinct sister-fields to the respective extended\n // type instead.\n\n // avoids calling the getter if not absolutely necessary because it's called quite frequently\n if (this._fieldsById ? /* istanbul ignore next */ this._fieldsById[object.id] : this.fieldsById[object.id])\n throw Error(\"duplicate id \" + object.id + \" in \" + this);\n if (this.isReservedId(object.id))\n throw Error(\"id \" + object.id + \" is reserved in \" + this);\n if (this.isReservedName(object.name))\n throw Error(\"name '\" + object.name + \"' is reserved in \" + this);\n\n if (object.parent)\n object.parent.remove(object);\n this.fields[object.name] = object;\n object.message = this;\n object.onAdd(this);\n return clearCache(this);\n }\n if (object instanceof OneOf) {\n if (!this.oneofs)\n this.oneofs = {};\n this.oneofs[object.name] = object;\n object.onAdd(this);\n return clearCache(this);\n }\n return Namespace.prototype.add.call(this, object);\n};\n\n/**\n * Removes a nested object from this type.\n * @param {ReflectionObject} object Nested object to remove\n * @returns {Type} `this`\n * @throws {TypeError} If arguments are invalid\n * @throws {Error} If `object` is not a member of this type\n */\nType.prototype.remove = function remove(object) {\n if (object instanceof Field && object.extend === undefined) {\n // See Type#add for the reason why extension fields are excluded here.\n\n /* istanbul ignore if */\n if (!this.fields || this.fields[object.name] !== object)\n throw Error(object + \" is not a member of \" + this);\n\n delete this.fields[object.name];\n object.parent = null;\n object.onRemove(this);\n return clearCache(this);\n }\n if (object instanceof OneOf) {\n\n /* istanbul ignore if */\n if (!this.oneofs || this.oneofs[object.name] !== object)\n throw Error(object + \" is not a member of \" + this);\n\n delete this.oneofs[object.name];\n object.parent = null;\n object.onRemove(this);\n return clearCache(this);\n }\n return Namespace.prototype.remove.call(this, object);\n};\n\n/**\n * Tests if the specified id is reserved.\n * @param {number} id Id to test\n * @returns {boolean} `true` if reserved, otherwise `false`\n */\nType.prototype.isReservedId = function isReservedId(id) {\n return Namespace.isReservedId(this.reserved, id);\n};\n\n/**\n * Tests if the specified name is reserved.\n * @param {string} name Name to test\n * @returns {boolean} `true` if reserved, otherwise `false`\n */\nType.prototype.isReservedName = function isReservedName(name) {\n return Namespace.isReservedName(this.reserved, name);\n};\n\n/**\n * Creates a new message of this type using the specified properties.\n * @param {Object.} [properties] Properties to set\n * @returns {Message<{}>} Message instance\n */\nType.prototype.create = function create(properties) {\n return new this.ctor(properties);\n};\n\n/**\n * Sets up {@link Type#encode|encode}, {@link Type#decode|decode} and {@link Type#verify|verify}.\n * @returns {Type} `this`\n */\nType.prototype.setup = function setup() {\n // Sets up everything at once so that the prototype chain does not have to be re-evaluated\n // multiple times (V8, soft-deopt prototype-check).\n\n var fullName = this.fullName,\n types = [];\n for (var i = 0; i < /* initializes */ this.fieldsArray.length; ++i)\n types.push(this._fieldsArray[i].resolve().resolvedType);\n\n // Replace setup methods with type-specific generated functions\n this.encode = encoder(this)({\n Writer : Writer,\n types : types,\n util : util\n });\n this.decode = decoder(this)({\n Reader : Reader,\n types : types,\n util : util\n });\n this.verify = verifier(this)({\n types : types,\n util : util\n });\n this.fromObject = converter.fromObject(this)({\n types : types,\n util : util\n });\n this.toObject = converter.toObject(this)({\n types : types,\n util : util\n });\n\n // Inject custom wrappers for common types\n var wrapper = wrappers[fullName];\n if (wrapper) {\n var originalThis = Object.create(this);\n // if (wrapper.fromObject) {\n originalThis.fromObject = this.fromObject;\n this.fromObject = wrapper.fromObject.bind(originalThis);\n // }\n // if (wrapper.toObject) {\n originalThis.toObject = this.toObject;\n this.toObject = wrapper.toObject.bind(originalThis);\n // }\n }\n\n return this;\n};\n\n/**\n * Encodes a message of this type. Does not implicitly {@link Type#verify|verify} messages.\n * @param {Message<{}>|Object.} message Message instance or plain object\n * @param {Writer} [writer] Writer to encode to\n * @returns {Writer} writer\n */\nType.prototype.encode = function encode_setup(message, writer) {\n return this.setup().encode(message, writer); // overrides this method\n};\n\n/**\n * Encodes a message of this type preceeded by its byte length as a varint. Does not implicitly {@link Type#verify|verify} messages.\n * @param {Message<{}>|Object.} message Message instance or plain object\n * @param {Writer} [writer] Writer to encode to\n * @returns {Writer} writer\n */\nType.prototype.encodeDelimited = function encodeDelimited(message, writer) {\n return this.encode(message, writer && writer.len ? writer.fork() : writer).ldelim();\n};\n\n/**\n * Decodes a message of this type.\n * @param {Reader|Uint8Array} reader Reader or buffer to decode from\n * @param {number} [length] Length of the message, if known beforehand\n * @returns {Message<{}>} Decoded message\n * @throws {Error} If the payload is not a reader or valid buffer\n * @throws {util.ProtocolError<{}>} If required fields are missing\n */\nType.prototype.decode = function decode_setup(reader, length) {\n return this.setup().decode(reader, length); // overrides this method\n};\n\n/**\n * Decodes a message of this type preceeded by its byte length as a varint.\n * @param {Reader|Uint8Array} reader Reader or buffer to decode from\n * @returns {Message<{}>} Decoded message\n * @throws {Error} If the payload is not a reader or valid buffer\n * @throws {util.ProtocolError} If required fields are missing\n */\nType.prototype.decodeDelimited = function decodeDelimited(reader) {\n if (!(reader instanceof Reader))\n reader = Reader.create(reader);\n return this.decode(reader, reader.uint32());\n};\n\n/**\n * Verifies that field values are valid and that required fields are present.\n * @param {Object.} message Plain object to verify\n * @returns {null|string} `null` if valid, otherwise the reason why it is not\n */\nType.prototype.verify = function verify_setup(message) {\n return this.setup().verify(message); // overrides this method\n};\n\n/**\n * Creates a new message of this type from a plain object. Also converts values to their respective internal types.\n * @param {Object.} object Plain object to convert\n * @returns {Message<{}>} Message instance\n */\nType.prototype.fromObject = function fromObject(object) {\n return this.setup().fromObject(object);\n};\n\n/**\n * Conversion options as used by {@link Type#toObject} and {@link Message.toObject}.\n * @interface IConversionOptions\n * @property {Function} [longs] Long conversion type.\n * Valid values are `String` and `Number` (the global types).\n * Defaults to copy the present value, which is a possibly unsafe number without and a {@link Long} with a long library.\n * @property {Function} [enums] Enum value conversion type.\n * Only valid value is `String` (the global type).\n * Defaults to copy the present value, which is the numeric id.\n * @property {Function} [bytes] Bytes value conversion type.\n * Valid values are `Array` and (a base64 encoded) `String` (the global types).\n * Defaults to copy the present value, which usually is a Buffer under node and an Uint8Array in the browser.\n * @property {boolean} [defaults=false] Also sets default values on the resulting object\n * @property {boolean} [arrays=false] Sets empty arrays for missing repeated fields even if `defaults=false`\n * @property {boolean} [objects=false] Sets empty objects for missing map fields even if `defaults=false`\n * @property {boolean} [oneofs=false] Includes virtual oneof properties set to the present field's name, if any\n * @property {boolean} [json=false] Performs additional JSON compatibility conversions, i.e. NaN and Infinity to strings\n */\n\n/**\n * Creates a plain object from a message of this type. Also converts values to other types if specified.\n * @param {Message<{}>} message Message instance\n * @param {IConversionOptions} [options] Conversion options\n * @returns {Object.} Plain object\n */\nType.prototype.toObject = function toObject(message, options) {\n return this.setup().toObject(message, options);\n};\n\n/**\n * Decorator function as returned by {@link Type.d} (TypeScript).\n * @typedef TypeDecorator\n * @type {function}\n * @param {Constructor} target Target constructor\n * @returns {undefined}\n * @template T extends Message\n */\n\n/**\n * Type decorator (TypeScript).\n * @param {string} [typeName] Type name, defaults to the constructor's name\n * @returns {TypeDecorator} Decorator function\n * @template T extends Message\n */\nType.d = function decorateType(typeName) {\n return function typeDecorator(target) {\n util.decorateType(target, typeName);\n };\n};\n","\"use strict\";\n\n/**\n * Common type constants.\n * @namespace\n */\nvar types = exports;\n\nvar util = require(37);\n\nvar s = [\n \"double\", // 0\n \"float\", // 1\n \"int32\", // 2\n \"uint32\", // 3\n \"sint32\", // 4\n \"fixed32\", // 5\n \"sfixed32\", // 6\n \"int64\", // 7\n \"uint64\", // 8\n \"sint64\", // 9\n \"fixed64\", // 10\n \"sfixed64\", // 11\n \"bool\", // 12\n \"string\", // 13\n \"bytes\" // 14\n];\n\nfunction bake(values, offset) {\n var i = 0, o = {};\n offset |= 0;\n while (i < values.length) o[s[i + offset]] = values[i++];\n return o;\n}\n\n/**\n * Basic type wire types.\n * @type {Object.}\n * @const\n * @property {number} double=1 Fixed64 wire type\n * @property {number} float=5 Fixed32 wire type\n * @property {number} int32=0 Varint wire type\n * @property {number} uint32=0 Varint wire type\n * @property {number} sint32=0 Varint wire type\n * @property {number} fixed32=5 Fixed32 wire type\n * @property {number} sfixed32=5 Fixed32 wire type\n * @property {number} int64=0 Varint wire type\n * @property {number} uint64=0 Varint wire type\n * @property {number} sint64=0 Varint wire type\n * @property {number} fixed64=1 Fixed64 wire type\n * @property {number} sfixed64=1 Fixed64 wire type\n * @property {number} bool=0 Varint wire type\n * @property {number} string=2 Ldelim wire type\n * @property {number} bytes=2 Ldelim wire type\n */\ntypes.basic = bake([\n /* double */ 1,\n /* float */ 5,\n /* int32 */ 0,\n /* uint32 */ 0,\n /* sint32 */ 0,\n /* fixed32 */ 5,\n /* sfixed32 */ 5,\n /* int64 */ 0,\n /* uint64 */ 0,\n /* sint64 */ 0,\n /* fixed64 */ 1,\n /* sfixed64 */ 1,\n /* bool */ 0,\n /* string */ 2,\n /* bytes */ 2\n]);\n\n/**\n * Basic type defaults.\n * @type {Object.}\n * @const\n * @property {number} double=0 Double default\n * @property {number} float=0 Float default\n * @property {number} int32=0 Int32 default\n * @property {number} uint32=0 Uint32 default\n * @property {number} sint32=0 Sint32 default\n * @property {number} fixed32=0 Fixed32 default\n * @property {number} sfixed32=0 Sfixed32 default\n * @property {number} int64=0 Int64 default\n * @property {number} uint64=0 Uint64 default\n * @property {number} sint64=0 Sint32 default\n * @property {number} fixed64=0 Fixed64 default\n * @property {number} sfixed64=0 Sfixed64 default\n * @property {boolean} bool=false Bool default\n * @property {string} string=\"\" String default\n * @property {Array.} bytes=Array(0) Bytes default\n * @property {null} message=null Message default\n */\ntypes.defaults = bake([\n /* double */ 0,\n /* float */ 0,\n /* int32 */ 0,\n /* uint32 */ 0,\n /* sint32 */ 0,\n /* fixed32 */ 0,\n /* sfixed32 */ 0,\n /* int64 */ 0,\n /* uint64 */ 0,\n /* sint64 */ 0,\n /* fixed64 */ 0,\n /* sfixed64 */ 0,\n /* bool */ false,\n /* string */ \"\",\n /* bytes */ util.emptyArray,\n /* message */ null\n]);\n\n/**\n * Basic long type wire types.\n * @type {Object.}\n * @const\n * @property {number} int64=0 Varint wire type\n * @property {number} uint64=0 Varint wire type\n * @property {number} sint64=0 Varint wire type\n * @property {number} fixed64=1 Fixed64 wire type\n * @property {number} sfixed64=1 Fixed64 wire type\n */\ntypes.long = bake([\n /* int64 */ 0,\n /* uint64 */ 0,\n /* sint64 */ 0,\n /* fixed64 */ 1,\n /* sfixed64 */ 1\n], 7);\n\n/**\n * Allowed types for map keys with their associated wire type.\n * @type {Object.}\n * @const\n * @property {number} int32=0 Varint wire type\n * @property {number} uint32=0 Varint wire type\n * @property {number} sint32=0 Varint wire type\n * @property {number} fixed32=5 Fixed32 wire type\n * @property {number} sfixed32=5 Fixed32 wire type\n * @property {number} int64=0 Varint wire type\n * @property {number} uint64=0 Varint wire type\n * @property {number} sint64=0 Varint wire type\n * @property {number} fixed64=1 Fixed64 wire type\n * @property {number} sfixed64=1 Fixed64 wire type\n * @property {number} bool=0 Varint wire type\n * @property {number} string=2 Ldelim wire type\n */\ntypes.mapKey = bake([\n /* int32 */ 0,\n /* uint32 */ 0,\n /* sint32 */ 0,\n /* fixed32 */ 5,\n /* sfixed32 */ 5,\n /* int64 */ 0,\n /* uint64 */ 0,\n /* sint64 */ 0,\n /* fixed64 */ 1,\n /* sfixed64 */ 1,\n /* bool */ 0,\n /* string */ 2\n], 2);\n\n/**\n * Allowed types for packed repeated fields with their associated wire type.\n * @type {Object.}\n * @const\n * @property {number} double=1 Fixed64 wire type\n * @property {number} float=5 Fixed32 wire type\n * @property {number} int32=0 Varint wire type\n * @property {number} uint32=0 Varint wire type\n * @property {number} sint32=0 Varint wire type\n * @property {number} fixed32=5 Fixed32 wire type\n * @property {number} sfixed32=5 Fixed32 wire type\n * @property {number} int64=0 Varint wire type\n * @property {number} uint64=0 Varint wire type\n * @property {number} sint64=0 Varint wire type\n * @property {number} fixed64=1 Fixed64 wire type\n * @property {number} sfixed64=1 Fixed64 wire type\n * @property {number} bool=0 Varint wire type\n */\ntypes.packed = bake([\n /* double */ 1,\n /* float */ 5,\n /* int32 */ 0,\n /* uint32 */ 0,\n /* sint32 */ 0,\n /* fixed32 */ 5,\n /* sfixed32 */ 5,\n /* int64 */ 0,\n /* uint64 */ 0,\n /* sint64 */ 0,\n /* fixed64 */ 1,\n /* sfixed64 */ 1,\n /* bool */ 0\n]);\n","\"use strict\";\n\n/**\n * Various utility functions.\n * @namespace\n */\nvar util = module.exports = require(39);\n\nvar roots = require(30);\n\nvar Type, // cyclic\n Enum;\n\nutil.codegen = require(3);\nutil.fetch = require(5);\nutil.path = require(8);\n\n/**\n * Node's fs module if available.\n * @type {Object.}\n */\nutil.fs = util.inquire(\"fs\");\n\n/**\n * Converts an object's values to an array.\n * @param {Object.} object Object to convert\n * @returns {Array.<*>} Converted array\n */\nutil.toArray = function toArray(object) {\n if (object) {\n var keys = Object.keys(object),\n array = new Array(keys.length),\n index = 0;\n while (index < keys.length)\n array[index] = object[keys[index++]];\n return array;\n }\n return [];\n};\n\n/**\n * Converts an array of keys immediately followed by their respective value to an object, omitting undefined values.\n * @param {Array.<*>} array Array to convert\n * @returns {Object.} Converted object\n */\nutil.toObject = function toObject(array) {\n var object = {},\n index = 0;\n while (index < array.length) {\n var key = array[index++],\n val = array[index++];\n if (val !== undefined)\n object[key] = val;\n }\n return object;\n};\n\nvar safePropBackslashRe = /\\\\/g,\n safePropQuoteRe = /\"/g;\n\n/**\n * Tests whether the specified name is a reserved word in JS.\n * @param {string} name Name to test\n * @returns {boolean} `true` if reserved, otherwise `false`\n */\nutil.isReserved = function isReserved(name) {\n return /^(?:do|if|in|for|let|new|try|var|case|else|enum|eval|false|null|this|true|void|with|break|catch|class|const|super|throw|while|yield|delete|export|import|public|return|static|switch|typeof|default|extends|finally|package|private|continue|debugger|function|arguments|interface|protected|implements|instanceof)$/.test(name);\n};\n\n/**\n * Returns a safe property accessor for the specified property name.\n * @param {string} prop Property name\n * @returns {string} Safe accessor\n */\nutil.safeProp = function safeProp(prop) {\n if (!/^[$\\w_]+$/.test(prop) || util.isReserved(prop))\n return \"[\\\"\" + prop.replace(safePropBackslashRe, \"\\\\\\\\\").replace(safePropQuoteRe, \"\\\\\\\"\") + \"\\\"]\";\n return \".\" + prop;\n};\n\n/**\n * Converts the first character of a string to upper case.\n * @param {string} str String to convert\n * @returns {string} Converted string\n */\nutil.ucFirst = function ucFirst(str) {\n return str.charAt(0).toUpperCase() + str.substring(1);\n};\n\nvar camelCaseRe = /_([a-z])/g;\n\n/**\n * Converts a string to camel case.\n * @param {string} str String to convert\n * @returns {string} Converted string\n */\nutil.camelCase = function camelCase(str) {\n return str.substring(0, 1)\n + str.substring(1)\n .replace(camelCaseRe, function($0, $1) { return $1.toUpperCase(); });\n};\n\n/**\n * Compares reflected fields by id.\n * @param {Field} a First field\n * @param {Field} b Second field\n * @returns {number} Comparison value\n */\nutil.compareFieldsById = function compareFieldsById(a, b) {\n return a.id - b.id;\n};\n\n/**\n * Decorator helper for types (TypeScript).\n * @param {Constructor} ctor Constructor function\n * @param {string} [typeName] Type name, defaults to the constructor's name\n * @returns {Type} Reflected type\n * @template T extends Message\n * @property {Root} root Decorators root\n */\nutil.decorateType = function decorateType(ctor, typeName) {\n\n /* istanbul ignore if */\n if (ctor.$type) {\n if (typeName && ctor.$type.name !== typeName) {\n util.decorateRoot.remove(ctor.$type);\n ctor.$type.name = typeName;\n util.decorateRoot.add(ctor.$type);\n }\n return ctor.$type;\n }\n\n /* istanbul ignore next */\n if (!Type)\n Type = require(35);\n\n var type = new Type(typeName || ctor.name);\n util.decorateRoot.add(type);\n type.ctor = ctor; // sets up .encode, .decode etc.\n Object.defineProperty(ctor, \"$type\", { value: type, enumerable: false });\n Object.defineProperty(ctor.prototype, \"$type\", { value: type, enumerable: false });\n return type;\n};\n\nvar decorateEnumIndex = 0;\n\n/**\n * Decorator helper for enums (TypeScript).\n * @param {Object} object Enum object\n * @returns {Enum} Reflected enum\n */\nutil.decorateEnum = function decorateEnum(object) {\n\n /* istanbul ignore if */\n if (object.$type)\n return object.$type;\n\n /* istanbul ignore next */\n if (!Enum)\n Enum = require(15);\n\n var enm = new Enum(\"Enum\" + decorateEnumIndex++, object);\n util.decorateRoot.add(enm);\n Object.defineProperty(object, \"$type\", { value: enm, enumerable: false });\n return enm;\n};\n\n\n/**\n * Sets the value of a property by property path. If a value already exists, it is turned to an array\n * @param {Object.} dst Destination object\n * @param {string} path dot '.' delimited path of the property to set\n * @param {Object} value the value to set\n * @returns {Object.} Destination object\n */\nutil.setProperty = function setProperty(dst, path, value) {\n function setProp(dst, path, value) {\n var part = path.shift();\n if (part === \"__proto__\" || part === \"prototype\") {\n return dst;\n }\n if (path.length > 0) {\n dst[part] = setProp(dst[part] || {}, path, value);\n } else {\n var prevValue = dst[part];\n if (prevValue)\n value = [].concat(prevValue).concat(value);\n dst[part] = value;\n }\n return dst;\n }\n\n if (typeof dst !== \"object\")\n throw TypeError(\"dst must be an object\");\n if (!path)\n throw TypeError(\"path must be specified\");\n\n path = path.split(\".\");\n return setProp(dst, path, value);\n};\n\n/**\n * Decorator root (TypeScript).\n * @name util.decorateRoot\n * @type {Root}\n * @readonly\n */\nObject.defineProperty(util, \"decorateRoot\", {\n get: function() {\n return roots[\"decorated\"] || (roots[\"decorated\"] = new (require(29))());\n }\n});\n","\"use strict\";\nmodule.exports = LongBits;\n\nvar util = require(39);\n\n/**\n * Constructs new long bits.\n * @classdesc Helper class for working with the low and high bits of a 64 bit value.\n * @memberof util\n * @constructor\n * @param {number} lo Low 32 bits, unsigned\n * @param {number} hi High 32 bits, unsigned\n */\nfunction LongBits(lo, hi) {\n\n // note that the casts below are theoretically unnecessary as of today, but older statically\n // generated converter code might still call the ctor with signed 32bits. kept for compat.\n\n /**\n * Low bits.\n * @type {number}\n */\n this.lo = lo >>> 0;\n\n /**\n * High bits.\n * @type {number}\n */\n this.hi = hi >>> 0;\n}\n\n/**\n * Zero bits.\n * @memberof util.LongBits\n * @type {util.LongBits}\n */\nvar zero = LongBits.zero = new LongBits(0, 0);\n\nzero.toNumber = function() { return 0; };\nzero.zzEncode = zero.zzDecode = function() { return this; };\nzero.length = function() { return 1; };\n\n/**\n * Zero hash.\n * @memberof util.LongBits\n * @type {string}\n */\nvar zeroHash = LongBits.zeroHash = \"\\0\\0\\0\\0\\0\\0\\0\\0\";\n\n/**\n * Constructs new long bits from the specified number.\n * @param {number} value Value\n * @returns {util.LongBits} Instance\n */\nLongBits.fromNumber = function fromNumber(value) {\n if (value === 0)\n return zero;\n var sign = value < 0;\n if (sign)\n value = -value;\n var lo = value >>> 0,\n hi = (value - lo) / 4294967296 >>> 0;\n if (sign) {\n hi = ~hi >>> 0;\n lo = ~lo >>> 0;\n if (++lo > 4294967295) {\n lo = 0;\n if (++hi > 4294967295)\n hi = 0;\n }\n }\n return new LongBits(lo, hi);\n};\n\n/**\n * Constructs new long bits from a number, long or string.\n * @param {Long|number|string} value Value\n * @returns {util.LongBits} Instance\n */\nLongBits.from = function from(value) {\n if (typeof value === \"number\")\n return LongBits.fromNumber(value);\n if (util.isString(value)) {\n /* istanbul ignore else */\n if (util.Long)\n value = util.Long.fromString(value);\n else\n return LongBits.fromNumber(parseInt(value, 10));\n }\n return value.low || value.high ? new LongBits(value.low >>> 0, value.high >>> 0) : zero;\n};\n\n/**\n * Converts this long bits to a possibly unsafe JavaScript number.\n * @param {boolean} [unsigned=false] Whether unsigned or not\n * @returns {number} Possibly unsafe number\n */\nLongBits.prototype.toNumber = function toNumber(unsigned) {\n if (!unsigned && this.hi >>> 31) {\n var lo = ~this.lo + 1 >>> 0,\n hi = ~this.hi >>> 0;\n if (!lo)\n hi = hi + 1 >>> 0;\n return -(lo + hi * 4294967296);\n }\n return this.lo + this.hi * 4294967296;\n};\n\n/**\n * Converts this long bits to a long.\n * @param {boolean} [unsigned=false] Whether unsigned or not\n * @returns {Long} Long\n */\nLongBits.prototype.toLong = function toLong(unsigned) {\n return util.Long\n ? new util.Long(this.lo | 0, this.hi | 0, Boolean(unsigned))\n /* istanbul ignore next */\n : { low: this.lo | 0, high: this.hi | 0, unsigned: Boolean(unsigned) };\n};\n\nvar charCodeAt = String.prototype.charCodeAt;\n\n/**\n * Constructs new long bits from the specified 8 characters long hash.\n * @param {string} hash Hash\n * @returns {util.LongBits} Bits\n */\nLongBits.fromHash = function fromHash(hash) {\n if (hash === zeroHash)\n return zero;\n return new LongBits(\n ( charCodeAt.call(hash, 0)\n | charCodeAt.call(hash, 1) << 8\n | charCodeAt.call(hash, 2) << 16\n | charCodeAt.call(hash, 3) << 24) >>> 0\n ,\n ( charCodeAt.call(hash, 4)\n | charCodeAt.call(hash, 5) << 8\n | charCodeAt.call(hash, 6) << 16\n | charCodeAt.call(hash, 7) << 24) >>> 0\n );\n};\n\n/**\n * Converts this long bits to a 8 characters long hash.\n * @returns {string} Hash\n */\nLongBits.prototype.toHash = function toHash() {\n return String.fromCharCode(\n this.lo & 255,\n this.lo >>> 8 & 255,\n this.lo >>> 16 & 255,\n this.lo >>> 24 ,\n this.hi & 255,\n this.hi >>> 8 & 255,\n this.hi >>> 16 & 255,\n this.hi >>> 24\n );\n};\n\n/**\n * Zig-zag encodes this long bits.\n * @returns {util.LongBits} `this`\n */\nLongBits.prototype.zzEncode = function zzEncode() {\n var mask = this.hi >> 31;\n this.hi = ((this.hi << 1 | this.lo >>> 31) ^ mask) >>> 0;\n this.lo = ( this.lo << 1 ^ mask) >>> 0;\n return this;\n};\n\n/**\n * Zig-zag decodes this long bits.\n * @returns {util.LongBits} `this`\n */\nLongBits.prototype.zzDecode = function zzDecode() {\n var mask = -(this.lo & 1);\n this.lo = ((this.lo >>> 1 | this.hi << 31) ^ mask) >>> 0;\n this.hi = ( this.hi >>> 1 ^ mask) >>> 0;\n return this;\n};\n\n/**\n * Calculates the length of this longbits when encoded as a varint.\n * @returns {number} Length\n */\nLongBits.prototype.length = function length() {\n var part0 = this.lo,\n part1 = (this.lo >>> 28 | this.hi << 4) >>> 0,\n part2 = this.hi >>> 24;\n return part2 === 0\n ? part1 === 0\n ? part0 < 16384\n ? part0 < 128 ? 1 : 2\n : part0 < 2097152 ? 3 : 4\n : part1 < 16384\n ? part1 < 128 ? 5 : 6\n : part1 < 2097152 ? 7 : 8\n : part2 < 128 ? 9 : 10;\n};\n","\"use strict\";\nvar util = exports;\n\n// used to return a Promise where callback is omitted\nutil.asPromise = require(1);\n\n// converts to / from base64 encoded strings\nutil.base64 = require(2);\n\n// base class of rpc.Service\nutil.EventEmitter = require(4);\n\n// float handling accross browsers\nutil.float = require(6);\n\n// requires modules optionally and hides the call from bundlers\nutil.inquire = require(7);\n\n// converts to / from utf8 encoded strings\nutil.utf8 = require(10);\n\n// provides a node-like buffer pool in the browser\nutil.pool = require(9);\n\n// utility to work with the low and high bits of a 64 bit value\nutil.LongBits = require(38);\n\n/**\n * Whether running within node or not.\n * @memberof util\n * @type {boolean}\n */\nutil.isNode = Boolean(typeof global !== \"undefined\"\n && global\n && global.process\n && global.process.versions\n && global.process.versions.node);\n\n/**\n * Global object reference.\n * @memberof util\n * @type {Object}\n */\nutil.global = util.isNode && global\n || typeof window !== \"undefined\" && window\n || typeof self !== \"undefined\" && self\n || this; // eslint-disable-line no-invalid-this\n\n/**\n * An immuable empty array.\n * @memberof util\n * @type {Array.<*>}\n * @const\n */\nutil.emptyArray = Object.freeze ? Object.freeze([]) : /* istanbul ignore next */ []; // used on prototypes\n\n/**\n * An immutable empty object.\n * @type {Object}\n * @const\n */\nutil.emptyObject = Object.freeze ? Object.freeze({}) : /* istanbul ignore next */ {}; // used on prototypes\n\n/**\n * Tests if the specified value is an integer.\n * @function\n * @param {*} value Value to test\n * @returns {boolean} `true` if the value is an integer\n */\nutil.isInteger = Number.isInteger || /* istanbul ignore next */ function isInteger(value) {\n return typeof value === \"number\" && isFinite(value) && Math.floor(value) === value;\n};\n\n/**\n * Tests if the specified value is a string.\n * @param {*} value Value to test\n * @returns {boolean} `true` if the value is a string\n */\nutil.isString = function isString(value) {\n return typeof value === \"string\" || value instanceof String;\n};\n\n/**\n * Tests if the specified value is a non-null object.\n * @param {*} value Value to test\n * @returns {boolean} `true` if the value is a non-null object\n */\nutil.isObject = function isObject(value) {\n return value && typeof value === \"object\";\n};\n\n/**\n * Checks if a property on a message is considered to be present.\n * This is an alias of {@link util.isSet}.\n * @function\n * @param {Object} obj Plain object or message instance\n * @param {string} prop Property name\n * @returns {boolean} `true` if considered to be present, otherwise `false`\n */\nutil.isset =\n\n/**\n * Checks if a property on a message is considered to be present.\n * @param {Object} obj Plain object or message instance\n * @param {string} prop Property name\n * @returns {boolean} `true` if considered to be present, otherwise `false`\n */\nutil.isSet = function isSet(obj, prop) {\n var value = obj[prop];\n if (value != null && obj.hasOwnProperty(prop)) // eslint-disable-line eqeqeq, no-prototype-builtins\n return typeof value !== \"object\" || (Array.isArray(value) ? value.length : Object.keys(value).length) > 0;\n return false;\n};\n\n/**\n * Any compatible Buffer instance.\n * This is a minimal stand-alone definition of a Buffer instance. The actual type is that exported by node's typings.\n * @interface Buffer\n * @extends Uint8Array\n */\n\n/**\n * Node's Buffer class if available.\n * @type {Constructor}\n */\nutil.Buffer = (function() {\n try {\n var Buffer = util.inquire(\"buffer\").Buffer;\n // refuse to use non-node buffers if not explicitly assigned (perf reasons):\n return Buffer.prototype.utf8Write ? Buffer : /* istanbul ignore next */ null;\n } catch (e) {\n /* istanbul ignore next */\n return null;\n }\n})();\n\n// Internal alias of or polyfull for Buffer.from.\nutil._Buffer_from = null;\n\n// Internal alias of or polyfill for Buffer.allocUnsafe.\nutil._Buffer_allocUnsafe = null;\n\n/**\n * Creates a new buffer of whatever type supported by the environment.\n * @param {number|number[]} [sizeOrArray=0] Buffer size or number array\n * @returns {Uint8Array|Buffer} Buffer\n */\nutil.newBuffer = function newBuffer(sizeOrArray) {\n /* istanbul ignore next */\n return typeof sizeOrArray === \"number\"\n ? util.Buffer\n ? util._Buffer_allocUnsafe(sizeOrArray)\n : new util.Array(sizeOrArray)\n : util.Buffer\n ? util._Buffer_from(sizeOrArray)\n : typeof Uint8Array === \"undefined\"\n ? sizeOrArray\n : new Uint8Array(sizeOrArray);\n};\n\n/**\n * Array implementation used in the browser. `Uint8Array` if supported, otherwise `Array`.\n * @type {Constructor}\n */\nutil.Array = typeof Uint8Array !== \"undefined\" ? Uint8Array /* istanbul ignore next */ : Array;\n\n/**\n * Any compatible Long instance.\n * This is a minimal stand-alone definition of a Long instance. The actual type is that exported by long.js.\n * @interface Long\n * @property {number} low Low bits\n * @property {number} high High bits\n * @property {boolean} unsigned Whether unsigned or not\n */\n\n/**\n * Long.js's Long class if available.\n * @type {Constructor}\n */\nutil.Long = /* istanbul ignore next */ util.global.dcodeIO && /* istanbul ignore next */ util.global.dcodeIO.Long\n || /* istanbul ignore next */ util.global.Long\n || util.inquire(\"long\");\n\n/**\n * Regular expression used to verify 2 bit (`bool`) map keys.\n * @type {RegExp}\n * @const\n */\nutil.key2Re = /^true|false|0|1$/;\n\n/**\n * Regular expression used to verify 32 bit (`int32` etc.) map keys.\n * @type {RegExp}\n * @const\n */\nutil.key32Re = /^-?(?:0|[1-9][0-9]*)$/;\n\n/**\n * Regular expression used to verify 64 bit (`int64` etc.) map keys.\n * @type {RegExp}\n * @const\n */\nutil.key64Re = /^(?:[\\\\x00-\\\\xff]{8}|-?(?:0|[1-9][0-9]*))$/;\n\n/**\n * Converts a number or long to an 8 characters long hash string.\n * @param {Long|number} value Value to convert\n * @returns {string} Hash\n */\nutil.longToHash = function longToHash(value) {\n return value\n ? util.LongBits.from(value).toHash()\n : util.LongBits.zeroHash;\n};\n\n/**\n * Converts an 8 characters long hash string to a long or number.\n * @param {string} hash Hash\n * @param {boolean} [unsigned=false] Whether unsigned or not\n * @returns {Long|number} Original value\n */\nutil.longFromHash = function longFromHash(hash, unsigned) {\n var bits = util.LongBits.fromHash(hash);\n if (util.Long)\n return util.Long.fromBits(bits.lo, bits.hi, unsigned);\n return bits.toNumber(Boolean(unsigned));\n};\n\n/**\n * Merges the properties of the source object into the destination object.\n * @memberof util\n * @param {Object.} dst Destination object\n * @param {Object.} src Source object\n * @param {boolean} [ifNotSet=false] Merges only if the key is not already set\n * @returns {Object.} Destination object\n */\nfunction merge(dst, src, ifNotSet) { // used by converters\n for (var keys = Object.keys(src), i = 0; i < keys.length; ++i)\n if (dst[keys[i]] === undefined || !ifNotSet)\n dst[keys[i]] = src[keys[i]];\n return dst;\n}\n\nutil.merge = merge;\n\n/**\n * Converts the first character of a string to lower case.\n * @param {string} str String to convert\n * @returns {string} Converted string\n */\nutil.lcFirst = function lcFirst(str) {\n return str.charAt(0).toLowerCase() + str.substring(1);\n};\n\n/**\n * Creates a custom error constructor.\n * @memberof util\n * @param {string} name Error name\n * @returns {Constructor} Custom error constructor\n */\nfunction newError(name) {\n\n function CustomError(message, properties) {\n\n if (!(this instanceof CustomError))\n return new CustomError(message, properties);\n\n // Error.call(this, message);\n // ^ just returns a new error instance because the ctor can be called as a function\n\n Object.defineProperty(this, \"message\", { get: function() { return message; } });\n\n /* istanbul ignore next */\n if (Error.captureStackTrace) // node\n Error.captureStackTrace(this, CustomError);\n else\n Object.defineProperty(this, \"stack\", { value: new Error().stack || \"\" });\n\n if (properties)\n merge(this, properties);\n }\n\n CustomError.prototype = Object.create(Error.prototype, {\n constructor: {\n value: CustomError,\n writable: true,\n enumerable: false,\n configurable: true,\n },\n name: {\n get: function get() { return name; },\n set: undefined,\n enumerable: false,\n // configurable: false would accurately preserve the behavior of\n // the original, but I'm guessing that was not intentional.\n // For an actual error subclass, this property would\n // be configurable.\n configurable: true,\n },\n toString: {\n value: function value() { return this.name + \": \" + this.message; },\n writable: true,\n enumerable: false,\n configurable: true,\n },\n });\n\n return CustomError;\n}\n\nutil.newError = newError;\n\n/**\n * Constructs a new protocol error.\n * @classdesc Error subclass indicating a protocol specifc error.\n * @memberof util\n * @extends Error\n * @template T extends Message\n * @constructor\n * @param {string} message Error message\n * @param {Object.} [properties] Additional properties\n * @example\n * try {\n * MyMessage.decode(someBuffer); // throws if required fields are missing\n * } catch (e) {\n * if (e instanceof ProtocolError && e.instance)\n * console.log(\"decoded so far: \" + JSON.stringify(e.instance));\n * }\n */\nutil.ProtocolError = newError(\"ProtocolError\");\n\n/**\n * So far decoded message instance.\n * @name util.ProtocolError#instance\n * @type {Message}\n */\n\n/**\n * A OneOf getter as returned by {@link util.oneOfGetter}.\n * @typedef OneOfGetter\n * @type {function}\n * @returns {string|undefined} Set field name, if any\n */\n\n/**\n * Builds a getter for a oneof's present field name.\n * @param {string[]} fieldNames Field names\n * @returns {OneOfGetter} Unbound getter\n */\nutil.oneOfGetter = function getOneOf(fieldNames) {\n var fieldMap = {};\n for (var i = 0; i < fieldNames.length; ++i)\n fieldMap[fieldNames[i]] = 1;\n\n /**\n * @returns {string|undefined} Set field name, if any\n * @this Object\n * @ignore\n */\n return function() { // eslint-disable-line consistent-return\n for (var keys = Object.keys(this), i = keys.length - 1; i > -1; --i)\n if (fieldMap[keys[i]] === 1 && this[keys[i]] !== undefined && this[keys[i]] !== null)\n return keys[i];\n };\n};\n\n/**\n * A OneOf setter as returned by {@link util.oneOfSetter}.\n * @typedef OneOfSetter\n * @type {function}\n * @param {string|undefined} value Field name\n * @returns {undefined}\n */\n\n/**\n * Builds a setter for a oneof's present field name.\n * @param {string[]} fieldNames Field names\n * @returns {OneOfSetter} Unbound setter\n */\nutil.oneOfSetter = function setOneOf(fieldNames) {\n\n /**\n * @param {string} name Field name\n * @returns {undefined}\n * @this Object\n * @ignore\n */\n return function(name) {\n for (var i = 0; i < fieldNames.length; ++i)\n if (fieldNames[i] !== name)\n delete this[fieldNames[i]];\n };\n};\n\n/**\n * Default conversion options used for {@link Message#toJSON} implementations.\n *\n * These options are close to proto3's JSON mapping with the exception that internal types like Any are handled just like messages. More precisely:\n *\n * - Longs become strings\n * - Enums become string keys\n * - Bytes become base64 encoded strings\n * - (Sub-)Messages become plain objects\n * - Maps become plain objects with all string keys\n * - Repeated fields become arrays\n * - NaN and Infinity for float and double fields become strings\n *\n * @type {IConversionOptions}\n * @see https://developers.google.com/protocol-buffers/docs/proto3?hl=en#json\n */\nutil.toJSONOptions = {\n longs: String,\n enums: String,\n bytes: String,\n json: true\n};\n\n// Sets up buffer utility according to the environment (called in index-minimal)\nutil._configure = function() {\n var Buffer = util.Buffer;\n /* istanbul ignore if */\n if (!Buffer) {\n util._Buffer_from = util._Buffer_allocUnsafe = null;\n return;\n }\n // because node 4.x buffers are incompatible & immutable\n // see: https://github.com/dcodeIO/protobuf.js/pull/665\n util._Buffer_from = Buffer.from !== Uint8Array.from && Buffer.from ||\n /* istanbul ignore next */\n function Buffer_from(value, encoding) {\n return new Buffer(value, encoding);\n };\n util._Buffer_allocUnsafe = Buffer.allocUnsafe ||\n /* istanbul ignore next */\n function Buffer_allocUnsafe(size) {\n return new Buffer(size);\n };\n};\n","\"use strict\";\nmodule.exports = verifier;\n\nvar Enum = require(15),\n util = require(37);\n\nfunction invalid(field, expected) {\n return field.name + \": \" + expected + (field.repeated && expected !== \"array\" ? \"[]\" : field.map && expected !== \"object\" ? \"{k:\"+field.keyType+\"}\" : \"\") + \" expected\";\n}\n\n/**\n * Generates a partial value verifier.\n * @param {Codegen} gen Codegen instance\n * @param {Field} field Reflected field\n * @param {number} fieldIndex Field index\n * @param {string} ref Variable reference\n * @returns {Codegen} Codegen instance\n * @ignore\n */\nfunction genVerifyValue(gen, field, fieldIndex, ref) {\n /* eslint-disable no-unexpected-multiline */\n if (field.resolvedType) {\n if (field.resolvedType instanceof Enum) { gen\n (\"switch(%s){\", ref)\n (\"default:\")\n (\"return%j\", invalid(field, \"enum value\"));\n for (var keys = Object.keys(field.resolvedType.values), j = 0; j < keys.length; ++j) gen\n (\"case %i:\", field.resolvedType.values[keys[j]]);\n gen\n (\"break\")\n (\"}\");\n } else {\n gen\n (\"{\")\n (\"var e=types[%i].verify(%s);\", fieldIndex, ref)\n (\"if(e)\")\n (\"return%j+e\", field.name + \".\")\n (\"}\");\n }\n } else {\n switch (field.type) {\n case \"int32\":\n case \"uint32\":\n case \"sint32\":\n case \"fixed32\":\n case \"sfixed32\": gen\n (\"if(!util.isInteger(%s))\", ref)\n (\"return%j\", invalid(field, \"integer\"));\n break;\n case \"int64\":\n case \"uint64\":\n case \"sint64\":\n case \"fixed64\":\n case \"sfixed64\": gen\n (\"if(!util.isInteger(%s)&&!(%s&&util.isInteger(%s.low)&&util.isInteger(%s.high)))\", ref, ref, ref, ref)\n (\"return%j\", invalid(field, \"integer|Long\"));\n break;\n case \"float\":\n case \"double\": gen\n (\"if(typeof %s!==\\\"number\\\")\", ref)\n (\"return%j\", invalid(field, \"number\"));\n break;\n case \"bool\": gen\n (\"if(typeof %s!==\\\"boolean\\\")\", ref)\n (\"return%j\", invalid(field, \"boolean\"));\n break;\n case \"string\": gen\n (\"if(!util.isString(%s))\", ref)\n (\"return%j\", invalid(field, \"string\"));\n break;\n case \"bytes\": gen\n (\"if(!(%s&&typeof %s.length===\\\"number\\\"||util.isString(%s)))\", ref, ref, ref)\n (\"return%j\", invalid(field, \"buffer\"));\n break;\n }\n }\n return gen;\n /* eslint-enable no-unexpected-multiline */\n}\n\n/**\n * Generates a partial key verifier.\n * @param {Codegen} gen Codegen instance\n * @param {Field} field Reflected field\n * @param {string} ref Variable reference\n * @returns {Codegen} Codegen instance\n * @ignore\n */\nfunction genVerifyKey(gen, field, ref) {\n /* eslint-disable no-unexpected-multiline */\n switch (field.keyType) {\n case \"int32\":\n case \"uint32\":\n case \"sint32\":\n case \"fixed32\":\n case \"sfixed32\": gen\n (\"if(!util.key32Re.test(%s))\", ref)\n (\"return%j\", invalid(field, \"integer key\"));\n break;\n case \"int64\":\n case \"uint64\":\n case \"sint64\":\n case \"fixed64\":\n case \"sfixed64\": gen\n (\"if(!util.key64Re.test(%s))\", ref) // see comment above: x is ok, d is not\n (\"return%j\", invalid(field, \"integer|Long key\"));\n break;\n case \"bool\": gen\n (\"if(!util.key2Re.test(%s))\", ref)\n (\"return%j\", invalid(field, \"boolean key\"));\n break;\n }\n return gen;\n /* eslint-enable no-unexpected-multiline */\n}\n\n/**\n * Generates a verifier specific to the specified message type.\n * @param {Type} mtype Message type\n * @returns {Codegen} Codegen instance\n */\nfunction verifier(mtype) {\n /* eslint-disable no-unexpected-multiline */\n\n var gen = util.codegen([\"m\"], mtype.name + \"$verify\")\n (\"if(typeof m!==\\\"object\\\"||m===null)\")\n (\"return%j\", \"object expected\");\n var oneofs = mtype.oneofsArray,\n seenFirstField = {};\n if (oneofs.length) gen\n (\"var p={}\");\n\n for (var i = 0; i < /* initializes */ mtype.fieldsArray.length; ++i) {\n var field = mtype._fieldsArray[i].resolve(),\n ref = \"m\" + util.safeProp(field.name);\n\n if (field.optional) gen\n (\"if(%s!=null&&m.hasOwnProperty(%j)){\", ref, field.name); // !== undefined && !== null\n\n // map fields\n if (field.map) { gen\n (\"if(!util.isObject(%s))\", ref)\n (\"return%j\", invalid(field, \"object\"))\n (\"var k=Object.keys(%s)\", ref)\n (\"for(var i=0;i}\n * @const\n */\nvar wrappers = exports;\n\nvar Message = require(21);\n\n/**\n * From object converter part of an {@link IWrapper}.\n * @typedef WrapperFromObjectConverter\n * @type {function}\n * @param {Object.} object Plain object\n * @returns {Message<{}>} Message instance\n * @this Type\n */\n\n/**\n * To object converter part of an {@link IWrapper}.\n * @typedef WrapperToObjectConverter\n * @type {function}\n * @param {Message<{}>} message Message instance\n * @param {IConversionOptions} [options] Conversion options\n * @returns {Object.} Plain object\n * @this Type\n */\n\n/**\n * Common type wrapper part of {@link wrappers}.\n * @interface IWrapper\n * @property {WrapperFromObjectConverter} [fromObject] From object converter\n * @property {WrapperToObjectConverter} [toObject] To object converter\n */\n\n// Custom wrapper for Any\nwrappers[\".google.protobuf.Any\"] = {\n\n fromObject: function(object) {\n\n // unwrap value type if mapped\n if (object && object[\"@type\"]) {\n // Only use fully qualified type name after the last '/'\n var name = object[\"@type\"].substring(object[\"@type\"].lastIndexOf(\"/\") + 1);\n var type = this.lookup(name);\n /* istanbul ignore else */\n if (type) {\n // type_url does not accept leading \".\"\n var type_url = object[\"@type\"].charAt(0) === \".\" ?\n object[\"@type\"].slice(1) : object[\"@type\"];\n // type_url prefix is optional, but path seperator is required\n if (type_url.indexOf(\"/\") === -1) {\n type_url = \"/\" + type_url;\n }\n return this.create({\n type_url: type_url,\n value: type.encode(type.fromObject(object)).finish()\n });\n }\n }\n\n return this.fromObject(object);\n },\n\n toObject: function(message, options) {\n\n // Default prefix\n var googleApi = \"type.googleapis.com/\";\n var prefix = \"\";\n var name = \"\";\n\n // decode value if requested and unmapped\n if (options && options.json && message.type_url && message.value) {\n // Only use fully qualified type name after the last '/'\n name = message.type_url.substring(message.type_url.lastIndexOf(\"/\") + 1);\n // Separate the prefix used\n prefix = message.type_url.substring(0, message.type_url.lastIndexOf(\"/\") + 1);\n var type = this.lookup(name);\n /* istanbul ignore else */\n if (type)\n message = type.decode(message.value);\n }\n\n // wrap value if unmapped\n if (!(message instanceof this.ctor) && message instanceof Message) {\n var object = message.$type.toObject(message, options);\n var messageName = message.$type.fullName[0] === \".\" ?\n message.$type.fullName.slice(1) : message.$type.fullName;\n // Default to type.googleapis.com prefix if no prefix is used\n if (prefix === \"\") {\n prefix = googleApi;\n }\n name = prefix + messageName;\n object[\"@type\"] = name;\n return object;\n }\n\n return this.toObject(message, options);\n }\n};\n","\"use strict\";\nmodule.exports = Writer;\n\nvar util = require(39);\n\nvar BufferWriter; // cyclic\n\nvar LongBits = util.LongBits,\n base64 = util.base64,\n utf8 = util.utf8;\n\n/**\n * Constructs a new writer operation instance.\n * @classdesc Scheduled writer operation.\n * @constructor\n * @param {function(*, Uint8Array, number)} fn Function to call\n * @param {number} len Value byte length\n * @param {*} val Value to write\n * @ignore\n */\nfunction Op(fn, len, val) {\n\n /**\n * Function to call.\n * @type {function(Uint8Array, number, *)}\n */\n this.fn = fn;\n\n /**\n * Value byte length.\n * @type {number}\n */\n this.len = len;\n\n /**\n * Next operation.\n * @type {Writer.Op|undefined}\n */\n this.next = undefined;\n\n /**\n * Value to write.\n * @type {*}\n */\n this.val = val; // type varies\n}\n\n/* istanbul ignore next */\nfunction noop() {} // eslint-disable-line no-empty-function\n\n/**\n * Constructs a new writer state instance.\n * @classdesc Copied writer state.\n * @memberof Writer\n * @constructor\n * @param {Writer} writer Writer to copy state from\n * @ignore\n */\nfunction State(writer) {\n\n /**\n * Current head.\n * @type {Writer.Op}\n */\n this.head = writer.head;\n\n /**\n * Current tail.\n * @type {Writer.Op}\n */\n this.tail = writer.tail;\n\n /**\n * Current buffer length.\n * @type {number}\n */\n this.len = writer.len;\n\n /**\n * Next state.\n * @type {State|null}\n */\n this.next = writer.states;\n}\n\n/**\n * Constructs a new writer instance.\n * @classdesc Wire format writer using `Uint8Array` if available, otherwise `Array`.\n * @constructor\n */\nfunction Writer() {\n\n /**\n * Current length.\n * @type {number}\n */\n this.len = 0;\n\n /**\n * Operations head.\n * @type {Object}\n */\n this.head = new Op(noop, 0, 0);\n\n /**\n * Operations tail\n * @type {Object}\n */\n this.tail = this.head;\n\n /**\n * Linked forked states.\n * @type {Object|null}\n */\n this.states = null;\n\n // When a value is written, the writer calculates its byte length and puts it into a linked\n // list of operations to perform when finish() is called. This both allows us to allocate\n // buffers of the exact required size and reduces the amount of work we have to do compared\n // to first calculating over objects and then encoding over objects. In our case, the encoding\n // part is just a linked list walk calling operations with already prepared values.\n}\n\nvar create = function create() {\n return util.Buffer\n ? function create_buffer_setup() {\n return (Writer.create = function create_buffer() {\n return new BufferWriter();\n })();\n }\n /* istanbul ignore next */\n : function create_array() {\n return new Writer();\n };\n};\n\n/**\n * Creates a new writer.\n * @function\n * @returns {BufferWriter|Writer} A {@link BufferWriter} when Buffers are supported, otherwise a {@link Writer}\n */\nWriter.create = create();\n\n/**\n * Allocates a buffer of the specified size.\n * @param {number} size Buffer size\n * @returns {Uint8Array} Buffer\n */\nWriter.alloc = function alloc(size) {\n return new util.Array(size);\n};\n\n// Use Uint8Array buffer pool in the browser, just like node does with buffers\n/* istanbul ignore else */\nif (util.Array !== Array)\n Writer.alloc = util.pool(Writer.alloc, util.Array.prototype.subarray);\n\n/**\n * Pushes a new operation to the queue.\n * @param {function(Uint8Array, number, *)} fn Function to call\n * @param {number} len Value byte length\n * @param {number} val Value to write\n * @returns {Writer} `this`\n * @private\n */\nWriter.prototype._push = function push(fn, len, val) {\n this.tail = this.tail.next = new Op(fn, len, val);\n this.len += len;\n return this;\n};\n\nfunction writeByte(val, buf, pos) {\n buf[pos] = val & 255;\n}\n\nfunction writeVarint32(val, buf, pos) {\n while (val > 127) {\n buf[pos++] = val & 127 | 128;\n val >>>= 7;\n }\n buf[pos] = val;\n}\n\n/**\n * Constructs a new varint writer operation instance.\n * @classdesc Scheduled varint writer operation.\n * @extends Op\n * @constructor\n * @param {number} len Value byte length\n * @param {number} val Value to write\n * @ignore\n */\nfunction VarintOp(len, val) {\n this.len = len;\n this.next = undefined;\n this.val = val;\n}\n\nVarintOp.prototype = Object.create(Op.prototype);\nVarintOp.prototype.fn = writeVarint32;\n\n/**\n * Writes an unsigned 32 bit value as a varint.\n * @param {number} value Value to write\n * @returns {Writer} `this`\n */\nWriter.prototype.uint32 = function write_uint32(value) {\n // here, the call to this.push has been inlined and a varint specific Op subclass is used.\n // uint32 is by far the most frequently used operation and benefits significantly from this.\n this.len += (this.tail = this.tail.next = new VarintOp(\n (value = value >>> 0)\n < 128 ? 1\n : value < 16384 ? 2\n : value < 2097152 ? 3\n : value < 268435456 ? 4\n : 5,\n value)).len;\n return this;\n};\n\n/**\n * Writes a signed 32 bit value as a varint.\n * @function\n * @param {number} value Value to write\n * @returns {Writer} `this`\n */\nWriter.prototype.int32 = function write_int32(value) {\n return value < 0\n ? this._push(writeVarint64, 10, LongBits.fromNumber(value)) // 10 bytes per spec\n : this.uint32(value);\n};\n\n/**\n * Writes a 32 bit value as a varint, zig-zag encoded.\n * @param {number} value Value to write\n * @returns {Writer} `this`\n */\nWriter.prototype.sint32 = function write_sint32(value) {\n return this.uint32((value << 1 ^ value >> 31) >>> 0);\n};\n\nfunction writeVarint64(val, buf, pos) {\n while (val.hi) {\n buf[pos++] = val.lo & 127 | 128;\n val.lo = (val.lo >>> 7 | val.hi << 25) >>> 0;\n val.hi >>>= 7;\n }\n while (val.lo > 127) {\n buf[pos++] = val.lo & 127 | 128;\n val.lo = val.lo >>> 7;\n }\n buf[pos++] = val.lo;\n}\n\n/**\n * Writes an unsigned 64 bit value as a varint.\n * @param {Long|number|string} value Value to write\n * @returns {Writer} `this`\n * @throws {TypeError} If `value` is a string and no long library is present.\n */\nWriter.prototype.uint64 = function write_uint64(value) {\n var bits = LongBits.from(value);\n return this._push(writeVarint64, bits.length(), bits);\n};\n\n/**\n * Writes a signed 64 bit value as a varint.\n * @function\n * @param {Long|number|string} value Value to write\n * @returns {Writer} `this`\n * @throws {TypeError} If `value` is a string and no long library is present.\n */\nWriter.prototype.int64 = Writer.prototype.uint64;\n\n/**\n * Writes a signed 64 bit value as a varint, zig-zag encoded.\n * @param {Long|number|string} value Value to write\n * @returns {Writer} `this`\n * @throws {TypeError} If `value` is a string and no long library is present.\n */\nWriter.prototype.sint64 = function write_sint64(value) {\n var bits = LongBits.from(value).zzEncode();\n return this._push(writeVarint64, bits.length(), bits);\n};\n\n/**\n * Writes a boolish value as a varint.\n * @param {boolean} value Value to write\n * @returns {Writer} `this`\n */\nWriter.prototype.bool = function write_bool(value) {\n return this._push(writeByte, 1, value ? 1 : 0);\n};\n\nfunction writeFixed32(val, buf, pos) {\n buf[pos ] = val & 255;\n buf[pos + 1] = val >>> 8 & 255;\n buf[pos + 2] = val >>> 16 & 255;\n buf[pos + 3] = val >>> 24;\n}\n\n/**\n * Writes an unsigned 32 bit value as fixed 32 bits.\n * @param {number} value Value to write\n * @returns {Writer} `this`\n */\nWriter.prototype.fixed32 = function write_fixed32(value) {\n return this._push(writeFixed32, 4, value >>> 0);\n};\n\n/**\n * Writes a signed 32 bit value as fixed 32 bits.\n * @function\n * @param {number} value Value to write\n * @returns {Writer} `this`\n */\nWriter.prototype.sfixed32 = Writer.prototype.fixed32;\n\n/**\n * Writes an unsigned 64 bit value as fixed 64 bits.\n * @param {Long|number|string} value Value to write\n * @returns {Writer} `this`\n * @throws {TypeError} If `value` is a string and no long library is present.\n */\nWriter.prototype.fixed64 = function write_fixed64(value) {\n var bits = LongBits.from(value);\n return this._push(writeFixed32, 4, bits.lo)._push(writeFixed32, 4, bits.hi);\n};\n\n/**\n * Writes a signed 64 bit value as fixed 64 bits.\n * @function\n * @param {Long|number|string} value Value to write\n * @returns {Writer} `this`\n * @throws {TypeError} If `value` is a string and no long library is present.\n */\nWriter.prototype.sfixed64 = Writer.prototype.fixed64;\n\n/**\n * Writes a float (32 bit).\n * @function\n * @param {number} value Value to write\n * @returns {Writer} `this`\n */\nWriter.prototype.float = function write_float(value) {\n return this._push(util.float.writeFloatLE, 4, value);\n};\n\n/**\n * Writes a double (64 bit float).\n * @function\n * @param {number} value Value to write\n * @returns {Writer} `this`\n */\nWriter.prototype.double = function write_double(value) {\n return this._push(util.float.writeDoubleLE, 8, value);\n};\n\nvar writeBytes = util.Array.prototype.set\n ? function writeBytes_set(val, buf, pos) {\n buf.set(val, pos); // also works for plain array values\n }\n /* istanbul ignore next */\n : function writeBytes_for(val, buf, pos) {\n for (var i = 0; i < val.length; ++i)\n buf[pos + i] = val[i];\n };\n\n/**\n * Writes a sequence of bytes.\n * @param {Uint8Array|string} value Buffer or base64 encoded string to write\n * @returns {Writer} `this`\n */\nWriter.prototype.bytes = function write_bytes(value) {\n var len = value.length >>> 0;\n if (!len)\n return this._push(writeByte, 1, 0);\n if (util.isString(value)) {\n var buf = Writer.alloc(len = base64.length(value));\n base64.decode(value, buf, 0);\n value = buf;\n }\n return this.uint32(len)._push(writeBytes, len, value);\n};\n\n/**\n * Writes a string.\n * @param {string} value Value to write\n * @returns {Writer} `this`\n */\nWriter.prototype.string = function write_string(value) {\n var len = utf8.length(value);\n return len\n ? this.uint32(len)._push(utf8.write, len, value)\n : this._push(writeByte, 1, 0);\n};\n\n/**\n * Forks this writer's state by pushing it to a stack.\n * Calling {@link Writer#reset|reset} or {@link Writer#ldelim|ldelim} resets the writer to the previous state.\n * @returns {Writer} `this`\n */\nWriter.prototype.fork = function fork() {\n this.states = new State(this);\n this.head = this.tail = new Op(noop, 0, 0);\n this.len = 0;\n return this;\n};\n\n/**\n * Resets this instance to the last state.\n * @returns {Writer} `this`\n */\nWriter.prototype.reset = function reset() {\n if (this.states) {\n this.head = this.states.head;\n this.tail = this.states.tail;\n this.len = this.states.len;\n this.states = this.states.next;\n } else {\n this.head = this.tail = new Op(noop, 0, 0);\n this.len = 0;\n }\n return this;\n};\n\n/**\n * Resets to the last state and appends the fork state's current write length as a varint followed by its operations.\n * @returns {Writer} `this`\n */\nWriter.prototype.ldelim = function ldelim() {\n var head = this.head,\n tail = this.tail,\n len = this.len;\n this.reset().uint32(len);\n if (len) {\n this.tail.next = head.next; // skip noop\n this.tail = tail;\n this.len += len;\n }\n return this;\n};\n\n/**\n * Finishes the write operation.\n * @returns {Uint8Array} Finished buffer\n */\nWriter.prototype.finish = function finish() {\n var head = this.head.next, // skip noop\n buf = this.constructor.alloc(this.len),\n pos = 0;\n while (head) {\n head.fn(head.val, buf, pos);\n pos += head.len;\n head = head.next;\n }\n // this.head = this.tail = null;\n return buf;\n};\n\nWriter._configure = function(BufferWriter_) {\n BufferWriter = BufferWriter_;\n Writer.create = create();\n BufferWriter._configure();\n};\n","\"use strict\";\nmodule.exports = BufferWriter;\n\n// extends Writer\nvar Writer = require(42);\n(BufferWriter.prototype = Object.create(Writer.prototype)).constructor = BufferWriter;\n\nvar util = require(39);\n\n/**\n * Constructs a new buffer writer instance.\n * @classdesc Wire format writer using node buffers.\n * @extends Writer\n * @constructor\n */\nfunction BufferWriter() {\n Writer.call(this);\n}\n\nBufferWriter._configure = function () {\n /**\n * Allocates a buffer of the specified size.\n * @function\n * @param {number} size Buffer size\n * @returns {Buffer} Buffer\n */\n BufferWriter.alloc = util._Buffer_allocUnsafe;\n\n BufferWriter.writeBytesBuffer = util.Buffer && util.Buffer.prototype instanceof Uint8Array && util.Buffer.prototype.set.name === \"set\"\n ? function writeBytesBuffer_set(val, buf, pos) {\n buf.set(val, pos); // faster than copy (requires node >= 4 where Buffers extend Uint8Array and set is properly inherited)\n // also works for plain array values\n }\n /* istanbul ignore next */\n : function writeBytesBuffer_copy(val, buf, pos) {\n if (val.copy) // Buffer values\n val.copy(buf, pos, 0, val.length);\n else for (var i = 0; i < val.length;) // plain array values\n buf[pos++] = val[i++];\n };\n};\n\n\n/**\n * @override\n */\nBufferWriter.prototype.bytes = function write_bytes_buffer(value) {\n if (util.isString(value))\n value = util._Buffer_from(value, \"base64\");\n var len = value.length >>> 0;\n this.uint32(len);\n if (len)\n this._push(BufferWriter.writeBytesBuffer, len, value);\n return this;\n};\n\nfunction writeStringBuffer(val, buf, pos) {\n if (val.length < 40) // plain js is faster for short strings (probably due to redundant assertions)\n util.utf8.write(val, buf, pos);\n else if (buf.utf8Write)\n buf.utf8Write(val, pos);\n else\n buf.write(val, pos);\n}\n\n/**\n * @override\n */\nBufferWriter.prototype.string = function write_string_buffer(value) {\n var len = util.Buffer.byteLength(value);\n this.uint32(len);\n if (len)\n this._push(writeStringBuffer, len, value);\n return this;\n};\n\n\n/**\n * Finishes the write operation.\n * @name BufferWriter#finish\n * @function\n * @returns {Buffer} Finished buffer\n */\n\nBufferWriter._configure();\n"],"sourceRoot":"."} \ No newline at end of file diff --git a/node_modules/protobufjs/ext/debug/README.md b/node_modules/protobufjs/ext/debug/README.md new file mode 100644 index 0000000..a48517e --- /dev/null +++ b/node_modules/protobufjs/ext/debug/README.md @@ -0,0 +1,4 @@ +protobufjs/ext/debug +========================= + +Experimental debugging extension. diff --git a/node_modules/protobufjs/ext/debug/index.js b/node_modules/protobufjs/ext/debug/index.js new file mode 100644 index 0000000..2b79766 --- /dev/null +++ b/node_modules/protobufjs/ext/debug/index.js @@ -0,0 +1,71 @@ +"use strict"; +var protobuf = require("../.."); + +/** + * Debugging utility functions. Only present in debug builds. + * @namespace + */ +var debug = protobuf.debug = module.exports = {}; + +var codegen = protobuf.util.codegen; + +var debugFnRe = /function ([^(]+)\(([^)]*)\) {/g; + +// Counts number of calls to any generated function +function codegen_debug() { + codegen_debug.supported = codegen.supported; + codegen_debug.verbose = codegen.verbose; + var gen = codegen.apply(null, Array.prototype.slice.call(arguments)); + gen.str = (function(str) { return function str_debug() { + return str.apply(null, Array.prototype.slice.call(arguments)).replace(debugFnRe, "function $1($2) {\n\t$1.calls=($1.calls|0)+1"); + };})(gen.str); + return gen; +} + +/** + * Returns a list of unused types within the specified root. + * @param {NamespaceBase} ns Namespace to search + * @returns {Type[]} Unused types + */ +debug.unusedTypes = function unusedTypes(ns) { + + /* istanbul ignore if */ + if (!(ns instanceof protobuf.Namespace)) + throw TypeError("ns must be a Namespace"); + + /* istanbul ignore if */ + if (!ns.nested) + return []; + + var unused = []; + for (var names = Object.keys(ns.nested), i = 0; i < names.length; ++i) { + var nested = ns.nested[names[i]]; + if (nested instanceof protobuf.Type) { + var calls = (nested.encode.calls|0) + + (nested.decode.calls|0) + + (nested.verify.calls|0) + + (nested.toObject.calls|0) + + (nested.fromObject.calls|0); + if (!calls) + unused.push(nested); + } else if (nested instanceof protobuf.Namespace) + Array.prototype.push.apply(unused, unusedTypes(nested)); + } + return unused; +}; + +/** + * Enables debugging extensions. + * @returns {undefined} + */ +debug.enable = function enable() { + protobuf.util.codegen = codegen_debug; +}; + +/** + * Disables debugging extensions. + * @returns {undefined} + */ +debug.disable = function disable() { + protobuf.util.codegen = codegen; +}; diff --git a/node_modules/protobufjs/ext/descriptor/README.md b/node_modules/protobufjs/ext/descriptor/README.md new file mode 100644 index 0000000..3bc4c6c --- /dev/null +++ b/node_modules/protobufjs/ext/descriptor/README.md @@ -0,0 +1,72 @@ +protobufjs/ext/descriptor +========================= + +Experimental extension for interoperability with [descriptor.proto](https://github.com/google/protobuf/blob/master/src/google/protobuf/descriptor.proto) types. + +Usage +----- + +```js +var protobuf = require("protobufjs"), // requires the full library + descriptor = require("protobufjs/ext/descriptor"); + +var root = ...; + +// convert any existing root instance to the corresponding descriptor type +var descriptorMsg = root.toDescriptor("proto2"); +// ^ returns a FileDescriptorSet message, see table below + +// encode to a descriptor buffer +var buffer = descriptor.FileDescriptorSet.encode(descriptorMsg).finish(); + +// decode from a descriptor buffer +var decodedDescriptor = descriptor.FileDescriptorSet.decode(buffer); + +// convert any existing descriptor to a root instance +root = protobuf.Root.fromDescriptor(decodedDescriptor); +// ^ expects a FileDescriptorSet message or buffer, see table below + +// and start all over again +``` + +API +--- + +The extension adds `.fromDescriptor(descriptor[, syntax])` and `#toDescriptor([syntax])` methods to reflection objects and exports the `.google.protobuf` namespace of the internally used `Root` instance containing the following types present in descriptor.proto: + +| Descriptor type | protobuf.js type | Remarks +|-------------------------------|------------------|--------- +| **FileDescriptorSet** | Root | +| FileDescriptorProto | | dependencies are not supported +| FileOptions | | +| FileOptionsOptimizeMode | | +| SourceCodeInfo | | not supported +| SourceCodeInfoLocation | | +| GeneratedCodeInfo | | not supported +| GeneratedCodeInfoAnnotation | | +| **DescriptorProto** | Type | +| MessageOptions | | +| DescriptorProtoExtensionRange | | +| DescriptorProtoReservedRange | | +| **FieldDescriptorProto** | Field | +| FieldDescriptorProtoLabel | | +| FieldDescriptorProtoType | | +| FieldOptions | | +| FieldOptionsCType | | +| FieldOptionsJSType | | +| **OneofDescriptorProto** | OneOf | +| OneofOptions | | +| **EnumDescriptorProto** | Enum | +| EnumOptions | | +| EnumValueDescriptorProto | | +| EnumValueOptions | | not supported +| **ServiceDescriptorProto** | Service | +| ServiceOptions | | +| **MethodDescriptorProto** | Method | +| MethodOptions | | +| UninterpretedOption | | not supported +| UninterpretedOptionNamePart | | + +Note that not all features of descriptor.proto translate perfectly to a protobuf.js root instance. A root instance has only limited knowlege of packages or individual files for example, which is then compensated by guessing and generating fictional file names. + +When using TypeScript, the respective interface types can be used to reference specific message instances (i.e. `protobuf.Message`). diff --git a/node_modules/protobufjs/ext/descriptor/index.d.ts b/node_modules/protobufjs/ext/descriptor/index.d.ts new file mode 100644 index 0000000..1df2efc --- /dev/null +++ b/node_modules/protobufjs/ext/descriptor/index.d.ts @@ -0,0 +1,191 @@ +import * as $protobuf from "../.."; +export const FileDescriptorSet: $protobuf.Type; + +export const FileDescriptorProto: $protobuf.Type; + +export const DescriptorProto: $protobuf.Type & { + ExtensionRange: $protobuf.Type, + ReservedRange: $protobuf.Type +}; + +export const FieldDescriptorProto: $protobuf.Type & { + Label: $protobuf.Enum, + Type: $protobuf.Enum +}; + +export const OneofDescriptorProto: $protobuf.Type; + +export const EnumDescriptorProto: $protobuf.Type; + +export const ServiceDescriptorProto: $protobuf.Type; + +export const EnumValueDescriptorProto: $protobuf.Type; + +export const MethodDescriptorProto: $protobuf.Type; + +export const FileOptions: $protobuf.Type & { + OptimizeMode: $protobuf.Enum +}; + +export const MessageOptions: $protobuf.Type; + +export const FieldOptions: $protobuf.Type & { + CType: $protobuf.Enum, + JSType: $protobuf.Enum +}; + +export const OneofOptions: $protobuf.Type; + +export const EnumOptions: $protobuf.Type; + +export const EnumValueOptions: $protobuf.Type; + +export const ServiceOptions: $protobuf.Type; + +export const MethodOptions: $protobuf.Type; + +export const UninterpretedOption: $protobuf.Type & { + NamePart: $protobuf.Type +}; + +export const SourceCodeInfo: $protobuf.Type & { + Location: $protobuf.Type +}; + +export const GeneratedCodeInfo: $protobuf.Type & { + Annotation: $protobuf.Type +}; + +export interface IFileDescriptorSet { + file: IFileDescriptorProto[]; +} + +export interface IFileDescriptorProto { + name?: string; + package?: string; + dependency?: any; + publicDependency?: any; + weakDependency?: any; + messageType?: IDescriptorProto[]; + enumType?: IEnumDescriptorProto[]; + service?: IServiceDescriptorProto[]; + extension?: IFieldDescriptorProto[]; + options?: IFileOptions; + sourceCodeInfo?: any; + syntax?: string; +} + +export interface IFileOptions { + javaPackage?: string; + javaOuterClassname?: string; + javaMultipleFiles?: boolean; + javaGenerateEqualsAndHash?: boolean; + javaStringCheckUtf8?: boolean; + optimizeFor?: IFileOptionsOptimizeMode; + goPackage?: string; + ccGenericServices?: boolean; + javaGenericServices?: boolean; + pyGenericServices?: boolean; + deprecated?: boolean; + ccEnableArenas?: boolean; + objcClassPrefix?: string; + csharpNamespace?: string; +} + +type IFileOptionsOptimizeMode = number; + +export interface IDescriptorProto { + name?: string; + field?: IFieldDescriptorProto[]; + extension?: IFieldDescriptorProto[]; + nestedType?: IDescriptorProto[]; + enumType?: IEnumDescriptorProto[]; + extensionRange?: IDescriptorProtoExtensionRange[]; + oneofDecl?: IOneofDescriptorProto[]; + options?: IMessageOptions; + reservedRange?: IDescriptorProtoReservedRange[]; + reservedName?: string[]; +} + +export interface IMessageOptions { + mapEntry?: boolean; +} + +export interface IDescriptorProtoExtensionRange { + start?: number; + end?: number; +} + +export interface IDescriptorProtoReservedRange { + start?: number; + end?: number; +} + +export interface IFieldDescriptorProto { + name?: string; + number?: number; + label?: IFieldDescriptorProtoLabel; + type?: IFieldDescriptorProtoType; + typeName?: string; + extendee?: string; + defaultValue?: string; + oneofIndex?: number; + jsonName?: any; + options?: IFieldOptions; +} + +type IFieldDescriptorProtoLabel = number; + +type IFieldDescriptorProtoType = number; + +export interface IFieldOptions { + packed?: boolean; + jstype?: IFieldOptionsJSType; +} + +type IFieldOptionsJSType = number; + +export interface IEnumDescriptorProto { + name?: string; + value?: IEnumValueDescriptorProto[]; + options?: IEnumOptions; +} + +export interface IEnumValueDescriptorProto { + name?: string; + number?: number; + options?: any; +} + +export interface IEnumOptions { + allowAlias?: boolean; + deprecated?: boolean; +} + +export interface IOneofDescriptorProto { + name?: string; + options?: any; +} + +export interface IServiceDescriptorProto { + name?: string; + method?: IMethodDescriptorProto[]; + options?: IServiceOptions; +} + +export interface IServiceOptions { + deprecated?: boolean; +} + +export interface IMethodDescriptorProto { + name?: string; + inputType?: string; + outputType?: string; + options?: IMethodOptions; + clientStreaming?: boolean; + serverStreaming?: boolean; +} + +export interface IMethodOptions { + deprecated?: boolean; +} diff --git a/node_modules/protobufjs/ext/descriptor/index.js b/node_modules/protobufjs/ext/descriptor/index.js new file mode 100644 index 0000000..6aafd2a --- /dev/null +++ b/node_modules/protobufjs/ext/descriptor/index.js @@ -0,0 +1,1052 @@ +"use strict"; +var $protobuf = require("../.."); +module.exports = exports = $protobuf.descriptor = $protobuf.Root.fromJSON(require("../../google/protobuf/descriptor.json")).lookup(".google.protobuf"); + +var Namespace = $protobuf.Namespace, + Root = $protobuf.Root, + Enum = $protobuf.Enum, + Type = $protobuf.Type, + Field = $protobuf.Field, + MapField = $protobuf.MapField, + OneOf = $protobuf.OneOf, + Service = $protobuf.Service, + Method = $protobuf.Method; + +// --- Root --- + +/** + * Properties of a FileDescriptorSet message. + * @interface IFileDescriptorSet + * @property {IFileDescriptorProto[]} file Files + */ + +/** + * Properties of a FileDescriptorProto message. + * @interface IFileDescriptorProto + * @property {string} [name] File name + * @property {string} [package] Package + * @property {*} [dependency] Not supported + * @property {*} [publicDependency] Not supported + * @property {*} [weakDependency] Not supported + * @property {IDescriptorProto[]} [messageType] Nested message types + * @property {IEnumDescriptorProto[]} [enumType] Nested enums + * @property {IServiceDescriptorProto[]} [service] Nested services + * @property {IFieldDescriptorProto[]} [extension] Nested extension fields + * @property {IFileOptions} [options] Options + * @property {*} [sourceCodeInfo] Not supported + * @property {string} [syntax="proto2"] Syntax + */ + +/** + * Properties of a FileOptions message. + * @interface IFileOptions + * @property {string} [javaPackage] + * @property {string} [javaOuterClassname] + * @property {boolean} [javaMultipleFiles] + * @property {boolean} [javaGenerateEqualsAndHash] + * @property {boolean} [javaStringCheckUtf8] + * @property {IFileOptionsOptimizeMode} [optimizeFor=1] + * @property {string} [goPackage] + * @property {boolean} [ccGenericServices] + * @property {boolean} [javaGenericServices] + * @property {boolean} [pyGenericServices] + * @property {boolean} [deprecated] + * @property {boolean} [ccEnableArenas] + * @property {string} [objcClassPrefix] + * @property {string} [csharpNamespace] + */ + +/** + * Values of he FileOptions.OptimizeMode enum. + * @typedef IFileOptionsOptimizeMode + * @type {number} + * @property {number} SPEED=1 + * @property {number} CODE_SIZE=2 + * @property {number} LITE_RUNTIME=3 + */ + +/** + * Creates a root from a descriptor set. + * @param {IFileDescriptorSet|Reader|Uint8Array} descriptor Descriptor + * @returns {Root} Root instance + */ +Root.fromDescriptor = function fromDescriptor(descriptor) { + + // Decode the descriptor message if specified as a buffer: + if (typeof descriptor.length === "number") + descriptor = exports.FileDescriptorSet.decode(descriptor); + + var root = new Root(); + + if (descriptor.file) { + var fileDescriptor, + filePackage; + for (var j = 0, i; j < descriptor.file.length; ++j) { + filePackage = root; + if ((fileDescriptor = descriptor.file[j])["package"] && fileDescriptor["package"].length) + filePackage = root.define(fileDescriptor["package"]); + if (fileDescriptor.name && fileDescriptor.name.length) + root.files.push(filePackage.filename = fileDescriptor.name); + if (fileDescriptor.messageType) + for (i = 0; i < fileDescriptor.messageType.length; ++i) + filePackage.add(Type.fromDescriptor(fileDescriptor.messageType[i], fileDescriptor.syntax)); + if (fileDescriptor.enumType) + for (i = 0; i < fileDescriptor.enumType.length; ++i) + filePackage.add(Enum.fromDescriptor(fileDescriptor.enumType[i])); + if (fileDescriptor.extension) + for (i = 0; i < fileDescriptor.extension.length; ++i) + filePackage.add(Field.fromDescriptor(fileDescriptor.extension[i])); + if (fileDescriptor.service) + for (i = 0; i < fileDescriptor.service.length; ++i) + filePackage.add(Service.fromDescriptor(fileDescriptor.service[i])); + var opts = fromDescriptorOptions(fileDescriptor.options, exports.FileOptions); + if (opts) { + var ks = Object.keys(opts); + for (i = 0; i < ks.length; ++i) + filePackage.setOption(ks[i], opts[ks[i]]); + } + } + } + + return root; +}; + +/** + * Converts a root to a descriptor set. + * @returns {Message} Descriptor + * @param {string} [syntax="proto2"] Syntax + */ +Root.prototype.toDescriptor = function toDescriptor(syntax) { + var set = exports.FileDescriptorSet.create(); + Root_toDescriptorRecursive(this, set.file, syntax); + return set; +}; + +// Traverses a namespace and assembles the descriptor set +function Root_toDescriptorRecursive(ns, files, syntax) { + + // Create a new file + var file = exports.FileDescriptorProto.create({ name: ns.filename || (ns.fullName.substring(1).replace(/\./g, "_") || "root") + ".proto" }); + if (syntax) + file.syntax = syntax; + if (!(ns instanceof Root)) + file["package"] = ns.fullName.substring(1); + + // Add nested types + for (var i = 0, nested; i < ns.nestedArray.length; ++i) + if ((nested = ns._nestedArray[i]) instanceof Type) + file.messageType.push(nested.toDescriptor(syntax)); + else if (nested instanceof Enum) + file.enumType.push(nested.toDescriptor()); + else if (nested instanceof Field) + file.extension.push(nested.toDescriptor(syntax)); + else if (nested instanceof Service) + file.service.push(nested.toDescriptor()); + else if (nested instanceof /* plain */ Namespace) + Root_toDescriptorRecursive(nested, files, syntax); // requires new file + + // Keep package-level options + file.options = toDescriptorOptions(ns.options, exports.FileOptions); + + // And keep the file only if there is at least one nested object + if (file.messageType.length + file.enumType.length + file.extension.length + file.service.length) + files.push(file); +} + +// --- Type --- + +/** + * Properties of a DescriptorProto message. + * @interface IDescriptorProto + * @property {string} [name] Message type name + * @property {IFieldDescriptorProto[]} [field] Fields + * @property {IFieldDescriptorProto[]} [extension] Extension fields + * @property {IDescriptorProto[]} [nestedType] Nested message types + * @property {IEnumDescriptorProto[]} [enumType] Nested enums + * @property {IDescriptorProtoExtensionRange[]} [extensionRange] Extension ranges + * @property {IOneofDescriptorProto[]} [oneofDecl] Oneofs + * @property {IMessageOptions} [options] Not supported + * @property {IDescriptorProtoReservedRange[]} [reservedRange] Reserved ranges + * @property {string[]} [reservedName] Reserved names + */ + +/** + * Properties of a MessageOptions message. + * @interface IMessageOptions + * @property {boolean} [mapEntry=false] Whether this message is a map entry + */ + +/** + * Properties of an ExtensionRange message. + * @interface IDescriptorProtoExtensionRange + * @property {number} [start] Start field id + * @property {number} [end] End field id + */ + +/** + * Properties of a ReservedRange message. + * @interface IDescriptorProtoReservedRange + * @property {number} [start] Start field id + * @property {number} [end] End field id + */ + +var unnamedMessageIndex = 0; + +/** + * Creates a type from a descriptor. + * @param {IDescriptorProto|Reader|Uint8Array} descriptor Descriptor + * @param {string} [syntax="proto2"] Syntax + * @returns {Type} Type instance + */ +Type.fromDescriptor = function fromDescriptor(descriptor, syntax) { + + // Decode the descriptor message if specified as a buffer: + if (typeof descriptor.length === "number") + descriptor = exports.DescriptorProto.decode(descriptor); + + // Create the message type + var type = new Type(descriptor.name.length ? descriptor.name : "Type" + unnamedMessageIndex++, fromDescriptorOptions(descriptor.options, exports.MessageOptions)), + i; + + /* Oneofs */ if (descriptor.oneofDecl) + for (i = 0; i < descriptor.oneofDecl.length; ++i) + type.add(OneOf.fromDescriptor(descriptor.oneofDecl[i])); + /* Fields */ if (descriptor.field) + for (i = 0; i < descriptor.field.length; ++i) { + var field = Field.fromDescriptor(descriptor.field[i], syntax); + type.add(field); + if (descriptor.field[i].hasOwnProperty("oneofIndex")) // eslint-disable-line no-prototype-builtins + type.oneofsArray[descriptor.field[i].oneofIndex].add(field); + } + /* Extension fields */ if (descriptor.extension) + for (i = 0; i < descriptor.extension.length; ++i) + type.add(Field.fromDescriptor(descriptor.extension[i], syntax)); + /* Nested types */ if (descriptor.nestedType) + for (i = 0; i < descriptor.nestedType.length; ++i) { + type.add(Type.fromDescriptor(descriptor.nestedType[i], syntax)); + if (descriptor.nestedType[i].options && descriptor.nestedType[i].options.mapEntry) + type.setOption("map_entry", true); + } + /* Nested enums */ if (descriptor.enumType) + for (i = 0; i < descriptor.enumType.length; ++i) + type.add(Enum.fromDescriptor(descriptor.enumType[i])); + /* Extension ranges */ if (descriptor.extensionRange && descriptor.extensionRange.length) { + type.extensions = []; + for (i = 0; i < descriptor.extensionRange.length; ++i) + type.extensions.push([ descriptor.extensionRange[i].start, descriptor.extensionRange[i].end ]); + } + /* Reserved... */ if (descriptor.reservedRange && descriptor.reservedRange.length || descriptor.reservedName && descriptor.reservedName.length) { + type.reserved = []; + /* Ranges */ if (descriptor.reservedRange) + for (i = 0; i < descriptor.reservedRange.length; ++i) + type.reserved.push([ descriptor.reservedRange[i].start, descriptor.reservedRange[i].end ]); + /* Names */ if (descriptor.reservedName) + for (i = 0; i < descriptor.reservedName.length; ++i) + type.reserved.push(descriptor.reservedName[i]); + } + + return type; +}; + +/** + * Converts a type to a descriptor. + * @returns {Message} Descriptor + * @param {string} [syntax="proto2"] Syntax + */ +Type.prototype.toDescriptor = function toDescriptor(syntax) { + var descriptor = exports.DescriptorProto.create({ name: this.name }), + i; + + /* Fields */ for (i = 0; i < this.fieldsArray.length; ++i) { + var fieldDescriptor; + descriptor.field.push(fieldDescriptor = this._fieldsArray[i].toDescriptor(syntax)); + if (this._fieldsArray[i] instanceof MapField) { // map fields are repeated FieldNameEntry + var keyType = toDescriptorType(this._fieldsArray[i].keyType, this._fieldsArray[i].resolvedKeyType), + valueType = toDescriptorType(this._fieldsArray[i].type, this._fieldsArray[i].resolvedType), + valueTypeName = valueType === /* type */ 11 || valueType === /* enum */ 14 + ? this._fieldsArray[i].resolvedType && shortname(this.parent, this._fieldsArray[i].resolvedType) || this._fieldsArray[i].type + : undefined; + descriptor.nestedType.push(exports.DescriptorProto.create({ + name: fieldDescriptor.typeName, + field: [ + exports.FieldDescriptorProto.create({ name: "key", number: 1, label: 1, type: keyType }), // can't reference a type or enum + exports.FieldDescriptorProto.create({ name: "value", number: 2, label: 1, type: valueType, typeName: valueTypeName }) + ], + options: exports.MessageOptions.create({ mapEntry: true }) + })); + } + } + /* Oneofs */ for (i = 0; i < this.oneofsArray.length; ++i) + descriptor.oneofDecl.push(this._oneofsArray[i].toDescriptor()); + /* Nested... */ for (i = 0; i < this.nestedArray.length; ++i) { + /* Extension fields */ if (this._nestedArray[i] instanceof Field) + descriptor.field.push(this._nestedArray[i].toDescriptor(syntax)); + /* Types */ else if (this._nestedArray[i] instanceof Type) + descriptor.nestedType.push(this._nestedArray[i].toDescriptor(syntax)); + /* Enums */ else if (this._nestedArray[i] instanceof Enum) + descriptor.enumType.push(this._nestedArray[i].toDescriptor()); + // plain nested namespaces become packages instead in Root#toDescriptor + } + /* Extension ranges */ if (this.extensions) + for (i = 0; i < this.extensions.length; ++i) + descriptor.extensionRange.push(exports.DescriptorProto.ExtensionRange.create({ start: this.extensions[i][0], end: this.extensions[i][1] })); + /* Reserved... */ if (this.reserved) + for (i = 0; i < this.reserved.length; ++i) + /* Names */ if (typeof this.reserved[i] === "string") + descriptor.reservedName.push(this.reserved[i]); + /* Ranges */ else + descriptor.reservedRange.push(exports.DescriptorProto.ReservedRange.create({ start: this.reserved[i][0], end: this.reserved[i][1] })); + + descriptor.options = toDescriptorOptions(this.options, exports.MessageOptions); + + return descriptor; +}; + +// --- Field --- + +/** + * Properties of a FieldDescriptorProto message. + * @interface IFieldDescriptorProto + * @property {string} [name] Field name + * @property {number} [number] Field id + * @property {IFieldDescriptorProtoLabel} [label] Field rule + * @property {IFieldDescriptorProtoType} [type] Field basic type + * @property {string} [typeName] Field type name + * @property {string} [extendee] Extended type name + * @property {string} [defaultValue] Literal default value + * @property {number} [oneofIndex] Oneof index if part of a oneof + * @property {*} [jsonName] Not supported + * @property {IFieldOptions} [options] Field options + */ + +/** + * Values of the FieldDescriptorProto.Label enum. + * @typedef IFieldDescriptorProtoLabel + * @type {number} + * @property {number} LABEL_OPTIONAL=1 + * @property {number} LABEL_REQUIRED=2 + * @property {number} LABEL_REPEATED=3 + */ + +/** + * Values of the FieldDescriptorProto.Type enum. + * @typedef IFieldDescriptorProtoType + * @type {number} + * @property {number} TYPE_DOUBLE=1 + * @property {number} TYPE_FLOAT=2 + * @property {number} TYPE_INT64=3 + * @property {number} TYPE_UINT64=4 + * @property {number} TYPE_INT32=5 + * @property {number} TYPE_FIXED64=6 + * @property {number} TYPE_FIXED32=7 + * @property {number} TYPE_BOOL=8 + * @property {number} TYPE_STRING=9 + * @property {number} TYPE_GROUP=10 + * @property {number} TYPE_MESSAGE=11 + * @property {number} TYPE_BYTES=12 + * @property {number} TYPE_UINT32=13 + * @property {number} TYPE_ENUM=14 + * @property {number} TYPE_SFIXED32=15 + * @property {number} TYPE_SFIXED64=16 + * @property {number} TYPE_SINT32=17 + * @property {number} TYPE_SINT64=18 + */ + +/** + * Properties of a FieldOptions message. + * @interface IFieldOptions + * @property {boolean} [packed] Whether packed or not (defaults to `false` for proto2 and `true` for proto3) + * @property {IFieldOptionsJSType} [jstype] JavaScript value type (not used by protobuf.js) + */ + +/** + * Values of the FieldOptions.JSType enum. + * @typedef IFieldOptionsJSType + * @type {number} + * @property {number} JS_NORMAL=0 + * @property {number} JS_STRING=1 + * @property {number} JS_NUMBER=2 + */ + +// copied here from parse.js +var numberRe = /^(?![eE])[0-9]*(?:\.[0-9]*)?(?:[eE][+-]?[0-9]+)?$/; + +/** + * Creates a field from a descriptor. + * @param {IFieldDescriptorProto|Reader|Uint8Array} descriptor Descriptor + * @param {string} [syntax="proto2"] Syntax + * @returns {Field} Field instance + */ +Field.fromDescriptor = function fromDescriptor(descriptor, syntax) { + + // Decode the descriptor message if specified as a buffer: + if (typeof descriptor.length === "number") + descriptor = exports.DescriptorProto.decode(descriptor); + + if (typeof descriptor.number !== "number") + throw Error("missing field id"); + + // Rewire field type + var fieldType; + if (descriptor.typeName && descriptor.typeName.length) + fieldType = descriptor.typeName; + else + fieldType = fromDescriptorType(descriptor.type); + + // Rewire field rule + var fieldRule; + switch (descriptor.label) { + // 0 is reserved for errors + case 1: fieldRule = undefined; break; + case 2: fieldRule = "required"; break; + case 3: fieldRule = "repeated"; break; + default: throw Error("illegal label: " + descriptor.label); + } + + var extendee = descriptor.extendee; + if (descriptor.extendee !== undefined) { + extendee = extendee.length ? extendee : undefined; + } + var field = new Field( + descriptor.name.length ? descriptor.name : "field" + descriptor.number, + descriptor.number, + fieldType, + fieldRule, + extendee + ); + + field.options = fromDescriptorOptions(descriptor.options, exports.FieldOptions); + + if (descriptor.defaultValue && descriptor.defaultValue.length) { + var defaultValue = descriptor.defaultValue; + switch (defaultValue) { + case "true": case "TRUE": + defaultValue = true; + break; + case "false": case "FALSE": + defaultValue = false; + break; + default: + var match = numberRe.exec(defaultValue); + if (match) + defaultValue = parseInt(defaultValue); // eslint-disable-line radix + break; + } + field.setOption("default", defaultValue); + } + + if (packableDescriptorType(descriptor.type)) { + if (syntax === "proto3") { // defaults to packed=true (internal preset is packed=true) + if (descriptor.options && !descriptor.options.packed) + field.setOption("packed", false); + } else if (!(descriptor.options && descriptor.options.packed)) // defaults to packed=false + field.setOption("packed", false); + } + + return field; +}; + +/** + * Converts a field to a descriptor. + * @returns {Message} Descriptor + * @param {string} [syntax="proto2"] Syntax + */ +Field.prototype.toDescriptor = function toDescriptor(syntax) { + var descriptor = exports.FieldDescriptorProto.create({ name: this.name, number: this.id }); + + if (this.map) { + + descriptor.type = 11; // message + descriptor.typeName = $protobuf.util.ucFirst(this.name); // fieldName -> FieldNameEntry (built in Type#toDescriptor) + descriptor.label = 3; // repeated + + } else { + + // Rewire field type + switch (descriptor.type = toDescriptorType(this.type, this.resolve().resolvedType)) { + case 10: // group + case 11: // type + case 14: // enum + descriptor.typeName = this.resolvedType ? shortname(this.parent, this.resolvedType) : this.type; + break; + } + + // Rewire field rule + switch (this.rule) { + case "repeated": descriptor.label = 3; break; + case "required": descriptor.label = 2; break; + default: descriptor.label = 1; break; + } + + } + + // Handle extension field + descriptor.extendee = this.extensionField ? this.extensionField.parent.fullName : this.extend; + + // Handle part of oneof + if (this.partOf) + if ((descriptor.oneofIndex = this.parent.oneofsArray.indexOf(this.partOf)) < 0) + throw Error("missing oneof"); + + if (this.options) { + descriptor.options = toDescriptorOptions(this.options, exports.FieldOptions); + if (this.options["default"] != null) + descriptor.defaultValue = String(this.options["default"]); + } + + if (syntax === "proto3") { // defaults to packed=true + if (!this.packed) + (descriptor.options || (descriptor.options = exports.FieldOptions.create())).packed = false; + } else if (this.packed) // defaults to packed=false + (descriptor.options || (descriptor.options = exports.FieldOptions.create())).packed = true; + + return descriptor; +}; + +// --- Enum --- + +/** + * Properties of an EnumDescriptorProto message. + * @interface IEnumDescriptorProto + * @property {string} [name] Enum name + * @property {IEnumValueDescriptorProto[]} [value] Enum values + * @property {IEnumOptions} [options] Enum options + */ + +/** + * Properties of an EnumValueDescriptorProto message. + * @interface IEnumValueDescriptorProto + * @property {string} [name] Name + * @property {number} [number] Value + * @property {*} [options] Not supported + */ + +/** + * Properties of an EnumOptions message. + * @interface IEnumOptions + * @property {boolean} [allowAlias] Whether aliases are allowed + * @property {boolean} [deprecated] + */ + +var unnamedEnumIndex = 0; + +/** + * Creates an enum from a descriptor. + * @param {IEnumDescriptorProto|Reader|Uint8Array} descriptor Descriptor + * @returns {Enum} Enum instance + */ +Enum.fromDescriptor = function fromDescriptor(descriptor) { + + // Decode the descriptor message if specified as a buffer: + if (typeof descriptor.length === "number") + descriptor = exports.EnumDescriptorProto.decode(descriptor); + + // Construct values object + var values = {}; + if (descriptor.value) + for (var i = 0; i < descriptor.value.length; ++i) { + var name = descriptor.value[i].name, + value = descriptor.value[i].number || 0; + values[name && name.length ? name : "NAME" + value] = value; + } + + return new Enum( + descriptor.name && descriptor.name.length ? descriptor.name : "Enum" + unnamedEnumIndex++, + values, + fromDescriptorOptions(descriptor.options, exports.EnumOptions) + ); +}; + +/** + * Converts an enum to a descriptor. + * @returns {Message} Descriptor + */ +Enum.prototype.toDescriptor = function toDescriptor() { + + // Values + var values = []; + for (var i = 0, ks = Object.keys(this.values); i < ks.length; ++i) + values.push(exports.EnumValueDescriptorProto.create({ name: ks[i], number: this.values[ks[i]] })); + + return exports.EnumDescriptorProto.create({ + name: this.name, + value: values, + options: toDescriptorOptions(this.options, exports.EnumOptions) + }); +}; + +// --- OneOf --- + +/** + * Properties of a OneofDescriptorProto message. + * @interface IOneofDescriptorProto + * @property {string} [name] Oneof name + * @property {*} [options] Not supported + */ + +var unnamedOneofIndex = 0; + +/** + * Creates a oneof from a descriptor. + * @param {IOneofDescriptorProto|Reader|Uint8Array} descriptor Descriptor + * @returns {OneOf} OneOf instance + */ +OneOf.fromDescriptor = function fromDescriptor(descriptor) { + + // Decode the descriptor message if specified as a buffer: + if (typeof descriptor.length === "number") + descriptor = exports.OneofDescriptorProto.decode(descriptor); + + return new OneOf( + // unnamedOneOfIndex is global, not per type, because we have no ref to a type here + descriptor.name && descriptor.name.length ? descriptor.name : "oneof" + unnamedOneofIndex++ + // fromDescriptorOptions(descriptor.options, exports.OneofOptions) - only uninterpreted_option + ); +}; + +/** + * Converts a oneof to a descriptor. + * @returns {Message} Descriptor + */ +OneOf.prototype.toDescriptor = function toDescriptor() { + return exports.OneofDescriptorProto.create({ + name: this.name + // options: toDescriptorOptions(this.options, exports.OneofOptions) - only uninterpreted_option + }); +}; + +// --- Service --- + +/** + * Properties of a ServiceDescriptorProto message. + * @interface IServiceDescriptorProto + * @property {string} [name] Service name + * @property {IMethodDescriptorProto[]} [method] Methods + * @property {IServiceOptions} [options] Options + */ + +/** + * Properties of a ServiceOptions message. + * @interface IServiceOptions + * @property {boolean} [deprecated] + */ + +var unnamedServiceIndex = 0; + +/** + * Creates a service from a descriptor. + * @param {IServiceDescriptorProto|Reader|Uint8Array} descriptor Descriptor + * @returns {Service} Service instance + */ +Service.fromDescriptor = function fromDescriptor(descriptor) { + + // Decode the descriptor message if specified as a buffer: + if (typeof descriptor.length === "number") + descriptor = exports.ServiceDescriptorProto.decode(descriptor); + + var service = new Service(descriptor.name && descriptor.name.length ? descriptor.name : "Service" + unnamedServiceIndex++, fromDescriptorOptions(descriptor.options, exports.ServiceOptions)); + if (descriptor.method) + for (var i = 0; i < descriptor.method.length; ++i) + service.add(Method.fromDescriptor(descriptor.method[i])); + + return service; +}; + +/** + * Converts a service to a descriptor. + * @returns {Message} Descriptor + */ +Service.prototype.toDescriptor = function toDescriptor() { + + // Methods + var methods = []; + for (var i = 0; i < this.methodsArray.length; ++i) + methods.push(this._methodsArray[i].toDescriptor()); + + return exports.ServiceDescriptorProto.create({ + name: this.name, + method: methods, + options: toDescriptorOptions(this.options, exports.ServiceOptions) + }); +}; + +// --- Method --- + +/** + * Properties of a MethodDescriptorProto message. + * @interface IMethodDescriptorProto + * @property {string} [name] Method name + * @property {string} [inputType] Request type name + * @property {string} [outputType] Response type name + * @property {IMethodOptions} [options] Not supported + * @property {boolean} [clientStreaming=false] Whether requests are streamed + * @property {boolean} [serverStreaming=false] Whether responses are streamed + */ + +/** + * Properties of a MethodOptions message. + * @interface IMethodOptions + * @property {boolean} [deprecated] + */ + +var unnamedMethodIndex = 0; + +/** + * Creates a method from a descriptor. + * @param {IMethodDescriptorProto|Reader|Uint8Array} descriptor Descriptor + * @returns {Method} Reflected method instance + */ +Method.fromDescriptor = function fromDescriptor(descriptor) { + + // Decode the descriptor message if specified as a buffer: + if (typeof descriptor.length === "number") + descriptor = exports.MethodDescriptorProto.decode(descriptor); + + return new Method( + // unnamedMethodIndex is global, not per service, because we have no ref to a service here + descriptor.name && descriptor.name.length ? descriptor.name : "Method" + unnamedMethodIndex++, + "rpc", + descriptor.inputType, + descriptor.outputType, + Boolean(descriptor.clientStreaming), + Boolean(descriptor.serverStreaming), + fromDescriptorOptions(descriptor.options, exports.MethodOptions) + ); +}; + +/** + * Converts a method to a descriptor. + * @returns {Message} Descriptor + */ +Method.prototype.toDescriptor = function toDescriptor() { + return exports.MethodDescriptorProto.create({ + name: this.name, + inputType: this.resolvedRequestType ? this.resolvedRequestType.fullName : this.requestType, + outputType: this.resolvedResponseType ? this.resolvedResponseType.fullName : this.responseType, + clientStreaming: this.requestStream, + serverStreaming: this.responseStream, + options: toDescriptorOptions(this.options, exports.MethodOptions) + }); +}; + +// --- utility --- + +// Converts a descriptor type to a protobuf.js basic type +function fromDescriptorType(type) { + switch (type) { + // 0 is reserved for errors + case 1: return "double"; + case 2: return "float"; + case 3: return "int64"; + case 4: return "uint64"; + case 5: return "int32"; + case 6: return "fixed64"; + case 7: return "fixed32"; + case 8: return "bool"; + case 9: return "string"; + case 12: return "bytes"; + case 13: return "uint32"; + case 15: return "sfixed32"; + case 16: return "sfixed64"; + case 17: return "sint32"; + case 18: return "sint64"; + } + throw Error("illegal type: " + type); +} + +// Tests if a descriptor type is packable +function packableDescriptorType(type) { + switch (type) { + case 1: // double + case 2: // float + case 3: // int64 + case 4: // uint64 + case 5: // int32 + case 6: // fixed64 + case 7: // fixed32 + case 8: // bool + case 13: // uint32 + case 14: // enum (!) + case 15: // sfixed32 + case 16: // sfixed64 + case 17: // sint32 + case 18: // sint64 + return true; + } + return false; +} + +// Converts a protobuf.js basic type to a descriptor type +function toDescriptorType(type, resolvedType) { + switch (type) { + // 0 is reserved for errors + case "double": return 1; + case "float": return 2; + case "int64": return 3; + case "uint64": return 4; + case "int32": return 5; + case "fixed64": return 6; + case "fixed32": return 7; + case "bool": return 8; + case "string": return 9; + case "bytes": return 12; + case "uint32": return 13; + case "sfixed32": return 15; + case "sfixed64": return 16; + case "sint32": return 17; + case "sint64": return 18; + } + if (resolvedType instanceof Enum) + return 14; + if (resolvedType instanceof Type) + return resolvedType.group ? 10 : 11; + throw Error("illegal type: " + type); +} + +// Converts descriptor options to an options object +function fromDescriptorOptions(options, type) { + if (!options) + return undefined; + var out = []; + for (var i = 0, field, key, val; i < type.fieldsArray.length; ++i) + if ((key = (field = type._fieldsArray[i]).name) !== "uninterpretedOption") + if (options.hasOwnProperty(key)) { // eslint-disable-line no-prototype-builtins + val = options[key]; + if (field.resolvedType instanceof Enum && typeof val === "number" && field.resolvedType.valuesById[val] !== undefined) + val = field.resolvedType.valuesById[val]; + out.push(underScore(key), val); + } + return out.length ? $protobuf.util.toObject(out) : undefined; +} + +// Converts an options object to descriptor options +function toDescriptorOptions(options, type) { + if (!options) + return undefined; + var out = []; + for (var i = 0, ks = Object.keys(options), key, val; i < ks.length; ++i) { + val = options[key = ks[i]]; + if (key === "default") + continue; + var field = type.fields[key]; + if (!field && !(field = type.fields[key = $protobuf.util.camelCase(key)])) + continue; + out.push(key, val); + } + return out.length ? type.fromObject($protobuf.util.toObject(out)) : undefined; +} + +// Calculates the shortest relative path from `from` to `to`. +function shortname(from, to) { + var fromPath = from.fullName.split("."), + toPath = to.fullName.split("."), + i = 0, + j = 0, + k = toPath.length - 1; + if (!(from instanceof Root) && to instanceof Namespace) + while (i < fromPath.length && j < k && fromPath[i] === toPath[j]) { + var other = to.lookup(fromPath[i++], true); + if (other !== null && other !== to) + break; + ++j; + } + else + for (; i < fromPath.length && j < k && fromPath[i] === toPath[j]; ++i, ++j); + return toPath.slice(j).join("."); +} + +// copied here from cli/targets/proto.js +function underScore(str) { + return str.substring(0,1) + + str.substring(1) + .replace(/([A-Z])(?=[a-z]|$)/g, function($0, $1) { return "_" + $1.toLowerCase(); }); +} + +// --- exports --- + +/** + * Reflected file descriptor set. + * @name FileDescriptorSet + * @type {Type} + * @const + * @tstype $protobuf.Type + */ + +/** + * Reflected file descriptor proto. + * @name FileDescriptorProto + * @type {Type} + * @const + * @tstype $protobuf.Type + */ + +/** + * Reflected descriptor proto. + * @name DescriptorProto + * @type {Type} + * @property {Type} ExtensionRange + * @property {Type} ReservedRange + * @const + * @tstype $protobuf.Type & { + * ExtensionRange: $protobuf.Type, + * ReservedRange: $protobuf.Type + * } + */ + +/** + * Reflected field descriptor proto. + * @name FieldDescriptorProto + * @type {Type} + * @property {Enum} Label + * @property {Enum} Type + * @const + * @tstype $protobuf.Type & { + * Label: $protobuf.Enum, + * Type: $protobuf.Enum + * } + */ + +/** + * Reflected oneof descriptor proto. + * @name OneofDescriptorProto + * @type {Type} + * @const + * @tstype $protobuf.Type + */ + +/** + * Reflected enum descriptor proto. + * @name EnumDescriptorProto + * @type {Type} + * @const + * @tstype $protobuf.Type + */ + +/** + * Reflected service descriptor proto. + * @name ServiceDescriptorProto + * @type {Type} + * @const + * @tstype $protobuf.Type + */ + +/** + * Reflected enum value descriptor proto. + * @name EnumValueDescriptorProto + * @type {Type} + * @const + * @tstype $protobuf.Type + */ + +/** + * Reflected method descriptor proto. + * @name MethodDescriptorProto + * @type {Type} + * @const + * @tstype $protobuf.Type + */ + +/** + * Reflected file options. + * @name FileOptions + * @type {Type} + * @property {Enum} OptimizeMode + * @const + * @tstype $protobuf.Type & { + * OptimizeMode: $protobuf.Enum + * } + */ + +/** + * Reflected message options. + * @name MessageOptions + * @type {Type} + * @const + * @tstype $protobuf.Type + */ + +/** + * Reflected field options. + * @name FieldOptions + * @type {Type} + * @property {Enum} CType + * @property {Enum} JSType + * @const + * @tstype $protobuf.Type & { + * CType: $protobuf.Enum, + * JSType: $protobuf.Enum + * } + */ + +/** + * Reflected oneof options. + * @name OneofOptions + * @type {Type} + * @const + * @tstype $protobuf.Type + */ + +/** + * Reflected enum options. + * @name EnumOptions + * @type {Type} + * @const + * @tstype $protobuf.Type + */ + +/** + * Reflected enum value options. + * @name EnumValueOptions + * @type {Type} + * @const + * @tstype $protobuf.Type + */ + +/** + * Reflected service options. + * @name ServiceOptions + * @type {Type} + * @const + * @tstype $protobuf.Type + */ + +/** + * Reflected method options. + * @name MethodOptions + * @type {Type} + * @const + * @tstype $protobuf.Type + */ + +/** + * Reflected uninterpretet option. + * @name UninterpretedOption + * @type {Type} + * @property {Type} NamePart + * @const + * @tstype $protobuf.Type & { + * NamePart: $protobuf.Type + * } + */ + +/** + * Reflected source code info. + * @name SourceCodeInfo + * @type {Type} + * @property {Type} Location + * @const + * @tstype $protobuf.Type & { + * Location: $protobuf.Type + * } + */ + +/** + * Reflected generated code info. + * @name GeneratedCodeInfo + * @type {Type} + * @property {Type} Annotation + * @const + * @tstype $protobuf.Type & { + * Annotation: $protobuf.Type + * } + */ diff --git a/node_modules/protobufjs/ext/descriptor/test.js b/node_modules/protobufjs/ext/descriptor/test.js new file mode 100644 index 0000000..ceb80f8 --- /dev/null +++ b/node_modules/protobufjs/ext/descriptor/test.js @@ -0,0 +1,54 @@ +/*eslint-disable no-console*/ +"use strict"; +var protobuf = require("../../"), + descriptor = require("."); + +/* var proto = { + nested: { + Message: { + fields: { + foo: { + type: "string", + id: 1 + } + }, + nested: { + SubMessage: { + fields: {} + } + } + }, + Enum: { + values: { + ONE: 1, + TWO: 2 + } + } + } +}; */ + +// var root = protobuf.Root.fromJSON(proto).resolveAll(); +var root = protobuf.loadSync("tests/data/google/protobuf/descriptor.proto").resolveAll(); + +// console.log("Original proto", JSON.stringify(root, null, 2)); + +var msg = root.toDescriptor(); + +// console.log("\nDescriptor", JSON.stringify(msg.toObject(), null, 2)); + +var buf = descriptor.FileDescriptorSet.encode(msg).finish(); +var root2 = protobuf.Root.fromDescriptor(buf, "proto2").resolveAll(); + +// console.log("\nDecoded proto", JSON.stringify(root2, null, 2)); + +var diff = require("deep-diff").diff(root.toJSON(), root2.toJSON()); +if (diff) { + diff.forEach(function(diff) { + console.log(diff.kind + " @ " + diff.path.join(".")); + console.log("lhs:", typeof diff.lhs, diff.lhs); + console.log("rhs:", typeof diff.rhs, diff.rhs); + console.log(); + }); + process.exitCode = 1; +} else + console.log("no differences"); diff --git a/node_modules/protobufjs/google/LICENSE b/node_modules/protobufjs/google/LICENSE new file mode 100644 index 0000000..868bd40 --- /dev/null +++ b/node_modules/protobufjs/google/LICENSE @@ -0,0 +1,27 @@ +Copyright 2014, Google Inc. All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are +met: + + * Redistributions of source code must retain the above copyright +notice, this list of conditions and the following disclaimer. + * Redistributions in binary form must reproduce the above +copyright notice, this list of conditions and the following disclaimer +in the documentation and/or other materials provided with the +distribution. + * Neither the name of Google Inc. nor the names of its +contributors may be used to endorse or promote products derived from +this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/node_modules/protobufjs/google/README.md b/node_modules/protobufjs/google/README.md new file mode 100644 index 0000000..09e3f23 --- /dev/null +++ b/node_modules/protobufjs/google/README.md @@ -0,0 +1 @@ +This folder contains stripped and pre-parsed definitions of common Google types. These files are not used by protobuf.js directly but are here so you can use or include them where required. diff --git a/node_modules/protobufjs/google/api/annotations.json b/node_modules/protobufjs/google/api/annotations.json new file mode 100644 index 0000000..3f13a73 --- /dev/null +++ b/node_modules/protobufjs/google/api/annotations.json @@ -0,0 +1,83 @@ +{ + "nested": { + "google": { + "nested": { + "api": { + "nested": { + "http": { + "type": "HttpRule", + "id": 72295728, + "extend": "google.protobuf.MethodOptions" + }, + "HttpRule": { + "oneofs": { + "pattern": { + "oneof": [ + "get", + "put", + "post", + "delete", + "patch", + "custom" + ] + } + }, + "fields": { + "get": { + "type": "string", + "id": 2 + }, + "put": { + "type": "string", + "id": 3 + }, + "post": { + "type": "string", + "id": 4 + }, + "delete": { + "type": "string", + "id": 5 + }, + "patch": { + "type": "string", + "id": 6 + }, + "custom": { + "type": "CustomHttpPattern", + "id": 8 + }, + "selector": { + "type": "string", + "id": 1 + }, + "body": { + "type": "string", + "id": 7 + }, + "additionalBindings": { + "rule": "repeated", + "type": "HttpRule", + "id": 11 + } + } + } + } + }, + "protobuf": { + "nested": { + "MethodOptions": { + "fields": {}, + "extensions": [ + [ + 1000, + 536870911 + ] + ] + } + } + } + } + } + } +} \ No newline at end of file diff --git a/node_modules/protobufjs/google/api/annotations.proto b/node_modules/protobufjs/google/api/annotations.proto new file mode 100644 index 0000000..63a8eef --- /dev/null +++ b/node_modules/protobufjs/google/api/annotations.proto @@ -0,0 +1,11 @@ +syntax = "proto3"; + +package google.api; + +import "google/api/http.proto"; +import "google/protobuf/descriptor.proto"; + +extend google.protobuf.MethodOptions { + + HttpRule http = 72295728; +} \ No newline at end of file diff --git a/node_modules/protobufjs/google/api/http.json b/node_modules/protobufjs/google/api/http.json new file mode 100644 index 0000000..e3a0f4f --- /dev/null +++ b/node_modules/protobufjs/google/api/http.json @@ -0,0 +1,86 @@ +{ + "nested": { + "google": { + "nested": { + "api": { + "nested": { + "Http": { + "fields": { + "rules": { + "rule": "repeated", + "type": "HttpRule", + "id": 1 + } + } + }, + "HttpRule": { + "oneofs": { + "pattern": { + "oneof": [ + "get", + "put", + "post", + "delete", + "patch", + "custom" + ] + } + }, + "fields": { + "get": { + "type": "string", + "id": 2 + }, + "put": { + "type": "string", + "id": 3 + }, + "post": { + "type": "string", + "id": 4 + }, + "delete": { + "type": "string", + "id": 5 + }, + "patch": { + "type": "string", + "id": 6 + }, + "custom": { + "type": "CustomHttpPattern", + "id": 8 + }, + "selector": { + "type": "string", + "id": 1 + }, + "body": { + "type": "string", + "id": 7 + }, + "additionalBindings": { + "rule": "repeated", + "type": "HttpRule", + "id": 11 + } + } + }, + "CustomHttpPattern": { + "fields": { + "kind": { + "type": "string", + "id": 1 + }, + "path": { + "type": "string", + "id": 2 + } + } + } + } + } + } + } + } +} \ No newline at end of file diff --git a/node_modules/protobufjs/google/api/http.proto b/node_modules/protobufjs/google/api/http.proto new file mode 100644 index 0000000..e9a7e9d --- /dev/null +++ b/node_modules/protobufjs/google/api/http.proto @@ -0,0 +1,31 @@ +syntax = "proto3"; + +package google.api; + +message Http { + + repeated HttpRule rules = 1; +} + +message HttpRule { + + oneof pattern { + + string get = 2; + string put = 3; + string post = 4; + string delete = 5; + string patch = 6; + CustomHttpPattern custom = 8; + } + + string selector = 1; + string body = 7; + repeated HttpRule additional_bindings = 11; +} + +message CustomHttpPattern { + + string kind = 1; + string path = 2; +} \ No newline at end of file diff --git a/node_modules/protobufjs/google/protobuf/api.json b/node_modules/protobufjs/google/protobuf/api.json new file mode 100644 index 0000000..5460612 --- /dev/null +++ b/node_modules/protobufjs/google/protobuf/api.json @@ -0,0 +1,118 @@ +{ + "nested": { + "google": { + "nested": { + "protobuf": { + "nested": { + "Api": { + "fields": { + "name": { + "type": "string", + "id": 1 + }, + "methods": { + "rule": "repeated", + "type": "Method", + "id": 2 + }, + "options": { + "rule": "repeated", + "type": "Option", + "id": 3 + }, + "version": { + "type": "string", + "id": 4 + }, + "sourceContext": { + "type": "SourceContext", + "id": 5 + }, + "mixins": { + "rule": "repeated", + "type": "Mixin", + "id": 6 + }, + "syntax": { + "type": "Syntax", + "id": 7 + } + } + }, + "Method": { + "fields": { + "name": { + "type": "string", + "id": 1 + }, + "requestTypeUrl": { + "type": "string", + "id": 2 + }, + "requestStreaming": { + "type": "bool", + "id": 3 + }, + "responseTypeUrl": { + "type": "string", + "id": 4 + }, + "responseStreaming": { + "type": "bool", + "id": 5 + }, + "options": { + "rule": "repeated", + "type": "Option", + "id": 6 + }, + "syntax": { + "type": "Syntax", + "id": 7 + } + } + }, + "Mixin": { + "fields": { + "name": { + "type": "string", + "id": 1 + }, + "root": { + "type": "string", + "id": 2 + } + } + }, + "SourceContext": { + "fields": { + "fileName": { + "type": "string", + "id": 1 + } + } + }, + "Option": { + "fields": { + "name": { + "type": "string", + "id": 1 + }, + "value": { + "type": "Any", + "id": 2 + } + } + }, + "Syntax": { + "values": { + "SYNTAX_PROTO2": 0, + "SYNTAX_PROTO3": 1 + } + } + } + } + } + } + } +} \ No newline at end of file diff --git a/node_modules/protobufjs/google/protobuf/api.proto b/node_modules/protobufjs/google/protobuf/api.proto new file mode 100644 index 0000000..cf6ae3f --- /dev/null +++ b/node_modules/protobufjs/google/protobuf/api.proto @@ -0,0 +1,34 @@ +syntax = "proto3"; + +package google.protobuf; + +import "google/protobuf/source_context.proto"; +import "google/protobuf/type.proto"; + +message Api { + + string name = 1; + repeated Method methods = 2; + repeated Option options = 3; + string version = 4; + SourceContext source_context = 5; + repeated Mixin mixins = 6; + Syntax syntax = 7; +} + +message Method { + + string name = 1; + string request_type_url = 2; + bool request_streaming = 3; + string response_type_url = 4; + bool response_streaming = 5; + repeated Option options = 6; + Syntax syntax = 7; +} + +message Mixin { + + string name = 1; + string root = 2; +} \ No newline at end of file diff --git a/node_modules/protobufjs/google/protobuf/descriptor.json b/node_modules/protobufjs/google/protobuf/descriptor.json new file mode 100644 index 0000000..f6c5c11 --- /dev/null +++ b/node_modules/protobufjs/google/protobuf/descriptor.json @@ -0,0 +1,739 @@ +{ + "nested": { + "google": { + "nested": { + "protobuf": { + "nested": { + "FileDescriptorSet": { + "fields": { + "file": { + "rule": "repeated", + "type": "FileDescriptorProto", + "id": 1 + } + } + }, + "FileDescriptorProto": { + "fields": { + "name": { + "type": "string", + "id": 1 + }, + "package": { + "type": "string", + "id": 2 + }, + "dependency": { + "rule": "repeated", + "type": "string", + "id": 3 + }, + "publicDependency": { + "rule": "repeated", + "type": "int32", + "id": 10, + "options": { + "packed": false + } + }, + "weakDependency": { + "rule": "repeated", + "type": "int32", + "id": 11, + "options": { + "packed": false + } + }, + "messageType": { + "rule": "repeated", + "type": "DescriptorProto", + "id": 4 + }, + "enumType": { + "rule": "repeated", + "type": "EnumDescriptorProto", + "id": 5 + }, + "service": { + "rule": "repeated", + "type": "ServiceDescriptorProto", + "id": 6 + }, + "extension": { + "rule": "repeated", + "type": "FieldDescriptorProto", + "id": 7 + }, + "options": { + "type": "FileOptions", + "id": 8 + }, + "sourceCodeInfo": { + "type": "SourceCodeInfo", + "id": 9 + }, + "syntax": { + "type": "string", + "id": 12 + } + } + }, + "DescriptorProto": { + "fields": { + "name": { + "type": "string", + "id": 1 + }, + "field": { + "rule": "repeated", + "type": "FieldDescriptorProto", + "id": 2 + }, + "extension": { + "rule": "repeated", + "type": "FieldDescriptorProto", + "id": 6 + }, + "nestedType": { + "rule": "repeated", + "type": "DescriptorProto", + "id": 3 + }, + "enumType": { + "rule": "repeated", + "type": "EnumDescriptorProto", + "id": 4 + }, + "extensionRange": { + "rule": "repeated", + "type": "ExtensionRange", + "id": 5 + }, + "oneofDecl": { + "rule": "repeated", + "type": "OneofDescriptorProto", + "id": 8 + }, + "options": { + "type": "MessageOptions", + "id": 7 + }, + "reservedRange": { + "rule": "repeated", + "type": "ReservedRange", + "id": 9 + }, + "reservedName": { + "rule": "repeated", + "type": "string", + "id": 10 + } + }, + "nested": { + "ExtensionRange": { + "fields": { + "start": { + "type": "int32", + "id": 1 + }, + "end": { + "type": "int32", + "id": 2 + } + } + }, + "ReservedRange": { + "fields": { + "start": { + "type": "int32", + "id": 1 + }, + "end": { + "type": "int32", + "id": 2 + } + } + } + } + }, + "FieldDescriptorProto": { + "fields": { + "name": { + "type": "string", + "id": 1 + }, + "number": { + "type": "int32", + "id": 3 + }, + "label": { + "type": "Label", + "id": 4 + }, + "type": { + "type": "Type", + "id": 5 + }, + "typeName": { + "type": "string", + "id": 6 + }, + "extendee": { + "type": "string", + "id": 2 + }, + "defaultValue": { + "type": "string", + "id": 7 + }, + "oneofIndex": { + "type": "int32", + "id": 9 + }, + "jsonName": { + "type": "string", + "id": 10 + }, + "options": { + "type": "FieldOptions", + "id": 8 + } + }, + "nested": { + "Type": { + "values": { + "TYPE_DOUBLE": 1, + "TYPE_FLOAT": 2, + "TYPE_INT64": 3, + "TYPE_UINT64": 4, + "TYPE_INT32": 5, + "TYPE_FIXED64": 6, + "TYPE_FIXED32": 7, + "TYPE_BOOL": 8, + "TYPE_STRING": 9, + "TYPE_GROUP": 10, + "TYPE_MESSAGE": 11, + "TYPE_BYTES": 12, + "TYPE_UINT32": 13, + "TYPE_ENUM": 14, + "TYPE_SFIXED32": 15, + "TYPE_SFIXED64": 16, + "TYPE_SINT32": 17, + "TYPE_SINT64": 18 + } + }, + "Label": { + "values": { + "LABEL_OPTIONAL": 1, + "LABEL_REQUIRED": 2, + "LABEL_REPEATED": 3 + } + } + } + }, + "OneofDescriptorProto": { + "fields": { + "name": { + "type": "string", + "id": 1 + }, + "options": { + "type": "OneofOptions", + "id": 2 + } + } + }, + "EnumDescriptorProto": { + "fields": { + "name": { + "type": "string", + "id": 1 + }, + "value": { + "rule": "repeated", + "type": "EnumValueDescriptorProto", + "id": 2 + }, + "options": { + "type": "EnumOptions", + "id": 3 + } + } + }, + "EnumValueDescriptorProto": { + "fields": { + "name": { + "type": "string", + "id": 1 + }, + "number": { + "type": "int32", + "id": 2 + }, + "options": { + "type": "EnumValueOptions", + "id": 3 + } + } + }, + "ServiceDescriptorProto": { + "fields": { + "name": { + "type": "string", + "id": 1 + }, + "method": { + "rule": "repeated", + "type": "MethodDescriptorProto", + "id": 2 + }, + "options": { + "type": "ServiceOptions", + "id": 3 + } + } + }, + "MethodDescriptorProto": { + "fields": { + "name": { + "type": "string", + "id": 1 + }, + "inputType": { + "type": "string", + "id": 2 + }, + "outputType": { + "type": "string", + "id": 3 + }, + "options": { + "type": "MethodOptions", + "id": 4 + }, + "clientStreaming": { + "type": "bool", + "id": 5 + }, + "serverStreaming": { + "type": "bool", + "id": 6 + } + } + }, + "FileOptions": { + "fields": { + "javaPackage": { + "type": "string", + "id": 1 + }, + "javaOuterClassname": { + "type": "string", + "id": 8 + }, + "javaMultipleFiles": { + "type": "bool", + "id": 10 + }, + "javaGenerateEqualsAndHash": { + "type": "bool", + "id": 20, + "options": { + "deprecated": true + } + }, + "javaStringCheckUtf8": { + "type": "bool", + "id": 27 + }, + "optimizeFor": { + "type": "OptimizeMode", + "id": 9, + "options": { + "default": "SPEED" + } + }, + "goPackage": { + "type": "string", + "id": 11 + }, + "ccGenericServices": { + "type": "bool", + "id": 16 + }, + "javaGenericServices": { + "type": "bool", + "id": 17 + }, + "pyGenericServices": { + "type": "bool", + "id": 18 + }, + "deprecated": { + "type": "bool", + "id": 23 + }, + "ccEnableArenas": { + "type": "bool", + "id": 31 + }, + "objcClassPrefix": { + "type": "string", + "id": 36 + }, + "csharpNamespace": { + "type": "string", + "id": 37 + }, + "uninterpretedOption": { + "rule": "repeated", + "type": "UninterpretedOption", + "id": 999 + } + }, + "extensions": [ + [ + 1000, + 536870911 + ] + ], + "reserved": [ + [ + 38, + 38 + ] + ], + "nested": { + "OptimizeMode": { + "values": { + "SPEED": 1, + "CODE_SIZE": 2, + "LITE_RUNTIME": 3 + } + } + } + }, + "MessageOptions": { + "fields": { + "messageSetWireFormat": { + "type": "bool", + "id": 1 + }, + "noStandardDescriptorAccessor": { + "type": "bool", + "id": 2 + }, + "deprecated": { + "type": "bool", + "id": 3 + }, + "mapEntry": { + "type": "bool", + "id": 7 + }, + "uninterpretedOption": { + "rule": "repeated", + "type": "UninterpretedOption", + "id": 999 + } + }, + "extensions": [ + [ + 1000, + 536870911 + ] + ], + "reserved": [ + [ + 8, + 8 + ] + ] + }, + "FieldOptions": { + "fields": { + "ctype": { + "type": "CType", + "id": 1, + "options": { + "default": "STRING" + } + }, + "packed": { + "type": "bool", + "id": 2 + }, + "jstype": { + "type": "JSType", + "id": 6, + "options": { + "default": "JS_NORMAL" + } + }, + "lazy": { + "type": "bool", + "id": 5 + }, + "deprecated": { + "type": "bool", + "id": 3 + }, + "weak": { + "type": "bool", + "id": 10 + }, + "uninterpretedOption": { + "rule": "repeated", + "type": "UninterpretedOption", + "id": 999 + } + }, + "extensions": [ + [ + 1000, + 536870911 + ] + ], + "reserved": [ + [ + 4, + 4 + ] + ], + "nested": { + "CType": { + "values": { + "STRING": 0, + "CORD": 1, + "STRING_PIECE": 2 + } + }, + "JSType": { + "values": { + "JS_NORMAL": 0, + "JS_STRING": 1, + "JS_NUMBER": 2 + } + } + } + }, + "OneofOptions": { + "fields": { + "uninterpretedOption": { + "rule": "repeated", + "type": "UninterpretedOption", + "id": 999 + } + }, + "extensions": [ + [ + 1000, + 536870911 + ] + ] + }, + "EnumOptions": { + "fields": { + "allowAlias": { + "type": "bool", + "id": 2 + }, + "deprecated": { + "type": "bool", + "id": 3 + }, + "uninterpretedOption": { + "rule": "repeated", + "type": "UninterpretedOption", + "id": 999 + } + }, + "extensions": [ + [ + 1000, + 536870911 + ] + ] + }, + "EnumValueOptions": { + "fields": { + "deprecated": { + "type": "bool", + "id": 1 + }, + "uninterpretedOption": { + "rule": "repeated", + "type": "UninterpretedOption", + "id": 999 + } + }, + "extensions": [ + [ + 1000, + 536870911 + ] + ] + }, + "ServiceOptions": { + "fields": { + "deprecated": { + "type": "bool", + "id": 33 + }, + "uninterpretedOption": { + "rule": "repeated", + "type": "UninterpretedOption", + "id": 999 + } + }, + "extensions": [ + [ + 1000, + 536870911 + ] + ] + }, + "MethodOptions": { + "fields": { + "deprecated": { + "type": "bool", + "id": 33 + }, + "uninterpretedOption": { + "rule": "repeated", + "type": "UninterpretedOption", + "id": 999 + } + }, + "extensions": [ + [ + 1000, + 536870911 + ] + ] + }, + "UninterpretedOption": { + "fields": { + "name": { + "rule": "repeated", + "type": "NamePart", + "id": 2 + }, + "identifierValue": { + "type": "string", + "id": 3 + }, + "positiveIntValue": { + "type": "uint64", + "id": 4 + }, + "negativeIntValue": { + "type": "int64", + "id": 5 + }, + "doubleValue": { + "type": "double", + "id": 6 + }, + "stringValue": { + "type": "bytes", + "id": 7 + }, + "aggregateValue": { + "type": "string", + "id": 8 + } + }, + "nested": { + "NamePart": { + "fields": { + "namePart": { + "rule": "required", + "type": "string", + "id": 1 + }, + "isExtension": { + "rule": "required", + "type": "bool", + "id": 2 + } + } + } + } + }, + "SourceCodeInfo": { + "fields": { + "location": { + "rule": "repeated", + "type": "Location", + "id": 1 + } + }, + "nested": { + "Location": { + "fields": { + "path": { + "rule": "repeated", + "type": "int32", + "id": 1 + }, + "span": { + "rule": "repeated", + "type": "int32", + "id": 2 + }, + "leadingComments": { + "type": "string", + "id": 3 + }, + "trailingComments": { + "type": "string", + "id": 4 + }, + "leadingDetachedComments": { + "rule": "repeated", + "type": "string", + "id": 6 + } + } + } + } + }, + "GeneratedCodeInfo": { + "fields": { + "annotation": { + "rule": "repeated", + "type": "Annotation", + "id": 1 + } + }, + "nested": { + "Annotation": { + "fields": { + "path": { + "rule": "repeated", + "type": "int32", + "id": 1 + }, + "sourceFile": { + "type": "string", + "id": 2 + }, + "begin": { + "type": "int32", + "id": 3 + }, + "end": { + "type": "int32", + "id": 4 + } + } + } + } + } + } + } + } + } + } +} \ No newline at end of file diff --git a/node_modules/protobufjs/google/protobuf/descriptor.proto b/node_modules/protobufjs/google/protobuf/descriptor.proto new file mode 100644 index 0000000..3279492 --- /dev/null +++ b/node_modules/protobufjs/google/protobuf/descriptor.proto @@ -0,0 +1,286 @@ +syntax = "proto2"; + +package google.protobuf; + +message FileDescriptorSet { + + repeated FileDescriptorProto file = 1; +} + +message FileDescriptorProto { + + optional string name = 1; + optional string package = 2; + repeated string dependency = 3; + repeated int32 public_dependency = 10; + repeated int32 weak_dependency = 11; + repeated DescriptorProto message_type = 4; + repeated EnumDescriptorProto enum_type = 5; + repeated ServiceDescriptorProto service = 6; + repeated FieldDescriptorProto extension = 7; + optional FileOptions options = 8; + optional SourceCodeInfo source_code_info = 9; + optional string syntax = 12; +} + +message DescriptorProto { + + optional string name = 1; + repeated FieldDescriptorProto field = 2; + repeated FieldDescriptorProto extension = 6; + repeated DescriptorProto nested_type = 3; + repeated EnumDescriptorProto enum_type = 4; + repeated ExtensionRange extension_range = 5; + repeated OneofDescriptorProto oneof_decl = 8; + optional MessageOptions options = 7; + repeated ReservedRange reserved_range = 9; + repeated string reserved_name = 10; + + message ExtensionRange { + + optional int32 start = 1; + optional int32 end = 2; + } + + message ReservedRange { + + optional int32 start = 1; + optional int32 end = 2; + } +} + +message FieldDescriptorProto { + + optional string name = 1; + optional int32 number = 3; + optional Label label = 4; + optional Type type = 5; + optional string type_name = 6; + optional string extendee = 2; + optional string default_value = 7; + optional int32 oneof_index = 9; + optional string json_name = 10; + optional FieldOptions options = 8; + + enum Type { + + TYPE_DOUBLE = 1; + TYPE_FLOAT = 2; + TYPE_INT64 = 3; + TYPE_UINT64 = 4; + TYPE_INT32 = 5; + TYPE_FIXED64 = 6; + TYPE_FIXED32 = 7; + TYPE_BOOL = 8; + TYPE_STRING = 9; + TYPE_GROUP = 10; + TYPE_MESSAGE = 11; + TYPE_BYTES = 12; + TYPE_UINT32 = 13; + TYPE_ENUM = 14; + TYPE_SFIXED32 = 15; + TYPE_SFIXED64 = 16; + TYPE_SINT32 = 17; + TYPE_SINT64 = 18; + } + + enum Label { + + LABEL_OPTIONAL = 1; + LABEL_REQUIRED = 2; + LABEL_REPEATED = 3; + } +} + +message OneofDescriptorProto { + + optional string name = 1; + optional OneofOptions options = 2; +} + +message EnumDescriptorProto { + + optional string name = 1; + repeated EnumValueDescriptorProto value = 2; + optional EnumOptions options = 3; +} + +message EnumValueDescriptorProto { + + optional string name = 1; + optional int32 number = 2; + optional EnumValueOptions options = 3; +} + +message ServiceDescriptorProto { + + optional string name = 1; + repeated MethodDescriptorProto method = 2; + optional ServiceOptions options = 3; +} + +message MethodDescriptorProto { + + optional string name = 1; + optional string input_type = 2; + optional string output_type = 3; + optional MethodOptions options = 4; + optional bool client_streaming = 5; + optional bool server_streaming = 6; +} + +message FileOptions { + + optional string java_package = 1; + optional string java_outer_classname = 8; + optional bool java_multiple_files = 10; + optional bool java_generate_equals_and_hash = 20 [deprecated=true]; + optional bool java_string_check_utf8 = 27; + optional OptimizeMode optimize_for = 9 [default=SPEED]; + optional string go_package = 11; + optional bool cc_generic_services = 16; + optional bool java_generic_services = 17; + optional bool py_generic_services = 18; + optional bool deprecated = 23; + optional bool cc_enable_arenas = 31; + optional string objc_class_prefix = 36; + optional string csharp_namespace = 37; + repeated UninterpretedOption uninterpreted_option = 999; + + enum OptimizeMode { + + SPEED = 1; + CODE_SIZE = 2; + LITE_RUNTIME = 3; + } + + extensions 1000 to max; + + reserved 38; +} + +message MessageOptions { + + optional bool message_set_wire_format = 1; + optional bool no_standard_descriptor_accessor = 2; + optional bool deprecated = 3; + optional bool map_entry = 7; + repeated UninterpretedOption uninterpreted_option = 999; + + extensions 1000 to max; + + reserved 8; +} + +message FieldOptions { + + optional CType ctype = 1 [default=STRING]; + optional bool packed = 2; + optional JSType jstype = 6 [default=JS_NORMAL]; + optional bool lazy = 5; + optional bool deprecated = 3; + optional bool weak = 10; + repeated UninterpretedOption uninterpreted_option = 999; + + enum CType { + + STRING = 0; + CORD = 1; + STRING_PIECE = 2; + } + + enum JSType { + + JS_NORMAL = 0; + JS_STRING = 1; + JS_NUMBER = 2; + } + + extensions 1000 to max; + + reserved 4; +} + +message OneofOptions { + + repeated UninterpretedOption uninterpreted_option = 999; + + extensions 1000 to max; +} + +message EnumOptions { + + optional bool allow_alias = 2; + optional bool deprecated = 3; + repeated UninterpretedOption uninterpreted_option = 999; + + extensions 1000 to max; +} + +message EnumValueOptions { + + optional bool deprecated = 1; + repeated UninterpretedOption uninterpreted_option = 999; + + extensions 1000 to max; +} + +message ServiceOptions { + + optional bool deprecated = 33; + repeated UninterpretedOption uninterpreted_option = 999; + + extensions 1000 to max; +} + +message MethodOptions { + + optional bool deprecated = 33; + repeated UninterpretedOption uninterpreted_option = 999; + + extensions 1000 to max; +} + +message UninterpretedOption { + + repeated NamePart name = 2; + optional string identifier_value = 3; + optional uint64 positive_int_value = 4; + optional int64 negative_int_value = 5; + optional double double_value = 6; + optional bytes string_value = 7; + optional string aggregate_value = 8; + + message NamePart { + + required string name_part = 1; + required bool is_extension = 2; + } +} + +message SourceCodeInfo { + + repeated Location location = 1; + + message Location { + + repeated int32 path = 1 [packed=true]; + repeated int32 span = 2 [packed=true]; + optional string leading_comments = 3; + optional string trailing_comments = 4; + repeated string leading_detached_comments = 6; + } +} + +message GeneratedCodeInfo { + + repeated Annotation annotation = 1; + + message Annotation { + + repeated int32 path = 1 [packed=true]; + optional string source_file = 2; + optional int32 begin = 3; + optional int32 end = 4; + } +} diff --git a/node_modules/protobufjs/google/protobuf/source_context.json b/node_modules/protobufjs/google/protobuf/source_context.json new file mode 100644 index 0000000..51adb63 --- /dev/null +++ b/node_modules/protobufjs/google/protobuf/source_context.json @@ -0,0 +1,20 @@ +{ + "nested": { + "google": { + "nested": { + "protobuf": { + "nested": { + "SourceContext": { + "fields": { + "fileName": { + "type": "string", + "id": 1 + } + } + } + } + } + } + } + } +} \ No newline at end of file diff --git a/node_modules/protobufjs/google/protobuf/source_context.proto b/node_modules/protobufjs/google/protobuf/source_context.proto new file mode 100644 index 0000000..584d36c --- /dev/null +++ b/node_modules/protobufjs/google/protobuf/source_context.proto @@ -0,0 +1,7 @@ +syntax = "proto3"; + +package google.protobuf; + +message SourceContext { + string file_name = 1; +} diff --git a/node_modules/protobufjs/google/protobuf/type.json b/node_modules/protobufjs/google/protobuf/type.json new file mode 100644 index 0000000..fffa70d --- /dev/null +++ b/node_modules/protobufjs/google/protobuf/type.json @@ -0,0 +1,202 @@ +{ + "nested": { + "google": { + "nested": { + "protobuf": { + "nested": { + "Type": { + "fields": { + "name": { + "type": "string", + "id": 1 + }, + "fields": { + "rule": "repeated", + "type": "Field", + "id": 2 + }, + "oneofs": { + "rule": "repeated", + "type": "string", + "id": 3 + }, + "options": { + "rule": "repeated", + "type": "Option", + "id": 4 + }, + "sourceContext": { + "type": "SourceContext", + "id": 5 + }, + "syntax": { + "type": "Syntax", + "id": 6 + } + } + }, + "Field": { + "fields": { + "kind": { + "type": "Kind", + "id": 1 + }, + "cardinality": { + "type": "Cardinality", + "id": 2 + }, + "number": { + "type": "int32", + "id": 3 + }, + "name": { + "type": "string", + "id": 4 + }, + "typeUrl": { + "type": "string", + "id": 6 + }, + "oneofIndex": { + "type": "int32", + "id": 7 + }, + "packed": { + "type": "bool", + "id": 8 + }, + "options": { + "rule": "repeated", + "type": "Option", + "id": 9 + }, + "jsonName": { + "type": "string", + "id": 10 + }, + "defaultValue": { + "type": "string", + "id": 11 + } + }, + "nested": { + "Kind": { + "values": { + "TYPE_UNKNOWN": 0, + "TYPE_DOUBLE": 1, + "TYPE_FLOAT": 2, + "TYPE_INT64": 3, + "TYPE_UINT64": 4, + "TYPE_INT32": 5, + "TYPE_FIXED64": 6, + "TYPE_FIXED32": 7, + "TYPE_BOOL": 8, + "TYPE_STRING": 9, + "TYPE_GROUP": 10, + "TYPE_MESSAGE": 11, + "TYPE_BYTES": 12, + "TYPE_UINT32": 13, + "TYPE_ENUM": 14, + "TYPE_SFIXED32": 15, + "TYPE_SFIXED64": 16, + "TYPE_SINT32": 17, + "TYPE_SINT64": 18 + } + }, + "Cardinality": { + "values": { + "CARDINALITY_UNKNOWN": 0, + "CARDINALITY_OPTIONAL": 1, + "CARDINALITY_REQUIRED": 2, + "CARDINALITY_REPEATED": 3 + } + } + } + }, + "Enum": { + "fields": { + "name": { + "type": "string", + "id": 1 + }, + "enumvalue": { + "rule": "repeated", + "type": "EnumValue", + "id": 2 + }, + "options": { + "rule": "repeated", + "type": "Option", + "id": 3 + }, + "sourceContext": { + "type": "SourceContext", + "id": 4 + }, + "syntax": { + "type": "Syntax", + "id": 5 + } + } + }, + "EnumValue": { + "fields": { + "name": { + "type": "string", + "id": 1 + }, + "number": { + "type": "int32", + "id": 2 + }, + "options": { + "rule": "repeated", + "type": "Option", + "id": 3 + } + } + }, + "Option": { + "fields": { + "name": { + "type": "string", + "id": 1 + }, + "value": { + "type": "Any", + "id": 2 + } + } + }, + "Syntax": { + "values": { + "SYNTAX_PROTO2": 0, + "SYNTAX_PROTO3": 1 + } + }, + "Any": { + "fields": { + "type_url": { + "type": "string", + "id": 1 + }, + "value": { + "type": "bytes", + "id": 2 + } + } + }, + "SourceContext": { + "fields": { + "fileName": { + "type": "string", + "id": 1 + } + } + } + } + } + } + } + } +} \ No newline at end of file diff --git a/node_modules/protobufjs/google/protobuf/type.proto b/node_modules/protobufjs/google/protobuf/type.proto new file mode 100644 index 0000000..8ee445b --- /dev/null +++ b/node_modules/protobufjs/google/protobuf/type.proto @@ -0,0 +1,89 @@ +syntax = "proto3"; + +package google.protobuf; + +import "google/protobuf/any.proto"; +import "google/protobuf/source_context.proto"; + +message Type { + + string name = 1; + repeated Field fields = 2; + repeated string oneofs = 3; + repeated Option options = 4; + SourceContext source_context = 5; + Syntax syntax = 6; +} + +message Field { + + Kind kind = 1; + Cardinality cardinality = 2; + int32 number = 3; + string name = 4; + string type_url = 6; + int32 oneof_index = 7; + bool packed = 8; + repeated Option options = 9; + string json_name = 10; + string default_value = 11; + + enum Kind { + + TYPE_UNKNOWN = 0; + TYPE_DOUBLE = 1; + TYPE_FLOAT = 2; + TYPE_INT64 = 3; + TYPE_UINT64 = 4; + TYPE_INT32 = 5; + TYPE_FIXED64 = 6; + TYPE_FIXED32 = 7; + TYPE_BOOL = 8; + TYPE_STRING = 9; + TYPE_GROUP = 10; + TYPE_MESSAGE = 11; + TYPE_BYTES = 12; + TYPE_UINT32 = 13; + TYPE_ENUM = 14; + TYPE_SFIXED32 = 15; + TYPE_SFIXED64 = 16; + TYPE_SINT32 = 17; + TYPE_SINT64 = 18; + } + + enum Cardinality { + + CARDINALITY_UNKNOWN = 0; + CARDINALITY_OPTIONAL = 1; + CARDINALITY_REQUIRED = 2; + CARDINALITY_REPEATED = 3; + } +} + +message Enum { + + string name = 1; + repeated EnumValue enumvalue = 2; + repeated Option options = 3; + SourceContext source_context = 4; + Syntax syntax = 5; +} + +message EnumValue { + + string name = 1; + int32 number = 2; + repeated Option options = 3; +} + +message Option { + + string name = 1; + Any value = 2; +} + +enum Syntax { + + SYNTAX_PROTO2 = 0; + SYNTAX_PROTO3 = 1; +} diff --git a/node_modules/protobufjs/index.d.ts b/node_modules/protobufjs/index.d.ts new file mode 100644 index 0000000..750ad2f --- /dev/null +++ b/node_modules/protobufjs/index.d.ts @@ -0,0 +1,2741 @@ +// DO NOT EDIT! This is a generated file. Edit the JSDoc in src/*.js instead and run 'npm run build:types'. + +export as namespace protobuf; + +/** + * Provides common type definitions. + * Can also be used to provide additional google types or your own custom types. + * @param name Short name as in `google/protobuf/[name].proto` or full file name + * @param json JSON definition within `google.protobuf` if a short name, otherwise the file's root definition + */ +export function common(name: string, json: { [k: string]: any }): void; + +export namespace common { + + /** Properties of a google.protobuf.Any message. */ + interface IAny { + typeUrl?: string; + bytes?: Uint8Array; + } + + /** Properties of a google.protobuf.Duration message. */ + interface IDuration { + seconds?: (number|Long); + nanos?: number; + } + + /** Properties of a google.protobuf.Timestamp message. */ + interface ITimestamp { + seconds?: (number|Long); + nanos?: number; + } + + /** Properties of a google.protobuf.Empty message. */ + interface IEmpty { + } + + /** Properties of a google.protobuf.Struct message. */ + interface IStruct { + fields?: { [k: string]: IValue }; + } + + /** Properties of a google.protobuf.Value message. */ + interface IValue { + kind?: string; + nullValue?: 0; + numberValue?: number; + stringValue?: string; + boolValue?: boolean; + structValue?: IStruct; + listValue?: IListValue; + } + + /** Properties of a google.protobuf.ListValue message. */ + interface IListValue { + values?: IValue[]; + } + + /** Properties of a google.protobuf.DoubleValue message. */ + interface IDoubleValue { + value?: number; + } + + /** Properties of a google.protobuf.FloatValue message. */ + interface IFloatValue { + value?: number; + } + + /** Properties of a google.protobuf.Int64Value message. */ + interface IInt64Value { + value?: (number|Long); + } + + /** Properties of a google.protobuf.UInt64Value message. */ + interface IUInt64Value { + value?: (number|Long); + } + + /** Properties of a google.protobuf.Int32Value message. */ + interface IInt32Value { + value?: number; + } + + /** Properties of a google.protobuf.UInt32Value message. */ + interface IUInt32Value { + value?: number; + } + + /** Properties of a google.protobuf.BoolValue message. */ + interface IBoolValue { + value?: boolean; + } + + /** Properties of a google.protobuf.StringValue message. */ + interface IStringValue { + value?: string; + } + + /** Properties of a google.protobuf.BytesValue message. */ + interface IBytesValue { + value?: Uint8Array; + } + + /** + * Gets the root definition of the specified common proto file. + * + * Bundled definitions are: + * - google/protobuf/any.proto + * - google/protobuf/duration.proto + * - google/protobuf/empty.proto + * - google/protobuf/field_mask.proto + * - google/protobuf/struct.proto + * - google/protobuf/timestamp.proto + * - google/protobuf/wrappers.proto + * + * @param file Proto file name + * @returns Root definition or `null` if not defined + */ + function get(file: string): (INamespace|null); +} + +/** Runtime message from/to plain object converters. */ +export namespace converter { + + /** + * Generates a plain object to runtime message converter specific to the specified message type. + * @param mtype Message type + * @returns Codegen instance + */ + function fromObject(mtype: Type): Codegen; + + /** + * Generates a runtime message to plain object converter specific to the specified message type. + * @param mtype Message type + * @returns Codegen instance + */ + function toObject(mtype: Type): Codegen; +} + +/** + * Generates a decoder specific to the specified message type. + * @param mtype Message type + * @returns Codegen instance + */ +export function decoder(mtype: Type): Codegen; + +/** + * Generates an encoder specific to the specified message type. + * @param mtype Message type + * @returns Codegen instance + */ +export function encoder(mtype: Type): Codegen; + +/** Reflected enum. */ +export class Enum extends ReflectionObject { + + /** + * Constructs a new enum instance. + * @param name Unique name within its namespace + * @param [values] Enum values as an object, by name + * @param [options] Declared options + * @param [comment] The comment for this enum + * @param [comments] The value comments for this enum + * @param [valuesOptions] The value options for this enum + */ + constructor(name: string, values?: { [k: string]: number }, options?: { [k: string]: any }, comment?: string, comments?: { [k: string]: string }, valuesOptions?: ({ [k: string]: { [k: string]: any } }|undefined)); + + /** Enum values by id. */ + public valuesById: { [k: number]: string }; + + /** Enum values by name. */ + public values: { [k: string]: number }; + + /** Enum comment text. */ + public comment: (string|null); + + /** Value comment texts, if any. */ + public comments: { [k: string]: string }; + + /** Values options, if any */ + public valuesOptions?: { [k: string]: { [k: string]: any } }; + + /** Reserved ranges, if any. */ + public reserved: (number[]|string)[]; + + /** + * Constructs an enum from an enum descriptor. + * @param name Enum name + * @param json Enum descriptor + * @returns Created enum + * @throws {TypeError} If arguments are invalid + */ + public static fromJSON(name: string, json: IEnum): Enum; + + /** + * Converts this enum to an enum descriptor. + * @param [toJSONOptions] JSON conversion options + * @returns Enum descriptor + */ + public toJSON(toJSONOptions?: IToJSONOptions): IEnum; + + /** + * Adds a value to this enum. + * @param name Value name + * @param id Value id + * @param [comment] Comment, if any + * @param {Object.|undefined} [options] Options, if any + * @returns `this` + * @throws {TypeError} If arguments are invalid + * @throws {Error} If there is already a value with this name or id + */ + public add(name: string, id: number, comment?: string, options?: ({ [k: string]: any }|undefined)): Enum; + + /** + * Removes a value from this enum + * @param name Value name + * @returns `this` + * @throws {TypeError} If arguments are invalid + * @throws {Error} If `name` is not a name of this enum + */ + public remove(name: string): Enum; + + /** + * Tests if the specified id is reserved. + * @param id Id to test + * @returns `true` if reserved, otherwise `false` + */ + public isReservedId(id: number): boolean; + + /** + * Tests if the specified name is reserved. + * @param name Name to test + * @returns `true` if reserved, otherwise `false` + */ + public isReservedName(name: string): boolean; +} + +/** Enum descriptor. */ +export interface IEnum { + + /** Enum values */ + values: { [k: string]: number }; + + /** Enum options */ + options?: { [k: string]: any }; +} + +/** Reflected message field. */ +export class Field extends FieldBase { + + /** + * Constructs a new message field instance. Note that {@link MapField|map fields} have their own class. + * @param name Unique name within its namespace + * @param id Unique id within its namespace + * @param type Value type + * @param [rule="optional"] Field rule + * @param [extend] Extended type if different from parent + * @param [options] Declared options + */ + constructor(name: string, id: number, type: string, rule?: (string|{ [k: string]: any }), extend?: (string|{ [k: string]: any }), options?: { [k: string]: any }); + + /** + * Constructs a field from a field descriptor. + * @param name Field name + * @param json Field descriptor + * @returns Created field + * @throws {TypeError} If arguments are invalid + */ + public static fromJSON(name: string, json: IField): Field; + + /** Determines whether this field is packed. Only relevant when repeated and working with proto2. */ + public readonly packed: boolean; + + /** + * Field decorator (TypeScript). + * @param fieldId Field id + * @param fieldType Field type + * @param [fieldRule="optional"] Field rule + * @param [defaultValue] Default value + * @returns Decorator function + */ + public static d(fieldId: number, fieldType: ("double"|"float"|"int32"|"uint32"|"sint32"|"fixed32"|"sfixed32"|"int64"|"uint64"|"sint64"|"fixed64"|"sfixed64"|"string"|"bool"|"bytes"|object), fieldRule?: ("optional"|"required"|"repeated"), defaultValue?: T): FieldDecorator; + + /** + * Field decorator (TypeScript). + * @param fieldId Field id + * @param fieldType Field type + * @param [fieldRule="optional"] Field rule + * @returns Decorator function + */ + public static d>(fieldId: number, fieldType: (Constructor|string), fieldRule?: ("optional"|"required"|"repeated")): FieldDecorator; +} + +/** Base class of all reflected message fields. This is not an actual class but here for the sake of having consistent type definitions. */ +export class FieldBase extends ReflectionObject { + + /** + * Not an actual constructor. Use {@link Field} instead. + * @param name Unique name within its namespace + * @param id Unique id within its namespace + * @param type Value type + * @param [rule="optional"] Field rule + * @param [extend] Extended type if different from parent + * @param [options] Declared options + * @param [comment] Comment associated with this field + */ + constructor(name: string, id: number, type: string, rule?: (string|{ [k: string]: any }), extend?: (string|{ [k: string]: any }), options?: { [k: string]: any }, comment?: string); + + /** Field type. */ + public type: string; + + /** Unique field id. */ + public id: number; + + /** Extended type if different from parent. */ + public extend?: string; + + /** Whether this field is required. */ + public required: boolean; + + /** Whether this field is optional. */ + public optional: boolean; + + /** Whether this field is repeated. */ + public repeated: boolean; + + /** Whether this field is a map or not. */ + public map: boolean; + + /** Message this field belongs to. */ + public message: (Type|null); + + /** OneOf this field belongs to, if any, */ + public partOf: (OneOf|null); + + /** The field type's default value. */ + public typeDefault: any; + + /** The field's default value on prototypes. */ + public defaultValue: any; + + /** Whether this field's value should be treated as a long. */ + public long: boolean; + + /** Whether this field's value is a buffer. */ + public bytes: boolean; + + /** Resolved type if not a basic type. */ + public resolvedType: (Type|Enum|null); + + /** Sister-field within the extended type if a declaring extension field. */ + public extensionField: (Field|null); + + /** Sister-field within the declaring namespace if an extended field. */ + public declaringField: (Field|null); + + /** Comment for this field. */ + public comment: (string|null); + + /** + * Converts this field to a field descriptor. + * @param [toJSONOptions] JSON conversion options + * @returns Field descriptor + */ + public toJSON(toJSONOptions?: IToJSONOptions): IField; + + /** + * Resolves this field's type references. + * @returns `this` + * @throws {Error} If any reference cannot be resolved + */ + public resolve(): Field; +} + +/** Field descriptor. */ +export interface IField { + + /** Field rule */ + rule?: string; + + /** Field type */ + type: string; + + /** Field id */ + id: number; + + /** Field options */ + options?: { [k: string]: any }; +} + +/** Extension field descriptor. */ +export interface IExtensionField extends IField { + + /** Extended type */ + extend: string; +} + +/** + * Decorator function as returned by {@link Field.d} and {@link MapField.d} (TypeScript). + * @param prototype Target prototype + * @param fieldName Field name + */ +type FieldDecorator = (prototype: object, fieldName: string) => void; + +/** + * A node-style callback as used by {@link load} and {@link Root#load}. + * @param error Error, if any, otherwise `null` + * @param [root] Root, if there hasn't been an error + */ +type LoadCallback = (error: (Error|null), root?: Root) => void; + +/** + * Loads one or multiple .proto or preprocessed .json files into a common root namespace and calls the callback. + * @param filename One or multiple files to load + * @param root Root namespace, defaults to create a new one if omitted. + * @param callback Callback function + * @see {@link Root#load} + */ +export function load(filename: (string|string[]), root: Root, callback: LoadCallback): void; + +/** + * Loads one or multiple .proto or preprocessed .json files into a common root namespace and calls the callback. + * @param filename One or multiple files to load + * @param callback Callback function + * @see {@link Root#load} + */ +export function load(filename: (string|string[]), callback: LoadCallback): void; + +/** + * Loads one or multiple .proto or preprocessed .json files into a common root namespace and returns a promise. + * @param filename One or multiple files to load + * @param [root] Root namespace, defaults to create a new one if omitted. + * @returns Promise + * @see {@link Root#load} + */ +export function load(filename: (string|string[]), root?: Root): Promise; + +/** + * Synchronously loads one or multiple .proto or preprocessed .json files into a common root namespace (node only). + * @param filename One or multiple files to load + * @param [root] Root namespace, defaults to create a new one if omitted. + * @returns Root namespace + * @throws {Error} If synchronous fetching is not supported (i.e. in browsers) or if a file's syntax is invalid + * @see {@link Root#loadSync} + */ +export function loadSync(filename: (string|string[]), root?: Root): Root; + +/** Build type, one of `"full"`, `"light"` or `"minimal"`. */ +export const build: string; + +/** Reconfigures the library according to the environment. */ +export function configure(): void; + +/** Reflected map field. */ +export class MapField extends FieldBase { + + /** + * Constructs a new map field instance. + * @param name Unique name within its namespace + * @param id Unique id within its namespace + * @param keyType Key type + * @param type Value type + * @param [options] Declared options + * @param [comment] Comment associated with this field + */ + constructor(name: string, id: number, keyType: string, type: string, options?: { [k: string]: any }, comment?: string); + + /** Key type. */ + public keyType: string; + + /** Resolved key type if not a basic type. */ + public resolvedKeyType: (ReflectionObject|null); + + /** + * Constructs a map field from a map field descriptor. + * @param name Field name + * @param json Map field descriptor + * @returns Created map field + * @throws {TypeError} If arguments are invalid + */ + public static fromJSON(name: string, json: IMapField): MapField; + + /** + * Converts this map field to a map field descriptor. + * @param [toJSONOptions] JSON conversion options + * @returns Map field descriptor + */ + public toJSON(toJSONOptions?: IToJSONOptions): IMapField; + + /** + * Map field decorator (TypeScript). + * @param fieldId Field id + * @param fieldKeyType Field key type + * @param fieldValueType Field value type + * @returns Decorator function + */ + public static d }>(fieldId: number, fieldKeyType: ("int32"|"uint32"|"sint32"|"fixed32"|"sfixed32"|"int64"|"uint64"|"sint64"|"fixed64"|"sfixed64"|"bool"|"string"), fieldValueType: ("double"|"float"|"int32"|"uint32"|"sint32"|"fixed32"|"sfixed32"|"int64"|"uint64"|"sint64"|"fixed64"|"sfixed64"|"bool"|"string"|"bytes"|object|Constructor<{}>)): FieldDecorator; +} + +/** Map field descriptor. */ +export interface IMapField extends IField { + + /** Key type */ + keyType: string; +} + +/** Extension map field descriptor. */ +export interface IExtensionMapField extends IMapField { + + /** Extended type */ + extend: string; +} + +/** Abstract runtime message. */ +export class Message { + + /** + * Constructs a new message instance. + * @param [properties] Properties to set + */ + constructor(properties?: Properties); + + /** Reference to the reflected type. */ + public static readonly $type: Type; + + /** Reference to the reflected type. */ + public readonly $type: Type; + + /** + * Creates a new message of this type using the specified properties. + * @param [properties] Properties to set + * @returns Message instance + */ + public static create>(this: Constructor, properties?: { [k: string]: any }): Message; + + /** + * Encodes a message of this type. + * @param message Message to encode + * @param [writer] Writer to use + * @returns Writer + */ + public static encode>(this: Constructor, message: (T|{ [k: string]: any }), writer?: Writer): Writer; + + /** + * Encodes a message of this type preceeded by its length as a varint. + * @param message Message to encode + * @param [writer] Writer to use + * @returns Writer + */ + public static encodeDelimited>(this: Constructor, message: (T|{ [k: string]: any }), writer?: Writer): Writer; + + /** + * Decodes a message of this type. + * @param reader Reader or buffer to decode + * @returns Decoded message + */ + public static decode>(this: Constructor, reader: (Reader|Uint8Array)): T; + + /** + * Decodes a message of this type preceeded by its length as a varint. + * @param reader Reader or buffer to decode + * @returns Decoded message + */ + public static decodeDelimited>(this: Constructor, reader: (Reader|Uint8Array)): T; + + /** + * Verifies a message of this type. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public static verify(message: { [k: string]: any }): (string|null); + + /** + * Creates a new message of this type from a plain object. Also converts values to their respective internal types. + * @param object Plain object + * @returns Message instance + */ + public static fromObject>(this: Constructor, object: { [k: string]: any }): T; + + /** + * Creates a plain object from a message of this type. Also converts values to other types if specified. + * @param message Message instance + * @param [options] Conversion options + * @returns Plain object + */ + public static toObject>(this: Constructor, message: T, options?: IConversionOptions): { [k: string]: any }; + + /** + * Converts this message to JSON. + * @returns JSON object + */ + public toJSON(): { [k: string]: any }; +} + +/** Reflected service method. */ +export class Method extends ReflectionObject { + + /** + * Constructs a new service method instance. + * @param name Method name + * @param type Method type, usually `"rpc"` + * @param requestType Request message type + * @param responseType Response message type + * @param [requestStream] Whether the request is streamed + * @param [responseStream] Whether the response is streamed + * @param [options] Declared options + * @param [comment] The comment for this method + * @param [parsedOptions] Declared options, properly parsed into an object + */ + constructor(name: string, type: (string|undefined), requestType: string, responseType: string, requestStream?: (boolean|{ [k: string]: any }), responseStream?: (boolean|{ [k: string]: any }), options?: { [k: string]: any }, comment?: string, parsedOptions?: { [k: string]: any }); + + /** Method type. */ + public type: string; + + /** Request type. */ + public requestType: string; + + /** Whether requests are streamed or not. */ + public requestStream?: boolean; + + /** Response type. */ + public responseType: string; + + /** Whether responses are streamed or not. */ + public responseStream?: boolean; + + /** Resolved request type. */ + public resolvedRequestType: (Type|null); + + /** Resolved response type. */ + public resolvedResponseType: (Type|null); + + /** Comment for this method */ + public comment: (string|null); + + /** Options properly parsed into an object */ + public parsedOptions: any; + + /** + * Constructs a method from a method descriptor. + * @param name Method name + * @param json Method descriptor + * @returns Created method + * @throws {TypeError} If arguments are invalid + */ + public static fromJSON(name: string, json: IMethod): Method; + + /** + * Converts this method to a method descriptor. + * @param [toJSONOptions] JSON conversion options + * @returns Method descriptor + */ + public toJSON(toJSONOptions?: IToJSONOptions): IMethod; +} + +/** Method descriptor. */ +export interface IMethod { + + /** Method type */ + type?: string; + + /** Request type */ + requestType: string; + + /** Response type */ + responseType: string; + + /** Whether requests are streamed */ + requestStream?: boolean; + + /** Whether responses are streamed */ + responseStream?: boolean; + + /** Method options */ + options?: { [k: string]: any }; + + /** Method comments */ + comment: string; + + /** Method options properly parsed into an object */ + parsedOptions?: { [k: string]: any }; +} + +/** Reflected namespace. */ +export class Namespace extends NamespaceBase { + + /** + * Constructs a new namespace instance. + * @param name Namespace name + * @param [options] Declared options + */ + constructor(name: string, options?: { [k: string]: any }); + + /** + * Constructs a namespace from JSON. + * @param name Namespace name + * @param json JSON object + * @returns Created namespace + * @throws {TypeError} If arguments are invalid + */ + public static fromJSON(name: string, json: { [k: string]: any }): Namespace; + + /** + * Converts an array of reflection objects to JSON. + * @param array Object array + * @param [toJSONOptions] JSON conversion options + * @returns JSON object or `undefined` when array is empty + */ + public static arrayToJSON(array: ReflectionObject[], toJSONOptions?: IToJSONOptions): ({ [k: string]: any }|undefined); + + /** + * Tests if the specified id is reserved. + * @param reserved Array of reserved ranges and names + * @param id Id to test + * @returns `true` if reserved, otherwise `false` + */ + public static isReservedId(reserved: ((number[]|string)[]|undefined), id: number): boolean; + + /** + * Tests if the specified name is reserved. + * @param reserved Array of reserved ranges and names + * @param name Name to test + * @returns `true` if reserved, otherwise `false` + */ + public static isReservedName(reserved: ((number[]|string)[]|undefined), name: string): boolean; +} + +/** Base class of all reflection objects containing nested objects. This is not an actual class but here for the sake of having consistent type definitions. */ +export abstract class NamespaceBase extends ReflectionObject { + + /** Nested objects by name. */ + public nested?: { [k: string]: ReflectionObject }; + + /** Nested objects of this namespace as an array for iteration. */ + public readonly nestedArray: ReflectionObject[]; + + /** + * Converts this namespace to a namespace descriptor. + * @param [toJSONOptions] JSON conversion options + * @returns Namespace descriptor + */ + public toJSON(toJSONOptions?: IToJSONOptions): INamespace; + + /** + * Adds nested objects to this namespace from nested object descriptors. + * @param nestedJson Any nested object descriptors + * @returns `this` + */ + public addJSON(nestedJson: { [k: string]: AnyNestedObject }): Namespace; + + /** + * Gets the nested object of the specified name. + * @param name Nested object name + * @returns The reflection object or `null` if it doesn't exist + */ + public get(name: string): (ReflectionObject|null); + + /** + * Gets the values of the nested {@link Enum|enum} of the specified name. + * This methods differs from {@link Namespace#get|get} in that it returns an enum's values directly and throws instead of returning `null`. + * @param name Nested enum name + * @returns Enum values + * @throws {Error} If there is no such enum + */ + public getEnum(name: string): { [k: string]: number }; + + /** + * Adds a nested object to this namespace. + * @param object Nested object to add + * @returns `this` + * @throws {TypeError} If arguments are invalid + * @throws {Error} If there is already a nested object with this name + */ + public add(object: ReflectionObject): Namespace; + + /** + * Removes a nested object from this namespace. + * @param object Nested object to remove + * @returns `this` + * @throws {TypeError} If arguments are invalid + * @throws {Error} If `object` is not a member of this namespace + */ + public remove(object: ReflectionObject): Namespace; + + /** + * Defines additial namespaces within this one if not yet existing. + * @param path Path to create + * @param [json] Nested types to create from JSON + * @returns Pointer to the last namespace created or `this` if path is empty + */ + public define(path: (string|string[]), json?: any): Namespace; + + /** + * Resolves this namespace's and all its nested objects' type references. Useful to validate a reflection tree, but comes at a cost. + * @returns `this` + */ + public resolveAll(): Namespace; + + /** + * Recursively looks up the reflection object matching the specified path in the scope of this namespace. + * @param path Path to look up + * @param filterTypes Filter types, any combination of the constructors of `protobuf.Type`, `protobuf.Enum`, `protobuf.Service` etc. + * @param [parentAlreadyChecked=false] If known, whether the parent has already been checked + * @returns Looked up object or `null` if none could be found + */ + public lookup(path: (string|string[]), filterTypes: (any|any[]), parentAlreadyChecked?: boolean): (ReflectionObject|null); + + /** + * Looks up the reflection object at the specified path, relative to this namespace. + * @param path Path to look up + * @param [parentAlreadyChecked=false] Whether the parent has already been checked + * @returns Looked up object or `null` if none could be found + */ + public lookup(path: (string|string[]), parentAlreadyChecked?: boolean): (ReflectionObject|null); + + /** + * Looks up the {@link Type|type} at the specified path, relative to this namespace. + * Besides its signature, this methods differs from {@link Namespace#lookup|lookup} in that it throws instead of returning `null`. + * @param path Path to look up + * @returns Looked up type + * @throws {Error} If `path` does not point to a type + */ + public lookupType(path: (string|string[])): Type; + + /** + * Looks up the values of the {@link Enum|enum} at the specified path, relative to this namespace. + * Besides its signature, this methods differs from {@link Namespace#lookup|lookup} in that it throws instead of returning `null`. + * @param path Path to look up + * @returns Looked up enum + * @throws {Error} If `path` does not point to an enum + */ + public lookupEnum(path: (string|string[])): Enum; + + /** + * Looks up the {@link Type|type} or {@link Enum|enum} at the specified path, relative to this namespace. + * Besides its signature, this methods differs from {@link Namespace#lookup|lookup} in that it throws instead of returning `null`. + * @param path Path to look up + * @returns Looked up type or enum + * @throws {Error} If `path` does not point to a type or enum + */ + public lookupTypeOrEnum(path: (string|string[])): Type; + + /** + * Looks up the {@link Service|service} at the specified path, relative to this namespace. + * Besides its signature, this methods differs from {@link Namespace#lookup|lookup} in that it throws instead of returning `null`. + * @param path Path to look up + * @returns Looked up service + * @throws {Error} If `path` does not point to a service + */ + public lookupService(path: (string|string[])): Service; +} + +/** Namespace descriptor. */ +export interface INamespace { + + /** Namespace options */ + options?: { [k: string]: any }; + + /** Nested object descriptors */ + nested?: { [k: string]: AnyNestedObject }; +} + +/** Any extension field descriptor. */ +type AnyExtensionField = (IExtensionField|IExtensionMapField); + +/** Any nested object descriptor. */ +type AnyNestedObject = (IEnum|IType|IService|AnyExtensionField|INamespace|IOneOf); + +/** Base class of all reflection objects. */ +export abstract class ReflectionObject { + + /** Options. */ + public options?: { [k: string]: any }; + + /** Parsed Options. */ + public parsedOptions?: { [k: string]: any[] }; + + /** Unique name within its namespace. */ + public name: string; + + /** Parent namespace. */ + public parent: (Namespace|null); + + /** Whether already resolved or not. */ + public resolved: boolean; + + /** Comment text, if any. */ + public comment: (string|null); + + /** Defining file name. */ + public filename: (string|null); + + /** Reference to the root namespace. */ + public readonly root: Root; + + /** Full name including leading dot. */ + public readonly fullName: string; + + /** + * Converts this reflection object to its descriptor representation. + * @returns Descriptor + */ + public toJSON(): { [k: string]: any }; + + /** + * Called when this object is added to a parent. + * @param parent Parent added to + */ + public onAdd(parent: ReflectionObject): void; + + /** + * Called when this object is removed from a parent. + * @param parent Parent removed from + */ + public onRemove(parent: ReflectionObject): void; + + /** + * Resolves this objects type references. + * @returns `this` + */ + public resolve(): ReflectionObject; + + /** + * Gets an option value. + * @param name Option name + * @returns Option value or `undefined` if not set + */ + public getOption(name: string): any; + + /** + * Sets an option. + * @param name Option name + * @param value Option value + * @param [ifNotSet] Sets the option only if it isn't currently set + * @returns `this` + */ + public setOption(name: string, value: any, ifNotSet?: boolean): ReflectionObject; + + /** + * Sets a parsed option. + * @param name parsed Option name + * @param value Option value + * @param propName dot '.' delimited full path of property within the option to set. if undefined\empty, will add a new option with that value + * @returns `this` + */ + public setParsedOption(name: string, value: any, propName: string): ReflectionObject; + + /** + * Sets multiple options. + * @param options Options to set + * @param [ifNotSet] Sets an option only if it isn't currently set + * @returns `this` + */ + public setOptions(options: { [k: string]: any }, ifNotSet?: boolean): ReflectionObject; + + /** + * Converts this instance to its string representation. + * @returns Class name[, space, full name] + */ + public toString(): string; +} + +/** Reflected oneof. */ +export class OneOf extends ReflectionObject { + + /** + * Constructs a new oneof instance. + * @param name Oneof name + * @param [fieldNames] Field names + * @param [options] Declared options + * @param [comment] Comment associated with this field + */ + constructor(name: string, fieldNames?: (string[]|{ [k: string]: any }), options?: { [k: string]: any }, comment?: string); + + /** Field names that belong to this oneof. */ + public oneof: string[]; + + /** Fields that belong to this oneof as an array for iteration. */ + public readonly fieldsArray: Field[]; + + /** Comment for this field. */ + public comment: (string|null); + + /** + * Constructs a oneof from a oneof descriptor. + * @param name Oneof name + * @param json Oneof descriptor + * @returns Created oneof + * @throws {TypeError} If arguments are invalid + */ + public static fromJSON(name: string, json: IOneOf): OneOf; + + /** + * Converts this oneof to a oneof descriptor. + * @param [toJSONOptions] JSON conversion options + * @returns Oneof descriptor + */ + public toJSON(toJSONOptions?: IToJSONOptions): IOneOf; + + /** + * Adds a field to this oneof and removes it from its current parent, if any. + * @param field Field to add + * @returns `this` + */ + public add(field: Field): OneOf; + + /** + * Removes a field from this oneof and puts it back to the oneof's parent. + * @param field Field to remove + * @returns `this` + */ + public remove(field: Field): OneOf; + + /** + * OneOf decorator (TypeScript). + * @param fieldNames Field names + * @returns Decorator function + */ + public static d(...fieldNames: string[]): OneOfDecorator; +} + +/** Oneof descriptor. */ +export interface IOneOf { + + /** Oneof field names */ + oneof: string[]; + + /** Oneof options */ + options?: { [k: string]: any }; +} + +/** + * Decorator function as returned by {@link OneOf.d} (TypeScript). + * @param prototype Target prototype + * @param oneofName OneOf name + */ +type OneOfDecorator = (prototype: object, oneofName: string) => void; + +/** + * Parses the given .proto source and returns an object with the parsed contents. + * @param source Source contents + * @param [options] Parse options. Defaults to {@link parse.defaults} when omitted. + * @returns Parser result + */ +export function parse(source: string, options?: IParseOptions): IParserResult; + +/** Result object returned from {@link parse}. */ +export interface IParserResult { + + /** Package name, if declared */ + package: (string|undefined); + + /** Imports, if any */ + imports: (string[]|undefined); + + /** Weak imports, if any */ + weakImports: (string[]|undefined); + + /** Syntax, if specified (either `"proto2"` or `"proto3"`) */ + syntax: (string|undefined); + + /** Populated root instance */ + root: Root; +} + +/** Options modifying the behavior of {@link parse}. */ +export interface IParseOptions { + + /** Keeps field casing instead of converting to camel case */ + keepCase?: boolean; + + /** Recognize double-slash comments in addition to doc-block comments. */ + alternateCommentMode?: boolean; + + /** Use trailing comment when both leading comment and trailing comment exist. */ + preferTrailingComment?: boolean; +} + +/** Options modifying the behavior of JSON serialization. */ +export interface IToJSONOptions { + + /** Serializes comments. */ + keepComments?: boolean; +} + +/** + * Parses the given .proto source and returns an object with the parsed contents. + * @param source Source contents + * @param root Root to populate + * @param [options] Parse options. Defaults to {@link parse.defaults} when omitted. + * @returns Parser result + */ +export function parse(source: string, root: Root, options?: IParseOptions): IParserResult; + +/** Wire format reader using `Uint8Array` if available, otherwise `Array`. */ +export class Reader { + + /** + * Constructs a new reader instance using the specified buffer. + * @param buffer Buffer to read from + */ + constructor(buffer: Uint8Array); + + /** Read buffer. */ + public buf: Uint8Array; + + /** Read buffer position. */ + public pos: number; + + /** Read buffer length. */ + public len: number; + + /** + * Creates a new reader using the specified buffer. + * @param buffer Buffer to read from + * @returns A {@link BufferReader} if `buffer` is a Buffer, otherwise a {@link Reader} + * @throws {Error} If `buffer` is not a valid buffer + */ + public static create(buffer: (Uint8Array|Buffer)): (Reader|BufferReader); + + /** + * Reads a varint as an unsigned 32 bit value. + * @returns Value read + */ + public uint32(): number; + + /** + * Reads a varint as a signed 32 bit value. + * @returns Value read + */ + public int32(): number; + + /** + * Reads a zig-zag encoded varint as a signed 32 bit value. + * @returns Value read + */ + public sint32(): number; + + /** + * Reads a varint as a signed 64 bit value. + * @returns Value read + */ + public int64(): Long; + + /** + * Reads a varint as an unsigned 64 bit value. + * @returns Value read + */ + public uint64(): Long; + + /** + * Reads a zig-zag encoded varint as a signed 64 bit value. + * @returns Value read + */ + public sint64(): Long; + + /** + * Reads a varint as a boolean. + * @returns Value read + */ + public bool(): boolean; + + /** + * Reads fixed 32 bits as an unsigned 32 bit integer. + * @returns Value read + */ + public fixed32(): number; + + /** + * Reads fixed 32 bits as a signed 32 bit integer. + * @returns Value read + */ + public sfixed32(): number; + + /** + * Reads fixed 64 bits. + * @returns Value read + */ + public fixed64(): Long; + + /** + * Reads zig-zag encoded fixed 64 bits. + * @returns Value read + */ + public sfixed64(): Long; + + /** + * Reads a float (32 bit) as a number. + * @returns Value read + */ + public float(): number; + + /** + * Reads a double (64 bit float) as a number. + * @returns Value read + */ + public double(): number; + + /** + * Reads a sequence of bytes preceeded by its length as a varint. + * @returns Value read + */ + public bytes(): Uint8Array; + + /** + * Reads a string preceeded by its byte length as a varint. + * @returns Value read + */ + public string(): string; + + /** + * Skips the specified number of bytes if specified, otherwise skips a varint. + * @param [length] Length if known, otherwise a varint is assumed + * @returns `this` + */ + public skip(length?: number): Reader; + + /** + * Skips the next element of the specified wire type. + * @param wireType Wire type received + * @returns `this` + */ + public skipType(wireType: number): Reader; +} + +/** Wire format reader using node buffers. */ +export class BufferReader extends Reader { + + /** + * Constructs a new buffer reader instance. + * @param buffer Buffer to read from + */ + constructor(buffer: Buffer); + + /** + * Reads a sequence of bytes preceeded by its length as a varint. + * @returns Value read + */ + public bytes(): Buffer; +} + +/** Root namespace wrapping all types, enums, services, sub-namespaces etc. that belong together. */ +export class Root extends NamespaceBase { + + /** + * Constructs a new root namespace instance. + * @param [options] Top level options + */ + constructor(options?: { [k: string]: any }); + + /** Deferred extension fields. */ + public deferred: Field[]; + + /** Resolved file names of loaded files. */ + public files: string[]; + + /** + * Loads a namespace descriptor into a root namespace. + * @param json Nameespace descriptor + * @param [root] Root namespace, defaults to create a new one if omitted + * @returns Root namespace + */ + public static fromJSON(json: INamespace, root?: Root): Root; + + /** + * Resolves the path of an imported file, relative to the importing origin. + * This method exists so you can override it with your own logic in case your imports are scattered over multiple directories. + * @param origin The file name of the importing file + * @param target The file name being imported + * @returns Resolved path to `target` or `null` to skip the file + */ + public resolvePath(origin: string, target: string): (string|null); + + /** + * Fetch content from file path or url + * This method exists so you can override it with your own logic. + * @param path File path or url + * @param callback Callback function + */ + public fetch(path: string, callback: FetchCallback): void; + + /** + * Loads one or multiple .proto or preprocessed .json files into this root namespace and calls the callback. + * @param filename Names of one or multiple files to load + * @param options Parse options + * @param callback Callback function + */ + public load(filename: (string|string[]), options: IParseOptions, callback: LoadCallback): void; + + /** + * Loads one or multiple .proto or preprocessed .json files into this root namespace and calls the callback. + * @param filename Names of one or multiple files to load + * @param callback Callback function + */ + public load(filename: (string|string[]), callback: LoadCallback): void; + + /** + * Loads one or multiple .proto or preprocessed .json files into this root namespace and returns a promise. + * @param filename Names of one or multiple files to load + * @param [options] Parse options. Defaults to {@link parse.defaults} when omitted. + * @returns Promise + */ + public load(filename: (string|string[]), options?: IParseOptions): Promise; + + /** + * Synchronously loads one or multiple .proto or preprocessed .json files into this root namespace (node only). + * @param filename Names of one or multiple files to load + * @param [options] Parse options. Defaults to {@link parse.defaults} when omitted. + * @returns Root namespace + * @throws {Error} If synchronous fetching is not supported (i.e. in browsers) or if a file's syntax is invalid + */ + public loadSync(filename: (string|string[]), options?: IParseOptions): Root; +} + +/** + * Named roots. + * This is where pbjs stores generated structures (the option `-r, --root` specifies a name). + * Can also be used manually to make roots available across modules. + */ +export let roots: { [k: string]: Root }; + +/** Streaming RPC helpers. */ +export namespace rpc { + + /** + * A service method callback as used by {@link rpc.ServiceMethod|ServiceMethod}. + * + * Differs from {@link RPCImplCallback} in that it is an actual callback of a service method which may not return `response = null`. + * @param error Error, if any + * @param [response] Response message + */ + type ServiceMethodCallback> = (error: (Error|null), response?: TRes) => void; + + /** + * A service method part of a {@link rpc.Service} as created by {@link Service.create}. + * @param request Request message or plain object + * @param [callback] Node-style callback called with the error, if any, and the response message + * @returns Promise if `callback` has been omitted, otherwise `undefined` + */ + type ServiceMethod, TRes extends Message> = (request: (TReq|Properties), callback?: rpc.ServiceMethodCallback) => Promise>; + + /** An RPC service as returned by {@link Service#create}. */ + class Service extends util.EventEmitter { + + /** + * Constructs a new RPC service instance. + * @param rpcImpl RPC implementation + * @param [requestDelimited=false] Whether requests are length-delimited + * @param [responseDelimited=false] Whether responses are length-delimited + */ + constructor(rpcImpl: RPCImpl, requestDelimited?: boolean, responseDelimited?: boolean); + + /** RPC implementation. Becomes `null` once the service is ended. */ + public rpcImpl: (RPCImpl|null); + + /** Whether requests are length-delimited. */ + public requestDelimited: boolean; + + /** Whether responses are length-delimited. */ + public responseDelimited: boolean; + + /** + * Calls a service method through {@link rpc.Service#rpcImpl|rpcImpl}. + * @param method Reflected or static method + * @param requestCtor Request constructor + * @param responseCtor Response constructor + * @param request Request message or plain object + * @param callback Service callback + */ + public rpcCall, TRes extends Message>(method: (Method|rpc.ServiceMethod), requestCtor: Constructor, responseCtor: Constructor, request: (TReq|Properties), callback: rpc.ServiceMethodCallback): void; + + /** + * Ends this service and emits the `end` event. + * @param [endedByRPC=false] Whether the service has been ended by the RPC implementation. + * @returns `this` + */ + public end(endedByRPC?: boolean): rpc.Service; + } +} + +/** + * RPC implementation passed to {@link Service#create} performing a service request on network level, i.e. by utilizing http requests or websockets. + * @param method Reflected or static method being called + * @param requestData Request data + * @param callback Callback function + */ +type RPCImpl = (method: (Method|rpc.ServiceMethod, Message<{}>>), requestData: Uint8Array, callback: RPCImplCallback) => void; + +/** + * Node-style callback as used by {@link RPCImpl}. + * @param error Error, if any, otherwise `null` + * @param [response] Response data or `null` to signal end of stream, if there hasn't been an error + */ +type RPCImplCallback = (error: (Error|null), response?: (Uint8Array|null)) => void; + +/** Reflected service. */ +export class Service extends NamespaceBase { + + /** + * Constructs a new service instance. + * @param name Service name + * @param [options] Service options + * @throws {TypeError} If arguments are invalid + */ + constructor(name: string, options?: { [k: string]: any }); + + /** Service methods. */ + public methods: { [k: string]: Method }; + + /** + * Constructs a service from a service descriptor. + * @param name Service name + * @param json Service descriptor + * @returns Created service + * @throws {TypeError} If arguments are invalid + */ + public static fromJSON(name: string, json: IService): Service; + + /** + * Converts this service to a service descriptor. + * @param [toJSONOptions] JSON conversion options + * @returns Service descriptor + */ + public toJSON(toJSONOptions?: IToJSONOptions): IService; + + /** Methods of this service as an array for iteration. */ + public readonly methodsArray: Method[]; + + /** + * Creates a runtime service using the specified rpc implementation. + * @param rpcImpl RPC implementation + * @param [requestDelimited=false] Whether requests are length-delimited + * @param [responseDelimited=false] Whether responses are length-delimited + * @returns RPC service. Useful where requests and/or responses are streamed. + */ + public create(rpcImpl: RPCImpl, requestDelimited?: boolean, responseDelimited?: boolean): rpc.Service; +} + +/** Service descriptor. */ +export interface IService extends INamespace { + + /** Method descriptors */ + methods: { [k: string]: IMethod }; +} + +/** + * Gets the next token and advances. + * @returns Next token or `null` on eof + */ +type TokenizerHandleNext = () => (string|null); + +/** + * Peeks for the next token. + * @returns Next token or `null` on eof + */ +type TokenizerHandlePeek = () => (string|null); + +/** + * Pushes a token back to the stack. + * @param token Token + */ +type TokenizerHandlePush = (token: string) => void; + +/** + * Skips the next token. + * @param expected Expected token + * @param [optional=false] If optional + * @returns Whether the token matched + * @throws {Error} If the token didn't match and is not optional + */ +type TokenizerHandleSkip = (expected: string, optional?: boolean) => boolean; + +/** + * Gets the comment on the previous line or, alternatively, the line comment on the specified line. + * @param [line] Line number + * @returns Comment text or `null` if none + */ +type TokenizerHandleCmnt = (line?: number) => (string|null); + +/** Handle object returned from {@link tokenize}. */ +export interface ITokenizerHandle { + + /** Gets the next token and advances (`null` on eof) */ + next: TokenizerHandleNext; + + /** Peeks for the next token (`null` on eof) */ + peek: TokenizerHandlePeek; + + /** Pushes a token back to the stack */ + push: TokenizerHandlePush; + + /** Skips a token, returns its presence and advances or, if non-optional and not present, throws */ + skip: TokenizerHandleSkip; + + /** Gets the comment on the previous line or the line comment on the specified line, if any */ + cmnt: TokenizerHandleCmnt; + + /** Current line number */ + line: number; +} + +/** + * Tokenizes the given .proto source and returns an object with useful utility functions. + * @param source Source contents + * @param alternateCommentMode Whether we should activate alternate comment parsing mode. + * @returns Tokenizer handle + */ +export function tokenize(source: string, alternateCommentMode: boolean): ITokenizerHandle; + +export namespace tokenize { + + /** + * Unescapes a string. + * @param str String to unescape + * @returns Unescaped string + */ + function unescape(str: string): string; +} + +/** Reflected message type. */ +export class Type extends NamespaceBase { + + /** + * Constructs a new reflected message type instance. + * @param name Message name + * @param [options] Declared options + */ + constructor(name: string, options?: { [k: string]: any }); + + /** Message fields. */ + public fields: { [k: string]: Field }; + + /** Oneofs declared within this namespace, if any. */ + public oneofs: { [k: string]: OneOf }; + + /** Extension ranges, if any. */ + public extensions: number[][]; + + /** Reserved ranges, if any. */ + public reserved: (number[]|string)[]; + + /** Message fields by id. */ + public readonly fieldsById: { [k: number]: Field }; + + /** Fields of this message as an array for iteration. */ + public readonly fieldsArray: Field[]; + + /** Oneofs of this message as an array for iteration. */ + public readonly oneofsArray: OneOf[]; + + /** + * The registered constructor, if any registered, otherwise a generic constructor. + * Assigning a function replaces the internal constructor. If the function does not extend {@link Message} yet, its prototype will be setup accordingly and static methods will be populated. If it already extends {@link Message}, it will just replace the internal constructor. + */ + public ctor: Constructor<{}>; + + /** + * Generates a constructor function for the specified type. + * @param mtype Message type + * @returns Codegen instance + */ + public static generateConstructor(mtype: Type): Codegen; + + /** + * Creates a message type from a message type descriptor. + * @param name Message name + * @param json Message type descriptor + * @returns Created message type + */ + public static fromJSON(name: string, json: IType): Type; + + /** + * Converts this message type to a message type descriptor. + * @param [toJSONOptions] JSON conversion options + * @returns Message type descriptor + */ + public toJSON(toJSONOptions?: IToJSONOptions): IType; + + /** + * Adds a nested object to this type. + * @param object Nested object to add + * @returns `this` + * @throws {TypeError} If arguments are invalid + * @throws {Error} If there is already a nested object with this name or, if a field, when there is already a field with this id + */ + public add(object: ReflectionObject): Type; + + /** + * Removes a nested object from this type. + * @param object Nested object to remove + * @returns `this` + * @throws {TypeError} If arguments are invalid + * @throws {Error} If `object` is not a member of this type + */ + public remove(object: ReflectionObject): Type; + + /** + * Tests if the specified id is reserved. + * @param id Id to test + * @returns `true` if reserved, otherwise `false` + */ + public isReservedId(id: number): boolean; + + /** + * Tests if the specified name is reserved. + * @param name Name to test + * @returns `true` if reserved, otherwise `false` + */ + public isReservedName(name: string): boolean; + + /** + * Creates a new message of this type using the specified properties. + * @param [properties] Properties to set + * @returns Message instance + */ + public create(properties?: { [k: string]: any }): Message<{}>; + + /** + * Sets up {@link Type#encode|encode}, {@link Type#decode|decode} and {@link Type#verify|verify}. + * @returns `this` + */ + public setup(): Type; + + /** + * Encodes a message of this type. Does not implicitly {@link Type#verify|verify} messages. + * @param message Message instance or plain object + * @param [writer] Writer to encode to + * @returns writer + */ + public encode(message: (Message<{}>|{ [k: string]: any }), writer?: Writer): Writer; + + /** + * Encodes a message of this type preceeded by its byte length as a varint. Does not implicitly {@link Type#verify|verify} messages. + * @param message Message instance or plain object + * @param [writer] Writer to encode to + * @returns writer + */ + public encodeDelimited(message: (Message<{}>|{ [k: string]: any }), writer?: Writer): Writer; + + /** + * Decodes a message of this type. + * @param reader Reader or buffer to decode from + * @param [length] Length of the message, if known beforehand + * @returns Decoded message + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {util.ProtocolError<{}>} If required fields are missing + */ + public decode(reader: (Reader|Uint8Array), length?: number): Message<{}>; + + /** + * Decodes a message of this type preceeded by its byte length as a varint. + * @param reader Reader or buffer to decode from + * @returns Decoded message + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {util.ProtocolError} If required fields are missing + */ + public decodeDelimited(reader: (Reader|Uint8Array)): Message<{}>; + + /** + * Verifies that field values are valid and that required fields are present. + * @param message Plain object to verify + * @returns `null` if valid, otherwise the reason why it is not + */ + public verify(message: { [k: string]: any }): (null|string); + + /** + * Creates a new message of this type from a plain object. Also converts values to their respective internal types. + * @param object Plain object to convert + * @returns Message instance + */ + public fromObject(object: { [k: string]: any }): Message<{}>; + + /** + * Creates a plain object from a message of this type. Also converts values to other types if specified. + * @param message Message instance + * @param [options] Conversion options + * @returns Plain object + */ + public toObject(message: Message<{}>, options?: IConversionOptions): { [k: string]: any }; + + /** + * Type decorator (TypeScript). + * @param [typeName] Type name, defaults to the constructor's name + * @returns Decorator function + */ + public static d>(typeName?: string): TypeDecorator; +} + +/** Message type descriptor. */ +export interface IType extends INamespace { + + /** Oneof descriptors */ + oneofs?: { [k: string]: IOneOf }; + + /** Field descriptors */ + fields: { [k: string]: IField }; + + /** Extension ranges */ + extensions?: number[][]; + + /** Reserved ranges */ + reserved?: number[][]; + + /** Whether a legacy group or not */ + group?: boolean; +} + +/** Conversion options as used by {@link Type#toObject} and {@link Message.toObject}. */ +export interface IConversionOptions { + + /** + * Long conversion type. + * Valid values are `String` and `Number` (the global types). + * Defaults to copy the present value, which is a possibly unsafe number without and a {@link Long} with a long library. + */ + longs?: Function; + + /** + * Enum value conversion type. + * Only valid value is `String` (the global type). + * Defaults to copy the present value, which is the numeric id. + */ + enums?: Function; + + /** + * Bytes value conversion type. + * Valid values are `Array` and (a base64 encoded) `String` (the global types). + * Defaults to copy the present value, which usually is a Buffer under node and an Uint8Array in the browser. + */ + bytes?: Function; + + /** Also sets default values on the resulting object */ + defaults?: boolean; + + /** Sets empty arrays for missing repeated fields even if `defaults=false` */ + arrays?: boolean; + + /** Sets empty objects for missing map fields even if `defaults=false` */ + objects?: boolean; + + /** Includes virtual oneof properties set to the present field's name, if any */ + oneofs?: boolean; + + /** Performs additional JSON compatibility conversions, i.e. NaN and Infinity to strings */ + json?: boolean; +} + +/** + * Decorator function as returned by {@link Type.d} (TypeScript). + * @param target Target constructor + */ +type TypeDecorator> = (target: Constructor) => void; + +/** Common type constants. */ +export namespace types { + + /** Basic type wire types. */ + const basic: { + "double": number, + "float": number, + "int32": number, + "uint32": number, + "sint32": number, + "fixed32": number, + "sfixed32": number, + "int64": number, + "uint64": number, + "sint64": number, + "fixed64": number, + "sfixed64": number, + "bool": number, + "string": number, + "bytes": number + }; + + /** Basic type defaults. */ + const defaults: { + "double": number, + "float": number, + "int32": number, + "uint32": number, + "sint32": number, + "fixed32": number, + "sfixed32": number, + "int64": number, + "uint64": number, + "sint64": number, + "fixed64": number, + "sfixed64": number, + "bool": boolean, + "string": string, + "bytes": number[], + "message": null + }; + + /** Basic long type wire types. */ + const long: { + "int64": number, + "uint64": number, + "sint64": number, + "fixed64": number, + "sfixed64": number + }; + + /** Allowed types for map keys with their associated wire type. */ + const mapKey: { + "int32": number, + "uint32": number, + "sint32": number, + "fixed32": number, + "sfixed32": number, + "int64": number, + "uint64": number, + "sint64": number, + "fixed64": number, + "sfixed64": number, + "bool": number, + "string": number + }; + + /** Allowed types for packed repeated fields with their associated wire type. */ + const packed: { + "double": number, + "float": number, + "int32": number, + "uint32": number, + "sint32": number, + "fixed32": number, + "sfixed32": number, + "int64": number, + "uint64": number, + "sint64": number, + "fixed64": number, + "sfixed64": number, + "bool": number + }; +} + +/** Constructor type. */ +export interface Constructor extends Function { + new(...params: any[]): T; prototype: T; +} + +/** Properties type. */ +type Properties = { [P in keyof T]?: T[P] }; + +/** + * Any compatible Buffer instance. + * This is a minimal stand-alone definition of a Buffer instance. The actual type is that exported by node's typings. + */ +export interface Buffer extends Uint8Array { +} + +/** + * Any compatible Long instance. + * This is a minimal stand-alone definition of a Long instance. The actual type is that exported by long.js. + */ +export interface Long { + + /** Low bits */ + low: number; + + /** High bits */ + high: number; + + /** Whether unsigned or not */ + unsigned: boolean; +} + +/** + * A OneOf getter as returned by {@link util.oneOfGetter}. + * @returns Set field name, if any + */ +type OneOfGetter = () => (string|undefined); + +/** + * A OneOf setter as returned by {@link util.oneOfSetter}. + * @param value Field name + */ +type OneOfSetter = (value: (string|undefined)) => void; + +/** Various utility functions. */ +export namespace util { + + /** Helper class for working with the low and high bits of a 64 bit value. */ + class LongBits { + + /** + * Constructs new long bits. + * @param lo Low 32 bits, unsigned + * @param hi High 32 bits, unsigned + */ + constructor(lo: number, hi: number); + + /** Low bits. */ + public lo: number; + + /** High bits. */ + public hi: number; + + /** Zero bits. */ + public static zero: util.LongBits; + + /** Zero hash. */ + public static zeroHash: string; + + /** + * Constructs new long bits from the specified number. + * @param value Value + * @returns Instance + */ + public static fromNumber(value: number): util.LongBits; + + /** + * Constructs new long bits from a number, long or string. + * @param value Value + * @returns Instance + */ + public static from(value: (Long|number|string)): util.LongBits; + + /** + * Converts this long bits to a possibly unsafe JavaScript number. + * @param [unsigned=false] Whether unsigned or not + * @returns Possibly unsafe number + */ + public toNumber(unsigned?: boolean): number; + + /** + * Converts this long bits to a long. + * @param [unsigned=false] Whether unsigned or not + * @returns Long + */ + public toLong(unsigned?: boolean): Long; + + /** + * Constructs new long bits from the specified 8 characters long hash. + * @param hash Hash + * @returns Bits + */ + public static fromHash(hash: string): util.LongBits; + + /** + * Converts this long bits to a 8 characters long hash. + * @returns Hash + */ + public toHash(): string; + + /** + * Zig-zag encodes this long bits. + * @returns `this` + */ + public zzEncode(): util.LongBits; + + /** + * Zig-zag decodes this long bits. + * @returns `this` + */ + public zzDecode(): util.LongBits; + + /** + * Calculates the length of this longbits when encoded as a varint. + * @returns Length + */ + public length(): number; + } + + /** Whether running within node or not. */ + let isNode: boolean; + + /** Global object reference. */ + let global: object; + + /** An immuable empty array. */ + const emptyArray: any[]; + + /** An immutable empty object. */ + const emptyObject: object; + + /** + * Tests if the specified value is an integer. + * @param value Value to test + * @returns `true` if the value is an integer + */ + function isInteger(value: any): boolean; + + /** + * Tests if the specified value is a string. + * @param value Value to test + * @returns `true` if the value is a string + */ + function isString(value: any): boolean; + + /** + * Tests if the specified value is a non-null object. + * @param value Value to test + * @returns `true` if the value is a non-null object + */ + function isObject(value: any): boolean; + + /** + * Checks if a property on a message is considered to be present. + * This is an alias of {@link util.isSet}. + * @param obj Plain object or message instance + * @param prop Property name + * @returns `true` if considered to be present, otherwise `false` + */ + function isset(obj: object, prop: string): boolean; + + /** + * Checks if a property on a message is considered to be present. + * @param obj Plain object or message instance + * @param prop Property name + * @returns `true` if considered to be present, otherwise `false` + */ + function isSet(obj: object, prop: string): boolean; + + /** Node's Buffer class if available. */ + let Buffer: Constructor; + + /** + * Creates a new buffer of whatever type supported by the environment. + * @param [sizeOrArray=0] Buffer size or number array + * @returns Buffer + */ + function newBuffer(sizeOrArray?: (number|number[])): (Uint8Array|Buffer); + + /** Array implementation used in the browser. `Uint8Array` if supported, otherwise `Array`. */ + let Array: Constructor; + + /** Long.js's Long class if available. */ + let Long: Constructor; + + /** Regular expression used to verify 2 bit (`bool`) map keys. */ + const key2Re: RegExp; + + /** Regular expression used to verify 32 bit (`int32` etc.) map keys. */ + const key32Re: RegExp; + + /** Regular expression used to verify 64 bit (`int64` etc.) map keys. */ + const key64Re: RegExp; + + /** + * Converts a number or long to an 8 characters long hash string. + * @param value Value to convert + * @returns Hash + */ + function longToHash(value: (Long|number)): string; + + /** + * Converts an 8 characters long hash string to a long or number. + * @param hash Hash + * @param [unsigned=false] Whether unsigned or not + * @returns Original value + */ + function longFromHash(hash: string, unsigned?: boolean): (Long|number); + + /** + * Merges the properties of the source object into the destination object. + * @param dst Destination object + * @param src Source object + * @param [ifNotSet=false] Merges only if the key is not already set + * @returns Destination object + */ + function merge(dst: { [k: string]: any }, src: { [k: string]: any }, ifNotSet?: boolean): { [k: string]: any }; + + /** + * Converts the first character of a string to lower case. + * @param str String to convert + * @returns Converted string + */ + function lcFirst(str: string): string; + + /** + * Creates a custom error constructor. + * @param name Error name + * @returns Custom error constructor + */ + function newError(name: string): Constructor; + + /** Error subclass indicating a protocol specifc error. */ + class ProtocolError> extends Error { + + /** + * Constructs a new protocol error. + * @param message Error message + * @param [properties] Additional properties + */ + constructor(message: string, properties?: { [k: string]: any }); + + /** So far decoded message instance. */ + public instance: Message; + } + + /** + * Builds a getter for a oneof's present field name. + * @param fieldNames Field names + * @returns Unbound getter + */ + function oneOfGetter(fieldNames: string[]): OneOfGetter; + + /** + * Builds a setter for a oneof's present field name. + * @param fieldNames Field names + * @returns Unbound setter + */ + function oneOfSetter(fieldNames: string[]): OneOfSetter; + + /** + * Default conversion options used for {@link Message#toJSON} implementations. + * + * These options are close to proto3's JSON mapping with the exception that internal types like Any are handled just like messages. More precisely: + * + * - Longs become strings + * - Enums become string keys + * - Bytes become base64 encoded strings + * - (Sub-)Messages become plain objects + * - Maps become plain objects with all string keys + * - Repeated fields become arrays + * - NaN and Infinity for float and double fields become strings + * + * @see https://developers.google.com/protocol-buffers/docs/proto3?hl=en#json + */ + let toJSONOptions: IConversionOptions; + + /** Node's fs module if available. */ + let fs: { [k: string]: any }; + + /** + * Converts an object's values to an array. + * @param object Object to convert + * @returns Converted array + */ + function toArray(object: { [k: string]: any }): any[]; + + /** + * Converts an array of keys immediately followed by their respective value to an object, omitting undefined values. + * @param array Array to convert + * @returns Converted object + */ + function toObject(array: any[]): { [k: string]: any }; + + /** + * Tests whether the specified name is a reserved word in JS. + * @param name Name to test + * @returns `true` if reserved, otherwise `false` + */ + function isReserved(name: string): boolean; + + /** + * Returns a safe property accessor for the specified property name. + * @param prop Property name + * @returns Safe accessor + */ + function safeProp(prop: string): string; + + /** + * Converts the first character of a string to upper case. + * @param str String to convert + * @returns Converted string + */ + function ucFirst(str: string): string; + + /** + * Converts a string to camel case. + * @param str String to convert + * @returns Converted string + */ + function camelCase(str: string): string; + + /** + * Compares reflected fields by id. + * @param a First field + * @param b Second field + * @returns Comparison value + */ + function compareFieldsById(a: Field, b: Field): number; + + /** + * Decorator helper for types (TypeScript). + * @param ctor Constructor function + * @param [typeName] Type name, defaults to the constructor's name + * @returns Reflected type + */ + function decorateType>(ctor: Constructor, typeName?: string): Type; + + /** + * Decorator helper for enums (TypeScript). + * @param object Enum object + * @returns Reflected enum + */ + function decorateEnum(object: object): Enum; + + /** + * Sets the value of a property by property path. If a value already exists, it is turned to an array + * @param dst Destination object + * @param path dot '.' delimited path of the property to set + * @param value the value to set + * @returns Destination object + */ + function setProperty(dst: { [k: string]: any }, path: string, value: object): { [k: string]: any }; + + /** Decorator root (TypeScript). */ + let decorateRoot: Root; + + /** + * Returns a promise from a node-style callback function. + * @param fn Function to call + * @param ctx Function context + * @param params Function arguments + * @returns Promisified function + */ + function asPromise(fn: asPromiseCallback, ctx: any, ...params: any[]): Promise; + + /** A minimal base64 implementation for number arrays. */ + namespace base64 { + + /** + * Calculates the byte length of a base64 encoded string. + * @param string Base64 encoded string + * @returns Byte length + */ + function length(string: string): number; + + /** + * Encodes a buffer to a base64 encoded string. + * @param buffer Source buffer + * @param start Source start + * @param end Source end + * @returns Base64 encoded string + */ + function encode(buffer: Uint8Array, start: number, end: number): string; + + /** + * Decodes a base64 encoded string to a buffer. + * @param string Source string + * @param buffer Destination buffer + * @param offset Destination offset + * @returns Number of bytes written + * @throws {Error} If encoding is invalid + */ + function decode(string: string, buffer: Uint8Array, offset: number): number; + + /** + * Tests if the specified string appears to be base64 encoded. + * @param string String to test + * @returns `true` if probably base64 encoded, otherwise false + */ + function test(string: string): boolean; + } + + /** + * Begins generating a function. + * @param functionParams Function parameter names + * @param [functionName] Function name if not anonymous + * @returns Appender that appends code to the function's body + */ + function codegen(functionParams: string[], functionName?: string): Codegen; + + namespace codegen { + + /** When set to `true`, codegen will log generated code to console. Useful for debugging. */ + let verbose: boolean; + } + + /** + * Begins generating a function. + * @param [functionName] Function name if not anonymous + * @returns Appender that appends code to the function's body + */ + function codegen(functionName?: string): Codegen; + + /** A minimal event emitter. */ + class EventEmitter { + + /** Constructs a new event emitter instance. */ + constructor(); + + /** + * Registers an event listener. + * @param evt Event name + * @param fn Listener + * @param [ctx] Listener context + * @returns `this` + */ + public on(evt: string, fn: EventEmitterListener, ctx?: any): this; + + /** + * Removes an event listener or any matching listeners if arguments are omitted. + * @param [evt] Event name. Removes all listeners if omitted. + * @param [fn] Listener to remove. Removes all listeners of `evt` if omitted. + * @returns `this` + */ + public off(evt?: string, fn?: EventEmitterListener): this; + + /** + * Emits an event by calling its listeners with the specified arguments. + * @param evt Event name + * @param args Arguments + * @returns `this` + */ + public emit(evt: string, ...args: any[]): this; + } + + /** Reads / writes floats / doubles from / to buffers. */ + namespace float { + + /** + * Writes a 32 bit float to a buffer using little endian byte order. + * @param val Value to write + * @param buf Target buffer + * @param pos Target buffer offset + */ + function writeFloatLE(val: number, buf: Uint8Array, pos: number): void; + + /** + * Writes a 32 bit float to a buffer using big endian byte order. + * @param val Value to write + * @param buf Target buffer + * @param pos Target buffer offset + */ + function writeFloatBE(val: number, buf: Uint8Array, pos: number): void; + + /** + * Reads a 32 bit float from a buffer using little endian byte order. + * @param buf Source buffer + * @param pos Source buffer offset + * @returns Value read + */ + function readFloatLE(buf: Uint8Array, pos: number): number; + + /** + * Reads a 32 bit float from a buffer using big endian byte order. + * @param buf Source buffer + * @param pos Source buffer offset + * @returns Value read + */ + function readFloatBE(buf: Uint8Array, pos: number): number; + + /** + * Writes a 64 bit double to a buffer using little endian byte order. + * @param val Value to write + * @param buf Target buffer + * @param pos Target buffer offset + */ + function writeDoubleLE(val: number, buf: Uint8Array, pos: number): void; + + /** + * Writes a 64 bit double to a buffer using big endian byte order. + * @param val Value to write + * @param buf Target buffer + * @param pos Target buffer offset + */ + function writeDoubleBE(val: number, buf: Uint8Array, pos: number): void; + + /** + * Reads a 64 bit double from a buffer using little endian byte order. + * @param buf Source buffer + * @param pos Source buffer offset + * @returns Value read + */ + function readDoubleLE(buf: Uint8Array, pos: number): number; + + /** + * Reads a 64 bit double from a buffer using big endian byte order. + * @param buf Source buffer + * @param pos Source buffer offset + * @returns Value read + */ + function readDoubleBE(buf: Uint8Array, pos: number): number; + } + + /** + * Fetches the contents of a file. + * @param filename File path or url + * @param options Fetch options + * @param callback Callback function + */ + function fetch(filename: string, options: IFetchOptions, callback: FetchCallback): void; + + /** + * Fetches the contents of a file. + * @param path File path or url + * @param callback Callback function + */ + function fetch(path: string, callback: FetchCallback): void; + + /** + * Fetches the contents of a file. + * @param path File path or url + * @param [options] Fetch options + * @returns Promise + */ + function fetch(path: string, options?: IFetchOptions): Promise<(string|Uint8Array)>; + + /** + * Requires a module only if available. + * @param moduleName Module to require + * @returns Required module if available and not empty, otherwise `null` + */ + function inquire(moduleName: string): object; + + /** A minimal path module to resolve Unix, Windows and URL paths alike. */ + namespace path { + + /** + * Tests if the specified path is absolute. + * @param path Path to test + * @returns `true` if path is absolute + */ + function isAbsolute(path: string): boolean; + + /** + * Normalizes the specified path. + * @param path Path to normalize + * @returns Normalized path + */ + function normalize(path: string): string; + + /** + * Resolves the specified include path against the specified origin path. + * @param originPath Path to the origin file + * @param includePath Include path relative to origin path + * @param [alreadyNormalized=false] `true` if both paths are already known to be normalized + * @returns Path to the include file + */ + function resolve(originPath: string, includePath: string, alreadyNormalized?: boolean): string; + } + + /** + * A general purpose buffer pool. + * @param alloc Allocator + * @param slice Slicer + * @param [size=8192] Slab size + * @returns Pooled allocator + */ + function pool(alloc: PoolAllocator, slice: PoolSlicer, size?: number): PoolAllocator; + + /** A minimal UTF8 implementation for number arrays. */ + namespace utf8 { + + /** + * Calculates the UTF8 byte length of a string. + * @param string String + * @returns Byte length + */ + function length(string: string): number; + + /** + * Reads UTF8 bytes as a string. + * @param buffer Source buffer + * @param start Source start + * @param end Source end + * @returns String read + */ + function read(buffer: Uint8Array, start: number, end: number): string; + + /** + * Writes a string as UTF8 bytes. + * @param string Source string + * @param buffer Destination buffer + * @param offset Destination offset + * @returns Bytes written + */ + function write(string: string, buffer: Uint8Array, offset: number): number; + } +} + +/** + * Generates a verifier specific to the specified message type. + * @param mtype Message type + * @returns Codegen instance + */ +export function verifier(mtype: Type): Codegen; + +/** Wrappers for common types. */ +export const wrappers: { [k: string]: IWrapper }; + +/** + * From object converter part of an {@link IWrapper}. + * @param object Plain object + * @returns Message instance + */ +type WrapperFromObjectConverter = (this: Type, object: { [k: string]: any }) => Message<{}>; + +/** + * To object converter part of an {@link IWrapper}. + * @param message Message instance + * @param [options] Conversion options + * @returns Plain object + */ +type WrapperToObjectConverter = (this: Type, message: Message<{}>, options?: IConversionOptions) => { [k: string]: any }; + +/** Common type wrapper part of {@link wrappers}. */ +export interface IWrapper { + + /** From object converter */ + fromObject?: WrapperFromObjectConverter; + + /** To object converter */ + toObject?: WrapperToObjectConverter; +} + +/** Wire format writer using `Uint8Array` if available, otherwise `Array`. */ +export class Writer { + + /** Constructs a new writer instance. */ + constructor(); + + /** Current length. */ + public len: number; + + /** Operations head. */ + public head: object; + + /** Operations tail */ + public tail: object; + + /** Linked forked states. */ + public states: (object|null); + + /** + * Creates a new writer. + * @returns A {@link BufferWriter} when Buffers are supported, otherwise a {@link Writer} + */ + public static create(): (BufferWriter|Writer); + + /** + * Allocates a buffer of the specified size. + * @param size Buffer size + * @returns Buffer + */ + public static alloc(size: number): Uint8Array; + + /** + * Writes an unsigned 32 bit value as a varint. + * @param value Value to write + * @returns `this` + */ + public uint32(value: number): Writer; + + /** + * Writes a signed 32 bit value as a varint. + * @param value Value to write + * @returns `this` + */ + public int32(value: number): Writer; + + /** + * Writes a 32 bit value as a varint, zig-zag encoded. + * @param value Value to write + * @returns `this` + */ + public sint32(value: number): Writer; + + /** + * Writes an unsigned 64 bit value as a varint. + * @param value Value to write + * @returns `this` + * @throws {TypeError} If `value` is a string and no long library is present. + */ + public uint64(value: (Long|number|string)): Writer; + + /** + * Writes a signed 64 bit value as a varint. + * @param value Value to write + * @returns `this` + * @throws {TypeError} If `value` is a string and no long library is present. + */ + public int64(value: (Long|number|string)): Writer; + + /** + * Writes a signed 64 bit value as a varint, zig-zag encoded. + * @param value Value to write + * @returns `this` + * @throws {TypeError} If `value` is a string and no long library is present. + */ + public sint64(value: (Long|number|string)): Writer; + + /** + * Writes a boolish value as a varint. + * @param value Value to write + * @returns `this` + */ + public bool(value: boolean): Writer; + + /** + * Writes an unsigned 32 bit value as fixed 32 bits. + * @param value Value to write + * @returns `this` + */ + public fixed32(value: number): Writer; + + /** + * Writes a signed 32 bit value as fixed 32 bits. + * @param value Value to write + * @returns `this` + */ + public sfixed32(value: number): Writer; + + /** + * Writes an unsigned 64 bit value as fixed 64 bits. + * @param value Value to write + * @returns `this` + * @throws {TypeError} If `value` is a string and no long library is present. + */ + public fixed64(value: (Long|number|string)): Writer; + + /** + * Writes a signed 64 bit value as fixed 64 bits. + * @param value Value to write + * @returns `this` + * @throws {TypeError} If `value` is a string and no long library is present. + */ + public sfixed64(value: (Long|number|string)): Writer; + + /** + * Writes a float (32 bit). + * @param value Value to write + * @returns `this` + */ + public float(value: number): Writer; + + /** + * Writes a double (64 bit float). + * @param value Value to write + * @returns `this` + */ + public double(value: number): Writer; + + /** + * Writes a sequence of bytes. + * @param value Buffer or base64 encoded string to write + * @returns `this` + */ + public bytes(value: (Uint8Array|string)): Writer; + + /** + * Writes a string. + * @param value Value to write + * @returns `this` + */ + public string(value: string): Writer; + + /** + * Forks this writer's state by pushing it to a stack. + * Calling {@link Writer#reset|reset} or {@link Writer#ldelim|ldelim} resets the writer to the previous state. + * @returns `this` + */ + public fork(): Writer; + + /** + * Resets this instance to the last state. + * @returns `this` + */ + public reset(): Writer; + + /** + * Resets to the last state and appends the fork state's current write length as a varint followed by its operations. + * @returns `this` + */ + public ldelim(): Writer; + + /** + * Finishes the write operation. + * @returns Finished buffer + */ + public finish(): Uint8Array; +} + +/** Wire format writer using node buffers. */ +export class BufferWriter extends Writer { + + /** Constructs a new buffer writer instance. */ + constructor(); + + /** + * Allocates a buffer of the specified size. + * @param size Buffer size + * @returns Buffer + */ + public static alloc(size: number): Buffer; + + /** + * Finishes the write operation. + * @returns Finished buffer + */ + public finish(): Buffer; +} + +/** + * Callback as used by {@link util.asPromise}. + * @param error Error, if any + * @param params Additional arguments + */ +type asPromiseCallback = (error: (Error|null), ...params: any[]) => void; + +/** + * Appends code to the function's body or finishes generation. + * @param [formatStringOrScope] Format string or, to finish the function, an object of additional scope variables, if any + * @param [formatParams] Format parameters + * @returns Itself or the generated function if finished + * @throws {Error} If format parameter counts do not match + */ +type Codegen = (formatStringOrScope?: (string|{ [k: string]: any }), ...formatParams: any[]) => (Codegen|Function); + +/** + * Event listener as used by {@link util.EventEmitter}. + * @param args Arguments + */ +type EventEmitterListener = (...args: any[]) => void; + +/** + * Node-style callback as used by {@link util.fetch}. + * @param error Error, if any, otherwise `null` + * @param [contents] File contents, if there hasn't been an error + */ +type FetchCallback = (error: Error, contents?: string) => void; + +/** Options as used by {@link util.fetch}. */ +export interface IFetchOptions { + + /** Whether expecting a binary response */ + binary?: boolean; + + /** If `true`, forces the use of XMLHttpRequest */ + xhr?: boolean; +} + +/** + * An allocator as used by {@link util.pool}. + * @param size Buffer size + * @returns Buffer + */ +type PoolAllocator = (size: number) => Uint8Array; + +/** + * A slicer as used by {@link util.pool}. + * @param start Start offset + * @param end End offset + * @returns Buffer slice + */ +type PoolSlicer = (this: Uint8Array, start: number, end: number) => Uint8Array; diff --git a/node_modules/protobufjs/index.js b/node_modules/protobufjs/index.js new file mode 100644 index 0000000..042042a --- /dev/null +++ b/node_modules/protobufjs/index.js @@ -0,0 +1,4 @@ +// full library entry point. + +"use strict"; +module.exports = require("./src/index"); diff --git a/node_modules/protobufjs/light.d.ts b/node_modules/protobufjs/light.d.ts new file mode 100644 index 0000000..d83e7f9 --- /dev/null +++ b/node_modules/protobufjs/light.d.ts @@ -0,0 +1,2 @@ +export as namespace protobuf; +export * from "./index"; diff --git a/node_modules/protobufjs/light.js b/node_modules/protobufjs/light.js new file mode 100644 index 0000000..1209e64 --- /dev/null +++ b/node_modules/protobufjs/light.js @@ -0,0 +1,4 @@ +// light library entry point. + +"use strict"; +module.exports = require("./src/index-light"); \ No newline at end of file diff --git a/node_modules/protobufjs/minimal.d.ts b/node_modules/protobufjs/minimal.d.ts new file mode 100644 index 0000000..d83e7f9 --- /dev/null +++ b/node_modules/protobufjs/minimal.d.ts @@ -0,0 +1,2 @@ +export as namespace protobuf; +export * from "./index"; diff --git a/node_modules/protobufjs/minimal.js b/node_modules/protobufjs/minimal.js new file mode 100644 index 0000000..1f35ec9 --- /dev/null +++ b/node_modules/protobufjs/minimal.js @@ -0,0 +1,4 @@ +// minimal library entry point. + +"use strict"; +module.exports = require("./src/index-minimal"); diff --git a/node_modules/protobufjs/package.json b/node_modules/protobufjs/package.json new file mode 100644 index 0000000..8a0e4cb --- /dev/null +++ b/node_modules/protobufjs/package.json @@ -0,0 +1,111 @@ +{ + "name": "protobufjs", + "version": "7.3.0", + "versionScheme": "~", + "description": "Protocol Buffers for JavaScript (& TypeScript).", + "author": "Daniel Wirtz ", + "license": "BSD-3-Clause", + "repository": "protobufjs/protobuf.js", + "bugs": "https://github.com/protobufjs/protobuf.js/issues", + "homepage": "https://protobufjs.github.io/protobuf.js/", + "engines": { + "node": ">=12.0.0" + }, + "eslintConfig": { + "env": { + "es6": true + }, + "parserOptions": { + "ecmaVersion": 6 + } + }, + "keywords": [ + "protobuf", + "protocol-buffers", + "serialization", + "typescript" + ], + "main": "index.js", + "types": "index.d.ts", + "scripts": { + "bench": "node bench", + "build": "npm run build:bundle && npm run build:types", + "build:bundle": "gulp --gulpfile scripts/gulpfile.js", + "build:types": "node cli/bin/pbts --main --global protobuf --out index.d.ts src/ lib/aspromise/index.js lib/base64/index.js lib/codegen/index.js lib/eventemitter/index.js lib/float/index.js lib/fetch/index.js lib/inquire/index.js lib/path/index.js lib/pool/index.js lib/utf8/index.js", + "changelog": "node scripts/changelog -w", + "coverage": "nyc tape -r ./lib/tape-adapter tests/*.js tests/node/*.js", + "docs": "jsdoc -c config/jsdoc.json -R README.md --verbose --pedantic", + "lint": "npm run lint:sources && npm run lint:types", + "lint:sources": "eslint \"**/*.js\" -c config/eslint.json", + "lint:types": "tslint \"**/*.d.ts\" -e \"**/node_modules/**\" -t stylish -c config/tslint.json", + "pages": "node scripts/pages", + "prepublish": "cd cli && npm install && cd .. && npm run build", + "postinstall": "node scripts/postinstall", + "prof": "node bench/prof", + "test": "npm run test:sources && npm run test:types", + "test:sources": "tape -r ./lib/tape-adapter tests/*.js tests/node/*.js", + "test:types": "tsc tests/comp_typescript.ts --lib es2015 --esModuleInterop --strictNullChecks --experimentalDecorators --emitDecoratorMetadata && tsc tests/data/test.js.ts --lib es2015 --esModuleInterop --noEmit --strictNullChecks && tsc tests/data/*.ts --lib es2015 --esModuleInterop --noEmit --strictNullChecks", + "make": "npm run lint:sources && npm run build && npm run lint:types && node ./scripts/gentests.js && npm test" + }, + "dependencies": { + "@protobufjs/aspromise": "^1.1.2", + "@protobufjs/base64": "^1.1.2", + "@protobufjs/codegen": "^2.0.4", + "@protobufjs/eventemitter": "^1.1.0", + "@protobufjs/fetch": "^1.1.0", + "@protobufjs/float": "^1.0.2", + "@protobufjs/inquire": "^1.1.0", + "@protobufjs/path": "^1.1.2", + "@protobufjs/pool": "^1.1.0", + "@protobufjs/utf8": "^1.1.0", + "@types/node": ">=13.7.0", + "long": "^5.0.0" + }, + "devDependencies": { + "benchmark": "^2.1.4", + "browserify": "^17.0.0", + "browserify-wrap": "^1.0.2", + "bundle-collapser": "^1.3.0", + "chalk": "^4.0.0", + "escodegen": "^1.13.0", + "eslint": "^8.15.0", + "espree": "^9.0.0", + "estraverse": "^5.1.0", + "gh-pages": "^4.0.0", + "git-raw-commits": "^2.0.3", + "git-semver-tags": "^4.0.0", + "google-protobuf": "^3.11.3", + "gulp": "^4.0.2", + "gulp-header": "^2.0.9", + "gulp-if": "^3.0.0", + "gulp-sourcemaps": "^3.0.0", + "gulp-uglify": "^3.0.2", + "jaguarjs-jsdoc": "github:dcodeIO/jaguarjs-jsdoc", + "jsdoc": "^4.0.0", + "minimist": "^1.2.0", + "nyc": "^15.0.0", + "reflect-metadata": "^0.1.13", + "tape": "^5.0.0", + "tslint": "^6.0.0", + "typescript": "^3.7.5", + "uglify-js": "^3.7.7", + "vinyl-buffer": "^1.0.1", + "vinyl-fs": "^3.0.3", + "vinyl-source-stream": "^2.0.0" + }, + "files": [ + "index.js", + "index.d.ts", + "light.d.ts", + "light.js", + "minimal.d.ts", + "minimal.js", + "package-lock.json", + "tsconfig.json", + "scripts/postinstall.js", + "dist/**", + "ext/**", + "google/**", + "src/**" + ] +} diff --git a/node_modules/protobufjs/scripts/postinstall.js b/node_modules/protobufjs/scripts/postinstall.js new file mode 100644 index 0000000..bf4ff45 --- /dev/null +++ b/node_modules/protobufjs/scripts/postinstall.js @@ -0,0 +1,32 @@ +"use strict"; + +var path = require("path"), + fs = require("fs"), + pkg = require(path.join(__dirname, "..", "package.json")); + +// check version scheme used by dependents +if (!pkg.versionScheme) + return; + +var warn = process.stderr.isTTY + ? "\x1b[30m\x1b[43mWARN\x1b[0m \x1b[35m" + path.basename(process.argv[1], ".js") + "\x1b[0m" + : "WARN " + path.basename(process.argv[1], ".js"); + +var basePkg; +try { + basePkg = JSON.parse(fs.readFileSync(path.join(__dirname, "..", "..", "package.json"))); +} catch (e) { + return; +} + +[ + "dependencies", + "devDependencies", + "optionalDependencies", + "peerDependencies" +] +.forEach(function(check) { + var version = basePkg && basePkg[check] && basePkg[check][pkg.name]; + if (typeof version === "string" && version.charAt(0) !== pkg.versionScheme) + process.stderr.write(pkg.name + " " + warn + " " + pkg.name + "@" + version + " is configured as a dependency of " + basePkg.name + ". use " + pkg.name + "@" + pkg.versionScheme + version.substring(1) + " instead for API compatibility.\n"); +}); diff --git a/node_modules/protobufjs/src/common.js b/node_modules/protobufjs/src/common.js new file mode 100644 index 0000000..489ee1c --- /dev/null +++ b/node_modules/protobufjs/src/common.js @@ -0,0 +1,399 @@ +"use strict"; +module.exports = common; + +var commonRe = /\/|\./; + +/** + * Provides common type definitions. + * Can also be used to provide additional google types or your own custom types. + * @param {string} name Short name as in `google/protobuf/[name].proto` or full file name + * @param {Object.} json JSON definition within `google.protobuf` if a short name, otherwise the file's root definition + * @returns {undefined} + * @property {INamespace} google/protobuf/any.proto Any + * @property {INamespace} google/protobuf/duration.proto Duration + * @property {INamespace} google/protobuf/empty.proto Empty + * @property {INamespace} google/protobuf/field_mask.proto FieldMask + * @property {INamespace} google/protobuf/struct.proto Struct, Value, NullValue and ListValue + * @property {INamespace} google/protobuf/timestamp.proto Timestamp + * @property {INamespace} google/protobuf/wrappers.proto Wrappers + * @example + * // manually provides descriptor.proto (assumes google/protobuf/ namespace and .proto extension) + * protobuf.common("descriptor", descriptorJson); + * + * // manually provides a custom definition (uses my.foo namespace) + * protobuf.common("my/foo/bar.proto", myFooBarJson); + */ +function common(name, json) { + if (!commonRe.test(name)) { + name = "google/protobuf/" + name + ".proto"; + json = { nested: { google: { nested: { protobuf: { nested: json } } } } }; + } + common[name] = json; +} + +// Not provided because of limited use (feel free to discuss or to provide yourself): +// +// google/protobuf/descriptor.proto +// google/protobuf/source_context.proto +// google/protobuf/type.proto +// +// Stripped and pre-parsed versions of these non-bundled files are instead available as part of +// the repository or package within the google/protobuf directory. + +common("any", { + + /** + * Properties of a google.protobuf.Any message. + * @interface IAny + * @type {Object} + * @property {string} [typeUrl] + * @property {Uint8Array} [bytes] + * @memberof common + */ + Any: { + fields: { + type_url: { + type: "string", + id: 1 + }, + value: { + type: "bytes", + id: 2 + } + } + } +}); + +var timeType; + +common("duration", { + + /** + * Properties of a google.protobuf.Duration message. + * @interface IDuration + * @type {Object} + * @property {number|Long} [seconds] + * @property {number} [nanos] + * @memberof common + */ + Duration: timeType = { + fields: { + seconds: { + type: "int64", + id: 1 + }, + nanos: { + type: "int32", + id: 2 + } + } + } +}); + +common("timestamp", { + + /** + * Properties of a google.protobuf.Timestamp message. + * @interface ITimestamp + * @type {Object} + * @property {number|Long} [seconds] + * @property {number} [nanos] + * @memberof common + */ + Timestamp: timeType +}); + +common("empty", { + + /** + * Properties of a google.protobuf.Empty message. + * @interface IEmpty + * @memberof common + */ + Empty: { + fields: {} + } +}); + +common("struct", { + + /** + * Properties of a google.protobuf.Struct message. + * @interface IStruct + * @type {Object} + * @property {Object.} [fields] + * @memberof common + */ + Struct: { + fields: { + fields: { + keyType: "string", + type: "Value", + id: 1 + } + } + }, + + /** + * Properties of a google.protobuf.Value message. + * @interface IValue + * @type {Object} + * @property {string} [kind] + * @property {0} [nullValue] + * @property {number} [numberValue] + * @property {string} [stringValue] + * @property {boolean} [boolValue] + * @property {IStruct} [structValue] + * @property {IListValue} [listValue] + * @memberof common + */ + Value: { + oneofs: { + kind: { + oneof: [ + "nullValue", + "numberValue", + "stringValue", + "boolValue", + "structValue", + "listValue" + ] + } + }, + fields: { + nullValue: { + type: "NullValue", + id: 1 + }, + numberValue: { + type: "double", + id: 2 + }, + stringValue: { + type: "string", + id: 3 + }, + boolValue: { + type: "bool", + id: 4 + }, + structValue: { + type: "Struct", + id: 5 + }, + listValue: { + type: "ListValue", + id: 6 + } + } + }, + + NullValue: { + values: { + NULL_VALUE: 0 + } + }, + + /** + * Properties of a google.protobuf.ListValue message. + * @interface IListValue + * @type {Object} + * @property {Array.} [values] + * @memberof common + */ + ListValue: { + fields: { + values: { + rule: "repeated", + type: "Value", + id: 1 + } + } + } +}); + +common("wrappers", { + + /** + * Properties of a google.protobuf.DoubleValue message. + * @interface IDoubleValue + * @type {Object} + * @property {number} [value] + * @memberof common + */ + DoubleValue: { + fields: { + value: { + type: "double", + id: 1 + } + } + }, + + /** + * Properties of a google.protobuf.FloatValue message. + * @interface IFloatValue + * @type {Object} + * @property {number} [value] + * @memberof common + */ + FloatValue: { + fields: { + value: { + type: "float", + id: 1 + } + } + }, + + /** + * Properties of a google.protobuf.Int64Value message. + * @interface IInt64Value + * @type {Object} + * @property {number|Long} [value] + * @memberof common + */ + Int64Value: { + fields: { + value: { + type: "int64", + id: 1 + } + } + }, + + /** + * Properties of a google.protobuf.UInt64Value message. + * @interface IUInt64Value + * @type {Object} + * @property {number|Long} [value] + * @memberof common + */ + UInt64Value: { + fields: { + value: { + type: "uint64", + id: 1 + } + } + }, + + /** + * Properties of a google.protobuf.Int32Value message. + * @interface IInt32Value + * @type {Object} + * @property {number} [value] + * @memberof common + */ + Int32Value: { + fields: { + value: { + type: "int32", + id: 1 + } + } + }, + + /** + * Properties of a google.protobuf.UInt32Value message. + * @interface IUInt32Value + * @type {Object} + * @property {number} [value] + * @memberof common + */ + UInt32Value: { + fields: { + value: { + type: "uint32", + id: 1 + } + } + }, + + /** + * Properties of a google.protobuf.BoolValue message. + * @interface IBoolValue + * @type {Object} + * @property {boolean} [value] + * @memberof common + */ + BoolValue: { + fields: { + value: { + type: "bool", + id: 1 + } + } + }, + + /** + * Properties of a google.protobuf.StringValue message. + * @interface IStringValue + * @type {Object} + * @property {string} [value] + * @memberof common + */ + StringValue: { + fields: { + value: { + type: "string", + id: 1 + } + } + }, + + /** + * Properties of a google.protobuf.BytesValue message. + * @interface IBytesValue + * @type {Object} + * @property {Uint8Array} [value] + * @memberof common + */ + BytesValue: { + fields: { + value: { + type: "bytes", + id: 1 + } + } + } +}); + +common("field_mask", { + + /** + * Properties of a google.protobuf.FieldMask message. + * @interface IDoubleValue + * @type {Object} + * @property {number} [value] + * @memberof common + */ + FieldMask: { + fields: { + paths: { + rule: "repeated", + type: "string", + id: 1 + } + } + } +}); + +/** + * Gets the root definition of the specified common proto file. + * + * Bundled definitions are: + * - google/protobuf/any.proto + * - google/protobuf/duration.proto + * - google/protobuf/empty.proto + * - google/protobuf/field_mask.proto + * - google/protobuf/struct.proto + * - google/protobuf/timestamp.proto + * - google/protobuf/wrappers.proto + * + * @param {string} file Proto file name + * @returns {INamespace|null} Root definition or `null` if not defined + */ +common.get = function get(file) { + return common[file] || null; +}; diff --git a/node_modules/protobufjs/src/converter.js b/node_modules/protobufjs/src/converter.js new file mode 100644 index 0000000..086e003 --- /dev/null +++ b/node_modules/protobufjs/src/converter.js @@ -0,0 +1,301 @@ +"use strict"; +/** + * Runtime message from/to plain object converters. + * @namespace + */ +var converter = exports; + +var Enum = require("./enum"), + util = require("./util"); + +/** + * Generates a partial value fromObject conveter. + * @param {Codegen} gen Codegen instance + * @param {Field} field Reflected field + * @param {number} fieldIndex Field index + * @param {string} prop Property reference + * @returns {Codegen} Codegen instance + * @ignore + */ +function genValuePartial_fromObject(gen, field, fieldIndex, prop) { + var defaultAlreadyEmitted = false; + /* eslint-disable no-unexpected-multiline, block-scoped-var, no-redeclare */ + if (field.resolvedType) { + if (field.resolvedType instanceof Enum) { gen + ("switch(d%s){", prop); + for (var values = field.resolvedType.values, keys = Object.keys(values), i = 0; i < keys.length; ++i) { + // enum unknown values passthrough + if (values[keys[i]] === field.typeDefault && !defaultAlreadyEmitted) { gen + ("default:") + ("if(typeof(d%s)===\"number\"){m%s=d%s;break}", prop, prop, prop); + if (!field.repeated) gen // fallback to default value only for + // arrays, to avoid leaving holes. + ("break"); // for non-repeated fields, just ignore + defaultAlreadyEmitted = true; + } + gen + ("case%j:", keys[i]) + ("case %i:", values[keys[i]]) + ("m%s=%j", prop, values[keys[i]]) + ("break"); + } gen + ("}"); + } else gen + ("if(typeof d%s!==\"object\")", prop) + ("throw TypeError(%j)", field.fullName + ": object expected") + ("m%s=types[%i].fromObject(d%s)", prop, fieldIndex, prop); + } else { + var isUnsigned = false; + switch (field.type) { + case "double": + case "float": gen + ("m%s=Number(d%s)", prop, prop); // also catches "NaN", "Infinity" + break; + case "uint32": + case "fixed32": gen + ("m%s=d%s>>>0", prop, prop); + break; + case "int32": + case "sint32": + case "sfixed32": gen + ("m%s=d%s|0", prop, prop); + break; + case "uint64": + isUnsigned = true; + // eslint-disable-next-line no-fallthrough + case "int64": + case "sint64": + case "fixed64": + case "sfixed64": gen + ("if(util.Long)") + ("(m%s=util.Long.fromValue(d%s)).unsigned=%j", prop, prop, isUnsigned) + ("else if(typeof d%s===\"string\")", prop) + ("m%s=parseInt(d%s,10)", prop, prop) + ("else if(typeof d%s===\"number\")", prop) + ("m%s=d%s", prop, prop) + ("else if(typeof d%s===\"object\")", prop) + ("m%s=new util.LongBits(d%s.low>>>0,d%s.high>>>0).toNumber(%s)", prop, prop, prop, isUnsigned ? "true" : ""); + break; + case "bytes": gen + ("if(typeof d%s===\"string\")", prop) + ("util.base64.decode(d%s,m%s=util.newBuffer(util.base64.length(d%s)),0)", prop, prop, prop) + ("else if(d%s.length >= 0)", prop) + ("m%s=d%s", prop, prop); + break; + case "string": gen + ("m%s=String(d%s)", prop, prop); + break; + case "bool": gen + ("m%s=Boolean(d%s)", prop, prop); + break; + /* default: gen + ("m%s=d%s", prop, prop); + break; */ + } + } + return gen; + /* eslint-enable no-unexpected-multiline, block-scoped-var, no-redeclare */ +} + +/** + * Generates a plain object to runtime message converter specific to the specified message type. + * @param {Type} mtype Message type + * @returns {Codegen} Codegen instance + */ +converter.fromObject = function fromObject(mtype) { + /* eslint-disable no-unexpected-multiline, block-scoped-var, no-redeclare */ + var fields = mtype.fieldsArray; + var gen = util.codegen(["d"], mtype.name + "$fromObject") + ("if(d instanceof this.ctor)") + ("return d"); + if (!fields.length) return gen + ("return new this.ctor"); + gen + ("var m=new this.ctor"); + for (var i = 0; i < fields.length; ++i) { + var field = fields[i].resolve(), + prop = util.safeProp(field.name); + + // Map fields + if (field.map) { gen + ("if(d%s){", prop) + ("if(typeof d%s!==\"object\")", prop) + ("throw TypeError(%j)", field.fullName + ": object expected") + ("m%s={}", prop) + ("for(var ks=Object.keys(d%s),i=0;i>>0,m%s.high>>>0).toNumber(%s):m%s", prop, prop, prop, prop, isUnsigned ? "true": "", prop); + break; + case "bytes": gen + ("d%s=o.bytes===String?util.base64.encode(m%s,0,m%s.length):o.bytes===Array?Array.prototype.slice.call(m%s):m%s", prop, prop, prop, prop, prop); + break; + default: gen + ("d%s=m%s", prop, prop); + break; + } + } + return gen; + /* eslint-enable no-unexpected-multiline, block-scoped-var, no-redeclare */ +} + +/** + * Generates a runtime message to plain object converter specific to the specified message type. + * @param {Type} mtype Message type + * @returns {Codegen} Codegen instance + */ +converter.toObject = function toObject(mtype) { + /* eslint-disable no-unexpected-multiline, block-scoped-var, no-redeclare */ + var fields = mtype.fieldsArray.slice().sort(util.compareFieldsById); + if (!fields.length) + return util.codegen()("return {}"); + var gen = util.codegen(["m", "o"], mtype.name + "$toObject") + ("if(!o)") + ("o={}") + ("var d={}"); + + var repeatedFields = [], + mapFields = [], + normalFields = [], + i = 0; + for (; i < fields.length; ++i) + if (!fields[i].partOf) + ( fields[i].resolve().repeated ? repeatedFields + : fields[i].map ? mapFields + : normalFields).push(fields[i]); + + if (repeatedFields.length) { gen + ("if(o.arrays||o.defaults){"); + for (i = 0; i < repeatedFields.length; ++i) gen + ("d%s=[]", util.safeProp(repeatedFields[i].name)); + gen + ("}"); + } + + if (mapFields.length) { gen + ("if(o.objects||o.defaults){"); + for (i = 0; i < mapFields.length; ++i) gen + ("d%s={}", util.safeProp(mapFields[i].name)); + gen + ("}"); + } + + if (normalFields.length) { gen + ("if(o.defaults){"); + for (i = 0; i < normalFields.length; ++i) { + var field = normalFields[i], + prop = util.safeProp(field.name); + if (field.resolvedType instanceof Enum) gen + ("d%s=o.enums===String?%j:%j", prop, field.resolvedType.valuesById[field.typeDefault], field.typeDefault); + else if (field.long) gen + ("if(util.Long){") + ("var n=new util.Long(%i,%i,%j)", field.typeDefault.low, field.typeDefault.high, field.typeDefault.unsigned) + ("d%s=o.longs===String?n.toString():o.longs===Number?n.toNumber():n", prop) + ("}else") + ("d%s=o.longs===String?%j:%i", prop, field.typeDefault.toString(), field.typeDefault.toNumber()); + else if (field.bytes) { + var arrayDefault = "[" + Array.prototype.slice.call(field.typeDefault).join(",") + "]"; + gen + ("if(o.bytes===String)d%s=%j", prop, String.fromCharCode.apply(String, field.typeDefault)) + ("else{") + ("d%s=%s", prop, arrayDefault) + ("if(o.bytes!==Array)d%s=util.newBuffer(d%s)", prop, prop) + ("}"); + } else gen + ("d%s=%j", prop, field.typeDefault); // also messages (=null) + } gen + ("}"); + } + var hasKs2 = false; + for (i = 0; i < fields.length; ++i) { + var field = fields[i], + index = mtype._fieldsArray.indexOf(field), + prop = util.safeProp(field.name); + if (field.map) { + if (!hasKs2) { hasKs2 = true; gen + ("var ks2"); + } gen + ("if(m%s&&(ks2=Object.keys(m%s)).length){", prop, prop) + ("d%s={}", prop) + ("for(var j=0;j>>3){"); + + var i = 0; + for (; i < /* initializes */ mtype.fieldsArray.length; ++i) { + var field = mtype._fieldsArray[i].resolve(), + type = field.resolvedType instanceof Enum ? "int32" : field.type, + ref = "m" + util.safeProp(field.name); gen + ("case %i: {", field.id); + + // Map fields + if (field.map) { gen + ("if(%s===util.emptyObject)", ref) + ("%s={}", ref) + ("var c2 = r.uint32()+r.pos"); + + if (types.defaults[field.keyType] !== undefined) gen + ("k=%j", types.defaults[field.keyType]); + else gen + ("k=null"); + + if (types.defaults[type] !== undefined) gen + ("value=%j", types.defaults[type]); + else gen + ("value=null"); + + gen + ("while(r.pos>>3){") + ("case 1: k=r.%s(); break", field.keyType) + ("case 2:"); + + if (types.basic[type] === undefined) gen + ("value=types[%i].decode(r,r.uint32())", i); // can't be groups + else gen + ("value=r.%s()", type); + + gen + ("break") + ("default:") + ("r.skipType(tag2&7)") + ("break") + ("}") + ("}"); + + if (types.long[field.keyType] !== undefined) gen + ("%s[typeof k===\"object\"?util.longToHash(k):k]=value", ref); + else gen + ("%s[k]=value", ref); + + // Repeated fields + } else if (field.repeated) { gen + + ("if(!(%s&&%s.length))", ref, ref) + ("%s=[]", ref); + + // Packable (always check for forward and backward compatiblity) + if (types.packed[type] !== undefined) gen + ("if((t&7)===2){") + ("var c2=r.uint32()+r.pos") + ("while(r.pos>> 0, (field.id << 3 | 4) >>> 0) + : gen("types[%i].encode(%s,w.uint32(%i).fork()).ldelim()", fieldIndex, ref, (field.id << 3 | 2) >>> 0); +} + +/** + * Generates an encoder specific to the specified message type. + * @param {Type} mtype Message type + * @returns {Codegen} Codegen instance + */ +function encoder(mtype) { + /* eslint-disable no-unexpected-multiline, block-scoped-var, no-redeclare */ + var gen = util.codegen(["m", "w"], mtype.name + "$encode") + ("if(!w)") + ("w=Writer.create()"); + + var i, ref; + + // "when a message is serialized its known fields should be written sequentially by field number" + var fields = /* initializes */ mtype.fieldsArray.slice().sort(util.compareFieldsById); + + for (var i = 0; i < fields.length; ++i) { + var field = fields[i].resolve(), + index = mtype._fieldsArray.indexOf(field), + type = field.resolvedType instanceof Enum ? "int32" : field.type, + wireType = types.basic[type]; + ref = "m" + util.safeProp(field.name); + + // Map fields + if (field.map) { + gen + ("if(%s!=null&&Object.hasOwnProperty.call(m,%j)){", ref, field.name) // !== undefined && !== null + ("for(var ks=Object.keys(%s),i=0;i>> 0, 8 | types.mapKey[field.keyType], field.keyType); + if (wireType === undefined) gen + ("types[%i].encode(%s[ks[i]],w.uint32(18).fork()).ldelim().ldelim()", index, ref); // can't be groups + else gen + (".uint32(%i).%s(%s[ks[i]]).ldelim()", 16 | wireType, type, ref); + gen + ("}") + ("}"); + + // Repeated fields + } else if (field.repeated) { gen + ("if(%s!=null&&%s.length){", ref, ref); // !== undefined && !== null + + // Packed repeated + if (field.packed && types.packed[type] !== undefined) { gen + + ("w.uint32(%i).fork()", (field.id << 3 | 2) >>> 0) + ("for(var i=0;i<%s.length;++i)", ref) + ("w.%s(%s[i])", type, ref) + ("w.ldelim()"); + + // Non-packed + } else { gen + + ("for(var i=0;i<%s.length;++i)", ref); + if (wireType === undefined) + genTypePartial(gen, field, index, ref + "[i]"); + else gen + ("w.uint32(%i).%s(%s[i])", (field.id << 3 | wireType) >>> 0, type, ref); + + } gen + ("}"); + + // Non-repeated + } else { + if (field.optional) gen + ("if(%s!=null&&Object.hasOwnProperty.call(m,%j))", ref, field.name); // !== undefined && !== null + + if (wireType === undefined) + genTypePartial(gen, field, index, ref); + else gen + ("w.uint32(%i).%s(%s)", (field.id << 3 | wireType) >>> 0, type, ref); + + } + } + + return gen + ("return w"); + /* eslint-enable no-unexpected-multiline, block-scoped-var, no-redeclare */ +} diff --git a/node_modules/protobufjs/src/enum.js b/node_modules/protobufjs/src/enum.js new file mode 100644 index 0000000..1c01620 --- /dev/null +++ b/node_modules/protobufjs/src/enum.js @@ -0,0 +1,198 @@ +"use strict"; +module.exports = Enum; + +// extends ReflectionObject +var ReflectionObject = require("./object"); +((Enum.prototype = Object.create(ReflectionObject.prototype)).constructor = Enum).className = "Enum"; + +var Namespace = require("./namespace"), + util = require("./util"); + +/** + * Constructs a new enum instance. + * @classdesc Reflected enum. + * @extends ReflectionObject + * @constructor + * @param {string} name Unique name within its namespace + * @param {Object.} [values] Enum values as an object, by name + * @param {Object.} [options] Declared options + * @param {string} [comment] The comment for this enum + * @param {Object.} [comments] The value comments for this enum + * @param {Object.>|undefined} [valuesOptions] The value options for this enum + */ +function Enum(name, values, options, comment, comments, valuesOptions) { + ReflectionObject.call(this, name, options); + + if (values && typeof values !== "object") + throw TypeError("values must be an object"); + + /** + * Enum values by id. + * @type {Object.} + */ + this.valuesById = {}; + + /** + * Enum values by name. + * @type {Object.} + */ + this.values = Object.create(this.valuesById); // toJSON, marker + + /** + * Enum comment text. + * @type {string|null} + */ + this.comment = comment; + + /** + * Value comment texts, if any. + * @type {Object.} + */ + this.comments = comments || {}; + + /** + * Values options, if any + * @type {Object>|undefined} + */ + this.valuesOptions = valuesOptions; + + /** + * Reserved ranges, if any. + * @type {Array.} + */ + this.reserved = undefined; // toJSON + + // Note that values inherit valuesById on their prototype which makes them a TypeScript- + // compatible enum. This is used by pbts to write actual enum definitions that work for + // static and reflection code alike instead of emitting generic object definitions. + + if (values) + for (var keys = Object.keys(values), i = 0; i < keys.length; ++i) + if (typeof values[keys[i]] === "number") // use forward entries only + this.valuesById[ this.values[keys[i]] = values[keys[i]] ] = keys[i]; +} + +/** + * Enum descriptor. + * @interface IEnum + * @property {Object.} values Enum values + * @property {Object.} [options] Enum options + */ + +/** + * Constructs an enum from an enum descriptor. + * @param {string} name Enum name + * @param {IEnum} json Enum descriptor + * @returns {Enum} Created enum + * @throws {TypeError} If arguments are invalid + */ +Enum.fromJSON = function fromJSON(name, json) { + var enm = new Enum(name, json.values, json.options, json.comment, json.comments); + enm.reserved = json.reserved; + return enm; +}; + +/** + * Converts this enum to an enum descriptor. + * @param {IToJSONOptions} [toJSONOptions] JSON conversion options + * @returns {IEnum} Enum descriptor + */ +Enum.prototype.toJSON = function toJSON(toJSONOptions) { + var keepComments = toJSONOptions ? Boolean(toJSONOptions.keepComments) : false; + return util.toObject([ + "options" , this.options, + "valuesOptions" , this.valuesOptions, + "values" , this.values, + "reserved" , this.reserved && this.reserved.length ? this.reserved : undefined, + "comment" , keepComments ? this.comment : undefined, + "comments" , keepComments ? this.comments : undefined + ]); +}; + +/** + * Adds a value to this enum. + * @param {string} name Value name + * @param {number} id Value id + * @param {string} [comment] Comment, if any + * @param {Object.|undefined} [options] Options, if any + * @returns {Enum} `this` + * @throws {TypeError} If arguments are invalid + * @throws {Error} If there is already a value with this name or id + */ +Enum.prototype.add = function add(name, id, comment, options) { + // utilized by the parser but not by .fromJSON + + if (!util.isString(name)) + throw TypeError("name must be a string"); + + if (!util.isInteger(id)) + throw TypeError("id must be an integer"); + + if (this.values[name] !== undefined) + throw Error("duplicate name '" + name + "' in " + this); + + if (this.isReservedId(id)) + throw Error("id " + id + " is reserved in " + this); + + if (this.isReservedName(name)) + throw Error("name '" + name + "' is reserved in " + this); + + if (this.valuesById[id] !== undefined) { + if (!(this.options && this.options.allow_alias)) + throw Error("duplicate id " + id + " in " + this); + this.values[name] = id; + } else + this.valuesById[this.values[name] = id] = name; + + if (options) { + if (this.valuesOptions === undefined) + this.valuesOptions = {}; + this.valuesOptions[name] = options || null; + } + + this.comments[name] = comment || null; + return this; +}; + +/** + * Removes a value from this enum + * @param {string} name Value name + * @returns {Enum} `this` + * @throws {TypeError} If arguments are invalid + * @throws {Error} If `name` is not a name of this enum + */ +Enum.prototype.remove = function remove(name) { + + if (!util.isString(name)) + throw TypeError("name must be a string"); + + var val = this.values[name]; + if (val == null) + throw Error("name '" + name + "' does not exist in " + this); + + delete this.valuesById[val]; + delete this.values[name]; + delete this.comments[name]; + if (this.valuesOptions) + delete this.valuesOptions[name]; + + return this; +}; + +/** + * Tests if the specified id is reserved. + * @param {number} id Id to test + * @returns {boolean} `true` if reserved, otherwise `false` + */ +Enum.prototype.isReservedId = function isReservedId(id) { + return Namespace.isReservedId(this.reserved, id); +}; + +/** + * Tests if the specified name is reserved. + * @param {string} name Name to test + * @returns {boolean} `true` if reserved, otherwise `false` + */ +Enum.prototype.isReservedName = function isReservedName(name) { + return Namespace.isReservedName(this.reserved, name); +}; diff --git a/node_modules/protobufjs/src/field.js b/node_modules/protobufjs/src/field.js new file mode 100644 index 0000000..e0feb8b --- /dev/null +++ b/node_modules/protobufjs/src/field.js @@ -0,0 +1,377 @@ +"use strict"; +module.exports = Field; + +// extends ReflectionObject +var ReflectionObject = require("./object"); +((Field.prototype = Object.create(ReflectionObject.prototype)).constructor = Field).className = "Field"; + +var Enum = require("./enum"), + types = require("./types"), + util = require("./util"); + +var Type; // cyclic + +var ruleRe = /^required|optional|repeated$/; + +/** + * Constructs a new message field instance. Note that {@link MapField|map fields} have their own class. + * @name Field + * @classdesc Reflected message field. + * @extends FieldBase + * @constructor + * @param {string} name Unique name within its namespace + * @param {number} id Unique id within its namespace + * @param {string} type Value type + * @param {string|Object.} [rule="optional"] Field rule + * @param {string|Object.} [extend] Extended type if different from parent + * @param {Object.} [options] Declared options + */ + +/** + * Constructs a field from a field descriptor. + * @param {string} name Field name + * @param {IField} json Field descriptor + * @returns {Field} Created field + * @throws {TypeError} If arguments are invalid + */ +Field.fromJSON = function fromJSON(name, json) { + return new Field(name, json.id, json.type, json.rule, json.extend, json.options, json.comment); +}; + +/** + * Not an actual constructor. Use {@link Field} instead. + * @classdesc Base class of all reflected message fields. This is not an actual class but here for the sake of having consistent type definitions. + * @exports FieldBase + * @extends ReflectionObject + * @constructor + * @param {string} name Unique name within its namespace + * @param {number} id Unique id within its namespace + * @param {string} type Value type + * @param {string|Object.} [rule="optional"] Field rule + * @param {string|Object.} [extend] Extended type if different from parent + * @param {Object.} [options] Declared options + * @param {string} [comment] Comment associated with this field + */ +function Field(name, id, type, rule, extend, options, comment) { + + if (util.isObject(rule)) { + comment = extend; + options = rule; + rule = extend = undefined; + } else if (util.isObject(extend)) { + comment = options; + options = extend; + extend = undefined; + } + + ReflectionObject.call(this, name, options); + + if (!util.isInteger(id) || id < 0) + throw TypeError("id must be a non-negative integer"); + + if (!util.isString(type)) + throw TypeError("type must be a string"); + + if (rule !== undefined && !ruleRe.test(rule = rule.toString().toLowerCase())) + throw TypeError("rule must be a string rule"); + + if (extend !== undefined && !util.isString(extend)) + throw TypeError("extend must be a string"); + + /** + * Field rule, if any. + * @type {string|undefined} + */ + if (rule === "proto3_optional") { + rule = "optional"; + } + this.rule = rule && rule !== "optional" ? rule : undefined; // toJSON + + /** + * Field type. + * @type {string} + */ + this.type = type; // toJSON + + /** + * Unique field id. + * @type {number} + */ + this.id = id; // toJSON, marker + + /** + * Extended type if different from parent. + * @type {string|undefined} + */ + this.extend = extend || undefined; // toJSON + + /** + * Whether this field is required. + * @type {boolean} + */ + this.required = rule === "required"; + + /** + * Whether this field is optional. + * @type {boolean} + */ + this.optional = !this.required; + + /** + * Whether this field is repeated. + * @type {boolean} + */ + this.repeated = rule === "repeated"; + + /** + * Whether this field is a map or not. + * @type {boolean} + */ + this.map = false; + + /** + * Message this field belongs to. + * @type {Type|null} + */ + this.message = null; + + /** + * OneOf this field belongs to, if any, + * @type {OneOf|null} + */ + this.partOf = null; + + /** + * The field type's default value. + * @type {*} + */ + this.typeDefault = null; + + /** + * The field's default value on prototypes. + * @type {*} + */ + this.defaultValue = null; + + /** + * Whether this field's value should be treated as a long. + * @type {boolean} + */ + this.long = util.Long ? types.long[type] !== undefined : /* istanbul ignore next */ false; + + /** + * Whether this field's value is a buffer. + * @type {boolean} + */ + this.bytes = type === "bytes"; + + /** + * Resolved type if not a basic type. + * @type {Type|Enum|null} + */ + this.resolvedType = null; + + /** + * Sister-field within the extended type if a declaring extension field. + * @type {Field|null} + */ + this.extensionField = null; + + /** + * Sister-field within the declaring namespace if an extended field. + * @type {Field|null} + */ + this.declaringField = null; + + /** + * Internally remembers whether this field is packed. + * @type {boolean|null} + * @private + */ + this._packed = null; + + /** + * Comment for this field. + * @type {string|null} + */ + this.comment = comment; +} + +/** + * Determines whether this field is packed. Only relevant when repeated and working with proto2. + * @name Field#packed + * @type {boolean} + * @readonly + */ +Object.defineProperty(Field.prototype, "packed", { + get: function() { + // defaults to packed=true if not explicity set to false + if (this._packed === null) + this._packed = this.getOption("packed") !== false; + return this._packed; + } +}); + +/** + * @override + */ +Field.prototype.setOption = function setOption(name, value, ifNotSet) { + if (name === "packed") // clear cached before setting + this._packed = null; + return ReflectionObject.prototype.setOption.call(this, name, value, ifNotSet); +}; + +/** + * Field descriptor. + * @interface IField + * @property {string} [rule="optional"] Field rule + * @property {string} type Field type + * @property {number} id Field id + * @property {Object.} [options] Field options + */ + +/** + * Extension field descriptor. + * @interface IExtensionField + * @extends IField + * @property {string} extend Extended type + */ + +/** + * Converts this field to a field descriptor. + * @param {IToJSONOptions} [toJSONOptions] JSON conversion options + * @returns {IField} Field descriptor + */ +Field.prototype.toJSON = function toJSON(toJSONOptions) { + var keepComments = toJSONOptions ? Boolean(toJSONOptions.keepComments) : false; + return util.toObject([ + "rule" , this.rule !== "optional" && this.rule || undefined, + "type" , this.type, + "id" , this.id, + "extend" , this.extend, + "options" , this.options, + "comment" , keepComments ? this.comment : undefined + ]); +}; + +/** + * Resolves this field's type references. + * @returns {Field} `this` + * @throws {Error} If any reference cannot be resolved + */ +Field.prototype.resolve = function resolve() { + + if (this.resolved) + return this; + + if ((this.typeDefault = types.defaults[this.type]) === undefined) { // if not a basic type, resolve it + this.resolvedType = (this.declaringField ? this.declaringField.parent : this.parent).lookupTypeOrEnum(this.type); + if (this.resolvedType instanceof Type) + this.typeDefault = null; + else // instanceof Enum + this.typeDefault = this.resolvedType.values[Object.keys(this.resolvedType.values)[0]]; // first defined + } else if (this.options && this.options.proto3_optional) { + // proto3 scalar value marked optional; should default to null + this.typeDefault = null; + } + + // use explicitly set default value if present + if (this.options && this.options["default"] != null) { + this.typeDefault = this.options["default"]; + if (this.resolvedType instanceof Enum && typeof this.typeDefault === "string") + this.typeDefault = this.resolvedType.values[this.typeDefault]; + } + + // remove unnecessary options + if (this.options) { + if (this.options.packed === true || this.options.packed !== undefined && this.resolvedType && !(this.resolvedType instanceof Enum)) + delete this.options.packed; + if (!Object.keys(this.options).length) + this.options = undefined; + } + + // convert to internal data type if necesssary + if (this.long) { + this.typeDefault = util.Long.fromNumber(this.typeDefault, this.type.charAt(0) === "u"); + + /* istanbul ignore else */ + if (Object.freeze) + Object.freeze(this.typeDefault); // long instances are meant to be immutable anyway (i.e. use small int cache that even requires it) + + } else if (this.bytes && typeof this.typeDefault === "string") { + var buf; + if (util.base64.test(this.typeDefault)) + util.base64.decode(this.typeDefault, buf = util.newBuffer(util.base64.length(this.typeDefault)), 0); + else + util.utf8.write(this.typeDefault, buf = util.newBuffer(util.utf8.length(this.typeDefault)), 0); + this.typeDefault = buf; + } + + // take special care of maps and repeated fields + if (this.map) + this.defaultValue = util.emptyObject; + else if (this.repeated) + this.defaultValue = util.emptyArray; + else + this.defaultValue = this.typeDefault; + + // ensure proper value on prototype + if (this.parent instanceof Type) + this.parent.ctor.prototype[this.name] = this.defaultValue; + + return ReflectionObject.prototype.resolve.call(this); +}; + +/** + * Decorator function as returned by {@link Field.d} and {@link MapField.d} (TypeScript). + * @typedef FieldDecorator + * @type {function} + * @param {Object} prototype Target prototype + * @param {string} fieldName Field name + * @returns {undefined} + */ + +/** + * Field decorator (TypeScript). + * @name Field.d + * @function + * @param {number} fieldId Field id + * @param {"double"|"float"|"int32"|"uint32"|"sint32"|"fixed32"|"sfixed32"|"int64"|"uint64"|"sint64"|"fixed64"|"sfixed64"|"string"|"bool"|"bytes"|Object} fieldType Field type + * @param {"optional"|"required"|"repeated"} [fieldRule="optional"] Field rule + * @param {T} [defaultValue] Default value + * @returns {FieldDecorator} Decorator function + * @template T extends number | number[] | Long | Long[] | string | string[] | boolean | boolean[] | Uint8Array | Uint8Array[] | Buffer | Buffer[] + */ +Field.d = function decorateField(fieldId, fieldType, fieldRule, defaultValue) { + + // submessage: decorate the submessage and use its name as the type + if (typeof fieldType === "function") + fieldType = util.decorateType(fieldType).name; + + // enum reference: create a reflected copy of the enum and keep reuseing it + else if (fieldType && typeof fieldType === "object") + fieldType = util.decorateEnum(fieldType).name; + + return function fieldDecorator(prototype, fieldName) { + util.decorateType(prototype.constructor) + .add(new Field(fieldName, fieldId, fieldType, fieldRule, { "default": defaultValue })); + }; +}; + +/** + * Field decorator (TypeScript). + * @name Field.d + * @function + * @param {number} fieldId Field id + * @param {Constructor|string} fieldType Field type + * @param {"optional"|"required"|"repeated"} [fieldRule="optional"] Field rule + * @returns {FieldDecorator} Decorator function + * @template T extends Message + * @variation 2 + */ +// like Field.d but without a default value + +// Sets up cyclic dependencies (called in index-light) +Field._configure = function configure(Type_) { + Type = Type_; +}; diff --git a/node_modules/protobufjs/src/index-light.js b/node_modules/protobufjs/src/index-light.js new file mode 100644 index 0000000..32c6a05 --- /dev/null +++ b/node_modules/protobufjs/src/index-light.js @@ -0,0 +1,104 @@ +"use strict"; +var protobuf = module.exports = require("./index-minimal"); + +protobuf.build = "light"; + +/** + * A node-style callback as used by {@link load} and {@link Root#load}. + * @typedef LoadCallback + * @type {function} + * @param {Error|null} error Error, if any, otherwise `null` + * @param {Root} [root] Root, if there hasn't been an error + * @returns {undefined} + */ + +/** + * Loads one or multiple .proto or preprocessed .json files into a common root namespace and calls the callback. + * @param {string|string[]} filename One or multiple files to load + * @param {Root} root Root namespace, defaults to create a new one if omitted. + * @param {LoadCallback} callback Callback function + * @returns {undefined} + * @see {@link Root#load} + */ +function load(filename, root, callback) { + if (typeof root === "function") { + callback = root; + root = new protobuf.Root(); + } else if (!root) + root = new protobuf.Root(); + return root.load(filename, callback); +} + +/** + * Loads one or multiple .proto or preprocessed .json files into a common root namespace and calls the callback. + * @name load + * @function + * @param {string|string[]} filename One or multiple files to load + * @param {LoadCallback} callback Callback function + * @returns {undefined} + * @see {@link Root#load} + * @variation 2 + */ +// function load(filename:string, callback:LoadCallback):undefined + +/** + * Loads one or multiple .proto or preprocessed .json files into a common root namespace and returns a promise. + * @name load + * @function + * @param {string|string[]} filename One or multiple files to load + * @param {Root} [root] Root namespace, defaults to create a new one if omitted. + * @returns {Promise} Promise + * @see {@link Root#load} + * @variation 3 + */ +// function load(filename:string, [root:Root]):Promise + +protobuf.load = load; + +/** + * Synchronously loads one or multiple .proto or preprocessed .json files into a common root namespace (node only). + * @param {string|string[]} filename One or multiple files to load + * @param {Root} [root] Root namespace, defaults to create a new one if omitted. + * @returns {Root} Root namespace + * @throws {Error} If synchronous fetching is not supported (i.e. in browsers) or if a file's syntax is invalid + * @see {@link Root#loadSync} + */ +function loadSync(filename, root) { + if (!root) + root = new protobuf.Root(); + return root.loadSync(filename); +} + +protobuf.loadSync = loadSync; + +// Serialization +protobuf.encoder = require("./encoder"); +protobuf.decoder = require("./decoder"); +protobuf.verifier = require("./verifier"); +protobuf.converter = require("./converter"); + +// Reflection +protobuf.ReflectionObject = require("./object"); +protobuf.Namespace = require("./namespace"); +protobuf.Root = require("./root"); +protobuf.Enum = require("./enum"); +protobuf.Type = require("./type"); +protobuf.Field = require("./field"); +protobuf.OneOf = require("./oneof"); +protobuf.MapField = require("./mapfield"); +protobuf.Service = require("./service"); +protobuf.Method = require("./method"); + +// Runtime +protobuf.Message = require("./message"); +protobuf.wrappers = require("./wrappers"); + +// Utility +protobuf.types = require("./types"); +protobuf.util = require("./util"); + +// Set up possibly cyclic reflection dependencies +protobuf.ReflectionObject._configure(protobuf.Root); +protobuf.Namespace._configure(protobuf.Type, protobuf.Service, protobuf.Enum); +protobuf.Root._configure(protobuf.Type); +protobuf.Field._configure(protobuf.Type); diff --git a/node_modules/protobufjs/src/index-minimal.js b/node_modules/protobufjs/src/index-minimal.js new file mode 100644 index 0000000..1f4aaea --- /dev/null +++ b/node_modules/protobufjs/src/index-minimal.js @@ -0,0 +1,36 @@ +"use strict"; +var protobuf = exports; + +/** + * Build type, one of `"full"`, `"light"` or `"minimal"`. + * @name build + * @type {string} + * @const + */ +protobuf.build = "minimal"; + +// Serialization +protobuf.Writer = require("./writer"); +protobuf.BufferWriter = require("./writer_buffer"); +protobuf.Reader = require("./reader"); +protobuf.BufferReader = require("./reader_buffer"); + +// Utility +protobuf.util = require("./util/minimal"); +protobuf.rpc = require("./rpc"); +protobuf.roots = require("./roots"); +protobuf.configure = configure; + +/* istanbul ignore next */ +/** + * Reconfigures the library according to the environment. + * @returns {undefined} + */ +function configure() { + protobuf.util._configure(); + protobuf.Writer._configure(protobuf.BufferWriter); + protobuf.Reader._configure(protobuf.BufferReader); +} + +// Set up buffer utility according to the environment +configure(); diff --git a/node_modules/protobufjs/src/index.js b/node_modules/protobufjs/src/index.js new file mode 100644 index 0000000..56bd3d5 --- /dev/null +++ b/node_modules/protobufjs/src/index.js @@ -0,0 +1,12 @@ +"use strict"; +var protobuf = module.exports = require("./index-light"); + +protobuf.build = "full"; + +// Parser +protobuf.tokenize = require("./tokenize"); +protobuf.parse = require("./parse"); +protobuf.common = require("./common"); + +// Configure parser +protobuf.Root._configure(protobuf.Type, protobuf.parse, protobuf.common); diff --git a/node_modules/protobufjs/src/mapfield.js b/node_modules/protobufjs/src/mapfield.js new file mode 100644 index 0000000..67c7097 --- /dev/null +++ b/node_modules/protobufjs/src/mapfield.js @@ -0,0 +1,126 @@ +"use strict"; +module.exports = MapField; + +// extends Field +var Field = require("./field"); +((MapField.prototype = Object.create(Field.prototype)).constructor = MapField).className = "MapField"; + +var types = require("./types"), + util = require("./util"); + +/** + * Constructs a new map field instance. + * @classdesc Reflected map field. + * @extends FieldBase + * @constructor + * @param {string} name Unique name within its namespace + * @param {number} id Unique id within its namespace + * @param {string} keyType Key type + * @param {string} type Value type + * @param {Object.} [options] Declared options + * @param {string} [comment] Comment associated with this field + */ +function MapField(name, id, keyType, type, options, comment) { + Field.call(this, name, id, type, undefined, undefined, options, comment); + + /* istanbul ignore if */ + if (!util.isString(keyType)) + throw TypeError("keyType must be a string"); + + /** + * Key type. + * @type {string} + */ + this.keyType = keyType; // toJSON, marker + + /** + * Resolved key type if not a basic type. + * @type {ReflectionObject|null} + */ + this.resolvedKeyType = null; + + // Overrides Field#map + this.map = true; +} + +/** + * Map field descriptor. + * @interface IMapField + * @extends {IField} + * @property {string} keyType Key type + */ + +/** + * Extension map field descriptor. + * @interface IExtensionMapField + * @extends IMapField + * @property {string} extend Extended type + */ + +/** + * Constructs a map field from a map field descriptor. + * @param {string} name Field name + * @param {IMapField} json Map field descriptor + * @returns {MapField} Created map field + * @throws {TypeError} If arguments are invalid + */ +MapField.fromJSON = function fromJSON(name, json) { + return new MapField(name, json.id, json.keyType, json.type, json.options, json.comment); +}; + +/** + * Converts this map field to a map field descriptor. + * @param {IToJSONOptions} [toJSONOptions] JSON conversion options + * @returns {IMapField} Map field descriptor + */ +MapField.prototype.toJSON = function toJSON(toJSONOptions) { + var keepComments = toJSONOptions ? Boolean(toJSONOptions.keepComments) : false; + return util.toObject([ + "keyType" , this.keyType, + "type" , this.type, + "id" , this.id, + "extend" , this.extend, + "options" , this.options, + "comment" , keepComments ? this.comment : undefined + ]); +}; + +/** + * @override + */ +MapField.prototype.resolve = function resolve() { + if (this.resolved) + return this; + + // Besides a value type, map fields have a key type that may be "any scalar type except for floating point types and bytes" + if (types.mapKey[this.keyType] === undefined) + throw Error("invalid key type: " + this.keyType); + + return Field.prototype.resolve.call(this); +}; + +/** + * Map field decorator (TypeScript). + * @name MapField.d + * @function + * @param {number} fieldId Field id + * @param {"int32"|"uint32"|"sint32"|"fixed32"|"sfixed32"|"int64"|"uint64"|"sint64"|"fixed64"|"sfixed64"|"bool"|"string"} fieldKeyType Field key type + * @param {"double"|"float"|"int32"|"uint32"|"sint32"|"fixed32"|"sfixed32"|"int64"|"uint64"|"sint64"|"fixed64"|"sfixed64"|"bool"|"string"|"bytes"|Object|Constructor<{}>} fieldValueType Field value type + * @returns {FieldDecorator} Decorator function + * @template T extends { [key: string]: number | Long | string | boolean | Uint8Array | Buffer | number[] | Message<{}> } + */ +MapField.d = function decorateMapField(fieldId, fieldKeyType, fieldValueType) { + + // submessage value: decorate the submessage and use its name as the type + if (typeof fieldValueType === "function") + fieldValueType = util.decorateType(fieldValueType).name; + + // enum reference value: create a reflected copy of the enum and keep reuseing it + else if (fieldValueType && typeof fieldValueType === "object") + fieldValueType = util.decorateEnum(fieldValueType).name; + + return function mapFieldDecorator(prototype, fieldName) { + util.decorateType(prototype.constructor) + .add(new MapField(fieldName, fieldId, fieldKeyType, fieldValueType)); + }; +}; diff --git a/node_modules/protobufjs/src/message.js b/node_modules/protobufjs/src/message.js new file mode 100644 index 0000000..3f94bf6 --- /dev/null +++ b/node_modules/protobufjs/src/message.js @@ -0,0 +1,139 @@ +"use strict"; +module.exports = Message; + +var util = require("./util/minimal"); + +/** + * Constructs a new message instance. + * @classdesc Abstract runtime message. + * @constructor + * @param {Properties} [properties] Properties to set + * @template T extends object = object + */ +function Message(properties) { + // not used internally + if (properties) + for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) + this[keys[i]] = properties[keys[i]]; +} + +/** + * Reference to the reflected type. + * @name Message.$type + * @type {Type} + * @readonly + */ + +/** + * Reference to the reflected type. + * @name Message#$type + * @type {Type} + * @readonly + */ + +/*eslint-disable valid-jsdoc*/ + +/** + * Creates a new message of this type using the specified properties. + * @param {Object.} [properties] Properties to set + * @returns {Message} Message instance + * @template T extends Message + * @this Constructor + */ +Message.create = function create(properties) { + return this.$type.create(properties); +}; + +/** + * Encodes a message of this type. + * @param {T|Object.} message Message to encode + * @param {Writer} [writer] Writer to use + * @returns {Writer} Writer + * @template T extends Message + * @this Constructor + */ +Message.encode = function encode(message, writer) { + return this.$type.encode(message, writer); +}; + +/** + * Encodes a message of this type preceeded by its length as a varint. + * @param {T|Object.} message Message to encode + * @param {Writer} [writer] Writer to use + * @returns {Writer} Writer + * @template T extends Message + * @this Constructor + */ +Message.encodeDelimited = function encodeDelimited(message, writer) { + return this.$type.encodeDelimited(message, writer); +}; + +/** + * Decodes a message of this type. + * @name Message.decode + * @function + * @param {Reader|Uint8Array} reader Reader or buffer to decode + * @returns {T} Decoded message + * @template T extends Message + * @this Constructor + */ +Message.decode = function decode(reader) { + return this.$type.decode(reader); +}; + +/** + * Decodes a message of this type preceeded by its length as a varint. + * @name Message.decodeDelimited + * @function + * @param {Reader|Uint8Array} reader Reader or buffer to decode + * @returns {T} Decoded message + * @template T extends Message + * @this Constructor + */ +Message.decodeDelimited = function decodeDelimited(reader) { + return this.$type.decodeDelimited(reader); +}; + +/** + * Verifies a message of this type. + * @name Message.verify + * @function + * @param {Object.} message Plain object to verify + * @returns {string|null} `null` if valid, otherwise the reason why it is not + */ +Message.verify = function verify(message) { + return this.$type.verify(message); +}; + +/** + * Creates a new message of this type from a plain object. Also converts values to their respective internal types. + * @param {Object.} object Plain object + * @returns {T} Message instance + * @template T extends Message + * @this Constructor + */ +Message.fromObject = function fromObject(object) { + return this.$type.fromObject(object); +}; + +/** + * Creates a plain object from a message of this type. Also converts values to other types if specified. + * @param {T} message Message instance + * @param {IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + * @template T extends Message + * @this Constructor + */ +Message.toObject = function toObject(message, options) { + return this.$type.toObject(message, options); +}; + +/** + * Converts this message to JSON. + * @returns {Object.} JSON object + */ +Message.prototype.toJSON = function toJSON() { + return this.$type.toObject(this, util.toJSONOptions); +}; + +/*eslint-enable valid-jsdoc*/ \ No newline at end of file diff --git a/node_modules/protobufjs/src/method.js b/node_modules/protobufjs/src/method.js new file mode 100644 index 0000000..18a6ab2 --- /dev/null +++ b/node_modules/protobufjs/src/method.js @@ -0,0 +1,160 @@ +"use strict"; +module.exports = Method; + +// extends ReflectionObject +var ReflectionObject = require("./object"); +((Method.prototype = Object.create(ReflectionObject.prototype)).constructor = Method).className = "Method"; + +var util = require("./util"); + +/** + * Constructs a new service method instance. + * @classdesc Reflected service method. + * @extends ReflectionObject + * @constructor + * @param {string} name Method name + * @param {string|undefined} type Method type, usually `"rpc"` + * @param {string} requestType Request message type + * @param {string} responseType Response message type + * @param {boolean|Object.} [requestStream] Whether the request is streamed + * @param {boolean|Object.} [responseStream] Whether the response is streamed + * @param {Object.} [options] Declared options + * @param {string} [comment] The comment for this method + * @param {Object.} [parsedOptions] Declared options, properly parsed into an object + */ +function Method(name, type, requestType, responseType, requestStream, responseStream, options, comment, parsedOptions) { + + /* istanbul ignore next */ + if (util.isObject(requestStream)) { + options = requestStream; + requestStream = responseStream = undefined; + } else if (util.isObject(responseStream)) { + options = responseStream; + responseStream = undefined; + } + + /* istanbul ignore if */ + if (!(type === undefined || util.isString(type))) + throw TypeError("type must be a string"); + + /* istanbul ignore if */ + if (!util.isString(requestType)) + throw TypeError("requestType must be a string"); + + /* istanbul ignore if */ + if (!util.isString(responseType)) + throw TypeError("responseType must be a string"); + + ReflectionObject.call(this, name, options); + + /** + * Method type. + * @type {string} + */ + this.type = type || "rpc"; // toJSON + + /** + * Request type. + * @type {string} + */ + this.requestType = requestType; // toJSON, marker + + /** + * Whether requests are streamed or not. + * @type {boolean|undefined} + */ + this.requestStream = requestStream ? true : undefined; // toJSON + + /** + * Response type. + * @type {string} + */ + this.responseType = responseType; // toJSON + + /** + * Whether responses are streamed or not. + * @type {boolean|undefined} + */ + this.responseStream = responseStream ? true : undefined; // toJSON + + /** + * Resolved request type. + * @type {Type|null} + */ + this.resolvedRequestType = null; + + /** + * Resolved response type. + * @type {Type|null} + */ + this.resolvedResponseType = null; + + /** + * Comment for this method + * @type {string|null} + */ + this.comment = comment; + + /** + * Options properly parsed into an object + */ + this.parsedOptions = parsedOptions; +} + +/** + * Method descriptor. + * @interface IMethod + * @property {string} [type="rpc"] Method type + * @property {string} requestType Request type + * @property {string} responseType Response type + * @property {boolean} [requestStream=false] Whether requests are streamed + * @property {boolean} [responseStream=false] Whether responses are streamed + * @property {Object.} [options] Method options + * @property {string} comment Method comments + * @property {Object.} [parsedOptions] Method options properly parsed into an object + */ + +/** + * Constructs a method from a method descriptor. + * @param {string} name Method name + * @param {IMethod} json Method descriptor + * @returns {Method} Created method + * @throws {TypeError} If arguments are invalid + */ +Method.fromJSON = function fromJSON(name, json) { + return new Method(name, json.type, json.requestType, json.responseType, json.requestStream, json.responseStream, json.options, json.comment, json.parsedOptions); +}; + +/** + * Converts this method to a method descriptor. + * @param {IToJSONOptions} [toJSONOptions] JSON conversion options + * @returns {IMethod} Method descriptor + */ +Method.prototype.toJSON = function toJSON(toJSONOptions) { + var keepComments = toJSONOptions ? Boolean(toJSONOptions.keepComments) : false; + return util.toObject([ + "type" , this.type !== "rpc" && /* istanbul ignore next */ this.type || undefined, + "requestType" , this.requestType, + "requestStream" , this.requestStream, + "responseType" , this.responseType, + "responseStream" , this.responseStream, + "options" , this.options, + "comment" , keepComments ? this.comment : undefined, + "parsedOptions" , this.parsedOptions, + ]); +}; + +/** + * @override + */ +Method.prototype.resolve = function resolve() { + + /* istanbul ignore if */ + if (this.resolved) + return this; + + this.resolvedRequestType = this.parent.lookupType(this.requestType); + this.resolvedResponseType = this.parent.lookupType(this.responseType); + + return ReflectionObject.prototype.resolve.call(this); +}; diff --git a/node_modules/protobufjs/src/namespace.js b/node_modules/protobufjs/src/namespace.js new file mode 100644 index 0000000..731afc7 --- /dev/null +++ b/node_modules/protobufjs/src/namespace.js @@ -0,0 +1,433 @@ +"use strict"; +module.exports = Namespace; + +// extends ReflectionObject +var ReflectionObject = require("./object"); +((Namespace.prototype = Object.create(ReflectionObject.prototype)).constructor = Namespace).className = "Namespace"; + +var Field = require("./field"), + util = require("./util"), + OneOf = require("./oneof"); + +var Type, // cyclic + Service, + Enum; + +/** + * Constructs a new namespace instance. + * @name Namespace + * @classdesc Reflected namespace. + * @extends NamespaceBase + * @constructor + * @param {string} name Namespace name + * @param {Object.} [options] Declared options + */ + +/** + * Constructs a namespace from JSON. + * @memberof Namespace + * @function + * @param {string} name Namespace name + * @param {Object.} json JSON object + * @returns {Namespace} Created namespace + * @throws {TypeError} If arguments are invalid + */ +Namespace.fromJSON = function fromJSON(name, json) { + return new Namespace(name, json.options).addJSON(json.nested); +}; + +/** + * Converts an array of reflection objects to JSON. + * @memberof Namespace + * @param {ReflectionObject[]} array Object array + * @param {IToJSONOptions} [toJSONOptions] JSON conversion options + * @returns {Object.|undefined} JSON object or `undefined` when array is empty + */ +function arrayToJSON(array, toJSONOptions) { + if (!(array && array.length)) + return undefined; + var obj = {}; + for (var i = 0; i < array.length; ++i) + obj[array[i].name] = array[i].toJSON(toJSONOptions); + return obj; +} + +Namespace.arrayToJSON = arrayToJSON; + +/** + * Tests if the specified id is reserved. + * @param {Array.|undefined} reserved Array of reserved ranges and names + * @param {number} id Id to test + * @returns {boolean} `true` if reserved, otherwise `false` + */ +Namespace.isReservedId = function isReservedId(reserved, id) { + if (reserved) + for (var i = 0; i < reserved.length; ++i) + if (typeof reserved[i] !== "string" && reserved[i][0] <= id && reserved[i][1] > id) + return true; + return false; +}; + +/** + * Tests if the specified name is reserved. + * @param {Array.|undefined} reserved Array of reserved ranges and names + * @param {string} name Name to test + * @returns {boolean} `true` if reserved, otherwise `false` + */ +Namespace.isReservedName = function isReservedName(reserved, name) { + if (reserved) + for (var i = 0; i < reserved.length; ++i) + if (reserved[i] === name) + return true; + return false; +}; + +/** + * Not an actual constructor. Use {@link Namespace} instead. + * @classdesc Base class of all reflection objects containing nested objects. This is not an actual class but here for the sake of having consistent type definitions. + * @exports NamespaceBase + * @extends ReflectionObject + * @abstract + * @constructor + * @param {string} name Namespace name + * @param {Object.} [options] Declared options + * @see {@link Namespace} + */ +function Namespace(name, options) { + ReflectionObject.call(this, name, options); + + /** + * Nested objects by name. + * @type {Object.|undefined} + */ + this.nested = undefined; // toJSON + + /** + * Cached nested objects as an array. + * @type {ReflectionObject[]|null} + * @private + */ + this._nestedArray = null; +} + +function clearCache(namespace) { + namespace._nestedArray = null; + return namespace; +} + +/** + * Nested objects of this namespace as an array for iteration. + * @name NamespaceBase#nestedArray + * @type {ReflectionObject[]} + * @readonly + */ +Object.defineProperty(Namespace.prototype, "nestedArray", { + get: function() { + return this._nestedArray || (this._nestedArray = util.toArray(this.nested)); + } +}); + +/** + * Namespace descriptor. + * @interface INamespace + * @property {Object.} [options] Namespace options + * @property {Object.} [nested] Nested object descriptors + */ + +/** + * Any extension field descriptor. + * @typedef AnyExtensionField + * @type {IExtensionField|IExtensionMapField} + */ + +/** + * Any nested object descriptor. + * @typedef AnyNestedObject + * @type {IEnum|IType|IService|AnyExtensionField|INamespace|IOneOf} + */ + +/** + * Converts this namespace to a namespace descriptor. + * @param {IToJSONOptions} [toJSONOptions] JSON conversion options + * @returns {INamespace} Namespace descriptor + */ +Namespace.prototype.toJSON = function toJSON(toJSONOptions) { + return util.toObject([ + "options" , this.options, + "nested" , arrayToJSON(this.nestedArray, toJSONOptions) + ]); +}; + +/** + * Adds nested objects to this namespace from nested object descriptors. + * @param {Object.} nestedJson Any nested object descriptors + * @returns {Namespace} `this` + */ +Namespace.prototype.addJSON = function addJSON(nestedJson) { + var ns = this; + /* istanbul ignore else */ + if (nestedJson) { + for (var names = Object.keys(nestedJson), i = 0, nested; i < names.length; ++i) { + nested = nestedJson[names[i]]; + ns.add( // most to least likely + ( nested.fields !== undefined + ? Type.fromJSON + : nested.values !== undefined + ? Enum.fromJSON + : nested.methods !== undefined + ? Service.fromJSON + : nested.id !== undefined + ? Field.fromJSON + : Namespace.fromJSON )(names[i], nested) + ); + } + } + return this; +}; + +/** + * Gets the nested object of the specified name. + * @param {string} name Nested object name + * @returns {ReflectionObject|null} The reflection object or `null` if it doesn't exist + */ +Namespace.prototype.get = function get(name) { + return this.nested && this.nested[name] + || null; +}; + +/** + * Gets the values of the nested {@link Enum|enum} of the specified name. + * This methods differs from {@link Namespace#get|get} in that it returns an enum's values directly and throws instead of returning `null`. + * @param {string} name Nested enum name + * @returns {Object.} Enum values + * @throws {Error} If there is no such enum + */ +Namespace.prototype.getEnum = function getEnum(name) { + if (this.nested && this.nested[name] instanceof Enum) + return this.nested[name].values; + throw Error("no such enum: " + name); +}; + +/** + * Adds a nested object to this namespace. + * @param {ReflectionObject} object Nested object to add + * @returns {Namespace} `this` + * @throws {TypeError} If arguments are invalid + * @throws {Error} If there is already a nested object with this name + */ +Namespace.prototype.add = function add(object) { + + if (!(object instanceof Field && object.extend !== undefined || object instanceof Type || object instanceof OneOf || object instanceof Enum || object instanceof Service || object instanceof Namespace)) + throw TypeError("object must be a valid nested object"); + + if (!this.nested) + this.nested = {}; + else { + var prev = this.get(object.name); + if (prev) { + if (prev instanceof Namespace && object instanceof Namespace && !(prev instanceof Type || prev instanceof Service)) { + // replace plain namespace but keep existing nested elements and options + var nested = prev.nestedArray; + for (var i = 0; i < nested.length; ++i) + object.add(nested[i]); + this.remove(prev); + if (!this.nested) + this.nested = {}; + object.setOptions(prev.options, true); + + } else + throw Error("duplicate name '" + object.name + "' in " + this); + } + } + this.nested[object.name] = object; + object.onAdd(this); + return clearCache(this); +}; + +/** + * Removes a nested object from this namespace. + * @param {ReflectionObject} object Nested object to remove + * @returns {Namespace} `this` + * @throws {TypeError} If arguments are invalid + * @throws {Error} If `object` is not a member of this namespace + */ +Namespace.prototype.remove = function remove(object) { + + if (!(object instanceof ReflectionObject)) + throw TypeError("object must be a ReflectionObject"); + if (object.parent !== this) + throw Error(object + " is not a member of " + this); + + delete this.nested[object.name]; + if (!Object.keys(this.nested).length) + this.nested = undefined; + + object.onRemove(this); + return clearCache(this); +}; + +/** + * Defines additial namespaces within this one if not yet existing. + * @param {string|string[]} path Path to create + * @param {*} [json] Nested types to create from JSON + * @returns {Namespace} Pointer to the last namespace created or `this` if path is empty + */ +Namespace.prototype.define = function define(path, json) { + + if (util.isString(path)) + path = path.split("."); + else if (!Array.isArray(path)) + throw TypeError("illegal path"); + if (path && path.length && path[0] === "") + throw Error("path must be relative"); + + var ptr = this; + while (path.length > 0) { + var part = path.shift(); + if (ptr.nested && ptr.nested[part]) { + ptr = ptr.nested[part]; + if (!(ptr instanceof Namespace)) + throw Error("path conflicts with non-namespace objects"); + } else + ptr.add(ptr = new Namespace(part)); + } + if (json) + ptr.addJSON(json); + return ptr; +}; + +/** + * Resolves this namespace's and all its nested objects' type references. Useful to validate a reflection tree, but comes at a cost. + * @returns {Namespace} `this` + */ +Namespace.prototype.resolveAll = function resolveAll() { + var nested = this.nestedArray, i = 0; + while (i < nested.length) + if (nested[i] instanceof Namespace) + nested[i++].resolveAll(); + else + nested[i++].resolve(); + return this.resolve(); +}; + +/** + * Recursively looks up the reflection object matching the specified path in the scope of this namespace. + * @param {string|string[]} path Path to look up + * @param {*|Array.<*>} filterTypes Filter types, any combination of the constructors of `protobuf.Type`, `protobuf.Enum`, `protobuf.Service` etc. + * @param {boolean} [parentAlreadyChecked=false] If known, whether the parent has already been checked + * @returns {ReflectionObject|null} Looked up object or `null` if none could be found + */ +Namespace.prototype.lookup = function lookup(path, filterTypes, parentAlreadyChecked) { + + /* istanbul ignore next */ + if (typeof filterTypes === "boolean") { + parentAlreadyChecked = filterTypes; + filterTypes = undefined; + } else if (filterTypes && !Array.isArray(filterTypes)) + filterTypes = [ filterTypes ]; + + if (util.isString(path) && path.length) { + if (path === ".") + return this.root; + path = path.split("."); + } else if (!path.length) + return this; + + // Start at root if path is absolute + if (path[0] === "") + return this.root.lookup(path.slice(1), filterTypes); + + // Test if the first part matches any nested object, and if so, traverse if path contains more + var found = this.get(path[0]); + if (found) { + if (path.length === 1) { + if (!filterTypes || filterTypes.indexOf(found.constructor) > -1) + return found; + } else if (found instanceof Namespace && (found = found.lookup(path.slice(1), filterTypes, true))) + return found; + + // Otherwise try each nested namespace + } else + for (var i = 0; i < this.nestedArray.length; ++i) + if (this._nestedArray[i] instanceof Namespace && (found = this._nestedArray[i].lookup(path, filterTypes, true))) + return found; + + // If there hasn't been a match, try again at the parent + if (this.parent === null || parentAlreadyChecked) + return null; + return this.parent.lookup(path, filterTypes); +}; + +/** + * Looks up the reflection object at the specified path, relative to this namespace. + * @name NamespaceBase#lookup + * @function + * @param {string|string[]} path Path to look up + * @param {boolean} [parentAlreadyChecked=false] Whether the parent has already been checked + * @returns {ReflectionObject|null} Looked up object or `null` if none could be found + * @variation 2 + */ +// lookup(path: string, [parentAlreadyChecked: boolean]) + +/** + * Looks up the {@link Type|type} at the specified path, relative to this namespace. + * Besides its signature, this methods differs from {@link Namespace#lookup|lookup} in that it throws instead of returning `null`. + * @param {string|string[]} path Path to look up + * @returns {Type} Looked up type + * @throws {Error} If `path` does not point to a type + */ +Namespace.prototype.lookupType = function lookupType(path) { + var found = this.lookup(path, [ Type ]); + if (!found) + throw Error("no such type: " + path); + return found; +}; + +/** + * Looks up the values of the {@link Enum|enum} at the specified path, relative to this namespace. + * Besides its signature, this methods differs from {@link Namespace#lookup|lookup} in that it throws instead of returning `null`. + * @param {string|string[]} path Path to look up + * @returns {Enum} Looked up enum + * @throws {Error} If `path` does not point to an enum + */ +Namespace.prototype.lookupEnum = function lookupEnum(path) { + var found = this.lookup(path, [ Enum ]); + if (!found) + throw Error("no such Enum '" + path + "' in " + this); + return found; +}; + +/** + * Looks up the {@link Type|type} or {@link Enum|enum} at the specified path, relative to this namespace. + * Besides its signature, this methods differs from {@link Namespace#lookup|lookup} in that it throws instead of returning `null`. + * @param {string|string[]} path Path to look up + * @returns {Type} Looked up type or enum + * @throws {Error} If `path` does not point to a type or enum + */ +Namespace.prototype.lookupTypeOrEnum = function lookupTypeOrEnum(path) { + var found = this.lookup(path, [ Type, Enum ]); + if (!found) + throw Error("no such Type or Enum '" + path + "' in " + this); + return found; +}; + +/** + * Looks up the {@link Service|service} at the specified path, relative to this namespace. + * Besides its signature, this methods differs from {@link Namespace#lookup|lookup} in that it throws instead of returning `null`. + * @param {string|string[]} path Path to look up + * @returns {Service} Looked up service + * @throws {Error} If `path` does not point to a service + */ +Namespace.prototype.lookupService = function lookupService(path) { + var found = this.lookup(path, [ Service ]); + if (!found) + throw Error("no such Service '" + path + "' in " + this); + return found; +}; + +// Sets up cyclic dependencies (called in index-light) +Namespace._configure = function(Type_, Service_, Enum_) { + Type = Type_; + Service = Service_; + Enum = Enum_; +}; diff --git a/node_modules/protobufjs/src/object.js b/node_modules/protobufjs/src/object.js new file mode 100644 index 0000000..bd04cec --- /dev/null +++ b/node_modules/protobufjs/src/object.js @@ -0,0 +1,243 @@ +"use strict"; +module.exports = ReflectionObject; + +ReflectionObject.className = "ReflectionObject"; + +var util = require("./util"); + +var Root; // cyclic + +/** + * Constructs a new reflection object instance. + * @classdesc Base class of all reflection objects. + * @constructor + * @param {string} name Object name + * @param {Object.} [options] Declared options + * @abstract + */ +function ReflectionObject(name, options) { + + if (!util.isString(name)) + throw TypeError("name must be a string"); + + if (options && !util.isObject(options)) + throw TypeError("options must be an object"); + + /** + * Options. + * @type {Object.|undefined} + */ + this.options = options; // toJSON + + /** + * Parsed Options. + * @type {Array.>|undefined} + */ + this.parsedOptions = null; + + /** + * Unique name within its namespace. + * @type {string} + */ + this.name = name; + + /** + * Parent namespace. + * @type {Namespace|null} + */ + this.parent = null; + + /** + * Whether already resolved or not. + * @type {boolean} + */ + this.resolved = false; + + /** + * Comment text, if any. + * @type {string|null} + */ + this.comment = null; + + /** + * Defining file name. + * @type {string|null} + */ + this.filename = null; +} + +Object.defineProperties(ReflectionObject.prototype, { + + /** + * Reference to the root namespace. + * @name ReflectionObject#root + * @type {Root} + * @readonly + */ + root: { + get: function() { + var ptr = this; + while (ptr.parent !== null) + ptr = ptr.parent; + return ptr; + } + }, + + /** + * Full name including leading dot. + * @name ReflectionObject#fullName + * @type {string} + * @readonly + */ + fullName: { + get: function() { + var path = [ this.name ], + ptr = this.parent; + while (ptr) { + path.unshift(ptr.name); + ptr = ptr.parent; + } + return path.join("."); + } + } +}); + +/** + * Converts this reflection object to its descriptor representation. + * @returns {Object.} Descriptor + * @abstract + */ +ReflectionObject.prototype.toJSON = /* istanbul ignore next */ function toJSON() { + throw Error(); // not implemented, shouldn't happen +}; + +/** + * Called when this object is added to a parent. + * @param {ReflectionObject} parent Parent added to + * @returns {undefined} + */ +ReflectionObject.prototype.onAdd = function onAdd(parent) { + if (this.parent && this.parent !== parent) + this.parent.remove(this); + this.parent = parent; + this.resolved = false; + var root = parent.root; + if (root instanceof Root) + root._handleAdd(this); +}; + +/** + * Called when this object is removed from a parent. + * @param {ReflectionObject} parent Parent removed from + * @returns {undefined} + */ +ReflectionObject.prototype.onRemove = function onRemove(parent) { + var root = parent.root; + if (root instanceof Root) + root._handleRemove(this); + this.parent = null; + this.resolved = false; +}; + +/** + * Resolves this objects type references. + * @returns {ReflectionObject} `this` + */ +ReflectionObject.prototype.resolve = function resolve() { + if (this.resolved) + return this; + if (this.root instanceof Root) + this.resolved = true; // only if part of a root + return this; +}; + +/** + * Gets an option value. + * @param {string} name Option name + * @returns {*} Option value or `undefined` if not set + */ +ReflectionObject.prototype.getOption = function getOption(name) { + if (this.options) + return this.options[name]; + return undefined; +}; + +/** + * Sets an option. + * @param {string} name Option name + * @param {*} value Option value + * @param {boolean} [ifNotSet] Sets the option only if it isn't currently set + * @returns {ReflectionObject} `this` + */ +ReflectionObject.prototype.setOption = function setOption(name, value, ifNotSet) { + if (!ifNotSet || !this.options || this.options[name] === undefined) + (this.options || (this.options = {}))[name] = value; + return this; +}; + +/** + * Sets a parsed option. + * @param {string} name parsed Option name + * @param {*} value Option value + * @param {string} propName dot '.' delimited full path of property within the option to set. if undefined\empty, will add a new option with that value + * @returns {ReflectionObject} `this` + */ +ReflectionObject.prototype.setParsedOption = function setParsedOption(name, value, propName) { + if (!this.parsedOptions) { + this.parsedOptions = []; + } + var parsedOptions = this.parsedOptions; + if (propName) { + // If setting a sub property of an option then try to merge it + // with an existing option + var opt = parsedOptions.find(function (opt) { + return Object.prototype.hasOwnProperty.call(opt, name); + }); + if (opt) { + // If we found an existing option - just merge the property value + var newValue = opt[name]; + util.setProperty(newValue, propName, value); + } else { + // otherwise, create a new option, set it's property and add it to the list + opt = {}; + opt[name] = util.setProperty({}, propName, value); + parsedOptions.push(opt); + } + } else { + // Always create a new option when setting the value of the option itself + var newOpt = {}; + newOpt[name] = value; + parsedOptions.push(newOpt); + } + return this; +}; + +/** + * Sets multiple options. + * @param {Object.} options Options to set + * @param {boolean} [ifNotSet] Sets an option only if it isn't currently set + * @returns {ReflectionObject} `this` + */ +ReflectionObject.prototype.setOptions = function setOptions(options, ifNotSet) { + if (options) + for (var keys = Object.keys(options), i = 0; i < keys.length; ++i) + this.setOption(keys[i], options[keys[i]], ifNotSet); + return this; +}; + +/** + * Converts this instance to its string representation. + * @returns {string} Class name[, space, full name] + */ +ReflectionObject.prototype.toString = function toString() { + var className = this.constructor.className, + fullName = this.fullName; + if (fullName.length) + return className + " " + fullName; + return className; +}; + +// Sets up cyclic dependencies (called in index-light) +ReflectionObject._configure = function(Root_) { + Root = Root_; +}; diff --git a/node_modules/protobufjs/src/oneof.js b/node_modules/protobufjs/src/oneof.js new file mode 100644 index 0000000..ba0e902 --- /dev/null +++ b/node_modules/protobufjs/src/oneof.js @@ -0,0 +1,203 @@ +"use strict"; +module.exports = OneOf; + +// extends ReflectionObject +var ReflectionObject = require("./object"); +((OneOf.prototype = Object.create(ReflectionObject.prototype)).constructor = OneOf).className = "OneOf"; + +var Field = require("./field"), + util = require("./util"); + +/** + * Constructs a new oneof instance. + * @classdesc Reflected oneof. + * @extends ReflectionObject + * @constructor + * @param {string} name Oneof name + * @param {string[]|Object.} [fieldNames] Field names + * @param {Object.} [options] Declared options + * @param {string} [comment] Comment associated with this field + */ +function OneOf(name, fieldNames, options, comment) { + if (!Array.isArray(fieldNames)) { + options = fieldNames; + fieldNames = undefined; + } + ReflectionObject.call(this, name, options); + + /* istanbul ignore if */ + if (!(fieldNames === undefined || Array.isArray(fieldNames))) + throw TypeError("fieldNames must be an Array"); + + /** + * Field names that belong to this oneof. + * @type {string[]} + */ + this.oneof = fieldNames || []; // toJSON, marker + + /** + * Fields that belong to this oneof as an array for iteration. + * @type {Field[]} + * @readonly + */ + this.fieldsArray = []; // declared readonly for conformance, possibly not yet added to parent + + /** + * Comment for this field. + * @type {string|null} + */ + this.comment = comment; +} + +/** + * Oneof descriptor. + * @interface IOneOf + * @property {Array.} oneof Oneof field names + * @property {Object.} [options] Oneof options + */ + +/** + * Constructs a oneof from a oneof descriptor. + * @param {string} name Oneof name + * @param {IOneOf} json Oneof descriptor + * @returns {OneOf} Created oneof + * @throws {TypeError} If arguments are invalid + */ +OneOf.fromJSON = function fromJSON(name, json) { + return new OneOf(name, json.oneof, json.options, json.comment); +}; + +/** + * Converts this oneof to a oneof descriptor. + * @param {IToJSONOptions} [toJSONOptions] JSON conversion options + * @returns {IOneOf} Oneof descriptor + */ +OneOf.prototype.toJSON = function toJSON(toJSONOptions) { + var keepComments = toJSONOptions ? Boolean(toJSONOptions.keepComments) : false; + return util.toObject([ + "options" , this.options, + "oneof" , this.oneof, + "comment" , keepComments ? this.comment : undefined + ]); +}; + +/** + * Adds the fields of the specified oneof to the parent if not already done so. + * @param {OneOf} oneof The oneof + * @returns {undefined} + * @inner + * @ignore + */ +function addFieldsToParent(oneof) { + if (oneof.parent) + for (var i = 0; i < oneof.fieldsArray.length; ++i) + if (!oneof.fieldsArray[i].parent) + oneof.parent.add(oneof.fieldsArray[i]); +} + +/** + * Adds a field to this oneof and removes it from its current parent, if any. + * @param {Field} field Field to add + * @returns {OneOf} `this` + */ +OneOf.prototype.add = function add(field) { + + /* istanbul ignore if */ + if (!(field instanceof Field)) + throw TypeError("field must be a Field"); + + if (field.parent && field.parent !== this.parent) + field.parent.remove(field); + this.oneof.push(field.name); + this.fieldsArray.push(field); + field.partOf = this; // field.parent remains null + addFieldsToParent(this); + return this; +}; + +/** + * Removes a field from this oneof and puts it back to the oneof's parent. + * @param {Field} field Field to remove + * @returns {OneOf} `this` + */ +OneOf.prototype.remove = function remove(field) { + + /* istanbul ignore if */ + if (!(field instanceof Field)) + throw TypeError("field must be a Field"); + + var index = this.fieldsArray.indexOf(field); + + /* istanbul ignore if */ + if (index < 0) + throw Error(field + " is not a member of " + this); + + this.fieldsArray.splice(index, 1); + index = this.oneof.indexOf(field.name); + + /* istanbul ignore else */ + if (index > -1) // theoretical + this.oneof.splice(index, 1); + + field.partOf = null; + return this; +}; + +/** + * @override + */ +OneOf.prototype.onAdd = function onAdd(parent) { + ReflectionObject.prototype.onAdd.call(this, parent); + var self = this; + // Collect present fields + for (var i = 0; i < this.oneof.length; ++i) { + var field = parent.get(this.oneof[i]); + if (field && !field.partOf) { + field.partOf = self; + self.fieldsArray.push(field); + } + } + // Add not yet present fields + addFieldsToParent(this); +}; + +/** + * @override + */ +OneOf.prototype.onRemove = function onRemove(parent) { + for (var i = 0, field; i < this.fieldsArray.length; ++i) + if ((field = this.fieldsArray[i]).parent) + field.parent.remove(field); + ReflectionObject.prototype.onRemove.call(this, parent); +}; + +/** + * Decorator function as returned by {@link OneOf.d} (TypeScript). + * @typedef OneOfDecorator + * @type {function} + * @param {Object} prototype Target prototype + * @param {string} oneofName OneOf name + * @returns {undefined} + */ + +/** + * OneOf decorator (TypeScript). + * @function + * @param {...string} fieldNames Field names + * @returns {OneOfDecorator} Decorator function + * @template T extends string + */ +OneOf.d = function decorateOneOf() { + var fieldNames = new Array(arguments.length), + index = 0; + while (index < arguments.length) + fieldNames[index] = arguments[index++]; + return function oneOfDecorator(prototype, oneofName) { + util.decorateType(prototype.constructor) + .add(new OneOf(oneofName, fieldNames)); + Object.defineProperty(prototype, oneofName, { + get: util.oneOfGetter(fieldNames), + set: util.oneOfSetter(fieldNames) + }); + }; +}; diff --git a/node_modules/protobufjs/src/parse.js b/node_modules/protobufjs/src/parse.js new file mode 100644 index 0000000..f5f070e --- /dev/null +++ b/node_modules/protobufjs/src/parse.js @@ -0,0 +1,889 @@ +"use strict"; +module.exports = parse; + +parse.filename = null; +parse.defaults = { keepCase: false }; + +var tokenize = require("./tokenize"), + Root = require("./root"), + Type = require("./type"), + Field = require("./field"), + MapField = require("./mapfield"), + OneOf = require("./oneof"), + Enum = require("./enum"), + Service = require("./service"), + Method = require("./method"), + types = require("./types"), + util = require("./util"); + +var base10Re = /^[1-9][0-9]*$/, + base10NegRe = /^-?[1-9][0-9]*$/, + base16Re = /^0[x][0-9a-fA-F]+$/, + base16NegRe = /^-?0[x][0-9a-fA-F]+$/, + base8Re = /^0[0-7]+$/, + base8NegRe = /^-?0[0-7]+$/, + numberRe = /^(?![eE])[0-9]*(?:\.[0-9]*)?(?:[eE][+-]?[0-9]+)?$/, + nameRe = /^[a-zA-Z_][a-zA-Z_0-9]*$/, + typeRefRe = /^(?:\.?[a-zA-Z_][a-zA-Z_0-9]*)(?:\.[a-zA-Z_][a-zA-Z_0-9]*)*$/, + fqTypeRefRe = /^(?:\.[a-zA-Z_][a-zA-Z_0-9]*)+$/; + +/** + * Result object returned from {@link parse}. + * @interface IParserResult + * @property {string|undefined} package Package name, if declared + * @property {string[]|undefined} imports Imports, if any + * @property {string[]|undefined} weakImports Weak imports, if any + * @property {string|undefined} syntax Syntax, if specified (either `"proto2"` or `"proto3"`) + * @property {Root} root Populated root instance + */ + +/** + * Options modifying the behavior of {@link parse}. + * @interface IParseOptions + * @property {boolean} [keepCase=false] Keeps field casing instead of converting to camel case + * @property {boolean} [alternateCommentMode=false] Recognize double-slash comments in addition to doc-block comments. + * @property {boolean} [preferTrailingComment=false] Use trailing comment when both leading comment and trailing comment exist. + */ + +/** + * Options modifying the behavior of JSON serialization. + * @interface IToJSONOptions + * @property {boolean} [keepComments=false] Serializes comments. + */ + +/** + * Parses the given .proto source and returns an object with the parsed contents. + * @param {string} source Source contents + * @param {Root} root Root to populate + * @param {IParseOptions} [options] Parse options. Defaults to {@link parse.defaults} when omitted. + * @returns {IParserResult} Parser result + * @property {string} filename=null Currently processing file name for error reporting, if known + * @property {IParseOptions} defaults Default {@link IParseOptions} + */ +function parse(source, root, options) { + /* eslint-disable callback-return */ + if (!(root instanceof Root)) { + options = root; + root = new Root(); + } + if (!options) + options = parse.defaults; + + var preferTrailingComment = options.preferTrailingComment || false; + var tn = tokenize(source, options.alternateCommentMode || false), + next = tn.next, + push = tn.push, + peek = tn.peek, + skip = tn.skip, + cmnt = tn.cmnt; + + var head = true, + pkg, + imports, + weakImports, + syntax, + isProto3 = false; + + var ptr = root; + + var applyCase = options.keepCase ? function(name) { return name; } : util.camelCase; + + /* istanbul ignore next */ + function illegal(token, name, insideTryCatch) { + var filename = parse.filename; + if (!insideTryCatch) + parse.filename = null; + return Error("illegal " + (name || "token") + " '" + token + "' (" + (filename ? filename + ", " : "") + "line " + tn.line + ")"); + } + + function readString() { + var values = [], + token; + do { + /* istanbul ignore if */ + if ((token = next()) !== "\"" && token !== "'") + throw illegal(token); + + values.push(next()); + skip(token); + token = peek(); + } while (token === "\"" || token === "'"); + return values.join(""); + } + + function readValue(acceptTypeRef) { + var token = next(); + switch (token) { + case "'": + case "\"": + push(token); + return readString(); + case "true": case "TRUE": + return true; + case "false": case "FALSE": + return false; + } + try { + return parseNumber(token, /* insideTryCatch */ true); + } catch (e) { + + /* istanbul ignore else */ + if (acceptTypeRef && typeRefRe.test(token)) + return token; + + /* istanbul ignore next */ + throw illegal(token, "value"); + } + } + + function readRanges(target, acceptStrings) { + var token, start; + do { + if (acceptStrings && ((token = peek()) === "\"" || token === "'")) + target.push(readString()); + else + target.push([ start = parseId(next()), skip("to", true) ? parseId(next()) : start ]); + } while (skip(",", true)); + var dummy = {options: undefined}; + dummy.setOption = function(name, value) { + if (this.options === undefined) this.options = {}; + this.options[name] = value; + }; + ifBlock( + dummy, + function parseRange_block(token) { + /* istanbul ignore else */ + if (token === "option") { + parseOption(dummy, token); // skip + skip(";"); + } else + throw illegal(token); + }, + function parseRange_line() { + parseInlineOptions(dummy); // skip + }); + } + + function parseNumber(token, insideTryCatch) { + var sign = 1; + if (token.charAt(0) === "-") { + sign = -1; + token = token.substring(1); + } + switch (token) { + case "inf": case "INF": case "Inf": + return sign * Infinity; + case "nan": case "NAN": case "Nan": case "NaN": + return NaN; + case "0": + return 0; + } + if (base10Re.test(token)) + return sign * parseInt(token, 10); + if (base16Re.test(token)) + return sign * parseInt(token, 16); + if (base8Re.test(token)) + return sign * parseInt(token, 8); + + /* istanbul ignore else */ + if (numberRe.test(token)) + return sign * parseFloat(token); + + /* istanbul ignore next */ + throw illegal(token, "number", insideTryCatch); + } + + function parseId(token, acceptNegative) { + switch (token) { + case "max": case "MAX": case "Max": + return 536870911; + case "0": + return 0; + } + + /* istanbul ignore if */ + if (!acceptNegative && token.charAt(0) === "-") + throw illegal(token, "id"); + + if (base10NegRe.test(token)) + return parseInt(token, 10); + if (base16NegRe.test(token)) + return parseInt(token, 16); + + /* istanbul ignore else */ + if (base8NegRe.test(token)) + return parseInt(token, 8); + + /* istanbul ignore next */ + throw illegal(token, "id"); + } + + function parsePackage() { + + /* istanbul ignore if */ + if (pkg !== undefined) + throw illegal("package"); + + pkg = next(); + + /* istanbul ignore if */ + if (!typeRefRe.test(pkg)) + throw illegal(pkg, "name"); + + ptr = ptr.define(pkg); + skip(";"); + } + + function parseImport() { + var token = peek(); + var whichImports; + switch (token) { + case "weak": + whichImports = weakImports || (weakImports = []); + next(); + break; + case "public": + next(); + // eslint-disable-next-line no-fallthrough + default: + whichImports = imports || (imports = []); + break; + } + token = readString(); + skip(";"); + whichImports.push(token); + } + + function parseSyntax() { + skip("="); + syntax = readString(); + isProto3 = syntax === "proto3"; + + /* istanbul ignore if */ + if (!isProto3 && syntax !== "proto2") + throw illegal(syntax, "syntax"); + + skip(";"); + } + + function parseCommon(parent, token) { + switch (token) { + + case "option": + parseOption(parent, token); + skip(";"); + return true; + + case "message": + parseType(parent, token); + return true; + + case "enum": + parseEnum(parent, token); + return true; + + case "service": + parseService(parent, token); + return true; + + case "extend": + parseExtension(parent, token); + return true; + } + return false; + } + + function ifBlock(obj, fnIf, fnElse) { + var trailingLine = tn.line; + if (obj) { + if(typeof obj.comment !== "string") { + obj.comment = cmnt(); // try block-type comment + } + obj.filename = parse.filename; + } + if (skip("{", true)) { + var token; + while ((token = next()) !== "}") + fnIf(token); + skip(";", true); + } else { + if (fnElse) + fnElse(); + skip(";"); + if (obj && (typeof obj.comment !== "string" || preferTrailingComment)) + obj.comment = cmnt(trailingLine) || obj.comment; // try line-type comment + } + } + + function parseType(parent, token) { + + /* istanbul ignore if */ + if (!nameRe.test(token = next())) + throw illegal(token, "type name"); + + var type = new Type(token); + ifBlock(type, function parseType_block(token) { + if (parseCommon(type, token)) + return; + + switch (token) { + + case "map": + parseMapField(type, token); + break; + + case "required": + case "repeated": + parseField(type, token); + break; + + case "optional": + /* istanbul ignore if */ + if (isProto3) { + parseField(type, "proto3_optional"); + } else { + parseField(type, "optional"); + } + break; + + case "oneof": + parseOneOf(type, token); + break; + + case "extensions": + readRanges(type.extensions || (type.extensions = [])); + break; + + case "reserved": + readRanges(type.reserved || (type.reserved = []), true); + break; + + default: + /* istanbul ignore if */ + if (!isProto3 || !typeRefRe.test(token)) + throw illegal(token); + + push(token); + parseField(type, "optional"); + break; + } + }); + parent.add(type); + } + + function parseField(parent, rule, extend) { + var type = next(); + if (type === "group") { + parseGroup(parent, rule); + return; + } + // Type names can consume multiple tokens, in multiple variants: + // package.subpackage field tokens: "package.subpackage" [TYPE NAME ENDS HERE] "field" + // package . subpackage field tokens: "package" "." "subpackage" [TYPE NAME ENDS HERE] "field" + // package. subpackage field tokens: "package." "subpackage" [TYPE NAME ENDS HERE] "field" + // package .subpackage field tokens: "package" ".subpackage" [TYPE NAME ENDS HERE] "field" + // Keep reading tokens until we get a type name with no period at the end, + // and the next token does not start with a period. + while (type.endsWith(".") || peek().startsWith(".")) { + type += next(); + } + + /* istanbul ignore if */ + if (!typeRefRe.test(type)) + throw illegal(type, "type"); + + var name = next(); + + /* istanbul ignore if */ + if (!nameRe.test(name)) + throw illegal(name, "name"); + + name = applyCase(name); + skip("="); + + var field = new Field(name, parseId(next()), type, rule, extend); + ifBlock(field, function parseField_block(token) { + + /* istanbul ignore else */ + if (token === "option") { + parseOption(field, token); + skip(";"); + } else + throw illegal(token); + + }, function parseField_line() { + parseInlineOptions(field); + }); + + if (rule === "proto3_optional") { + // for proto3 optional fields, we create a single-member Oneof to mimic "optional" behavior + var oneof = new OneOf("_" + name); + field.setOption("proto3_optional", true); + oneof.add(field); + parent.add(oneof); + } else { + parent.add(field); + } + + // JSON defaults to packed=true if not set so we have to set packed=false explicity when + // parsing proto2 descriptors without the option, where applicable. This must be done for + // all known packable types and anything that could be an enum (= is not a basic type). + if (!isProto3 && field.repeated && (types.packed[type] !== undefined || types.basic[type] === undefined)) + field.setOption("packed", false, /* ifNotSet */ true); + } + + function parseGroup(parent, rule) { + var name = next(); + + /* istanbul ignore if */ + if (!nameRe.test(name)) + throw illegal(name, "name"); + + var fieldName = util.lcFirst(name); + if (name === fieldName) + name = util.ucFirst(name); + skip("="); + var id = parseId(next()); + var type = new Type(name); + type.group = true; + var field = new Field(fieldName, id, name, rule); + field.filename = parse.filename; + ifBlock(type, function parseGroup_block(token) { + switch (token) { + + case "option": + parseOption(type, token); + skip(";"); + break; + + case "required": + case "repeated": + parseField(type, token); + break; + + case "optional": + /* istanbul ignore if */ + if (isProto3) { + parseField(type, "proto3_optional"); + } else { + parseField(type, "optional"); + } + break; + + case "message": + parseType(type, token); + break; + + case "enum": + parseEnum(type, token); + break; + + /* istanbul ignore next */ + default: + throw illegal(token); // there are no groups with proto3 semantics + } + }); + parent.add(type) + .add(field); + } + + function parseMapField(parent) { + skip("<"); + var keyType = next(); + + /* istanbul ignore if */ + if (types.mapKey[keyType] === undefined) + throw illegal(keyType, "type"); + + skip(","); + var valueType = next(); + + /* istanbul ignore if */ + if (!typeRefRe.test(valueType)) + throw illegal(valueType, "type"); + + skip(">"); + var name = next(); + + /* istanbul ignore if */ + if (!nameRe.test(name)) + throw illegal(name, "name"); + + skip("="); + var field = new MapField(applyCase(name), parseId(next()), keyType, valueType); + ifBlock(field, function parseMapField_block(token) { + + /* istanbul ignore else */ + if (token === "option") { + parseOption(field, token); + skip(";"); + } else + throw illegal(token); + + }, function parseMapField_line() { + parseInlineOptions(field); + }); + parent.add(field); + } + + function parseOneOf(parent, token) { + + /* istanbul ignore if */ + if (!nameRe.test(token = next())) + throw illegal(token, "name"); + + var oneof = new OneOf(applyCase(token)); + ifBlock(oneof, function parseOneOf_block(token) { + if (token === "option") { + parseOption(oneof, token); + skip(";"); + } else { + push(token); + parseField(oneof, "optional"); + } + }); + parent.add(oneof); + } + + function parseEnum(parent, token) { + + /* istanbul ignore if */ + if (!nameRe.test(token = next())) + throw illegal(token, "name"); + + var enm = new Enum(token); + ifBlock(enm, function parseEnum_block(token) { + switch(token) { + case "option": + parseOption(enm, token); + skip(";"); + break; + + case "reserved": + readRanges(enm.reserved || (enm.reserved = []), true); + break; + + default: + parseEnumValue(enm, token); + } + }); + parent.add(enm); + } + + function parseEnumValue(parent, token) { + + /* istanbul ignore if */ + if (!nameRe.test(token)) + throw illegal(token, "name"); + + skip("="); + var value = parseId(next(), true), + dummy = { + options: undefined + }; + dummy.setOption = function(name, value) { + if (this.options === undefined) + this.options = {}; + this.options[name] = value; + }; + ifBlock(dummy, function parseEnumValue_block(token) { + + /* istanbul ignore else */ + if (token === "option") { + parseOption(dummy, token); // skip + skip(";"); + } else + throw illegal(token); + + }, function parseEnumValue_line() { + parseInlineOptions(dummy); // skip + }); + parent.add(token, value, dummy.comment, dummy.options); + } + + function parseOption(parent, token) { + var isCustom = skip("(", true); + + /* istanbul ignore if */ + if (!typeRefRe.test(token = next())) + throw illegal(token, "name"); + + var name = token; + var option = name; + var propName; + + if (isCustom) { + skip(")"); + name = "(" + name + ")"; + option = name; + token = peek(); + if (fqTypeRefRe.test(token)) { + propName = token.slice(1); //remove '.' before property name + name += token; + next(); + } + } + skip("="); + var optionValue = parseOptionValue(parent, name); + setParsedOption(parent, option, optionValue, propName); + } + + function parseOptionValue(parent, name) { + // { a: "foo" b { c: "bar" } } + if (skip("{", true)) { + var objectResult = {}; + + while (!skip("}", true)) { + /* istanbul ignore if */ + if (!nameRe.test(token = next())) { + throw illegal(token, "name"); + } + if (token === null) { + throw illegal(token, "end of input"); + } + + var value; + var propName = token; + + skip(":", true); + + if (peek() === "{") + value = parseOptionValue(parent, name + "." + token); + else if (peek() === "[") { + // option (my_option) = { + // repeated_value: [ "foo", "bar" ] + // }; + value = []; + var lastValue; + if (skip("[", true)) { + do { + lastValue = readValue(true); + value.push(lastValue); + } while (skip(",", true)); + skip("]"); + if (typeof lastValue !== "undefined") { + setOption(parent, name + "." + token, lastValue); + } + } + } else { + value = readValue(true); + setOption(parent, name + "." + token, value); + } + + var prevValue = objectResult[propName]; + + if (prevValue) + value = [].concat(prevValue).concat(value); + + objectResult[propName] = value; + + // Semicolons and commas can be optional + skip(",", true); + skip(";", true); + } + + return objectResult; + } + + var simpleValue = readValue(true); + setOption(parent, name, simpleValue); + return simpleValue; + // Does not enforce a delimiter to be universal + } + + function setOption(parent, name, value) { + if (parent.setOption) + parent.setOption(name, value); + } + + function setParsedOption(parent, name, value, propName) { + if (parent.setParsedOption) + parent.setParsedOption(name, value, propName); + } + + function parseInlineOptions(parent) { + if (skip("[", true)) { + do { + parseOption(parent, "option"); + } while (skip(",", true)); + skip("]"); + } + return parent; + } + + function parseService(parent, token) { + + /* istanbul ignore if */ + if (!nameRe.test(token = next())) + throw illegal(token, "service name"); + + var service = new Service(token); + ifBlock(service, function parseService_block(token) { + if (parseCommon(service, token)) + return; + + /* istanbul ignore else */ + if (token === "rpc") + parseMethod(service, token); + else + throw illegal(token); + }); + parent.add(service); + } + + function parseMethod(parent, token) { + // Get the comment of the preceding line now (if one exists) in case the + // method is defined across multiple lines. + var commentText = cmnt(); + + var type = token; + + /* istanbul ignore if */ + if (!nameRe.test(token = next())) + throw illegal(token, "name"); + + var name = token, + requestType, requestStream, + responseType, responseStream; + + skip("("); + if (skip("stream", true)) + requestStream = true; + + /* istanbul ignore if */ + if (!typeRefRe.test(token = next())) + throw illegal(token); + + requestType = token; + skip(")"); skip("returns"); skip("("); + if (skip("stream", true)) + responseStream = true; + + /* istanbul ignore if */ + if (!typeRefRe.test(token = next())) + throw illegal(token); + + responseType = token; + skip(")"); + + var method = new Method(name, type, requestType, responseType, requestStream, responseStream); + method.comment = commentText; + ifBlock(method, function parseMethod_block(token) { + + /* istanbul ignore else */ + if (token === "option") { + parseOption(method, token); + skip(";"); + } else + throw illegal(token); + + }); + parent.add(method); + } + + function parseExtension(parent, token) { + + /* istanbul ignore if */ + if (!typeRefRe.test(token = next())) + throw illegal(token, "reference"); + + var reference = token; + ifBlock(null, function parseExtension_block(token) { + switch (token) { + + case "required": + case "repeated": + parseField(parent, token, reference); + break; + + case "optional": + /* istanbul ignore if */ + if (isProto3) { + parseField(parent, "proto3_optional", reference); + } else { + parseField(parent, "optional", reference); + } + break; + + default: + /* istanbul ignore if */ + if (!isProto3 || !typeRefRe.test(token)) + throw illegal(token); + push(token); + parseField(parent, "optional", reference); + break; + } + }); + } + + var token; + while ((token = next()) !== null) { + switch (token) { + + case "package": + + /* istanbul ignore if */ + if (!head) + throw illegal(token); + + parsePackage(); + break; + + case "import": + + /* istanbul ignore if */ + if (!head) + throw illegal(token); + + parseImport(); + break; + + case "syntax": + + /* istanbul ignore if */ + if (!head) + throw illegal(token); + + parseSyntax(); + break; + + case "option": + + parseOption(ptr, token); + skip(";"); + break; + + default: + + /* istanbul ignore else */ + if (parseCommon(ptr, token)) { + head = false; + continue; + } + + /* istanbul ignore next */ + throw illegal(token); + } + } + + parse.filename = null; + return { + "package" : pkg, + "imports" : imports, + weakImports : weakImports, + syntax : syntax, + root : root + }; +} + +/** + * Parses the given .proto source and returns an object with the parsed contents. + * @name parse + * @function + * @param {string} source Source contents + * @param {IParseOptions} [options] Parse options. Defaults to {@link parse.defaults} when omitted. + * @returns {IParserResult} Parser result + * @property {string} filename=null Currently processing file name for error reporting, if known + * @property {IParseOptions} defaults Default {@link IParseOptions} + * @variation 2 + */ diff --git a/node_modules/protobufjs/src/reader.js b/node_modules/protobufjs/src/reader.js new file mode 100644 index 0000000..b4fbf29 --- /dev/null +++ b/node_modules/protobufjs/src/reader.js @@ -0,0 +1,416 @@ +"use strict"; +module.exports = Reader; + +var util = require("./util/minimal"); + +var BufferReader; // cyclic + +var LongBits = util.LongBits, + utf8 = util.utf8; + +/* istanbul ignore next */ +function indexOutOfRange(reader, writeLength) { + return RangeError("index out of range: " + reader.pos + " + " + (writeLength || 1) + " > " + reader.len); +} + +/** + * Constructs a new reader instance using the specified buffer. + * @classdesc Wire format reader using `Uint8Array` if available, otherwise `Array`. + * @constructor + * @param {Uint8Array} buffer Buffer to read from + */ +function Reader(buffer) { + + /** + * Read buffer. + * @type {Uint8Array} + */ + this.buf = buffer; + + /** + * Read buffer position. + * @type {number} + */ + this.pos = 0; + + /** + * Read buffer length. + * @type {number} + */ + this.len = buffer.length; +} + +var create_array = typeof Uint8Array !== "undefined" + ? function create_typed_array(buffer) { + if (buffer instanceof Uint8Array || Array.isArray(buffer)) + return new Reader(buffer); + throw Error("illegal buffer"); + } + /* istanbul ignore next */ + : function create_array(buffer) { + if (Array.isArray(buffer)) + return new Reader(buffer); + throw Error("illegal buffer"); + }; + +var create = function create() { + return util.Buffer + ? function create_buffer_setup(buffer) { + return (Reader.create = function create_buffer(buffer) { + return util.Buffer.isBuffer(buffer) + ? new BufferReader(buffer) + /* istanbul ignore next */ + : create_array(buffer); + })(buffer); + } + /* istanbul ignore next */ + : create_array; +}; + +/** + * Creates a new reader using the specified buffer. + * @function + * @param {Uint8Array|Buffer} buffer Buffer to read from + * @returns {Reader|BufferReader} A {@link BufferReader} if `buffer` is a Buffer, otherwise a {@link Reader} + * @throws {Error} If `buffer` is not a valid buffer + */ +Reader.create = create(); + +Reader.prototype._slice = util.Array.prototype.subarray || /* istanbul ignore next */ util.Array.prototype.slice; + +/** + * Reads a varint as an unsigned 32 bit value. + * @function + * @returns {number} Value read + */ +Reader.prototype.uint32 = (function read_uint32_setup() { + var value = 4294967295; // optimizer type-hint, tends to deopt otherwise (?!) + return function read_uint32() { + value = ( this.buf[this.pos] & 127 ) >>> 0; if (this.buf[this.pos++] < 128) return value; + value = (value | (this.buf[this.pos] & 127) << 7) >>> 0; if (this.buf[this.pos++] < 128) return value; + value = (value | (this.buf[this.pos] & 127) << 14) >>> 0; if (this.buf[this.pos++] < 128) return value; + value = (value | (this.buf[this.pos] & 127) << 21) >>> 0; if (this.buf[this.pos++] < 128) return value; + value = (value | (this.buf[this.pos] & 15) << 28) >>> 0; if (this.buf[this.pos++] < 128) return value; + + /* istanbul ignore if */ + if ((this.pos += 5) > this.len) { + this.pos = this.len; + throw indexOutOfRange(this, 10); + } + return value; + }; +})(); + +/** + * Reads a varint as a signed 32 bit value. + * @returns {number} Value read + */ +Reader.prototype.int32 = function read_int32() { + return this.uint32() | 0; +}; + +/** + * Reads a zig-zag encoded varint as a signed 32 bit value. + * @returns {number} Value read + */ +Reader.prototype.sint32 = function read_sint32() { + var value = this.uint32(); + return value >>> 1 ^ -(value & 1) | 0; +}; + +/* eslint-disable no-invalid-this */ + +function readLongVarint() { + // tends to deopt with local vars for octet etc. + var bits = new LongBits(0, 0); + var i = 0; + if (this.len - this.pos > 4) { // fast route (lo) + for (; i < 4; ++i) { + // 1st..4th + bits.lo = (bits.lo | (this.buf[this.pos] & 127) << i * 7) >>> 0; + if (this.buf[this.pos++] < 128) + return bits; + } + // 5th + bits.lo = (bits.lo | (this.buf[this.pos] & 127) << 28) >>> 0; + bits.hi = (bits.hi | (this.buf[this.pos] & 127) >> 4) >>> 0; + if (this.buf[this.pos++] < 128) + return bits; + i = 0; + } else { + for (; i < 3; ++i) { + /* istanbul ignore if */ + if (this.pos >= this.len) + throw indexOutOfRange(this); + // 1st..3th + bits.lo = (bits.lo | (this.buf[this.pos] & 127) << i * 7) >>> 0; + if (this.buf[this.pos++] < 128) + return bits; + } + // 4th + bits.lo = (bits.lo | (this.buf[this.pos++] & 127) << i * 7) >>> 0; + return bits; + } + if (this.len - this.pos > 4) { // fast route (hi) + for (; i < 5; ++i) { + // 6th..10th + bits.hi = (bits.hi | (this.buf[this.pos] & 127) << i * 7 + 3) >>> 0; + if (this.buf[this.pos++] < 128) + return bits; + } + } else { + for (; i < 5; ++i) { + /* istanbul ignore if */ + if (this.pos >= this.len) + throw indexOutOfRange(this); + // 6th..10th + bits.hi = (bits.hi | (this.buf[this.pos] & 127) << i * 7 + 3) >>> 0; + if (this.buf[this.pos++] < 128) + return bits; + } + } + /* istanbul ignore next */ + throw Error("invalid varint encoding"); +} + +/* eslint-enable no-invalid-this */ + +/** + * Reads a varint as a signed 64 bit value. + * @name Reader#int64 + * @function + * @returns {Long} Value read + */ + +/** + * Reads a varint as an unsigned 64 bit value. + * @name Reader#uint64 + * @function + * @returns {Long} Value read + */ + +/** + * Reads a zig-zag encoded varint as a signed 64 bit value. + * @name Reader#sint64 + * @function + * @returns {Long} Value read + */ + +/** + * Reads a varint as a boolean. + * @returns {boolean} Value read + */ +Reader.prototype.bool = function read_bool() { + return this.uint32() !== 0; +}; + +function readFixed32_end(buf, end) { // note that this uses `end`, not `pos` + return (buf[end - 4] + | buf[end - 3] << 8 + | buf[end - 2] << 16 + | buf[end - 1] << 24) >>> 0; +} + +/** + * Reads fixed 32 bits as an unsigned 32 bit integer. + * @returns {number} Value read + */ +Reader.prototype.fixed32 = function read_fixed32() { + + /* istanbul ignore if */ + if (this.pos + 4 > this.len) + throw indexOutOfRange(this, 4); + + return readFixed32_end(this.buf, this.pos += 4); +}; + +/** + * Reads fixed 32 bits as a signed 32 bit integer. + * @returns {number} Value read + */ +Reader.prototype.sfixed32 = function read_sfixed32() { + + /* istanbul ignore if */ + if (this.pos + 4 > this.len) + throw indexOutOfRange(this, 4); + + return readFixed32_end(this.buf, this.pos += 4) | 0; +}; + +/* eslint-disable no-invalid-this */ + +function readFixed64(/* this: Reader */) { + + /* istanbul ignore if */ + if (this.pos + 8 > this.len) + throw indexOutOfRange(this, 8); + + return new LongBits(readFixed32_end(this.buf, this.pos += 4), readFixed32_end(this.buf, this.pos += 4)); +} + +/* eslint-enable no-invalid-this */ + +/** + * Reads fixed 64 bits. + * @name Reader#fixed64 + * @function + * @returns {Long} Value read + */ + +/** + * Reads zig-zag encoded fixed 64 bits. + * @name Reader#sfixed64 + * @function + * @returns {Long} Value read + */ + +/** + * Reads a float (32 bit) as a number. + * @function + * @returns {number} Value read + */ +Reader.prototype.float = function read_float() { + + /* istanbul ignore if */ + if (this.pos + 4 > this.len) + throw indexOutOfRange(this, 4); + + var value = util.float.readFloatLE(this.buf, this.pos); + this.pos += 4; + return value; +}; + +/** + * Reads a double (64 bit float) as a number. + * @function + * @returns {number} Value read + */ +Reader.prototype.double = function read_double() { + + /* istanbul ignore if */ + if (this.pos + 8 > this.len) + throw indexOutOfRange(this, 4); + + var value = util.float.readDoubleLE(this.buf, this.pos); + this.pos += 8; + return value; +}; + +/** + * Reads a sequence of bytes preceeded by its length as a varint. + * @returns {Uint8Array} Value read + */ +Reader.prototype.bytes = function read_bytes() { + var length = this.uint32(), + start = this.pos, + end = this.pos + length; + + /* istanbul ignore if */ + if (end > this.len) + throw indexOutOfRange(this, length); + + this.pos += length; + if (Array.isArray(this.buf)) // plain array + return this.buf.slice(start, end); + + if (start === end) { // fix for IE 10/Win8 and others' subarray returning array of size 1 + var nativeBuffer = util.Buffer; + return nativeBuffer + ? nativeBuffer.alloc(0) + : new this.buf.constructor(0); + } + return this._slice.call(this.buf, start, end); +}; + +/** + * Reads a string preceeded by its byte length as a varint. + * @returns {string} Value read + */ +Reader.prototype.string = function read_string() { + var bytes = this.bytes(); + return utf8.read(bytes, 0, bytes.length); +}; + +/** + * Skips the specified number of bytes if specified, otherwise skips a varint. + * @param {number} [length] Length if known, otherwise a varint is assumed + * @returns {Reader} `this` + */ +Reader.prototype.skip = function skip(length) { + if (typeof length === "number") { + /* istanbul ignore if */ + if (this.pos + length > this.len) + throw indexOutOfRange(this, length); + this.pos += length; + } else { + do { + /* istanbul ignore if */ + if (this.pos >= this.len) + throw indexOutOfRange(this); + } while (this.buf[this.pos++] & 128); + } + return this; +}; + +/** + * Skips the next element of the specified wire type. + * @param {number} wireType Wire type received + * @returns {Reader} `this` + */ +Reader.prototype.skipType = function(wireType) { + switch (wireType) { + case 0: + this.skip(); + break; + case 1: + this.skip(8); + break; + case 2: + this.skip(this.uint32()); + break; + case 3: + while ((wireType = this.uint32() & 7) !== 4) { + this.skipType(wireType); + } + break; + case 5: + this.skip(4); + break; + + /* istanbul ignore next */ + default: + throw Error("invalid wire type " + wireType + " at offset " + this.pos); + } + return this; +}; + +Reader._configure = function(BufferReader_) { + BufferReader = BufferReader_; + Reader.create = create(); + BufferReader._configure(); + + var fn = util.Long ? "toLong" : /* istanbul ignore next */ "toNumber"; + util.merge(Reader.prototype, { + + int64: function read_int64() { + return readLongVarint.call(this)[fn](false); + }, + + uint64: function read_uint64() { + return readLongVarint.call(this)[fn](true); + }, + + sint64: function read_sint64() { + return readLongVarint.call(this).zzDecode()[fn](false); + }, + + fixed64: function read_fixed64() { + return readFixed64.call(this)[fn](true); + }, + + sfixed64: function read_sfixed64() { + return readFixed64.call(this)[fn](false); + } + + }); +}; diff --git a/node_modules/protobufjs/src/reader_buffer.js b/node_modules/protobufjs/src/reader_buffer.js new file mode 100644 index 0000000..e547424 --- /dev/null +++ b/node_modules/protobufjs/src/reader_buffer.js @@ -0,0 +1,51 @@ +"use strict"; +module.exports = BufferReader; + +// extends Reader +var Reader = require("./reader"); +(BufferReader.prototype = Object.create(Reader.prototype)).constructor = BufferReader; + +var util = require("./util/minimal"); + +/** + * Constructs a new buffer reader instance. + * @classdesc Wire format reader using node buffers. + * @extends Reader + * @constructor + * @param {Buffer} buffer Buffer to read from + */ +function BufferReader(buffer) { + Reader.call(this, buffer); + + /** + * Read buffer. + * @name BufferReader#buf + * @type {Buffer} + */ +} + +BufferReader._configure = function () { + /* istanbul ignore else */ + if (util.Buffer) + BufferReader.prototype._slice = util.Buffer.prototype.slice; +}; + + +/** + * @override + */ +BufferReader.prototype.string = function read_string_buffer() { + var len = this.uint32(); // modifies pos + return this.buf.utf8Slice + ? this.buf.utf8Slice(this.pos, this.pos = Math.min(this.pos + len, this.len)) + : this.buf.toString("utf-8", this.pos, this.pos = Math.min(this.pos + len, this.len)); +}; + +/** + * Reads a sequence of bytes preceeded by its length as a varint. + * @name BufferReader#bytes + * @function + * @returns {Buffer} Value read + */ + +BufferReader._configure(); diff --git a/node_modules/protobufjs/src/root.js b/node_modules/protobufjs/src/root.js new file mode 100644 index 0000000..2776f96 --- /dev/null +++ b/node_modules/protobufjs/src/root.js @@ -0,0 +1,368 @@ +"use strict"; +module.exports = Root; + +// extends Namespace +var Namespace = require("./namespace"); +((Root.prototype = Object.create(Namespace.prototype)).constructor = Root).className = "Root"; + +var Field = require("./field"), + Enum = require("./enum"), + OneOf = require("./oneof"), + util = require("./util"); + +var Type, // cyclic + parse, // might be excluded + common; // " + +/** + * Constructs a new root namespace instance. + * @classdesc Root namespace wrapping all types, enums, services, sub-namespaces etc. that belong together. + * @extends NamespaceBase + * @constructor + * @param {Object.} [options] Top level options + */ +function Root(options) { + Namespace.call(this, "", options); + + /** + * Deferred extension fields. + * @type {Field[]} + */ + this.deferred = []; + + /** + * Resolved file names of loaded files. + * @type {string[]} + */ + this.files = []; +} + +/** + * Loads a namespace descriptor into a root namespace. + * @param {INamespace} json Nameespace descriptor + * @param {Root} [root] Root namespace, defaults to create a new one if omitted + * @returns {Root} Root namespace + */ +Root.fromJSON = function fromJSON(json, root) { + if (!root) + root = new Root(); + if (json.options) + root.setOptions(json.options); + return root.addJSON(json.nested); +}; + +/** + * Resolves the path of an imported file, relative to the importing origin. + * This method exists so you can override it with your own logic in case your imports are scattered over multiple directories. + * @function + * @param {string} origin The file name of the importing file + * @param {string} target The file name being imported + * @returns {string|null} Resolved path to `target` or `null` to skip the file + */ +Root.prototype.resolvePath = util.path.resolve; + +/** + * Fetch content from file path or url + * This method exists so you can override it with your own logic. + * @function + * @param {string} path File path or url + * @param {FetchCallback} callback Callback function + * @returns {undefined} + */ +Root.prototype.fetch = util.fetch; + +// A symbol-like function to safely signal synchronous loading +/* istanbul ignore next */ +function SYNC() {} // eslint-disable-line no-empty-function + +/** + * Loads one or multiple .proto or preprocessed .json files into this root namespace and calls the callback. + * @param {string|string[]} filename Names of one or multiple files to load + * @param {IParseOptions} options Parse options + * @param {LoadCallback} callback Callback function + * @returns {undefined} + */ +Root.prototype.load = function load(filename, options, callback) { + if (typeof options === "function") { + callback = options; + options = undefined; + } + var self = this; + if (!callback) + return util.asPromise(load, self, filename, options); + + var sync = callback === SYNC; // undocumented + + // Finishes loading by calling the callback (exactly once) + function finish(err, root) { + /* istanbul ignore if */ + if (!callback) + return; + if (sync) + throw err; + var cb = callback; + callback = null; + cb(err, root); + } + + // Bundled definition existence checking + function getBundledFileName(filename) { + var idx = filename.lastIndexOf("google/protobuf/"); + if (idx > -1) { + var altname = filename.substring(idx); + if (altname in common) return altname; + } + return null; + } + + // Processes a single file + function process(filename, source) { + try { + if (util.isString(source) && source.charAt(0) === "{") + source = JSON.parse(source); + if (!util.isString(source)) + self.setOptions(source.options).addJSON(source.nested); + else { + parse.filename = filename; + var parsed = parse(source, self, options), + resolved, + i = 0; + if (parsed.imports) + for (; i < parsed.imports.length; ++i) + if (resolved = getBundledFileName(parsed.imports[i]) || self.resolvePath(filename, parsed.imports[i])) + fetch(resolved); + if (parsed.weakImports) + for (i = 0; i < parsed.weakImports.length; ++i) + if (resolved = getBundledFileName(parsed.weakImports[i]) || self.resolvePath(filename, parsed.weakImports[i])) + fetch(resolved, true); + } + } catch (err) { + finish(err); + } + if (!sync && !queued) + finish(null, self); // only once anyway + } + + // Fetches a single file + function fetch(filename, weak) { + filename = getBundledFileName(filename) || filename; + + // Skip if already loaded / attempted + if (self.files.indexOf(filename) > -1) + return; + self.files.push(filename); + + // Shortcut bundled definitions + if (filename in common) { + if (sync) + process(filename, common[filename]); + else { + ++queued; + setTimeout(function() { + --queued; + process(filename, common[filename]); + }); + } + return; + } + + // Otherwise fetch from disk or network + if (sync) { + var source; + try { + source = util.fs.readFileSync(filename).toString("utf8"); + } catch (err) { + if (!weak) + finish(err); + return; + } + process(filename, source); + } else { + ++queued; + self.fetch(filename, function(err, source) { + --queued; + /* istanbul ignore if */ + if (!callback) + return; // terminated meanwhile + if (err) { + /* istanbul ignore else */ + if (!weak) + finish(err); + else if (!queued) // can't be covered reliably + finish(null, self); + return; + } + process(filename, source); + }); + } + } + var queued = 0; + + // Assembling the root namespace doesn't require working type + // references anymore, so we can load everything in parallel + if (util.isString(filename)) + filename = [ filename ]; + for (var i = 0, resolved; i < filename.length; ++i) + if (resolved = self.resolvePath("", filename[i])) + fetch(resolved); + + if (sync) + return self; + if (!queued) + finish(null, self); + return undefined; +}; +// function load(filename:string, options:IParseOptions, callback:LoadCallback):undefined + +/** + * Loads one or multiple .proto or preprocessed .json files into this root namespace and calls the callback. + * @function Root#load + * @param {string|string[]} filename Names of one or multiple files to load + * @param {LoadCallback} callback Callback function + * @returns {undefined} + * @variation 2 + */ +// function load(filename:string, callback:LoadCallback):undefined + +/** + * Loads one or multiple .proto or preprocessed .json files into this root namespace and returns a promise. + * @function Root#load + * @param {string|string[]} filename Names of one or multiple files to load + * @param {IParseOptions} [options] Parse options. Defaults to {@link parse.defaults} when omitted. + * @returns {Promise} Promise + * @variation 3 + */ +// function load(filename:string, [options:IParseOptions]):Promise + +/** + * Synchronously loads one or multiple .proto or preprocessed .json files into this root namespace (node only). + * @function Root#loadSync + * @param {string|string[]} filename Names of one or multiple files to load + * @param {IParseOptions} [options] Parse options. Defaults to {@link parse.defaults} when omitted. + * @returns {Root} Root namespace + * @throws {Error} If synchronous fetching is not supported (i.e. in browsers) or if a file's syntax is invalid + */ +Root.prototype.loadSync = function loadSync(filename, options) { + if (!util.isNode) + throw Error("not supported"); + return this.load(filename, options, SYNC); +}; + +/** + * @override + */ +Root.prototype.resolveAll = function resolveAll() { + if (this.deferred.length) + throw Error("unresolvable extensions: " + this.deferred.map(function(field) { + return "'extend " + field.extend + "' in " + field.parent.fullName; + }).join(", ")); + return Namespace.prototype.resolveAll.call(this); +}; + +// only uppercased (and thus conflict-free) children are exposed, see below +var exposeRe = /^[A-Z]/; + +/** + * Handles a deferred declaring extension field by creating a sister field to represent it within its extended type. + * @param {Root} root Root instance + * @param {Field} field Declaring extension field witin the declaring type + * @returns {boolean} `true` if successfully added to the extended type, `false` otherwise + * @inner + * @ignore + */ +function tryHandleExtension(root, field) { + var extendedType = field.parent.lookup(field.extend); + if (extendedType) { + var sisterField = new Field(field.fullName, field.id, field.type, field.rule, undefined, field.options); + //do not allow to extend same field twice to prevent the error + if (extendedType.get(sisterField.name)) { + return true; + } + sisterField.declaringField = field; + field.extensionField = sisterField; + extendedType.add(sisterField); + return true; + } + return false; +} + +/** + * Called when any object is added to this root or its sub-namespaces. + * @param {ReflectionObject} object Object added + * @returns {undefined} + * @private + */ +Root.prototype._handleAdd = function _handleAdd(object) { + if (object instanceof Field) { + + if (/* an extension field (implies not part of a oneof) */ object.extend !== undefined && /* not already handled */ !object.extensionField) + if (!tryHandleExtension(this, object)) + this.deferred.push(object); + + } else if (object instanceof Enum) { + + if (exposeRe.test(object.name)) + object.parent[object.name] = object.values; // expose enum values as property of its parent + + } else if (!(object instanceof OneOf)) /* everything else is a namespace */ { + + if (object instanceof Type) // Try to handle any deferred extensions + for (var i = 0; i < this.deferred.length;) + if (tryHandleExtension(this, this.deferred[i])) + this.deferred.splice(i, 1); + else + ++i; + for (var j = 0; j < /* initializes */ object.nestedArray.length; ++j) // recurse into the namespace + this._handleAdd(object._nestedArray[j]); + if (exposeRe.test(object.name)) + object.parent[object.name] = object; // expose namespace as property of its parent + } + + // The above also adds uppercased (and thus conflict-free) nested types, services and enums as + // properties of namespaces just like static code does. This allows using a .d.ts generated for + // a static module with reflection-based solutions where the condition is met. +}; + +/** + * Called when any object is removed from this root or its sub-namespaces. + * @param {ReflectionObject} object Object removed + * @returns {undefined} + * @private + */ +Root.prototype._handleRemove = function _handleRemove(object) { + if (object instanceof Field) { + + if (/* an extension field */ object.extend !== undefined) { + if (/* already handled */ object.extensionField) { // remove its sister field + object.extensionField.parent.remove(object.extensionField); + object.extensionField = null; + } else { // cancel the extension + var index = this.deferred.indexOf(object); + /* istanbul ignore else */ + if (index > -1) + this.deferred.splice(index, 1); + } + } + + } else if (object instanceof Enum) { + + if (exposeRe.test(object.name)) + delete object.parent[object.name]; // unexpose enum values + + } else if (object instanceof Namespace) { + + for (var i = 0; i < /* initializes */ object.nestedArray.length; ++i) // recurse into the namespace + this._handleRemove(object._nestedArray[i]); + + if (exposeRe.test(object.name)) + delete object.parent[object.name]; // unexpose namespaces + + } +}; + +// Sets up cyclic dependencies (called in index-light) +Root._configure = function(Type_, parse_, common_) { + Type = Type_; + parse = parse_; + common = common_; +}; diff --git a/node_modules/protobufjs/src/roots.js b/node_modules/protobufjs/src/roots.js new file mode 100644 index 0000000..1d93086 --- /dev/null +++ b/node_modules/protobufjs/src/roots.js @@ -0,0 +1,18 @@ +"use strict"; +module.exports = {}; + +/** + * Named roots. + * This is where pbjs stores generated structures (the option `-r, --root` specifies a name). + * Can also be used manually to make roots available across modules. + * @name roots + * @type {Object.} + * @example + * // pbjs -r myroot -o compiled.js ... + * + * // in another module: + * require("./compiled.js"); + * + * // in any subsequent module: + * var root = protobuf.roots["myroot"]; + */ diff --git a/node_modules/protobufjs/src/rpc.js b/node_modules/protobufjs/src/rpc.js new file mode 100644 index 0000000..894e5c7 --- /dev/null +++ b/node_modules/protobufjs/src/rpc.js @@ -0,0 +1,36 @@ +"use strict"; + +/** + * Streaming RPC helpers. + * @namespace + */ +var rpc = exports; + +/** + * RPC implementation passed to {@link Service#create} performing a service request on network level, i.e. by utilizing http requests or websockets. + * @typedef RPCImpl + * @type {function} + * @param {Method|rpc.ServiceMethod,Message<{}>>} method Reflected or static method being called + * @param {Uint8Array} requestData Request data + * @param {RPCImplCallback} callback Callback function + * @returns {undefined} + * @example + * function rpcImpl(method, requestData, callback) { + * if (protobuf.util.lcFirst(method.name) !== "myMethod") // compatible with static code + * throw Error("no such method"); + * asynchronouslyObtainAResponse(requestData, function(err, responseData) { + * callback(err, responseData); + * }); + * } + */ + +/** + * Node-style callback as used by {@link RPCImpl}. + * @typedef RPCImplCallback + * @type {function} + * @param {Error|null} error Error, if any, otherwise `null` + * @param {Uint8Array|null} [response] Response data or `null` to signal end of stream, if there hasn't been an error + * @returns {undefined} + */ + +rpc.Service = require("./rpc/service"); diff --git a/node_modules/protobufjs/src/rpc/service.js b/node_modules/protobufjs/src/rpc/service.js new file mode 100644 index 0000000..757f382 --- /dev/null +++ b/node_modules/protobufjs/src/rpc/service.js @@ -0,0 +1,142 @@ +"use strict"; +module.exports = Service; + +var util = require("../util/minimal"); + +// Extends EventEmitter +(Service.prototype = Object.create(util.EventEmitter.prototype)).constructor = Service; + +/** + * A service method callback as used by {@link rpc.ServiceMethod|ServiceMethod}. + * + * Differs from {@link RPCImplCallback} in that it is an actual callback of a service method which may not return `response = null`. + * @typedef rpc.ServiceMethodCallback + * @template TRes extends Message + * @type {function} + * @param {Error|null} error Error, if any + * @param {TRes} [response] Response message + * @returns {undefined} + */ + +/** + * A service method part of a {@link rpc.Service} as created by {@link Service.create}. + * @typedef rpc.ServiceMethod + * @template TReq extends Message + * @template TRes extends Message + * @type {function} + * @param {TReq|Properties} request Request message or plain object + * @param {rpc.ServiceMethodCallback} [callback] Node-style callback called with the error, if any, and the response message + * @returns {Promise>} Promise if `callback` has been omitted, otherwise `undefined` + */ + +/** + * Constructs a new RPC service instance. + * @classdesc An RPC service as returned by {@link Service#create}. + * @exports rpc.Service + * @extends util.EventEmitter + * @constructor + * @param {RPCImpl} rpcImpl RPC implementation + * @param {boolean} [requestDelimited=false] Whether requests are length-delimited + * @param {boolean} [responseDelimited=false] Whether responses are length-delimited + */ +function Service(rpcImpl, requestDelimited, responseDelimited) { + + if (typeof rpcImpl !== "function") + throw TypeError("rpcImpl must be a function"); + + util.EventEmitter.call(this); + + /** + * RPC implementation. Becomes `null` once the service is ended. + * @type {RPCImpl|null} + */ + this.rpcImpl = rpcImpl; + + /** + * Whether requests are length-delimited. + * @type {boolean} + */ + this.requestDelimited = Boolean(requestDelimited); + + /** + * Whether responses are length-delimited. + * @type {boolean} + */ + this.responseDelimited = Boolean(responseDelimited); +} + +/** + * Calls a service method through {@link rpc.Service#rpcImpl|rpcImpl}. + * @param {Method|rpc.ServiceMethod} method Reflected or static method + * @param {Constructor} requestCtor Request constructor + * @param {Constructor} responseCtor Response constructor + * @param {TReq|Properties} request Request message or plain object + * @param {rpc.ServiceMethodCallback} callback Service callback + * @returns {undefined} + * @template TReq extends Message + * @template TRes extends Message + */ +Service.prototype.rpcCall = function rpcCall(method, requestCtor, responseCtor, request, callback) { + + if (!request) + throw TypeError("request must be specified"); + + var self = this; + if (!callback) + return util.asPromise(rpcCall, self, method, requestCtor, responseCtor, request); + + if (!self.rpcImpl) { + setTimeout(function() { callback(Error("already ended")); }, 0); + return undefined; + } + + try { + return self.rpcImpl( + method, + requestCtor[self.requestDelimited ? "encodeDelimited" : "encode"](request).finish(), + function rpcCallback(err, response) { + + if (err) { + self.emit("error", err, method); + return callback(err); + } + + if (response === null) { + self.end(/* endedByRPC */ true); + return undefined; + } + + if (!(response instanceof responseCtor)) { + try { + response = responseCtor[self.responseDelimited ? "decodeDelimited" : "decode"](response); + } catch (err) { + self.emit("error", err, method); + return callback(err); + } + } + + self.emit("data", response, method); + return callback(null, response); + } + ); + } catch (err) { + self.emit("error", err, method); + setTimeout(function() { callback(err); }, 0); + return undefined; + } +}; + +/** + * Ends this service and emits the `end` event. + * @param {boolean} [endedByRPC=false] Whether the service has been ended by the RPC implementation. + * @returns {rpc.Service} `this` + */ +Service.prototype.end = function end(endedByRPC) { + if (this.rpcImpl) { + if (!endedByRPC) // signal end to rpcImpl + this.rpcImpl(null, null, null); + this.rpcImpl = null; + this.emit("end").off(); + } + return this; +}; diff --git a/node_modules/protobufjs/src/service.js b/node_modules/protobufjs/src/service.js new file mode 100644 index 0000000..bc2c308 --- /dev/null +++ b/node_modules/protobufjs/src/service.js @@ -0,0 +1,167 @@ +"use strict"; +module.exports = Service; + +// extends Namespace +var Namespace = require("./namespace"); +((Service.prototype = Object.create(Namespace.prototype)).constructor = Service).className = "Service"; + +var Method = require("./method"), + util = require("./util"), + rpc = require("./rpc"); + +/** + * Constructs a new service instance. + * @classdesc Reflected service. + * @extends NamespaceBase + * @constructor + * @param {string} name Service name + * @param {Object.} [options] Service options + * @throws {TypeError} If arguments are invalid + */ +function Service(name, options) { + Namespace.call(this, name, options); + + /** + * Service methods. + * @type {Object.} + */ + this.methods = {}; // toJSON, marker + + /** + * Cached methods as an array. + * @type {Method[]|null} + * @private + */ + this._methodsArray = null; +} + +/** + * Service descriptor. + * @interface IService + * @extends INamespace + * @property {Object.} methods Method descriptors + */ + +/** + * Constructs a service from a service descriptor. + * @param {string} name Service name + * @param {IService} json Service descriptor + * @returns {Service} Created service + * @throws {TypeError} If arguments are invalid + */ +Service.fromJSON = function fromJSON(name, json) { + var service = new Service(name, json.options); + /* istanbul ignore else */ + if (json.methods) + for (var names = Object.keys(json.methods), i = 0; i < names.length; ++i) + service.add(Method.fromJSON(names[i], json.methods[names[i]])); + if (json.nested) + service.addJSON(json.nested); + service.comment = json.comment; + return service; +}; + +/** + * Converts this service to a service descriptor. + * @param {IToJSONOptions} [toJSONOptions] JSON conversion options + * @returns {IService} Service descriptor + */ +Service.prototype.toJSON = function toJSON(toJSONOptions) { + var inherited = Namespace.prototype.toJSON.call(this, toJSONOptions); + var keepComments = toJSONOptions ? Boolean(toJSONOptions.keepComments) : false; + return util.toObject([ + "options" , inherited && inherited.options || undefined, + "methods" , Namespace.arrayToJSON(this.methodsArray, toJSONOptions) || /* istanbul ignore next */ {}, + "nested" , inherited && inherited.nested || undefined, + "comment" , keepComments ? this.comment : undefined + ]); +}; + +/** + * Methods of this service as an array for iteration. + * @name Service#methodsArray + * @type {Method[]} + * @readonly + */ +Object.defineProperty(Service.prototype, "methodsArray", { + get: function() { + return this._methodsArray || (this._methodsArray = util.toArray(this.methods)); + } +}); + +function clearCache(service) { + service._methodsArray = null; + return service; +} + +/** + * @override + */ +Service.prototype.get = function get(name) { + return this.methods[name] + || Namespace.prototype.get.call(this, name); +}; + +/** + * @override + */ +Service.prototype.resolveAll = function resolveAll() { + var methods = this.methodsArray; + for (var i = 0; i < methods.length; ++i) + methods[i].resolve(); + return Namespace.prototype.resolve.call(this); +}; + +/** + * @override + */ +Service.prototype.add = function add(object) { + + /* istanbul ignore if */ + if (this.get(object.name)) + throw Error("duplicate name '" + object.name + "' in " + this); + + if (object instanceof Method) { + this.methods[object.name] = object; + object.parent = this; + return clearCache(this); + } + return Namespace.prototype.add.call(this, object); +}; + +/** + * @override + */ +Service.prototype.remove = function remove(object) { + if (object instanceof Method) { + + /* istanbul ignore if */ + if (this.methods[object.name] !== object) + throw Error(object + " is not a member of " + this); + + delete this.methods[object.name]; + object.parent = null; + return clearCache(this); + } + return Namespace.prototype.remove.call(this, object); +}; + +/** + * Creates a runtime service using the specified rpc implementation. + * @param {RPCImpl} rpcImpl RPC implementation + * @param {boolean} [requestDelimited=false] Whether requests are length-delimited + * @param {boolean} [responseDelimited=false] Whether responses are length-delimited + * @returns {rpc.Service} RPC service. Useful where requests and/or responses are streamed. + */ +Service.prototype.create = function create(rpcImpl, requestDelimited, responseDelimited) { + var rpcService = new rpc.Service(rpcImpl, requestDelimited, responseDelimited); + for (var i = 0, method; i < /* initializes */ this.methodsArray.length; ++i) { + var methodName = util.lcFirst((method = this._methodsArray[i]).resolve().name).replace(/[^$\w_]/g, ""); + rpcService[methodName] = util.codegen(["r","c"], util.isReserved(methodName) ? methodName + "_" : methodName)("return this.rpcCall(m,q,s,r,c)")({ + m: method, + q: method.resolvedRequestType.ctor, + s: method.resolvedResponseType.ctor + }); + } + return rpcService; +}; diff --git a/node_modules/protobufjs/src/tokenize.js b/node_modules/protobufjs/src/tokenize.js new file mode 100644 index 0000000..f107bea --- /dev/null +++ b/node_modules/protobufjs/src/tokenize.js @@ -0,0 +1,416 @@ +"use strict"; +module.exports = tokenize; + +var delimRe = /[\s{}=;:[\],'"()<>]/g, + stringDoubleRe = /(?:"([^"\\]*(?:\\.[^"\\]*)*)")/g, + stringSingleRe = /(?:'([^'\\]*(?:\\.[^'\\]*)*)')/g; + +var setCommentRe = /^ *[*/]+ */, + setCommentAltRe = /^\s*\*?\/*/, + setCommentSplitRe = /\n/g, + whitespaceRe = /\s/, + unescapeRe = /\\(.?)/g; + +var unescapeMap = { + "0": "\0", + "r": "\r", + "n": "\n", + "t": "\t" +}; + +/** + * Unescapes a string. + * @param {string} str String to unescape + * @returns {string} Unescaped string + * @property {Object.} map Special characters map + * @memberof tokenize + */ +function unescape(str) { + return str.replace(unescapeRe, function($0, $1) { + switch ($1) { + case "\\": + case "": + return $1; + default: + return unescapeMap[$1] || ""; + } + }); +} + +tokenize.unescape = unescape; + +/** + * Gets the next token and advances. + * @typedef TokenizerHandleNext + * @type {function} + * @returns {string|null} Next token or `null` on eof + */ + +/** + * Peeks for the next token. + * @typedef TokenizerHandlePeek + * @type {function} + * @returns {string|null} Next token or `null` on eof + */ + +/** + * Pushes a token back to the stack. + * @typedef TokenizerHandlePush + * @type {function} + * @param {string} token Token + * @returns {undefined} + */ + +/** + * Skips the next token. + * @typedef TokenizerHandleSkip + * @type {function} + * @param {string} expected Expected token + * @param {boolean} [optional=false] If optional + * @returns {boolean} Whether the token matched + * @throws {Error} If the token didn't match and is not optional + */ + +/** + * Gets the comment on the previous line or, alternatively, the line comment on the specified line. + * @typedef TokenizerHandleCmnt + * @type {function} + * @param {number} [line] Line number + * @returns {string|null} Comment text or `null` if none + */ + +/** + * Handle object returned from {@link tokenize}. + * @interface ITokenizerHandle + * @property {TokenizerHandleNext} next Gets the next token and advances (`null` on eof) + * @property {TokenizerHandlePeek} peek Peeks for the next token (`null` on eof) + * @property {TokenizerHandlePush} push Pushes a token back to the stack + * @property {TokenizerHandleSkip} skip Skips a token, returns its presence and advances or, if non-optional and not present, throws + * @property {TokenizerHandleCmnt} cmnt Gets the comment on the previous line or the line comment on the specified line, if any + * @property {number} line Current line number + */ + +/** + * Tokenizes the given .proto source and returns an object with useful utility functions. + * @param {string} source Source contents + * @param {boolean} alternateCommentMode Whether we should activate alternate comment parsing mode. + * @returns {ITokenizerHandle} Tokenizer handle + */ +function tokenize(source, alternateCommentMode) { + /* eslint-disable callback-return */ + source = source.toString(); + + var offset = 0, + length = source.length, + line = 1, + lastCommentLine = 0, + comments = {}; + + var stack = []; + + var stringDelim = null; + + /* istanbul ignore next */ + /** + * Creates an error for illegal syntax. + * @param {string} subject Subject + * @returns {Error} Error created + * @inner + */ + function illegal(subject) { + return Error("illegal " + subject + " (line " + line + ")"); + } + + /** + * Reads a string till its end. + * @returns {string} String read + * @inner + */ + function readString() { + var re = stringDelim === "'" ? stringSingleRe : stringDoubleRe; + re.lastIndex = offset - 1; + var match = re.exec(source); + if (!match) + throw illegal("string"); + offset = re.lastIndex; + push(stringDelim); + stringDelim = null; + return unescape(match[1]); + } + + /** + * Gets the character at `pos` within the source. + * @param {number} pos Position + * @returns {string} Character + * @inner + */ + function charAt(pos) { + return source.charAt(pos); + } + + /** + * Sets the current comment text. + * @param {number} start Start offset + * @param {number} end End offset + * @param {boolean} isLeading set if a leading comment + * @returns {undefined} + * @inner + */ + function setComment(start, end, isLeading) { + var comment = { + type: source.charAt(start++), + lineEmpty: false, + leading: isLeading, + }; + var lookback; + if (alternateCommentMode) { + lookback = 2; // alternate comment parsing: "//" or "/*" + } else { + lookback = 3; // "///" or "/**" + } + var commentOffset = start - lookback, + c; + do { + if (--commentOffset < 0 || + (c = source.charAt(commentOffset)) === "\n") { + comment.lineEmpty = true; + break; + } + } while (c === " " || c === "\t"); + var lines = source + .substring(start, end) + .split(setCommentSplitRe); + for (var i = 0; i < lines.length; ++i) + lines[i] = lines[i] + .replace(alternateCommentMode ? setCommentAltRe : setCommentRe, "") + .trim(); + comment.text = lines + .join("\n") + .trim(); + + comments[line] = comment; + lastCommentLine = line; + } + + function isDoubleSlashCommentLine(startOffset) { + var endOffset = findEndOfLine(startOffset); + + // see if remaining line matches comment pattern + var lineText = source.substring(startOffset, endOffset); + var isComment = /^\s*\/\//.test(lineText); + return isComment; + } + + function findEndOfLine(cursor) { + // find end of cursor's line + var endOffset = cursor; + while (endOffset < length && charAt(endOffset) !== "\n") { + endOffset++; + } + return endOffset; + } + + /** + * Obtains the next token. + * @returns {string|null} Next token or `null` on eof + * @inner + */ + function next() { + if (stack.length > 0) + return stack.shift(); + if (stringDelim) + return readString(); + var repeat, + prev, + curr, + start, + isDoc, + isLeadingComment = offset === 0; + do { + if (offset === length) + return null; + repeat = false; + while (whitespaceRe.test(curr = charAt(offset))) { + if (curr === "\n") { + isLeadingComment = true; + ++line; + } + if (++offset === length) + return null; + } + + if (charAt(offset) === "/") { + if (++offset === length) { + throw illegal("comment"); + } + if (charAt(offset) === "/") { // Line + if (!alternateCommentMode) { + // check for triple-slash comment + isDoc = charAt(start = offset + 1) === "/"; + + while (charAt(++offset) !== "\n") { + if (offset === length) { + return null; + } + } + ++offset; + if (isDoc) { + setComment(start, offset - 1, isLeadingComment); + // Trailing comment cannot not be multi-line, + // so leading comment state should be reset to handle potential next comments + isLeadingComment = true; + } + ++line; + repeat = true; + } else { + // check for double-slash comments, consolidating consecutive lines + start = offset; + isDoc = false; + if (isDoubleSlashCommentLine(offset - 1)) { + isDoc = true; + do { + offset = findEndOfLine(offset); + if (offset === length) { + break; + } + offset++; + if (!isLeadingComment) { + // Trailing comment cannot not be multi-line + break; + } + } while (isDoubleSlashCommentLine(offset)); + } else { + offset = Math.min(length, findEndOfLine(offset) + 1); + } + if (isDoc) { + setComment(start, offset, isLeadingComment); + isLeadingComment = true; + } + line++; + repeat = true; + } + } else if ((curr = charAt(offset)) === "*") { /* Block */ + // check for /** (regular comment mode) or /* (alternate comment mode) + start = offset + 1; + isDoc = alternateCommentMode || charAt(start) === "*"; + do { + if (curr === "\n") { + ++line; + } + if (++offset === length) { + throw illegal("comment"); + } + prev = curr; + curr = charAt(offset); + } while (prev !== "*" || curr !== "/"); + ++offset; + if (isDoc) { + setComment(start, offset - 2, isLeadingComment); + isLeadingComment = true; + } + repeat = true; + } else { + return "/"; + } + } + } while (repeat); + + // offset !== length if we got here + + var end = offset; + delimRe.lastIndex = 0; + var delim = delimRe.test(charAt(end++)); + if (!delim) + while (end < length && !delimRe.test(charAt(end))) + ++end; + var token = source.substring(offset, offset = end); + if (token === "\"" || token === "'") + stringDelim = token; + return token; + } + + /** + * Pushes a token back to the stack. + * @param {string} token Token + * @returns {undefined} + * @inner + */ + function push(token) { + stack.push(token); + } + + /** + * Peeks for the next token. + * @returns {string|null} Token or `null` on eof + * @inner + */ + function peek() { + if (!stack.length) { + var token = next(); + if (token === null) + return null; + push(token); + } + return stack[0]; + } + + /** + * Skips a token. + * @param {string} expected Expected token + * @param {boolean} [optional=false] Whether the token is optional + * @returns {boolean} `true` when skipped, `false` if not + * @throws {Error} When a required token is not present + * @inner + */ + function skip(expected, optional) { + var actual = peek(), + equals = actual === expected; + if (equals) { + next(); + return true; + } + if (!optional) + throw illegal("token '" + actual + "', '" + expected + "' expected"); + return false; + } + + /** + * Gets a comment. + * @param {number} [trailingLine] Line number if looking for a trailing comment + * @returns {string|null} Comment text + * @inner + */ + function cmnt(trailingLine) { + var ret = null; + var comment; + if (trailingLine === undefined) { + comment = comments[line - 1]; + delete comments[line - 1]; + if (comment && (alternateCommentMode || comment.type === "*" || comment.lineEmpty)) { + ret = comment.leading ? comment.text : null; + } + } else { + /* istanbul ignore else */ + if (lastCommentLine < trailingLine) { + peek(); + } + comment = comments[trailingLine]; + delete comments[trailingLine]; + if (comment && !comment.lineEmpty && (alternateCommentMode || comment.type === "/")) { + ret = comment.leading ? null : comment.text; + } + } + return ret; + } + + return Object.defineProperty({ + next: next, + peek: peek, + push: push, + skip: skip, + cmnt: cmnt + }, "line", { + get: function() { return line; } + }); + /* eslint-enable callback-return */ +} diff --git a/node_modules/protobufjs/src/type.js b/node_modules/protobufjs/src/type.js new file mode 100644 index 0000000..2e7bda4 --- /dev/null +++ b/node_modules/protobufjs/src/type.js @@ -0,0 +1,589 @@ +"use strict"; +module.exports = Type; + +// extends Namespace +var Namespace = require("./namespace"); +((Type.prototype = Object.create(Namespace.prototype)).constructor = Type).className = "Type"; + +var Enum = require("./enum"), + OneOf = require("./oneof"), + Field = require("./field"), + MapField = require("./mapfield"), + Service = require("./service"), + Message = require("./message"), + Reader = require("./reader"), + Writer = require("./writer"), + util = require("./util"), + encoder = require("./encoder"), + decoder = require("./decoder"), + verifier = require("./verifier"), + converter = require("./converter"), + wrappers = require("./wrappers"); + +/** + * Constructs a new reflected message type instance. + * @classdesc Reflected message type. + * @extends NamespaceBase + * @constructor + * @param {string} name Message name + * @param {Object.} [options] Declared options + */ +function Type(name, options) { + Namespace.call(this, name, options); + + /** + * Message fields. + * @type {Object.} + */ + this.fields = {}; // toJSON, marker + + /** + * Oneofs declared within this namespace, if any. + * @type {Object.} + */ + this.oneofs = undefined; // toJSON + + /** + * Extension ranges, if any. + * @type {number[][]} + */ + this.extensions = undefined; // toJSON + + /** + * Reserved ranges, if any. + * @type {Array.} + */ + this.reserved = undefined; // toJSON + + /*? + * Whether this type is a legacy group. + * @type {boolean|undefined} + */ + this.group = undefined; // toJSON + + /** + * Cached fields by id. + * @type {Object.|null} + * @private + */ + this._fieldsById = null; + + /** + * Cached fields as an array. + * @type {Field[]|null} + * @private + */ + this._fieldsArray = null; + + /** + * Cached oneofs as an array. + * @type {OneOf[]|null} + * @private + */ + this._oneofsArray = null; + + /** + * Cached constructor. + * @type {Constructor<{}>} + * @private + */ + this._ctor = null; +} + +Object.defineProperties(Type.prototype, { + + /** + * Message fields by id. + * @name Type#fieldsById + * @type {Object.} + * @readonly + */ + fieldsById: { + get: function() { + + /* istanbul ignore if */ + if (this._fieldsById) + return this._fieldsById; + + this._fieldsById = {}; + for (var names = Object.keys(this.fields), i = 0; i < names.length; ++i) { + var field = this.fields[names[i]], + id = field.id; + + /* istanbul ignore if */ + if (this._fieldsById[id]) + throw Error("duplicate id " + id + " in " + this); + + this._fieldsById[id] = field; + } + return this._fieldsById; + } + }, + + /** + * Fields of this message as an array for iteration. + * @name Type#fieldsArray + * @type {Field[]} + * @readonly + */ + fieldsArray: { + get: function() { + return this._fieldsArray || (this._fieldsArray = util.toArray(this.fields)); + } + }, + + /** + * Oneofs of this message as an array for iteration. + * @name Type#oneofsArray + * @type {OneOf[]} + * @readonly + */ + oneofsArray: { + get: function() { + return this._oneofsArray || (this._oneofsArray = util.toArray(this.oneofs)); + } + }, + + /** + * The registered constructor, if any registered, otherwise a generic constructor. + * Assigning a function replaces the internal constructor. If the function does not extend {@link Message} yet, its prototype will be setup accordingly and static methods will be populated. If it already extends {@link Message}, it will just replace the internal constructor. + * @name Type#ctor + * @type {Constructor<{}>} + */ + ctor: { + get: function() { + return this._ctor || (this.ctor = Type.generateConstructor(this)()); + }, + set: function(ctor) { + + // Ensure proper prototype + var prototype = ctor.prototype; + if (!(prototype instanceof Message)) { + (ctor.prototype = new Message()).constructor = ctor; + util.merge(ctor.prototype, prototype); + } + + // Classes and messages reference their reflected type + ctor.$type = ctor.prototype.$type = this; + + // Mix in static methods + util.merge(ctor, Message, true); + + this._ctor = ctor; + + // Messages have non-enumerable default values on their prototype + var i = 0; + for (; i < /* initializes */ this.fieldsArray.length; ++i) + this._fieldsArray[i].resolve(); // ensures a proper value + + // Messages have non-enumerable getters and setters for each virtual oneof field + var ctorProperties = {}; + for (i = 0; i < /* initializes */ this.oneofsArray.length; ++i) + ctorProperties[this._oneofsArray[i].resolve().name] = { + get: util.oneOfGetter(this._oneofsArray[i].oneof), + set: util.oneOfSetter(this._oneofsArray[i].oneof) + }; + if (i) + Object.defineProperties(ctor.prototype, ctorProperties); + } + } +}); + +/** + * Generates a constructor function for the specified type. + * @param {Type} mtype Message type + * @returns {Codegen} Codegen instance + */ +Type.generateConstructor = function generateConstructor(mtype) { + /* eslint-disable no-unexpected-multiline */ + var gen = util.codegen(["p"], mtype.name); + // explicitly initialize mutable object/array fields so that these aren't just inherited from the prototype + for (var i = 0, field; i < mtype.fieldsArray.length; ++i) + if ((field = mtype._fieldsArray[i]).map) gen + ("this%s={}", util.safeProp(field.name)); + else if (field.repeated) gen + ("this%s=[]", util.safeProp(field.name)); + return gen + ("if(p)for(var ks=Object.keys(p),i=0;i} [oneofs] Oneof descriptors + * @property {Object.} fields Field descriptors + * @property {number[][]} [extensions] Extension ranges + * @property {number[][]} [reserved] Reserved ranges + * @property {boolean} [group=false] Whether a legacy group or not + */ + +/** + * Creates a message type from a message type descriptor. + * @param {string} name Message name + * @param {IType} json Message type descriptor + * @returns {Type} Created message type + */ +Type.fromJSON = function fromJSON(name, json) { + var type = new Type(name, json.options); + type.extensions = json.extensions; + type.reserved = json.reserved; + var names = Object.keys(json.fields), + i = 0; + for (; i < names.length; ++i) + type.add( + ( typeof json.fields[names[i]].keyType !== "undefined" + ? MapField.fromJSON + : Field.fromJSON )(names[i], json.fields[names[i]]) + ); + if (json.oneofs) + for (names = Object.keys(json.oneofs), i = 0; i < names.length; ++i) + type.add(OneOf.fromJSON(names[i], json.oneofs[names[i]])); + if (json.nested) + for (names = Object.keys(json.nested), i = 0; i < names.length; ++i) { + var nested = json.nested[names[i]]; + type.add( // most to least likely + ( nested.id !== undefined + ? Field.fromJSON + : nested.fields !== undefined + ? Type.fromJSON + : nested.values !== undefined + ? Enum.fromJSON + : nested.methods !== undefined + ? Service.fromJSON + : Namespace.fromJSON )(names[i], nested) + ); + } + if (json.extensions && json.extensions.length) + type.extensions = json.extensions; + if (json.reserved && json.reserved.length) + type.reserved = json.reserved; + if (json.group) + type.group = true; + if (json.comment) + type.comment = json.comment; + return type; +}; + +/** + * Converts this message type to a message type descriptor. + * @param {IToJSONOptions} [toJSONOptions] JSON conversion options + * @returns {IType} Message type descriptor + */ +Type.prototype.toJSON = function toJSON(toJSONOptions) { + var inherited = Namespace.prototype.toJSON.call(this, toJSONOptions); + var keepComments = toJSONOptions ? Boolean(toJSONOptions.keepComments) : false; + return util.toObject([ + "options" , inherited && inherited.options || undefined, + "oneofs" , Namespace.arrayToJSON(this.oneofsArray, toJSONOptions), + "fields" , Namespace.arrayToJSON(this.fieldsArray.filter(function(obj) { return !obj.declaringField; }), toJSONOptions) || {}, + "extensions" , this.extensions && this.extensions.length ? this.extensions : undefined, + "reserved" , this.reserved && this.reserved.length ? this.reserved : undefined, + "group" , this.group || undefined, + "nested" , inherited && inherited.nested || undefined, + "comment" , keepComments ? this.comment : undefined + ]); +}; + +/** + * @override + */ +Type.prototype.resolveAll = function resolveAll() { + var fields = this.fieldsArray, i = 0; + while (i < fields.length) + fields[i++].resolve(); + var oneofs = this.oneofsArray; i = 0; + while (i < oneofs.length) + oneofs[i++].resolve(); + return Namespace.prototype.resolveAll.call(this); +}; + +/** + * @override + */ +Type.prototype.get = function get(name) { + return this.fields[name] + || this.oneofs && this.oneofs[name] + || this.nested && this.nested[name] + || null; +}; + +/** + * Adds a nested object to this type. + * @param {ReflectionObject} object Nested object to add + * @returns {Type} `this` + * @throws {TypeError} If arguments are invalid + * @throws {Error} If there is already a nested object with this name or, if a field, when there is already a field with this id + */ +Type.prototype.add = function add(object) { + + if (this.get(object.name)) + throw Error("duplicate name '" + object.name + "' in " + this); + + if (object instanceof Field && object.extend === undefined) { + // NOTE: Extension fields aren't actual fields on the declaring type, but nested objects. + // The root object takes care of adding distinct sister-fields to the respective extended + // type instead. + + // avoids calling the getter if not absolutely necessary because it's called quite frequently + if (this._fieldsById ? /* istanbul ignore next */ this._fieldsById[object.id] : this.fieldsById[object.id]) + throw Error("duplicate id " + object.id + " in " + this); + if (this.isReservedId(object.id)) + throw Error("id " + object.id + " is reserved in " + this); + if (this.isReservedName(object.name)) + throw Error("name '" + object.name + "' is reserved in " + this); + + if (object.parent) + object.parent.remove(object); + this.fields[object.name] = object; + object.message = this; + object.onAdd(this); + return clearCache(this); + } + if (object instanceof OneOf) { + if (!this.oneofs) + this.oneofs = {}; + this.oneofs[object.name] = object; + object.onAdd(this); + return clearCache(this); + } + return Namespace.prototype.add.call(this, object); +}; + +/** + * Removes a nested object from this type. + * @param {ReflectionObject} object Nested object to remove + * @returns {Type} `this` + * @throws {TypeError} If arguments are invalid + * @throws {Error} If `object` is not a member of this type + */ +Type.prototype.remove = function remove(object) { + if (object instanceof Field && object.extend === undefined) { + // See Type#add for the reason why extension fields are excluded here. + + /* istanbul ignore if */ + if (!this.fields || this.fields[object.name] !== object) + throw Error(object + " is not a member of " + this); + + delete this.fields[object.name]; + object.parent = null; + object.onRemove(this); + return clearCache(this); + } + if (object instanceof OneOf) { + + /* istanbul ignore if */ + if (!this.oneofs || this.oneofs[object.name] !== object) + throw Error(object + " is not a member of " + this); + + delete this.oneofs[object.name]; + object.parent = null; + object.onRemove(this); + return clearCache(this); + } + return Namespace.prototype.remove.call(this, object); +}; + +/** + * Tests if the specified id is reserved. + * @param {number} id Id to test + * @returns {boolean} `true` if reserved, otherwise `false` + */ +Type.prototype.isReservedId = function isReservedId(id) { + return Namespace.isReservedId(this.reserved, id); +}; + +/** + * Tests if the specified name is reserved. + * @param {string} name Name to test + * @returns {boolean} `true` if reserved, otherwise `false` + */ +Type.prototype.isReservedName = function isReservedName(name) { + return Namespace.isReservedName(this.reserved, name); +}; + +/** + * Creates a new message of this type using the specified properties. + * @param {Object.} [properties] Properties to set + * @returns {Message<{}>} Message instance + */ +Type.prototype.create = function create(properties) { + return new this.ctor(properties); +}; + +/** + * Sets up {@link Type#encode|encode}, {@link Type#decode|decode} and {@link Type#verify|verify}. + * @returns {Type} `this` + */ +Type.prototype.setup = function setup() { + // Sets up everything at once so that the prototype chain does not have to be re-evaluated + // multiple times (V8, soft-deopt prototype-check). + + var fullName = this.fullName, + types = []; + for (var i = 0; i < /* initializes */ this.fieldsArray.length; ++i) + types.push(this._fieldsArray[i].resolve().resolvedType); + + // Replace setup methods with type-specific generated functions + this.encode = encoder(this)({ + Writer : Writer, + types : types, + util : util + }); + this.decode = decoder(this)({ + Reader : Reader, + types : types, + util : util + }); + this.verify = verifier(this)({ + types : types, + util : util + }); + this.fromObject = converter.fromObject(this)({ + types : types, + util : util + }); + this.toObject = converter.toObject(this)({ + types : types, + util : util + }); + + // Inject custom wrappers for common types + var wrapper = wrappers[fullName]; + if (wrapper) { + var originalThis = Object.create(this); + // if (wrapper.fromObject) { + originalThis.fromObject = this.fromObject; + this.fromObject = wrapper.fromObject.bind(originalThis); + // } + // if (wrapper.toObject) { + originalThis.toObject = this.toObject; + this.toObject = wrapper.toObject.bind(originalThis); + // } + } + + return this; +}; + +/** + * Encodes a message of this type. Does not implicitly {@link Type#verify|verify} messages. + * @param {Message<{}>|Object.} message Message instance or plain object + * @param {Writer} [writer] Writer to encode to + * @returns {Writer} writer + */ +Type.prototype.encode = function encode_setup(message, writer) { + return this.setup().encode(message, writer); // overrides this method +}; + +/** + * Encodes a message of this type preceeded by its byte length as a varint. Does not implicitly {@link Type#verify|verify} messages. + * @param {Message<{}>|Object.} message Message instance or plain object + * @param {Writer} [writer] Writer to encode to + * @returns {Writer} writer + */ +Type.prototype.encodeDelimited = function encodeDelimited(message, writer) { + return this.encode(message, writer && writer.len ? writer.fork() : writer).ldelim(); +}; + +/** + * Decodes a message of this type. + * @param {Reader|Uint8Array} reader Reader or buffer to decode from + * @param {number} [length] Length of the message, if known beforehand + * @returns {Message<{}>} Decoded message + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {util.ProtocolError<{}>} If required fields are missing + */ +Type.prototype.decode = function decode_setup(reader, length) { + return this.setup().decode(reader, length); // overrides this method +}; + +/** + * Decodes a message of this type preceeded by its byte length as a varint. + * @param {Reader|Uint8Array} reader Reader or buffer to decode from + * @returns {Message<{}>} Decoded message + * @throws {Error} If the payload is not a reader or valid buffer + * @throws {util.ProtocolError} If required fields are missing + */ +Type.prototype.decodeDelimited = function decodeDelimited(reader) { + if (!(reader instanceof Reader)) + reader = Reader.create(reader); + return this.decode(reader, reader.uint32()); +}; + +/** + * Verifies that field values are valid and that required fields are present. + * @param {Object.} message Plain object to verify + * @returns {null|string} `null` if valid, otherwise the reason why it is not + */ +Type.prototype.verify = function verify_setup(message) { + return this.setup().verify(message); // overrides this method +}; + +/** + * Creates a new message of this type from a plain object. Also converts values to their respective internal types. + * @param {Object.} object Plain object to convert + * @returns {Message<{}>} Message instance + */ +Type.prototype.fromObject = function fromObject(object) { + return this.setup().fromObject(object); +}; + +/** + * Conversion options as used by {@link Type#toObject} and {@link Message.toObject}. + * @interface IConversionOptions + * @property {Function} [longs] Long conversion type. + * Valid values are `String` and `Number` (the global types). + * Defaults to copy the present value, which is a possibly unsafe number without and a {@link Long} with a long library. + * @property {Function} [enums] Enum value conversion type. + * Only valid value is `String` (the global type). + * Defaults to copy the present value, which is the numeric id. + * @property {Function} [bytes] Bytes value conversion type. + * Valid values are `Array` and (a base64 encoded) `String` (the global types). + * Defaults to copy the present value, which usually is a Buffer under node and an Uint8Array in the browser. + * @property {boolean} [defaults=false] Also sets default values on the resulting object + * @property {boolean} [arrays=false] Sets empty arrays for missing repeated fields even if `defaults=false` + * @property {boolean} [objects=false] Sets empty objects for missing map fields even if `defaults=false` + * @property {boolean} [oneofs=false] Includes virtual oneof properties set to the present field's name, if any + * @property {boolean} [json=false] Performs additional JSON compatibility conversions, i.e. NaN and Infinity to strings + */ + +/** + * Creates a plain object from a message of this type. Also converts values to other types if specified. + * @param {Message<{}>} message Message instance + * @param {IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + */ +Type.prototype.toObject = function toObject(message, options) { + return this.setup().toObject(message, options); +}; + +/** + * Decorator function as returned by {@link Type.d} (TypeScript). + * @typedef TypeDecorator + * @type {function} + * @param {Constructor} target Target constructor + * @returns {undefined} + * @template T extends Message + */ + +/** + * Type decorator (TypeScript). + * @param {string} [typeName] Type name, defaults to the constructor's name + * @returns {TypeDecorator} Decorator function + * @template T extends Message + */ +Type.d = function decorateType(typeName) { + return function typeDecorator(target) { + util.decorateType(target, typeName); + }; +}; diff --git a/node_modules/protobufjs/src/types.js b/node_modules/protobufjs/src/types.js new file mode 100644 index 0000000..5fda19a --- /dev/null +++ b/node_modules/protobufjs/src/types.js @@ -0,0 +1,196 @@ +"use strict"; + +/** + * Common type constants. + * @namespace + */ +var types = exports; + +var util = require("./util"); + +var s = [ + "double", // 0 + "float", // 1 + "int32", // 2 + "uint32", // 3 + "sint32", // 4 + "fixed32", // 5 + "sfixed32", // 6 + "int64", // 7 + "uint64", // 8 + "sint64", // 9 + "fixed64", // 10 + "sfixed64", // 11 + "bool", // 12 + "string", // 13 + "bytes" // 14 +]; + +function bake(values, offset) { + var i = 0, o = {}; + offset |= 0; + while (i < values.length) o[s[i + offset]] = values[i++]; + return o; +} + +/** + * Basic type wire types. + * @type {Object.} + * @const + * @property {number} double=1 Fixed64 wire type + * @property {number} float=5 Fixed32 wire type + * @property {number} int32=0 Varint wire type + * @property {number} uint32=0 Varint wire type + * @property {number} sint32=0 Varint wire type + * @property {number} fixed32=5 Fixed32 wire type + * @property {number} sfixed32=5 Fixed32 wire type + * @property {number} int64=0 Varint wire type + * @property {number} uint64=0 Varint wire type + * @property {number} sint64=0 Varint wire type + * @property {number} fixed64=1 Fixed64 wire type + * @property {number} sfixed64=1 Fixed64 wire type + * @property {number} bool=0 Varint wire type + * @property {number} string=2 Ldelim wire type + * @property {number} bytes=2 Ldelim wire type + */ +types.basic = bake([ + /* double */ 1, + /* float */ 5, + /* int32 */ 0, + /* uint32 */ 0, + /* sint32 */ 0, + /* fixed32 */ 5, + /* sfixed32 */ 5, + /* int64 */ 0, + /* uint64 */ 0, + /* sint64 */ 0, + /* fixed64 */ 1, + /* sfixed64 */ 1, + /* bool */ 0, + /* string */ 2, + /* bytes */ 2 +]); + +/** + * Basic type defaults. + * @type {Object.} + * @const + * @property {number} double=0 Double default + * @property {number} float=0 Float default + * @property {number} int32=0 Int32 default + * @property {number} uint32=0 Uint32 default + * @property {number} sint32=0 Sint32 default + * @property {number} fixed32=0 Fixed32 default + * @property {number} sfixed32=0 Sfixed32 default + * @property {number} int64=0 Int64 default + * @property {number} uint64=0 Uint64 default + * @property {number} sint64=0 Sint32 default + * @property {number} fixed64=0 Fixed64 default + * @property {number} sfixed64=0 Sfixed64 default + * @property {boolean} bool=false Bool default + * @property {string} string="" String default + * @property {Array.} bytes=Array(0) Bytes default + * @property {null} message=null Message default + */ +types.defaults = bake([ + /* double */ 0, + /* float */ 0, + /* int32 */ 0, + /* uint32 */ 0, + /* sint32 */ 0, + /* fixed32 */ 0, + /* sfixed32 */ 0, + /* int64 */ 0, + /* uint64 */ 0, + /* sint64 */ 0, + /* fixed64 */ 0, + /* sfixed64 */ 0, + /* bool */ false, + /* string */ "", + /* bytes */ util.emptyArray, + /* message */ null +]); + +/** + * Basic long type wire types. + * @type {Object.} + * @const + * @property {number} int64=0 Varint wire type + * @property {number} uint64=0 Varint wire type + * @property {number} sint64=0 Varint wire type + * @property {number} fixed64=1 Fixed64 wire type + * @property {number} sfixed64=1 Fixed64 wire type + */ +types.long = bake([ + /* int64 */ 0, + /* uint64 */ 0, + /* sint64 */ 0, + /* fixed64 */ 1, + /* sfixed64 */ 1 +], 7); + +/** + * Allowed types for map keys with their associated wire type. + * @type {Object.} + * @const + * @property {number} int32=0 Varint wire type + * @property {number} uint32=0 Varint wire type + * @property {number} sint32=0 Varint wire type + * @property {number} fixed32=5 Fixed32 wire type + * @property {number} sfixed32=5 Fixed32 wire type + * @property {number} int64=0 Varint wire type + * @property {number} uint64=0 Varint wire type + * @property {number} sint64=0 Varint wire type + * @property {number} fixed64=1 Fixed64 wire type + * @property {number} sfixed64=1 Fixed64 wire type + * @property {number} bool=0 Varint wire type + * @property {number} string=2 Ldelim wire type + */ +types.mapKey = bake([ + /* int32 */ 0, + /* uint32 */ 0, + /* sint32 */ 0, + /* fixed32 */ 5, + /* sfixed32 */ 5, + /* int64 */ 0, + /* uint64 */ 0, + /* sint64 */ 0, + /* fixed64 */ 1, + /* sfixed64 */ 1, + /* bool */ 0, + /* string */ 2 +], 2); + +/** + * Allowed types for packed repeated fields with their associated wire type. + * @type {Object.} + * @const + * @property {number} double=1 Fixed64 wire type + * @property {number} float=5 Fixed32 wire type + * @property {number} int32=0 Varint wire type + * @property {number} uint32=0 Varint wire type + * @property {number} sint32=0 Varint wire type + * @property {number} fixed32=5 Fixed32 wire type + * @property {number} sfixed32=5 Fixed32 wire type + * @property {number} int64=0 Varint wire type + * @property {number} uint64=0 Varint wire type + * @property {number} sint64=0 Varint wire type + * @property {number} fixed64=1 Fixed64 wire type + * @property {number} sfixed64=1 Fixed64 wire type + * @property {number} bool=0 Varint wire type + */ +types.packed = bake([ + /* double */ 1, + /* float */ 5, + /* int32 */ 0, + /* uint32 */ 0, + /* sint32 */ 0, + /* fixed32 */ 5, + /* sfixed32 */ 5, + /* int64 */ 0, + /* uint64 */ 0, + /* sint64 */ 0, + /* fixed64 */ 1, + /* sfixed64 */ 1, + /* bool */ 0 +]); diff --git a/node_modules/protobufjs/src/typescript.jsdoc b/node_modules/protobufjs/src/typescript.jsdoc new file mode 100644 index 0000000..9a67101 --- /dev/null +++ b/node_modules/protobufjs/src/typescript.jsdoc @@ -0,0 +1,15 @@ +/** + * Constructor type. + * @interface Constructor + * @extends Function + * @template T + * @tstype new(...params: any[]): T; prototype: T; + */ + +/** + * Properties type. + * @typedef Properties + * @template T + * @type {Object.} + * @tstype { [P in keyof T]?: T[P] } + */ diff --git a/node_modules/protobufjs/src/util.js b/node_modules/protobufjs/src/util.js new file mode 100644 index 0000000..6c50899 --- /dev/null +++ b/node_modules/protobufjs/src/util.js @@ -0,0 +1,212 @@ +"use strict"; + +/** + * Various utility functions. + * @namespace + */ +var util = module.exports = require("./util/minimal"); + +var roots = require("./roots"); + +var Type, // cyclic + Enum; + +util.codegen = require("@protobufjs/codegen"); +util.fetch = require("@protobufjs/fetch"); +util.path = require("@protobufjs/path"); + +/** + * Node's fs module if available. + * @type {Object.} + */ +util.fs = util.inquire("fs"); + +/** + * Converts an object's values to an array. + * @param {Object.} object Object to convert + * @returns {Array.<*>} Converted array + */ +util.toArray = function toArray(object) { + if (object) { + var keys = Object.keys(object), + array = new Array(keys.length), + index = 0; + while (index < keys.length) + array[index] = object[keys[index++]]; + return array; + } + return []; +}; + +/** + * Converts an array of keys immediately followed by their respective value to an object, omitting undefined values. + * @param {Array.<*>} array Array to convert + * @returns {Object.} Converted object + */ +util.toObject = function toObject(array) { + var object = {}, + index = 0; + while (index < array.length) { + var key = array[index++], + val = array[index++]; + if (val !== undefined) + object[key] = val; + } + return object; +}; + +var safePropBackslashRe = /\\/g, + safePropQuoteRe = /"/g; + +/** + * Tests whether the specified name is a reserved word in JS. + * @param {string} name Name to test + * @returns {boolean} `true` if reserved, otherwise `false` + */ +util.isReserved = function isReserved(name) { + return /^(?:do|if|in|for|let|new|try|var|case|else|enum|eval|false|null|this|true|void|with|break|catch|class|const|super|throw|while|yield|delete|export|import|public|return|static|switch|typeof|default|extends|finally|package|private|continue|debugger|function|arguments|interface|protected|implements|instanceof)$/.test(name); +}; + +/** + * Returns a safe property accessor for the specified property name. + * @param {string} prop Property name + * @returns {string} Safe accessor + */ +util.safeProp = function safeProp(prop) { + if (!/^[$\w_]+$/.test(prop) || util.isReserved(prop)) + return "[\"" + prop.replace(safePropBackslashRe, "\\\\").replace(safePropQuoteRe, "\\\"") + "\"]"; + return "." + prop; +}; + +/** + * Converts the first character of a string to upper case. + * @param {string} str String to convert + * @returns {string} Converted string + */ +util.ucFirst = function ucFirst(str) { + return str.charAt(0).toUpperCase() + str.substring(1); +}; + +var camelCaseRe = /_([a-z])/g; + +/** + * Converts a string to camel case. + * @param {string} str String to convert + * @returns {string} Converted string + */ +util.camelCase = function camelCase(str) { + return str.substring(0, 1) + + str.substring(1) + .replace(camelCaseRe, function($0, $1) { return $1.toUpperCase(); }); +}; + +/** + * Compares reflected fields by id. + * @param {Field} a First field + * @param {Field} b Second field + * @returns {number} Comparison value + */ +util.compareFieldsById = function compareFieldsById(a, b) { + return a.id - b.id; +}; + +/** + * Decorator helper for types (TypeScript). + * @param {Constructor} ctor Constructor function + * @param {string} [typeName] Type name, defaults to the constructor's name + * @returns {Type} Reflected type + * @template T extends Message + * @property {Root} root Decorators root + */ +util.decorateType = function decorateType(ctor, typeName) { + + /* istanbul ignore if */ + if (ctor.$type) { + if (typeName && ctor.$type.name !== typeName) { + util.decorateRoot.remove(ctor.$type); + ctor.$type.name = typeName; + util.decorateRoot.add(ctor.$type); + } + return ctor.$type; + } + + /* istanbul ignore next */ + if (!Type) + Type = require("./type"); + + var type = new Type(typeName || ctor.name); + util.decorateRoot.add(type); + type.ctor = ctor; // sets up .encode, .decode etc. + Object.defineProperty(ctor, "$type", { value: type, enumerable: false }); + Object.defineProperty(ctor.prototype, "$type", { value: type, enumerable: false }); + return type; +}; + +var decorateEnumIndex = 0; + +/** + * Decorator helper for enums (TypeScript). + * @param {Object} object Enum object + * @returns {Enum} Reflected enum + */ +util.decorateEnum = function decorateEnum(object) { + + /* istanbul ignore if */ + if (object.$type) + return object.$type; + + /* istanbul ignore next */ + if (!Enum) + Enum = require("./enum"); + + var enm = new Enum("Enum" + decorateEnumIndex++, object); + util.decorateRoot.add(enm); + Object.defineProperty(object, "$type", { value: enm, enumerable: false }); + return enm; +}; + + +/** + * Sets the value of a property by property path. If a value already exists, it is turned to an array + * @param {Object.} dst Destination object + * @param {string} path dot '.' delimited path of the property to set + * @param {Object} value the value to set + * @returns {Object.} Destination object + */ +util.setProperty = function setProperty(dst, path, value) { + function setProp(dst, path, value) { + var part = path.shift(); + if (part === "__proto__" || part === "prototype") { + return dst; + } + if (path.length > 0) { + dst[part] = setProp(dst[part] || {}, path, value); + } else { + var prevValue = dst[part]; + if (prevValue) + value = [].concat(prevValue).concat(value); + dst[part] = value; + } + return dst; + } + + if (typeof dst !== "object") + throw TypeError("dst must be an object"); + if (!path) + throw TypeError("path must be specified"); + + path = path.split("."); + return setProp(dst, path, value); +}; + +/** + * Decorator root (TypeScript). + * @name util.decorateRoot + * @type {Root} + * @readonly + */ +Object.defineProperty(util, "decorateRoot", { + get: function() { + return roots["decorated"] || (roots["decorated"] = new (require("./root"))()); + } +}); diff --git a/node_modules/protobufjs/src/util/longbits.js b/node_modules/protobufjs/src/util/longbits.js new file mode 100644 index 0000000..11bfb1c --- /dev/null +++ b/node_modules/protobufjs/src/util/longbits.js @@ -0,0 +1,200 @@ +"use strict"; +module.exports = LongBits; + +var util = require("../util/minimal"); + +/** + * Constructs new long bits. + * @classdesc Helper class for working with the low and high bits of a 64 bit value. + * @memberof util + * @constructor + * @param {number} lo Low 32 bits, unsigned + * @param {number} hi High 32 bits, unsigned + */ +function LongBits(lo, hi) { + + // note that the casts below are theoretically unnecessary as of today, but older statically + // generated converter code might still call the ctor with signed 32bits. kept for compat. + + /** + * Low bits. + * @type {number} + */ + this.lo = lo >>> 0; + + /** + * High bits. + * @type {number} + */ + this.hi = hi >>> 0; +} + +/** + * Zero bits. + * @memberof util.LongBits + * @type {util.LongBits} + */ +var zero = LongBits.zero = new LongBits(0, 0); + +zero.toNumber = function() { return 0; }; +zero.zzEncode = zero.zzDecode = function() { return this; }; +zero.length = function() { return 1; }; + +/** + * Zero hash. + * @memberof util.LongBits + * @type {string} + */ +var zeroHash = LongBits.zeroHash = "\0\0\0\0\0\0\0\0"; + +/** + * Constructs new long bits from the specified number. + * @param {number} value Value + * @returns {util.LongBits} Instance + */ +LongBits.fromNumber = function fromNumber(value) { + if (value === 0) + return zero; + var sign = value < 0; + if (sign) + value = -value; + var lo = value >>> 0, + hi = (value - lo) / 4294967296 >>> 0; + if (sign) { + hi = ~hi >>> 0; + lo = ~lo >>> 0; + if (++lo > 4294967295) { + lo = 0; + if (++hi > 4294967295) + hi = 0; + } + } + return new LongBits(lo, hi); +}; + +/** + * Constructs new long bits from a number, long or string. + * @param {Long|number|string} value Value + * @returns {util.LongBits} Instance + */ +LongBits.from = function from(value) { + if (typeof value === "number") + return LongBits.fromNumber(value); + if (util.isString(value)) { + /* istanbul ignore else */ + if (util.Long) + value = util.Long.fromString(value); + else + return LongBits.fromNumber(parseInt(value, 10)); + } + return value.low || value.high ? new LongBits(value.low >>> 0, value.high >>> 0) : zero; +}; + +/** + * Converts this long bits to a possibly unsafe JavaScript number. + * @param {boolean} [unsigned=false] Whether unsigned or not + * @returns {number} Possibly unsafe number + */ +LongBits.prototype.toNumber = function toNumber(unsigned) { + if (!unsigned && this.hi >>> 31) { + var lo = ~this.lo + 1 >>> 0, + hi = ~this.hi >>> 0; + if (!lo) + hi = hi + 1 >>> 0; + return -(lo + hi * 4294967296); + } + return this.lo + this.hi * 4294967296; +}; + +/** + * Converts this long bits to a long. + * @param {boolean} [unsigned=false] Whether unsigned or not + * @returns {Long} Long + */ +LongBits.prototype.toLong = function toLong(unsigned) { + return util.Long + ? new util.Long(this.lo | 0, this.hi | 0, Boolean(unsigned)) + /* istanbul ignore next */ + : { low: this.lo | 0, high: this.hi | 0, unsigned: Boolean(unsigned) }; +}; + +var charCodeAt = String.prototype.charCodeAt; + +/** + * Constructs new long bits from the specified 8 characters long hash. + * @param {string} hash Hash + * @returns {util.LongBits} Bits + */ +LongBits.fromHash = function fromHash(hash) { + if (hash === zeroHash) + return zero; + return new LongBits( + ( charCodeAt.call(hash, 0) + | charCodeAt.call(hash, 1) << 8 + | charCodeAt.call(hash, 2) << 16 + | charCodeAt.call(hash, 3) << 24) >>> 0 + , + ( charCodeAt.call(hash, 4) + | charCodeAt.call(hash, 5) << 8 + | charCodeAt.call(hash, 6) << 16 + | charCodeAt.call(hash, 7) << 24) >>> 0 + ); +}; + +/** + * Converts this long bits to a 8 characters long hash. + * @returns {string} Hash + */ +LongBits.prototype.toHash = function toHash() { + return String.fromCharCode( + this.lo & 255, + this.lo >>> 8 & 255, + this.lo >>> 16 & 255, + this.lo >>> 24 , + this.hi & 255, + this.hi >>> 8 & 255, + this.hi >>> 16 & 255, + this.hi >>> 24 + ); +}; + +/** + * Zig-zag encodes this long bits. + * @returns {util.LongBits} `this` + */ +LongBits.prototype.zzEncode = function zzEncode() { + var mask = this.hi >> 31; + this.hi = ((this.hi << 1 | this.lo >>> 31) ^ mask) >>> 0; + this.lo = ( this.lo << 1 ^ mask) >>> 0; + return this; +}; + +/** + * Zig-zag decodes this long bits. + * @returns {util.LongBits} `this` + */ +LongBits.prototype.zzDecode = function zzDecode() { + var mask = -(this.lo & 1); + this.lo = ((this.lo >>> 1 | this.hi << 31) ^ mask) >>> 0; + this.hi = ( this.hi >>> 1 ^ mask) >>> 0; + return this; +}; + +/** + * Calculates the length of this longbits when encoded as a varint. + * @returns {number} Length + */ +LongBits.prototype.length = function length() { + var part0 = this.lo, + part1 = (this.lo >>> 28 | this.hi << 4) >>> 0, + part2 = this.hi >>> 24; + return part2 === 0 + ? part1 === 0 + ? part0 < 16384 + ? part0 < 128 ? 1 : 2 + : part0 < 2097152 ? 3 : 4 + : part1 < 16384 + ? part1 < 128 ? 5 : 6 + : part1 < 2097152 ? 7 : 8 + : part2 < 128 ? 9 : 10; +}; diff --git a/node_modules/protobufjs/src/util/minimal.js b/node_modules/protobufjs/src/util/minimal.js new file mode 100644 index 0000000..62d6833 --- /dev/null +++ b/node_modules/protobufjs/src/util/minimal.js @@ -0,0 +1,438 @@ +"use strict"; +var util = exports; + +// used to return a Promise where callback is omitted +util.asPromise = require("@protobufjs/aspromise"); + +// converts to / from base64 encoded strings +util.base64 = require("@protobufjs/base64"); + +// base class of rpc.Service +util.EventEmitter = require("@protobufjs/eventemitter"); + +// float handling accross browsers +util.float = require("@protobufjs/float"); + +// requires modules optionally and hides the call from bundlers +util.inquire = require("@protobufjs/inquire"); + +// converts to / from utf8 encoded strings +util.utf8 = require("@protobufjs/utf8"); + +// provides a node-like buffer pool in the browser +util.pool = require("@protobufjs/pool"); + +// utility to work with the low and high bits of a 64 bit value +util.LongBits = require("./longbits"); + +/** + * Whether running within node or not. + * @memberof util + * @type {boolean} + */ +util.isNode = Boolean(typeof global !== "undefined" + && global + && global.process + && global.process.versions + && global.process.versions.node); + +/** + * Global object reference. + * @memberof util + * @type {Object} + */ +util.global = util.isNode && global + || typeof window !== "undefined" && window + || typeof self !== "undefined" && self + || this; // eslint-disable-line no-invalid-this + +/** + * An immuable empty array. + * @memberof util + * @type {Array.<*>} + * @const + */ +util.emptyArray = Object.freeze ? Object.freeze([]) : /* istanbul ignore next */ []; // used on prototypes + +/** + * An immutable empty object. + * @type {Object} + * @const + */ +util.emptyObject = Object.freeze ? Object.freeze({}) : /* istanbul ignore next */ {}; // used on prototypes + +/** + * Tests if the specified value is an integer. + * @function + * @param {*} value Value to test + * @returns {boolean} `true` if the value is an integer + */ +util.isInteger = Number.isInteger || /* istanbul ignore next */ function isInteger(value) { + return typeof value === "number" && isFinite(value) && Math.floor(value) === value; +}; + +/** + * Tests if the specified value is a string. + * @param {*} value Value to test + * @returns {boolean} `true` if the value is a string + */ +util.isString = function isString(value) { + return typeof value === "string" || value instanceof String; +}; + +/** + * Tests if the specified value is a non-null object. + * @param {*} value Value to test + * @returns {boolean} `true` if the value is a non-null object + */ +util.isObject = function isObject(value) { + return value && typeof value === "object"; +}; + +/** + * Checks if a property on a message is considered to be present. + * This is an alias of {@link util.isSet}. + * @function + * @param {Object} obj Plain object or message instance + * @param {string} prop Property name + * @returns {boolean} `true` if considered to be present, otherwise `false` + */ +util.isset = + +/** + * Checks if a property on a message is considered to be present. + * @param {Object} obj Plain object or message instance + * @param {string} prop Property name + * @returns {boolean} `true` if considered to be present, otherwise `false` + */ +util.isSet = function isSet(obj, prop) { + var value = obj[prop]; + if (value != null && obj.hasOwnProperty(prop)) // eslint-disable-line eqeqeq, no-prototype-builtins + return typeof value !== "object" || (Array.isArray(value) ? value.length : Object.keys(value).length) > 0; + return false; +}; + +/** + * Any compatible Buffer instance. + * This is a minimal stand-alone definition of a Buffer instance. The actual type is that exported by node's typings. + * @interface Buffer + * @extends Uint8Array + */ + +/** + * Node's Buffer class if available. + * @type {Constructor} + */ +util.Buffer = (function() { + try { + var Buffer = util.inquire("buffer").Buffer; + // refuse to use non-node buffers if not explicitly assigned (perf reasons): + return Buffer.prototype.utf8Write ? Buffer : /* istanbul ignore next */ null; + } catch (e) { + /* istanbul ignore next */ + return null; + } +})(); + +// Internal alias of or polyfull for Buffer.from. +util._Buffer_from = null; + +// Internal alias of or polyfill for Buffer.allocUnsafe. +util._Buffer_allocUnsafe = null; + +/** + * Creates a new buffer of whatever type supported by the environment. + * @param {number|number[]} [sizeOrArray=0] Buffer size or number array + * @returns {Uint8Array|Buffer} Buffer + */ +util.newBuffer = function newBuffer(sizeOrArray) { + /* istanbul ignore next */ + return typeof sizeOrArray === "number" + ? util.Buffer + ? util._Buffer_allocUnsafe(sizeOrArray) + : new util.Array(sizeOrArray) + : util.Buffer + ? util._Buffer_from(sizeOrArray) + : typeof Uint8Array === "undefined" + ? sizeOrArray + : new Uint8Array(sizeOrArray); +}; + +/** + * Array implementation used in the browser. `Uint8Array` if supported, otherwise `Array`. + * @type {Constructor} + */ +util.Array = typeof Uint8Array !== "undefined" ? Uint8Array /* istanbul ignore next */ : Array; + +/** + * Any compatible Long instance. + * This is a minimal stand-alone definition of a Long instance. The actual type is that exported by long.js. + * @interface Long + * @property {number} low Low bits + * @property {number} high High bits + * @property {boolean} unsigned Whether unsigned or not + */ + +/** + * Long.js's Long class if available. + * @type {Constructor} + */ +util.Long = /* istanbul ignore next */ util.global.dcodeIO && /* istanbul ignore next */ util.global.dcodeIO.Long + || /* istanbul ignore next */ util.global.Long + || util.inquire("long"); + +/** + * Regular expression used to verify 2 bit (`bool`) map keys. + * @type {RegExp} + * @const + */ +util.key2Re = /^true|false|0|1$/; + +/** + * Regular expression used to verify 32 bit (`int32` etc.) map keys. + * @type {RegExp} + * @const + */ +util.key32Re = /^-?(?:0|[1-9][0-9]*)$/; + +/** + * Regular expression used to verify 64 bit (`int64` etc.) map keys. + * @type {RegExp} + * @const + */ +util.key64Re = /^(?:[\\x00-\\xff]{8}|-?(?:0|[1-9][0-9]*))$/; + +/** + * Converts a number or long to an 8 characters long hash string. + * @param {Long|number} value Value to convert + * @returns {string} Hash + */ +util.longToHash = function longToHash(value) { + return value + ? util.LongBits.from(value).toHash() + : util.LongBits.zeroHash; +}; + +/** + * Converts an 8 characters long hash string to a long or number. + * @param {string} hash Hash + * @param {boolean} [unsigned=false] Whether unsigned or not + * @returns {Long|number} Original value + */ +util.longFromHash = function longFromHash(hash, unsigned) { + var bits = util.LongBits.fromHash(hash); + if (util.Long) + return util.Long.fromBits(bits.lo, bits.hi, unsigned); + return bits.toNumber(Boolean(unsigned)); +}; + +/** + * Merges the properties of the source object into the destination object. + * @memberof util + * @param {Object.} dst Destination object + * @param {Object.} src Source object + * @param {boolean} [ifNotSet=false] Merges only if the key is not already set + * @returns {Object.} Destination object + */ +function merge(dst, src, ifNotSet) { // used by converters + for (var keys = Object.keys(src), i = 0; i < keys.length; ++i) + if (dst[keys[i]] === undefined || !ifNotSet) + dst[keys[i]] = src[keys[i]]; + return dst; +} + +util.merge = merge; + +/** + * Converts the first character of a string to lower case. + * @param {string} str String to convert + * @returns {string} Converted string + */ +util.lcFirst = function lcFirst(str) { + return str.charAt(0).toLowerCase() + str.substring(1); +}; + +/** + * Creates a custom error constructor. + * @memberof util + * @param {string} name Error name + * @returns {Constructor} Custom error constructor + */ +function newError(name) { + + function CustomError(message, properties) { + + if (!(this instanceof CustomError)) + return new CustomError(message, properties); + + // Error.call(this, message); + // ^ just returns a new error instance because the ctor can be called as a function + + Object.defineProperty(this, "message", { get: function() { return message; } }); + + /* istanbul ignore next */ + if (Error.captureStackTrace) // node + Error.captureStackTrace(this, CustomError); + else + Object.defineProperty(this, "stack", { value: new Error().stack || "" }); + + if (properties) + merge(this, properties); + } + + CustomError.prototype = Object.create(Error.prototype, { + constructor: { + value: CustomError, + writable: true, + enumerable: false, + configurable: true, + }, + name: { + get: function get() { return name; }, + set: undefined, + enumerable: false, + // configurable: false would accurately preserve the behavior of + // the original, but I'm guessing that was not intentional. + // For an actual error subclass, this property would + // be configurable. + configurable: true, + }, + toString: { + value: function value() { return this.name + ": " + this.message; }, + writable: true, + enumerable: false, + configurable: true, + }, + }); + + return CustomError; +} + +util.newError = newError; + +/** + * Constructs a new protocol error. + * @classdesc Error subclass indicating a protocol specifc error. + * @memberof util + * @extends Error + * @template T extends Message + * @constructor + * @param {string} message Error message + * @param {Object.} [properties] Additional properties + * @example + * try { + * MyMessage.decode(someBuffer); // throws if required fields are missing + * } catch (e) { + * if (e instanceof ProtocolError && e.instance) + * console.log("decoded so far: " + JSON.stringify(e.instance)); + * } + */ +util.ProtocolError = newError("ProtocolError"); + +/** + * So far decoded message instance. + * @name util.ProtocolError#instance + * @type {Message} + */ + +/** + * A OneOf getter as returned by {@link util.oneOfGetter}. + * @typedef OneOfGetter + * @type {function} + * @returns {string|undefined} Set field name, if any + */ + +/** + * Builds a getter for a oneof's present field name. + * @param {string[]} fieldNames Field names + * @returns {OneOfGetter} Unbound getter + */ +util.oneOfGetter = function getOneOf(fieldNames) { + var fieldMap = {}; + for (var i = 0; i < fieldNames.length; ++i) + fieldMap[fieldNames[i]] = 1; + + /** + * @returns {string|undefined} Set field name, if any + * @this Object + * @ignore + */ + return function() { // eslint-disable-line consistent-return + for (var keys = Object.keys(this), i = keys.length - 1; i > -1; --i) + if (fieldMap[keys[i]] === 1 && this[keys[i]] !== undefined && this[keys[i]] !== null) + return keys[i]; + }; +}; + +/** + * A OneOf setter as returned by {@link util.oneOfSetter}. + * @typedef OneOfSetter + * @type {function} + * @param {string|undefined} value Field name + * @returns {undefined} + */ + +/** + * Builds a setter for a oneof's present field name. + * @param {string[]} fieldNames Field names + * @returns {OneOfSetter} Unbound setter + */ +util.oneOfSetter = function setOneOf(fieldNames) { + + /** + * @param {string} name Field name + * @returns {undefined} + * @this Object + * @ignore + */ + return function(name) { + for (var i = 0; i < fieldNames.length; ++i) + if (fieldNames[i] !== name) + delete this[fieldNames[i]]; + }; +}; + +/** + * Default conversion options used for {@link Message#toJSON} implementations. + * + * These options are close to proto3's JSON mapping with the exception that internal types like Any are handled just like messages. More precisely: + * + * - Longs become strings + * - Enums become string keys + * - Bytes become base64 encoded strings + * - (Sub-)Messages become plain objects + * - Maps become plain objects with all string keys + * - Repeated fields become arrays + * - NaN and Infinity for float and double fields become strings + * + * @type {IConversionOptions} + * @see https://developers.google.com/protocol-buffers/docs/proto3?hl=en#json + */ +util.toJSONOptions = { + longs: String, + enums: String, + bytes: String, + json: true +}; + +// Sets up buffer utility according to the environment (called in index-minimal) +util._configure = function() { + var Buffer = util.Buffer; + /* istanbul ignore if */ + if (!Buffer) { + util._Buffer_from = util._Buffer_allocUnsafe = null; + return; + } + // because node 4.x buffers are incompatible & immutable + // see: https://github.com/dcodeIO/protobuf.js/pull/665 + util._Buffer_from = Buffer.from !== Uint8Array.from && Buffer.from || + /* istanbul ignore next */ + function Buffer_from(value, encoding) { + return new Buffer(value, encoding); + }; + util._Buffer_allocUnsafe = Buffer.allocUnsafe || + /* istanbul ignore next */ + function Buffer_allocUnsafe(size) { + return new Buffer(size); + }; +}; diff --git a/node_modules/protobufjs/src/verifier.js b/node_modules/protobufjs/src/verifier.js new file mode 100644 index 0000000..d58e27a --- /dev/null +++ b/node_modules/protobufjs/src/verifier.js @@ -0,0 +1,177 @@ +"use strict"; +module.exports = verifier; + +var Enum = require("./enum"), + util = require("./util"); + +function invalid(field, expected) { + return field.name + ": " + expected + (field.repeated && expected !== "array" ? "[]" : field.map && expected !== "object" ? "{k:"+field.keyType+"}" : "") + " expected"; +} + +/** + * Generates a partial value verifier. + * @param {Codegen} gen Codegen instance + * @param {Field} field Reflected field + * @param {number} fieldIndex Field index + * @param {string} ref Variable reference + * @returns {Codegen} Codegen instance + * @ignore + */ +function genVerifyValue(gen, field, fieldIndex, ref) { + /* eslint-disable no-unexpected-multiline */ + if (field.resolvedType) { + if (field.resolvedType instanceof Enum) { gen + ("switch(%s){", ref) + ("default:") + ("return%j", invalid(field, "enum value")); + for (var keys = Object.keys(field.resolvedType.values), j = 0; j < keys.length; ++j) gen + ("case %i:", field.resolvedType.values[keys[j]]); + gen + ("break") + ("}"); + } else { + gen + ("{") + ("var e=types[%i].verify(%s);", fieldIndex, ref) + ("if(e)") + ("return%j+e", field.name + ".") + ("}"); + } + } else { + switch (field.type) { + case "int32": + case "uint32": + case "sint32": + case "fixed32": + case "sfixed32": gen + ("if(!util.isInteger(%s))", ref) + ("return%j", invalid(field, "integer")); + break; + case "int64": + case "uint64": + case "sint64": + case "fixed64": + case "sfixed64": gen + ("if(!util.isInteger(%s)&&!(%s&&util.isInteger(%s.low)&&util.isInteger(%s.high)))", ref, ref, ref, ref) + ("return%j", invalid(field, "integer|Long")); + break; + case "float": + case "double": gen + ("if(typeof %s!==\"number\")", ref) + ("return%j", invalid(field, "number")); + break; + case "bool": gen + ("if(typeof %s!==\"boolean\")", ref) + ("return%j", invalid(field, "boolean")); + break; + case "string": gen + ("if(!util.isString(%s))", ref) + ("return%j", invalid(field, "string")); + break; + case "bytes": gen + ("if(!(%s&&typeof %s.length===\"number\"||util.isString(%s)))", ref, ref, ref) + ("return%j", invalid(field, "buffer")); + break; + } + } + return gen; + /* eslint-enable no-unexpected-multiline */ +} + +/** + * Generates a partial key verifier. + * @param {Codegen} gen Codegen instance + * @param {Field} field Reflected field + * @param {string} ref Variable reference + * @returns {Codegen} Codegen instance + * @ignore + */ +function genVerifyKey(gen, field, ref) { + /* eslint-disable no-unexpected-multiline */ + switch (field.keyType) { + case "int32": + case "uint32": + case "sint32": + case "fixed32": + case "sfixed32": gen + ("if(!util.key32Re.test(%s))", ref) + ("return%j", invalid(field, "integer key")); + break; + case "int64": + case "uint64": + case "sint64": + case "fixed64": + case "sfixed64": gen + ("if(!util.key64Re.test(%s))", ref) // see comment above: x is ok, d is not + ("return%j", invalid(field, "integer|Long key")); + break; + case "bool": gen + ("if(!util.key2Re.test(%s))", ref) + ("return%j", invalid(field, "boolean key")); + break; + } + return gen; + /* eslint-enable no-unexpected-multiline */ +} + +/** + * Generates a verifier specific to the specified message type. + * @param {Type} mtype Message type + * @returns {Codegen} Codegen instance + */ +function verifier(mtype) { + /* eslint-disable no-unexpected-multiline */ + + var gen = util.codegen(["m"], mtype.name + "$verify") + ("if(typeof m!==\"object\"||m===null)") + ("return%j", "object expected"); + var oneofs = mtype.oneofsArray, + seenFirstField = {}; + if (oneofs.length) gen + ("var p={}"); + + for (var i = 0; i < /* initializes */ mtype.fieldsArray.length; ++i) { + var field = mtype._fieldsArray[i].resolve(), + ref = "m" + util.safeProp(field.name); + + if (field.optional) gen + ("if(%s!=null&&m.hasOwnProperty(%j)){", ref, field.name); // !== undefined && !== null + + // map fields + if (field.map) { gen + ("if(!util.isObject(%s))", ref) + ("return%j", invalid(field, "object")) + ("var k=Object.keys(%s)", ref) + ("for(var i=0;i} + * @const + */ +var wrappers = exports; + +var Message = require("./message"); + +/** + * From object converter part of an {@link IWrapper}. + * @typedef WrapperFromObjectConverter + * @type {function} + * @param {Object.} object Plain object + * @returns {Message<{}>} Message instance + * @this Type + */ + +/** + * To object converter part of an {@link IWrapper}. + * @typedef WrapperToObjectConverter + * @type {function} + * @param {Message<{}>} message Message instance + * @param {IConversionOptions} [options] Conversion options + * @returns {Object.} Plain object + * @this Type + */ + +/** + * Common type wrapper part of {@link wrappers}. + * @interface IWrapper + * @property {WrapperFromObjectConverter} [fromObject] From object converter + * @property {WrapperToObjectConverter} [toObject] To object converter + */ + +// Custom wrapper for Any +wrappers[".google.protobuf.Any"] = { + + fromObject: function(object) { + + // unwrap value type if mapped + if (object && object["@type"]) { + // Only use fully qualified type name after the last '/' + var name = object["@type"].substring(object["@type"].lastIndexOf("/") + 1); + var type = this.lookup(name); + /* istanbul ignore else */ + if (type) { + // type_url does not accept leading "." + var type_url = object["@type"].charAt(0) === "." ? + object["@type"].slice(1) : object["@type"]; + // type_url prefix is optional, but path seperator is required + if (type_url.indexOf("/") === -1) { + type_url = "/" + type_url; + } + return this.create({ + type_url: type_url, + value: type.encode(type.fromObject(object)).finish() + }); + } + } + + return this.fromObject(object); + }, + + toObject: function(message, options) { + + // Default prefix + var googleApi = "type.googleapis.com/"; + var prefix = ""; + var name = ""; + + // decode value if requested and unmapped + if (options && options.json && message.type_url && message.value) { + // Only use fully qualified type name after the last '/' + name = message.type_url.substring(message.type_url.lastIndexOf("/") + 1); + // Separate the prefix used + prefix = message.type_url.substring(0, message.type_url.lastIndexOf("/") + 1); + var type = this.lookup(name); + /* istanbul ignore else */ + if (type) + message = type.decode(message.value); + } + + // wrap value if unmapped + if (!(message instanceof this.ctor) && message instanceof Message) { + var object = message.$type.toObject(message, options); + var messageName = message.$type.fullName[0] === "." ? + message.$type.fullName.slice(1) : message.$type.fullName; + // Default to type.googleapis.com prefix if no prefix is used + if (prefix === "") { + prefix = googleApi; + } + name = prefix + messageName; + object["@type"] = name; + return object; + } + + return this.toObject(message, options); + } +}; diff --git a/node_modules/protobufjs/src/writer.js b/node_modules/protobufjs/src/writer.js new file mode 100644 index 0000000..cc84a00 --- /dev/null +++ b/node_modules/protobufjs/src/writer.js @@ -0,0 +1,465 @@ +"use strict"; +module.exports = Writer; + +var util = require("./util/minimal"); + +var BufferWriter; // cyclic + +var LongBits = util.LongBits, + base64 = util.base64, + utf8 = util.utf8; + +/** + * Constructs a new writer operation instance. + * @classdesc Scheduled writer operation. + * @constructor + * @param {function(*, Uint8Array, number)} fn Function to call + * @param {number} len Value byte length + * @param {*} val Value to write + * @ignore + */ +function Op(fn, len, val) { + + /** + * Function to call. + * @type {function(Uint8Array, number, *)} + */ + this.fn = fn; + + /** + * Value byte length. + * @type {number} + */ + this.len = len; + + /** + * Next operation. + * @type {Writer.Op|undefined} + */ + this.next = undefined; + + /** + * Value to write. + * @type {*} + */ + this.val = val; // type varies +} + +/* istanbul ignore next */ +function noop() {} // eslint-disable-line no-empty-function + +/** + * Constructs a new writer state instance. + * @classdesc Copied writer state. + * @memberof Writer + * @constructor + * @param {Writer} writer Writer to copy state from + * @ignore + */ +function State(writer) { + + /** + * Current head. + * @type {Writer.Op} + */ + this.head = writer.head; + + /** + * Current tail. + * @type {Writer.Op} + */ + this.tail = writer.tail; + + /** + * Current buffer length. + * @type {number} + */ + this.len = writer.len; + + /** + * Next state. + * @type {State|null} + */ + this.next = writer.states; +} + +/** + * Constructs a new writer instance. + * @classdesc Wire format writer using `Uint8Array` if available, otherwise `Array`. + * @constructor + */ +function Writer() { + + /** + * Current length. + * @type {number} + */ + this.len = 0; + + /** + * Operations head. + * @type {Object} + */ + this.head = new Op(noop, 0, 0); + + /** + * Operations tail + * @type {Object} + */ + this.tail = this.head; + + /** + * Linked forked states. + * @type {Object|null} + */ + this.states = null; + + // When a value is written, the writer calculates its byte length and puts it into a linked + // list of operations to perform when finish() is called. This both allows us to allocate + // buffers of the exact required size and reduces the amount of work we have to do compared + // to first calculating over objects and then encoding over objects. In our case, the encoding + // part is just a linked list walk calling operations with already prepared values. +} + +var create = function create() { + return util.Buffer + ? function create_buffer_setup() { + return (Writer.create = function create_buffer() { + return new BufferWriter(); + })(); + } + /* istanbul ignore next */ + : function create_array() { + return new Writer(); + }; +}; + +/** + * Creates a new writer. + * @function + * @returns {BufferWriter|Writer} A {@link BufferWriter} when Buffers are supported, otherwise a {@link Writer} + */ +Writer.create = create(); + +/** + * Allocates a buffer of the specified size. + * @param {number} size Buffer size + * @returns {Uint8Array} Buffer + */ +Writer.alloc = function alloc(size) { + return new util.Array(size); +}; + +// Use Uint8Array buffer pool in the browser, just like node does with buffers +/* istanbul ignore else */ +if (util.Array !== Array) + Writer.alloc = util.pool(Writer.alloc, util.Array.prototype.subarray); + +/** + * Pushes a new operation to the queue. + * @param {function(Uint8Array, number, *)} fn Function to call + * @param {number} len Value byte length + * @param {number} val Value to write + * @returns {Writer} `this` + * @private + */ +Writer.prototype._push = function push(fn, len, val) { + this.tail = this.tail.next = new Op(fn, len, val); + this.len += len; + return this; +}; + +function writeByte(val, buf, pos) { + buf[pos] = val & 255; +} + +function writeVarint32(val, buf, pos) { + while (val > 127) { + buf[pos++] = val & 127 | 128; + val >>>= 7; + } + buf[pos] = val; +} + +/** + * Constructs a new varint writer operation instance. + * @classdesc Scheduled varint writer operation. + * @extends Op + * @constructor + * @param {number} len Value byte length + * @param {number} val Value to write + * @ignore + */ +function VarintOp(len, val) { + this.len = len; + this.next = undefined; + this.val = val; +} + +VarintOp.prototype = Object.create(Op.prototype); +VarintOp.prototype.fn = writeVarint32; + +/** + * Writes an unsigned 32 bit value as a varint. + * @param {number} value Value to write + * @returns {Writer} `this` + */ +Writer.prototype.uint32 = function write_uint32(value) { + // here, the call to this.push has been inlined and a varint specific Op subclass is used. + // uint32 is by far the most frequently used operation and benefits significantly from this. + this.len += (this.tail = this.tail.next = new VarintOp( + (value = value >>> 0) + < 128 ? 1 + : value < 16384 ? 2 + : value < 2097152 ? 3 + : value < 268435456 ? 4 + : 5, + value)).len; + return this; +}; + +/** + * Writes a signed 32 bit value as a varint. + * @function + * @param {number} value Value to write + * @returns {Writer} `this` + */ +Writer.prototype.int32 = function write_int32(value) { + return value < 0 + ? this._push(writeVarint64, 10, LongBits.fromNumber(value)) // 10 bytes per spec + : this.uint32(value); +}; + +/** + * Writes a 32 bit value as a varint, zig-zag encoded. + * @param {number} value Value to write + * @returns {Writer} `this` + */ +Writer.prototype.sint32 = function write_sint32(value) { + return this.uint32((value << 1 ^ value >> 31) >>> 0); +}; + +function writeVarint64(val, buf, pos) { + while (val.hi) { + buf[pos++] = val.lo & 127 | 128; + val.lo = (val.lo >>> 7 | val.hi << 25) >>> 0; + val.hi >>>= 7; + } + while (val.lo > 127) { + buf[pos++] = val.lo & 127 | 128; + val.lo = val.lo >>> 7; + } + buf[pos++] = val.lo; +} + +/** + * Writes an unsigned 64 bit value as a varint. + * @param {Long|number|string} value Value to write + * @returns {Writer} `this` + * @throws {TypeError} If `value` is a string and no long library is present. + */ +Writer.prototype.uint64 = function write_uint64(value) { + var bits = LongBits.from(value); + return this._push(writeVarint64, bits.length(), bits); +}; + +/** + * Writes a signed 64 bit value as a varint. + * @function + * @param {Long|number|string} value Value to write + * @returns {Writer} `this` + * @throws {TypeError} If `value` is a string and no long library is present. + */ +Writer.prototype.int64 = Writer.prototype.uint64; + +/** + * Writes a signed 64 bit value as a varint, zig-zag encoded. + * @param {Long|number|string} value Value to write + * @returns {Writer} `this` + * @throws {TypeError} If `value` is a string and no long library is present. + */ +Writer.prototype.sint64 = function write_sint64(value) { + var bits = LongBits.from(value).zzEncode(); + return this._push(writeVarint64, bits.length(), bits); +}; + +/** + * Writes a boolish value as a varint. + * @param {boolean} value Value to write + * @returns {Writer} `this` + */ +Writer.prototype.bool = function write_bool(value) { + return this._push(writeByte, 1, value ? 1 : 0); +}; + +function writeFixed32(val, buf, pos) { + buf[pos ] = val & 255; + buf[pos + 1] = val >>> 8 & 255; + buf[pos + 2] = val >>> 16 & 255; + buf[pos + 3] = val >>> 24; +} + +/** + * Writes an unsigned 32 bit value as fixed 32 bits. + * @param {number} value Value to write + * @returns {Writer} `this` + */ +Writer.prototype.fixed32 = function write_fixed32(value) { + return this._push(writeFixed32, 4, value >>> 0); +}; + +/** + * Writes a signed 32 bit value as fixed 32 bits. + * @function + * @param {number} value Value to write + * @returns {Writer} `this` + */ +Writer.prototype.sfixed32 = Writer.prototype.fixed32; + +/** + * Writes an unsigned 64 bit value as fixed 64 bits. + * @param {Long|number|string} value Value to write + * @returns {Writer} `this` + * @throws {TypeError} If `value` is a string and no long library is present. + */ +Writer.prototype.fixed64 = function write_fixed64(value) { + var bits = LongBits.from(value); + return this._push(writeFixed32, 4, bits.lo)._push(writeFixed32, 4, bits.hi); +}; + +/** + * Writes a signed 64 bit value as fixed 64 bits. + * @function + * @param {Long|number|string} value Value to write + * @returns {Writer} `this` + * @throws {TypeError} If `value` is a string and no long library is present. + */ +Writer.prototype.sfixed64 = Writer.prototype.fixed64; + +/** + * Writes a float (32 bit). + * @function + * @param {number} value Value to write + * @returns {Writer} `this` + */ +Writer.prototype.float = function write_float(value) { + return this._push(util.float.writeFloatLE, 4, value); +}; + +/** + * Writes a double (64 bit float). + * @function + * @param {number} value Value to write + * @returns {Writer} `this` + */ +Writer.prototype.double = function write_double(value) { + return this._push(util.float.writeDoubleLE, 8, value); +}; + +var writeBytes = util.Array.prototype.set + ? function writeBytes_set(val, buf, pos) { + buf.set(val, pos); // also works for plain array values + } + /* istanbul ignore next */ + : function writeBytes_for(val, buf, pos) { + for (var i = 0; i < val.length; ++i) + buf[pos + i] = val[i]; + }; + +/** + * Writes a sequence of bytes. + * @param {Uint8Array|string} value Buffer or base64 encoded string to write + * @returns {Writer} `this` + */ +Writer.prototype.bytes = function write_bytes(value) { + var len = value.length >>> 0; + if (!len) + return this._push(writeByte, 1, 0); + if (util.isString(value)) { + var buf = Writer.alloc(len = base64.length(value)); + base64.decode(value, buf, 0); + value = buf; + } + return this.uint32(len)._push(writeBytes, len, value); +}; + +/** + * Writes a string. + * @param {string} value Value to write + * @returns {Writer} `this` + */ +Writer.prototype.string = function write_string(value) { + var len = utf8.length(value); + return len + ? this.uint32(len)._push(utf8.write, len, value) + : this._push(writeByte, 1, 0); +}; + +/** + * Forks this writer's state by pushing it to a stack. + * Calling {@link Writer#reset|reset} or {@link Writer#ldelim|ldelim} resets the writer to the previous state. + * @returns {Writer} `this` + */ +Writer.prototype.fork = function fork() { + this.states = new State(this); + this.head = this.tail = new Op(noop, 0, 0); + this.len = 0; + return this; +}; + +/** + * Resets this instance to the last state. + * @returns {Writer} `this` + */ +Writer.prototype.reset = function reset() { + if (this.states) { + this.head = this.states.head; + this.tail = this.states.tail; + this.len = this.states.len; + this.states = this.states.next; + } else { + this.head = this.tail = new Op(noop, 0, 0); + this.len = 0; + } + return this; +}; + +/** + * Resets to the last state and appends the fork state's current write length as a varint followed by its operations. + * @returns {Writer} `this` + */ +Writer.prototype.ldelim = function ldelim() { + var head = this.head, + tail = this.tail, + len = this.len; + this.reset().uint32(len); + if (len) { + this.tail.next = head.next; // skip noop + this.tail = tail; + this.len += len; + } + return this; +}; + +/** + * Finishes the write operation. + * @returns {Uint8Array} Finished buffer + */ +Writer.prototype.finish = function finish() { + var head = this.head.next, // skip noop + buf = this.constructor.alloc(this.len), + pos = 0; + while (head) { + head.fn(head.val, buf, pos); + pos += head.len; + head = head.next; + } + // this.head = this.tail = null; + return buf; +}; + +Writer._configure = function(BufferWriter_) { + BufferWriter = BufferWriter_; + Writer.create = create(); + BufferWriter._configure(); +}; diff --git a/node_modules/protobufjs/src/writer_buffer.js b/node_modules/protobufjs/src/writer_buffer.js new file mode 100644 index 0000000..09a4a91 --- /dev/null +++ b/node_modules/protobufjs/src/writer_buffer.js @@ -0,0 +1,85 @@ +"use strict"; +module.exports = BufferWriter; + +// extends Writer +var Writer = require("./writer"); +(BufferWriter.prototype = Object.create(Writer.prototype)).constructor = BufferWriter; + +var util = require("./util/minimal"); + +/** + * Constructs a new buffer writer instance. + * @classdesc Wire format writer using node buffers. + * @extends Writer + * @constructor + */ +function BufferWriter() { + Writer.call(this); +} + +BufferWriter._configure = function () { + /** + * Allocates a buffer of the specified size. + * @function + * @param {number} size Buffer size + * @returns {Buffer} Buffer + */ + BufferWriter.alloc = util._Buffer_allocUnsafe; + + BufferWriter.writeBytesBuffer = util.Buffer && util.Buffer.prototype instanceof Uint8Array && util.Buffer.prototype.set.name === "set" + ? function writeBytesBuffer_set(val, buf, pos) { + buf.set(val, pos); // faster than copy (requires node >= 4 where Buffers extend Uint8Array and set is properly inherited) + // also works for plain array values + } + /* istanbul ignore next */ + : function writeBytesBuffer_copy(val, buf, pos) { + if (val.copy) // Buffer values + val.copy(buf, pos, 0, val.length); + else for (var i = 0; i < val.length;) // plain array values + buf[pos++] = val[i++]; + }; +}; + + +/** + * @override + */ +BufferWriter.prototype.bytes = function write_bytes_buffer(value) { + if (util.isString(value)) + value = util._Buffer_from(value, "base64"); + var len = value.length >>> 0; + this.uint32(len); + if (len) + this._push(BufferWriter.writeBytesBuffer, len, value); + return this; +}; + +function writeStringBuffer(val, buf, pos) { + if (val.length < 40) // plain js is faster for short strings (probably due to redundant assertions) + util.utf8.write(val, buf, pos); + else if (buf.utf8Write) + buf.utf8Write(val, pos); + else + buf.write(val, pos); +} + +/** + * @override + */ +BufferWriter.prototype.string = function write_string_buffer(value) { + var len = util.Buffer.byteLength(value); + this.uint32(len); + if (len) + this._push(writeStringBuffer, len, value); + return this; +}; + + +/** + * Finishes the write operation. + * @name BufferWriter#finish + * @function + * @returns {Buffer} Finished buffer + */ + +BufferWriter._configure(); diff --git a/node_modules/protobufjs/tsconfig.json b/node_modules/protobufjs/tsconfig.json new file mode 100644 index 0000000..a0b3639 --- /dev/null +++ b/node_modules/protobufjs/tsconfig.json @@ -0,0 +1,8 @@ +{ + "compilerOptions": { + "target": "ES5", + "experimentalDecorators": true, + "emitDecoratorMetadata": true, + "esModuleInterop": true, + } +} \ No newline at end of file diff --git a/node_modules/require-directory/.jshintrc b/node_modules/require-directory/.jshintrc new file mode 100644 index 0000000..e14e4dc --- /dev/null +++ b/node_modules/require-directory/.jshintrc @@ -0,0 +1,67 @@ +{ + "maxerr" : 50, + "bitwise" : true, + "camelcase" : true, + "curly" : true, + "eqeqeq" : true, + "forin" : true, + "immed" : true, + "indent" : 2, + "latedef" : true, + "newcap" : true, + "noarg" : true, + "noempty" : true, + "nonew" : true, + "plusplus" : true, + "quotmark" : true, + "undef" : true, + "unused" : true, + "strict" : true, + "trailing" : true, + "maxparams" : false, + "maxdepth" : false, + "maxstatements" : false, + "maxcomplexity" : false, + "maxlen" : false, + "asi" : false, + "boss" : false, + "debug" : false, + "eqnull" : true, + "es5" : false, + "esnext" : false, + "moz" : false, + "evil" : false, + "expr" : true, + "funcscope" : true, + "globalstrict" : true, + "iterator" : true, + "lastsemic" : false, + "laxbreak" : false, + "laxcomma" : false, + "loopfunc" : false, + "multistr" : false, + "proto" : false, + "scripturl" : false, + "smarttabs" : false, + "shadow" : false, + "sub" : false, + "supernew" : false, + "validthis" : false, + "browser" : true, + "couch" : false, + "devel" : true, + "dojo" : false, + "jquery" : false, + "mootools" : false, + "node" : true, + "nonstandard" : false, + "prototypejs" : false, + "rhino" : false, + "worker" : false, + "wsh" : false, + "yui" : false, + "nomen" : true, + "onevar" : true, + "passfail" : false, + "white" : true +} diff --git a/node_modules/require-directory/.npmignore b/node_modules/require-directory/.npmignore new file mode 100644 index 0000000..47cf365 --- /dev/null +++ b/node_modules/require-directory/.npmignore @@ -0,0 +1 @@ +test/** diff --git a/node_modules/require-directory/.travis.yml b/node_modules/require-directory/.travis.yml new file mode 100644 index 0000000..20fd86b --- /dev/null +++ b/node_modules/require-directory/.travis.yml @@ -0,0 +1,3 @@ +language: node_js +node_js: + - 0.10 diff --git a/node_modules/require-directory/LICENSE b/node_modules/require-directory/LICENSE new file mode 100644 index 0000000..a70f253 --- /dev/null +++ b/node_modules/require-directory/LICENSE @@ -0,0 +1,22 @@ +The MIT License (MIT) + +Copyright (c) 2011 Troy Goode + +Permission is hereby granted, free of charge, to any person obtaining a +copy of this software and associated documentation files (the +"Software"), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be included +in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS +OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/require-directory/README.markdown b/node_modules/require-directory/README.markdown new file mode 100644 index 0000000..926a063 --- /dev/null +++ b/node_modules/require-directory/README.markdown @@ -0,0 +1,184 @@ +# require-directory + +Recursively iterates over specified directory, `require()`'ing each file, and returning a nested hash structure containing those modules. + +**[Follow me (@troygoode) on Twitter!](https://twitter.com/intent/user?screen_name=troygoode)** + +[![NPM](https://nodei.co/npm/require-directory.png?downloads=true&stars=true)](https://nodei.co/npm/require-directory/) + +[![build status](https://secure.travis-ci.org/troygoode/node-require-directory.png)](http://travis-ci.org/troygoode/node-require-directory) + +## How To Use + +### Installation (via [npm](https://npmjs.org/package/require-directory)) + +```bash +$ npm install require-directory +``` + +### Usage + +A common pattern in node.js is to include an index file which creates a hash of the files in its current directory. Given a directory structure like so: + +* app.js +* routes/ + * index.js + * home.js + * auth/ + * login.js + * logout.js + * register.js + +`routes/index.js` uses `require-directory` to build the hash (rather than doing so manually) like so: + +```javascript +var requireDirectory = require('require-directory'); +module.exports = requireDirectory(module); +``` + +`app.js` references `routes/index.js` like any other module, but it now has a hash/tree of the exports from the `./routes/` directory: + +```javascript +var routes = require('./routes'); + +// snip + +app.get('/', routes.home); +app.get('/register', routes.auth.register); +app.get('/login', routes.auth.login); +app.get('/logout', routes.auth.logout); +``` + +The `routes` variable above is the equivalent of this: + +```javascript +var routes = { + home: require('routes/home.js'), + auth: { + login: require('routes/auth/login.js'), + logout: require('routes/auth/logout.js'), + register: require('routes/auth/register.js') + } +}; +``` + +*Note that `routes.index` will be `undefined` as you would hope.* + +### Specifying Another Directory + +You can specify which directory you want to build a tree of (if it isn't the current directory for whatever reason) by passing it as the second parameter. Not specifying the path (`requireDirectory(module)`) is the equivelant of `requireDirectory(module, __dirname)`: + +```javascript +var requireDirectory = require('require-directory'); +module.exports = requireDirectory(module, './some/subdirectory'); +``` + +For example, in the [example in the Usage section](#usage) we could have avoided creating `routes/index.js` and instead changed the first lines of `app.js` to: + +```javascript +var requireDirectory = require('require-directory'); +var routes = requireDirectory(module, './routes'); +``` + +## Options + +You can pass an options hash to `require-directory` as the 2nd parameter (or 3rd if you're passing the path to another directory as the 2nd parameter already). Here are the available options: + +### Whitelisting + +Whitelisting (either via RegExp or function) allows you to specify that only certain files be loaded. + +```javascript +var requireDirectory = require('require-directory'), + whitelist = /onlyinclude.js$/, + hash = requireDirectory(module, {include: whitelist}); +``` + +```javascript +var requireDirectory = require('require-directory'), + check = function(path){ + if(/onlyinclude.js$/.test(path)){ + return true; // don't include + }else{ + return false; // go ahead and include + } + }, + hash = requireDirectory(module, {include: check}); +``` + +### Blacklisting + +Blacklisting (either via RegExp or function) allows you to specify that all but certain files should be loaded. + +```javascript +var requireDirectory = require('require-directory'), + blacklist = /dontinclude\.js$/, + hash = requireDirectory(module, {exclude: blacklist}); +``` + +```javascript +var requireDirectory = require('require-directory'), + check = function(path){ + if(/dontinclude\.js$/.test(path)){ + return false; // don't include + }else{ + return true; // go ahead and include + } + }, + hash = requireDirectory(module, {exclude: check}); +``` + +### Visiting Objects As They're Loaded + +`require-directory` takes a function as the `visit` option that will be called for each module that is added to module.exports. + +```javascript +var requireDirectory = require('require-directory'), + visitor = function(obj) { + console.log(obj); // will be called for every module that is loaded + }, + hash = requireDirectory(module, {visit: visitor}); +``` + +The visitor can also transform the objects by returning a value: + +```javascript +var requireDirectory = require('require-directory'), + visitor = function(obj) { + return obj(new Date()); + }, + hash = requireDirectory(module, {visit: visitor}); +``` + +### Renaming Keys + +```javascript +var requireDirectory = require('require-directory'), + renamer = function(name) { + return name.toUpperCase(); + }, + hash = requireDirectory(module, {rename: renamer}); +``` + +### No Recursion + +```javascript +var requireDirectory = require('require-directory'), + hash = requireDirectory(module, {recurse: false}); +``` + +## Run Unit Tests + +```bash +$ npm run lint +$ npm test +``` + +## License + +[MIT License](http://www.opensource.org/licenses/mit-license.php) + +## Author + +[Troy Goode](https://github.com/TroyGoode) ([troygoode@gmail.com](mailto:troygoode@gmail.com)) + diff --git a/node_modules/require-directory/index.js b/node_modules/require-directory/index.js new file mode 100644 index 0000000..cd37da7 --- /dev/null +++ b/node_modules/require-directory/index.js @@ -0,0 +1,86 @@ +'use strict'; + +var fs = require('fs'), + join = require('path').join, + resolve = require('path').resolve, + dirname = require('path').dirname, + defaultOptions = { + extensions: ['js', 'json', 'coffee'], + recurse: true, + rename: function (name) { + return name; + }, + visit: function (obj) { + return obj; + } + }; + +function checkFileInclusion(path, filename, options) { + return ( + // verify file has valid extension + (new RegExp('\\.(' + options.extensions.join('|') + ')$', 'i').test(filename)) && + + // if options.include is a RegExp, evaluate it and make sure the path passes + !(options.include && options.include instanceof RegExp && !options.include.test(path)) && + + // if options.include is a function, evaluate it and make sure the path passes + !(options.include && typeof options.include === 'function' && !options.include(path, filename)) && + + // if options.exclude is a RegExp, evaluate it and make sure the path doesn't pass + !(options.exclude && options.exclude instanceof RegExp && options.exclude.test(path)) && + + // if options.exclude is a function, evaluate it and make sure the path doesn't pass + !(options.exclude && typeof options.exclude === 'function' && options.exclude(path, filename)) + ); +} + +function requireDirectory(m, path, options) { + var retval = {}; + + // path is optional + if (path && !options && typeof path !== 'string') { + options = path; + path = null; + } + + // default options + options = options || {}; + for (var prop in defaultOptions) { + if (typeof options[prop] === 'undefined') { + options[prop] = defaultOptions[prop]; + } + } + + // if no path was passed in, assume the equivelant of __dirname from caller + // otherwise, resolve path relative to the equivalent of __dirname + path = !path ? dirname(m.filename) : resolve(dirname(m.filename), path); + + // get the path of each file in specified directory, append to current tree node, recurse + fs.readdirSync(path).forEach(function (filename) { + var joined = join(path, filename), + files, + key, + obj; + + if (fs.statSync(joined).isDirectory() && options.recurse) { + // this node is a directory; recurse + files = requireDirectory(m, joined, options); + // exclude empty directories + if (Object.keys(files).length) { + retval[options.rename(filename, joined, filename)] = files; + } + } else { + if (joined !== m.filename && checkFileInclusion(joined, filename, options)) { + // hash node key shouldn't include file extension + key = filename.substring(0, filename.lastIndexOf('.')); + obj = m.require(joined); + retval[options.rename(key, joined, filename)] = options.visit(obj, joined, filename) || obj; + } + } + }); + + return retval; +} + +module.exports = requireDirectory; +module.exports.defaults = defaultOptions; diff --git a/node_modules/require-directory/package.json b/node_modules/require-directory/package.json new file mode 100644 index 0000000..25ece4b --- /dev/null +++ b/node_modules/require-directory/package.json @@ -0,0 +1,40 @@ +{ + "author": "Troy Goode (http://github.com/troygoode/)", + "name": "require-directory", + "version": "2.1.1", + "description": "Recursively iterates over specified directory, require()'ing each file, and returning a nested hash structure containing those modules.", + "keywords": [ + "require", + "directory", + "library", + "recursive" + ], + "homepage": "https://github.com/troygoode/node-require-directory/", + "main": "index.js", + "repository": { + "type": "git", + "url": "git://github.com/troygoode/node-require-directory.git" + }, + "contributors": [ + { + "name": "Troy Goode", + "email": "troygoode@gmail.com", + "web": "http://github.com/troygoode/" + } + ], + "license": "MIT", + "bugs": { + "url": "http://github.com/troygoode/node-require-directory/issues/" + }, + "engines": { + "node": ">=0.10.0" + }, + "devDependencies": { + "jshint": "^2.6.0", + "mocha": "^2.1.0" + }, + "scripts": { + "test": "mocha", + "lint": "jshint index.js test/test.js" + } +} diff --git a/node_modules/string-width/index.d.ts b/node_modules/string-width/index.d.ts new file mode 100644 index 0000000..12b5309 --- /dev/null +++ b/node_modules/string-width/index.d.ts @@ -0,0 +1,29 @@ +declare const stringWidth: { + /** + Get the visual width of a string - the number of columns required to display it. + + Some Unicode characters are [fullwidth](https://en.wikipedia.org/wiki/Halfwidth_and_fullwidth_forms) and use double the normal width. [ANSI escape codes](https://en.wikipedia.org/wiki/ANSI_escape_code) are stripped and doesn't affect the width. + + @example + ``` + import stringWidth = require('string-width'); + + stringWidth('a'); + //=> 1 + + stringWidth('古'); + //=> 2 + + stringWidth('\u001B[1m古\u001B[22m'); + //=> 2 + ``` + */ + (string: string): number; + + // TODO: remove this in the next major version, refactor the whole definition to: + // declare function stringWidth(string: string): number; + // export = stringWidth; + default: typeof stringWidth; +} + +export = stringWidth; diff --git a/node_modules/string-width/index.js b/node_modules/string-width/index.js new file mode 100644 index 0000000..f4d261a --- /dev/null +++ b/node_modules/string-width/index.js @@ -0,0 +1,47 @@ +'use strict'; +const stripAnsi = require('strip-ansi'); +const isFullwidthCodePoint = require('is-fullwidth-code-point'); +const emojiRegex = require('emoji-regex'); + +const stringWidth = string => { + if (typeof string !== 'string' || string.length === 0) { + return 0; + } + + string = stripAnsi(string); + + if (string.length === 0) { + return 0; + } + + string = string.replace(emojiRegex(), ' '); + + let width = 0; + + for (let i = 0; i < string.length; i++) { + const code = string.codePointAt(i); + + // Ignore control characters + if (code <= 0x1F || (code >= 0x7F && code <= 0x9F)) { + continue; + } + + // Ignore combining characters + if (code >= 0x300 && code <= 0x36F) { + continue; + } + + // Surrogates + if (code > 0xFFFF) { + i++; + } + + width += isFullwidthCodePoint(code) ? 2 : 1; + } + + return width; +}; + +module.exports = stringWidth; +// TODO: remove this in the next major version +module.exports.default = stringWidth; diff --git a/node_modules/string-width/license b/node_modules/string-width/license new file mode 100644 index 0000000..e7af2f7 --- /dev/null +++ b/node_modules/string-width/license @@ -0,0 +1,9 @@ +MIT License + +Copyright (c) Sindre Sorhus (sindresorhus.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/string-width/package.json b/node_modules/string-width/package.json new file mode 100644 index 0000000..28ba7b4 --- /dev/null +++ b/node_modules/string-width/package.json @@ -0,0 +1,56 @@ +{ + "name": "string-width", + "version": "4.2.3", + "description": "Get the visual width of a string - the number of columns required to display it", + "license": "MIT", + "repository": "sindresorhus/string-width", + "author": { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "sindresorhus.com" + }, + "engines": { + "node": ">=8" + }, + "scripts": { + "test": "xo && ava && tsd" + }, + "files": [ + "index.js", + "index.d.ts" + ], + "keywords": [ + "string", + "character", + "unicode", + "width", + "visual", + "column", + "columns", + "fullwidth", + "full-width", + "full", + "ansi", + "escape", + "codes", + "cli", + "command-line", + "terminal", + "console", + "cjk", + "chinese", + "japanese", + "korean", + "fixed-width" + ], + "dependencies": { + "emoji-regex": "^8.0.0", + "is-fullwidth-code-point": "^3.0.0", + "strip-ansi": "^6.0.1" + }, + "devDependencies": { + "ava": "^1.4.1", + "tsd": "^0.7.1", + "xo": "^0.24.0" + } +} diff --git a/node_modules/string-width/readme.md b/node_modules/string-width/readme.md new file mode 100644 index 0000000..bdd3141 --- /dev/null +++ b/node_modules/string-width/readme.md @@ -0,0 +1,50 @@ +# string-width + +> Get the visual width of a string - the number of columns required to display it + +Some Unicode characters are [fullwidth](https://en.wikipedia.org/wiki/Halfwidth_and_fullwidth_forms) and use double the normal width. [ANSI escape codes](https://en.wikipedia.org/wiki/ANSI_escape_code) are stripped and doesn't affect the width. + +Useful to be able to measure the actual width of command-line output. + + +## Install + +``` +$ npm install string-width +``` + + +## Usage + +```js +const stringWidth = require('string-width'); + +stringWidth('a'); +//=> 1 + +stringWidth('古'); +//=> 2 + +stringWidth('\u001B[1m古\u001B[22m'); +//=> 2 +``` + + +## Related + +- [string-width-cli](https://github.com/sindresorhus/string-width-cli) - CLI for this module +- [string-length](https://github.com/sindresorhus/string-length) - Get the real length of a string +- [widest-line](https://github.com/sindresorhus/widest-line) - Get the visual width of the widest line in a string + + +--- + +
+ + Get professional support for this package with a Tidelift subscription + +
+ + Tidelift helps make open source sustainable for maintainers while giving companies
assurances about security, maintenance, and licensing for their dependencies. +
+
diff --git a/node_modules/strip-ansi/index.d.ts b/node_modules/strip-ansi/index.d.ts new file mode 100644 index 0000000..907fccc --- /dev/null +++ b/node_modules/strip-ansi/index.d.ts @@ -0,0 +1,17 @@ +/** +Strip [ANSI escape codes](https://en.wikipedia.org/wiki/ANSI_escape_code) from a string. + +@example +``` +import stripAnsi = require('strip-ansi'); + +stripAnsi('\u001B[4mUnicorn\u001B[0m'); +//=> 'Unicorn' + +stripAnsi('\u001B]8;;https://github.com\u0007Click\u001B]8;;\u0007'); +//=> 'Click' +``` +*/ +declare function stripAnsi(string: string): string; + +export = stripAnsi; diff --git a/node_modules/strip-ansi/index.js b/node_modules/strip-ansi/index.js new file mode 100644 index 0000000..9a593df --- /dev/null +++ b/node_modules/strip-ansi/index.js @@ -0,0 +1,4 @@ +'use strict'; +const ansiRegex = require('ansi-regex'); + +module.exports = string => typeof string === 'string' ? string.replace(ansiRegex(), '') : string; diff --git a/node_modules/strip-ansi/license b/node_modules/strip-ansi/license new file mode 100644 index 0000000..e7af2f7 --- /dev/null +++ b/node_modules/strip-ansi/license @@ -0,0 +1,9 @@ +MIT License + +Copyright (c) Sindre Sorhus (sindresorhus.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/strip-ansi/package.json b/node_modules/strip-ansi/package.json new file mode 100644 index 0000000..1a41108 --- /dev/null +++ b/node_modules/strip-ansi/package.json @@ -0,0 +1,54 @@ +{ + "name": "strip-ansi", + "version": "6.0.1", + "description": "Strip ANSI escape codes from a string", + "license": "MIT", + "repository": "chalk/strip-ansi", + "author": { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "sindresorhus.com" + }, + "engines": { + "node": ">=8" + }, + "scripts": { + "test": "xo && ava && tsd" + }, + "files": [ + "index.js", + "index.d.ts" + ], + "keywords": [ + "strip", + "trim", + "remove", + "ansi", + "styles", + "color", + "colour", + "colors", + "terminal", + "console", + "string", + "tty", + "escape", + "formatting", + "rgb", + "256", + "shell", + "xterm", + "log", + "logging", + "command-line", + "text" + ], + "dependencies": { + "ansi-regex": "^5.0.1" + }, + "devDependencies": { + "ava": "^2.4.0", + "tsd": "^0.10.0", + "xo": "^0.25.3" + } +} diff --git a/node_modules/strip-ansi/readme.md b/node_modules/strip-ansi/readme.md new file mode 100644 index 0000000..7c4b56d --- /dev/null +++ b/node_modules/strip-ansi/readme.md @@ -0,0 +1,46 @@ +# strip-ansi [![Build Status](https://travis-ci.org/chalk/strip-ansi.svg?branch=master)](https://travis-ci.org/chalk/strip-ansi) + +> Strip [ANSI escape codes](https://en.wikipedia.org/wiki/ANSI_escape_code) from a string + + +## Install + +``` +$ npm install strip-ansi +``` + + +## Usage + +```js +const stripAnsi = require('strip-ansi'); + +stripAnsi('\u001B[4mUnicorn\u001B[0m'); +//=> 'Unicorn' + +stripAnsi('\u001B]8;;https://github.com\u0007Click\u001B]8;;\u0007'); +//=> 'Click' +``` + + +## strip-ansi for enterprise + +Available as part of the Tidelift Subscription. + +The maintainers of strip-ansi and thousands of other packages are working with Tidelift to deliver commercial support and maintenance for the open source dependencies you use to build your applications. Save time, reduce risk, and improve code health, while paying the maintainers of the exact dependencies you use. [Learn more.](https://tidelift.com/subscription/pkg/npm-strip-ansi?utm_source=npm-strip-ansi&utm_medium=referral&utm_campaign=enterprise&utm_term=repo) + + +## Related + +- [strip-ansi-cli](https://github.com/chalk/strip-ansi-cli) - CLI for this module +- [strip-ansi-stream](https://github.com/chalk/strip-ansi-stream) - Streaming version of this module +- [has-ansi](https://github.com/chalk/has-ansi) - Check if a string has ANSI escape codes +- [ansi-regex](https://github.com/chalk/ansi-regex) - Regular expression for matching ANSI escape codes +- [chalk](https://github.com/chalk/chalk) - Terminal string styling done right + + +## Maintainers + +- [Sindre Sorhus](https://github.com/sindresorhus) +- [Josh Junon](https://github.com/qix-) + diff --git a/node_modules/undici-types/README.md b/node_modules/undici-types/README.md new file mode 100644 index 0000000..20a721c --- /dev/null +++ b/node_modules/undici-types/README.md @@ -0,0 +1,6 @@ +# undici-types + +This package is a dual-publish of the [undici](https://www.npmjs.com/package/undici) library types. The `undici` package **still contains types**. This package is for users who _only_ need undici types (such as for `@types/node`). It is published alongside every release of `undici`, so you can always use the same version. + +- [GitHub nodejs/undici](https://github.com/nodejs/undici) +- [Undici Documentation](https://undici.nodejs.org/#/) diff --git a/node_modules/undici-types/agent.d.ts b/node_modules/undici-types/agent.d.ts new file mode 100644 index 0000000..58081ce --- /dev/null +++ b/node_modules/undici-types/agent.d.ts @@ -0,0 +1,31 @@ +import { URL } from 'url' +import Pool from './pool' +import Dispatcher from "./dispatcher"; + +export default Agent + +declare class Agent extends Dispatcher{ + constructor(opts?: Agent.Options) + /** `true` after `dispatcher.close()` has been called. */ + closed: boolean; + /** `true` after `dispatcher.destroyed()` has been called or `dispatcher.close()` has been called and the dispatcher shutdown has completed. */ + destroyed: boolean; + /** Dispatches a request. */ + dispatch(options: Agent.DispatchOptions, handler: Dispatcher.DispatchHandlers): boolean; +} + +declare namespace Agent { + export interface Options extends Pool.Options { + /** Default: `(origin, opts) => new Pool(origin, opts)`. */ + factory?(origin: string | URL, opts: Object): Dispatcher; + /** Integer. Default: `0` */ + maxRedirections?: number; + + interceptors?: { Agent?: readonly Dispatcher.DispatchInterceptor[] } & Pool.Options["interceptors"] + } + + export interface DispatchOptions extends Dispatcher.DispatchOptions { + /** Integer. */ + maxRedirections?: number; + } +} diff --git a/node_modules/undici-types/api.d.ts b/node_modules/undici-types/api.d.ts new file mode 100644 index 0000000..400341d --- /dev/null +++ b/node_modules/undici-types/api.d.ts @@ -0,0 +1,43 @@ +import { URL, UrlObject } from 'url' +import { Duplex } from 'stream' +import Dispatcher from './dispatcher' + +export { + request, + stream, + pipeline, + connect, + upgrade, +} + +/** Performs an HTTP request. */ +declare function request( + url: string | URL | UrlObject, + options?: { dispatcher?: Dispatcher } & Omit & Partial>, +): Promise; + +/** A faster version of `request`. */ +declare function stream( + url: string | URL | UrlObject, + options: { dispatcher?: Dispatcher } & Omit, + factory: Dispatcher.StreamFactory +): Promise; + +/** For easy use with `stream.pipeline`. */ +declare function pipeline( + url: string | URL | UrlObject, + options: { dispatcher?: Dispatcher } & Omit, + handler: Dispatcher.PipelineHandler +): Duplex; + +/** Starts two-way communications with the requested resource. */ +declare function connect( + url: string | URL | UrlObject, + options?: { dispatcher?: Dispatcher } & Omit +): Promise; + +/** Upgrade to a different protocol. */ +declare function upgrade( + url: string | URL | UrlObject, + options?: { dispatcher?: Dispatcher } & Omit +): Promise; diff --git a/node_modules/undici-types/balanced-pool.d.ts b/node_modules/undici-types/balanced-pool.d.ts new file mode 100644 index 0000000..d1e9375 --- /dev/null +++ b/node_modules/undici-types/balanced-pool.d.ts @@ -0,0 +1,18 @@ +import Pool from './pool' +import Dispatcher from './dispatcher' +import { URL } from 'url' + +export default BalancedPool + +declare class BalancedPool extends Dispatcher { + constructor(url: string | string[] | URL | URL[], options?: Pool.Options); + + addUpstream(upstream: string | URL): BalancedPool; + removeUpstream(upstream: string | URL): BalancedPool; + upstreams: Array; + + /** `true` after `pool.close()` has been called. */ + closed: boolean; + /** `true` after `pool.destroyed()` has been called or `pool.close()` has been called and the pool shutdown has completed. */ + destroyed: boolean; +} diff --git a/node_modules/undici-types/cache.d.ts b/node_modules/undici-types/cache.d.ts new file mode 100644 index 0000000..4c33335 --- /dev/null +++ b/node_modules/undici-types/cache.d.ts @@ -0,0 +1,36 @@ +import type { RequestInfo, Response, Request } from './fetch' + +export interface CacheStorage { + match (request: RequestInfo, options?: MultiCacheQueryOptions): Promise, + has (cacheName: string): Promise, + open (cacheName: string): Promise, + delete (cacheName: string): Promise, + keys (): Promise +} + +declare const CacheStorage: { + prototype: CacheStorage + new(): CacheStorage +} + +export interface Cache { + match (request: RequestInfo, options?: CacheQueryOptions): Promise, + matchAll (request?: RequestInfo, options?: CacheQueryOptions): Promise, + add (request: RequestInfo): Promise, + addAll (requests: RequestInfo[]): Promise, + put (request: RequestInfo, response: Response): Promise, + delete (request: RequestInfo, options?: CacheQueryOptions): Promise, + keys (request?: RequestInfo, options?: CacheQueryOptions): Promise +} + +export interface CacheQueryOptions { + ignoreSearch?: boolean, + ignoreMethod?: boolean, + ignoreVary?: boolean +} + +export interface MultiCacheQueryOptions extends CacheQueryOptions { + cacheName?: string +} + +export declare const caches: CacheStorage diff --git a/node_modules/undici-types/client.d.ts b/node_modules/undici-types/client.d.ts new file mode 100644 index 0000000..74948b1 --- /dev/null +++ b/node_modules/undici-types/client.d.ts @@ -0,0 +1,97 @@ +import { URL } from 'url' +import { TlsOptions } from 'tls' +import Dispatcher from './dispatcher' +import buildConnector from "./connector"; + +/** + * A basic HTTP/1.1 client, mapped on top a single TCP/TLS connection. Pipelining is disabled by default. + */ +export class Client extends Dispatcher { + constructor(url: string | URL, options?: Client.Options); + /** Property to get and set the pipelining factor. */ + pipelining: number; + /** `true` after `client.close()` has been called. */ + closed: boolean; + /** `true` after `client.destroyed()` has been called or `client.close()` has been called and the client shutdown has completed. */ + destroyed: boolean; +} + +export declare namespace Client { + export interface OptionsInterceptors { + Client: readonly Dispatcher.DispatchInterceptor[]; + } + export interface Options { + /** TODO */ + interceptors?: OptionsInterceptors; + /** The maximum length of request headers in bytes. Default: Node.js' `--max-http-header-size` or `16384` (16KiB). */ + maxHeaderSize?: number; + /** The amount of time, in milliseconds, the parser will wait to receive the complete HTTP headers (Node 14 and above only). Default: `300e3` milliseconds (300s). */ + headersTimeout?: number; + /** @deprecated unsupported socketTimeout, use headersTimeout & bodyTimeout instead */ + socketTimeout?: never; + /** @deprecated unsupported requestTimeout, use headersTimeout & bodyTimeout instead */ + requestTimeout?: never; + /** TODO */ + connectTimeout?: number; + /** The timeout after which a request will time out, in milliseconds. Monitors time between receiving body data. Use `0` to disable it entirely. Default: `300e3` milliseconds (300s). */ + bodyTimeout?: number; + /** @deprecated unsupported idleTimeout, use keepAliveTimeout instead */ + idleTimeout?: never; + /** @deprecated unsupported keepAlive, use pipelining=0 instead */ + keepAlive?: never; + /** the timeout, in milliseconds, after which a socket without active requests will time out. Monitors time between activity on a connected socket. This value may be overridden by *keep-alive* hints from the server. Default: `4e3` milliseconds (4s). */ + keepAliveTimeout?: number; + /** @deprecated unsupported maxKeepAliveTimeout, use keepAliveMaxTimeout instead */ + maxKeepAliveTimeout?: never; + /** the maximum allowed `idleTimeout`, in milliseconds, when overridden by *keep-alive* hints from the server. Default: `600e3` milliseconds (10min). */ + keepAliveMaxTimeout?: number; + /** A number of milliseconds subtracted from server *keep-alive* hints when overriding `idleTimeout` to account for timing inaccuracies caused by e.g. transport latency. Default: `1e3` milliseconds (1s). */ + keepAliveTimeoutThreshold?: number; + /** TODO */ + socketPath?: string; + /** The amount of concurrent requests to be sent over the single TCP/TLS connection according to [RFC7230](https://tools.ietf.org/html/rfc7230#section-6.3.2). Default: `1`. */ + pipelining?: number; + /** @deprecated use the connect option instead */ + tls?: never; + /** If `true`, an error is thrown when the request content-length header doesn't match the length of the request body. Default: `true`. */ + strictContentLength?: boolean; + /** TODO */ + maxCachedSessions?: number; + /** TODO */ + maxRedirections?: number; + /** TODO */ + connect?: buildConnector.BuildOptions | buildConnector.connector; + /** TODO */ + maxRequestsPerClient?: number; + /** TODO */ + localAddress?: string; + /** Max response body size in bytes, -1 is disabled */ + maxResponseSize?: number; + /** Enables a family autodetection algorithm that loosely implements section 5 of RFC 8305. */ + autoSelectFamily?: boolean; + /** The amount of time in milliseconds to wait for a connection attempt to finish before trying the next address when using the `autoSelectFamily` option. */ + autoSelectFamilyAttemptTimeout?: number; + /** + * @description Enables support for H2 if the server has assigned bigger priority to it through ALPN negotiation. + * @default false + */ + allowH2?: boolean; + /** + * @description Dictates the maximum number of concurrent streams for a single H2 session. It can be overriden by a SETTINGS remote frame. + * @default 100 + */ + maxConcurrentStreams?: number + } + export interface SocketInfo { + localAddress?: string + localPort?: number + remoteAddress?: string + remotePort?: number + remoteFamily?: string + timeout?: number + bytesWritten?: number + bytesRead?: number + } +} + +export default Client; diff --git a/node_modules/undici-types/connector.d.ts b/node_modules/undici-types/connector.d.ts new file mode 100644 index 0000000..bd92433 --- /dev/null +++ b/node_modules/undici-types/connector.d.ts @@ -0,0 +1,34 @@ +import { TLSSocket, ConnectionOptions } from 'tls' +import { IpcNetConnectOpts, Socket, TcpNetConnectOpts } from 'net' + +export default buildConnector +declare function buildConnector (options?: buildConnector.BuildOptions): buildConnector.connector + +declare namespace buildConnector { + export type BuildOptions = (ConnectionOptions | TcpNetConnectOpts | IpcNetConnectOpts) & { + allowH2?: boolean; + maxCachedSessions?: number | null; + socketPath?: string | null; + timeout?: number | null; + port?: number; + keepAlive?: boolean | null; + keepAliveInitialDelay?: number | null; + } + + export interface Options { + hostname: string + host?: string + protocol: string + port: string + servername?: string + localAddress?: string | null + httpSocket?: Socket + } + + export type Callback = (...args: CallbackArgs) => void + type CallbackArgs = [null, Socket | TLSSocket] | [Error, null] + + export interface connector { + (options: buildConnector.Options, callback: buildConnector.Callback): void + } +} diff --git a/node_modules/undici-types/content-type.d.ts b/node_modules/undici-types/content-type.d.ts new file mode 100644 index 0000000..f2a87f1 --- /dev/null +++ b/node_modules/undici-types/content-type.d.ts @@ -0,0 +1,21 @@ +/// + +interface MIMEType { + type: string + subtype: string + parameters: Map + essence: string +} + +/** + * Parse a string to a {@link MIMEType} object. Returns `failure` if the string + * couldn't be parsed. + * @see https://mimesniff.spec.whatwg.org/#parse-a-mime-type + */ +export function parseMIMEType (input: string): 'failure' | MIMEType + +/** + * Convert a MIMEType object to a string. + * @see https://mimesniff.spec.whatwg.org/#serialize-a-mime-type + */ +export function serializeAMimeType (mimeType: MIMEType): string diff --git a/node_modules/undici-types/cookies.d.ts b/node_modules/undici-types/cookies.d.ts new file mode 100644 index 0000000..aa38cae --- /dev/null +++ b/node_modules/undici-types/cookies.d.ts @@ -0,0 +1,28 @@ +/// + +import type { Headers } from './fetch' + +export interface Cookie { + name: string + value: string + expires?: Date | number + maxAge?: number + domain?: string + path?: string + secure?: boolean + httpOnly?: boolean + sameSite?: 'Strict' | 'Lax' | 'None' + unparsed?: string[] +} + +export function deleteCookie ( + headers: Headers, + name: string, + attributes?: { name?: string, domain?: string } +): void + +export function getCookies (headers: Headers): Record + +export function getSetCookies (headers: Headers): Cookie[] + +export function setCookie (headers: Headers, cookie: Cookie): void diff --git a/node_modules/undici-types/diagnostics-channel.d.ts b/node_modules/undici-types/diagnostics-channel.d.ts new file mode 100644 index 0000000..85d4482 --- /dev/null +++ b/node_modules/undici-types/diagnostics-channel.d.ts @@ -0,0 +1,67 @@ +import { Socket } from "net"; +import { URL } from "url"; +import Connector from "./connector"; +import Dispatcher from "./dispatcher"; + +declare namespace DiagnosticsChannel { + interface Request { + origin?: string | URL; + completed: boolean; + method?: Dispatcher.HttpMethod; + path: string; + headers: string; + addHeader(key: string, value: string): Request; + } + interface Response { + statusCode: number; + statusText: string; + headers: Array; + } + type Error = unknown; + interface ConnectParams { + host: URL["host"]; + hostname: URL["hostname"]; + protocol: URL["protocol"]; + port: URL["port"]; + servername: string | null; + } + type Connector = Connector.connector; + export interface RequestCreateMessage { + request: Request; + } + export interface RequestBodySentMessage { + request: Request; + } + export interface RequestHeadersMessage { + request: Request; + response: Response; + } + export interface RequestTrailersMessage { + request: Request; + trailers: Array; + } + export interface RequestErrorMessage { + request: Request; + error: Error; + } + export interface ClientSendHeadersMessage { + request: Request; + headers: string; + socket: Socket; + } + export interface ClientBeforeConnectMessage { + connectParams: ConnectParams; + connector: Connector; + } + export interface ClientConnectedMessage { + socket: Socket; + connectParams: ConnectParams; + connector: Connector; + } + export interface ClientConnectErrorMessage { + error: Error; + socket: Socket; + connectParams: ConnectParams; + connector: Connector; + } +} diff --git a/node_modules/undici-types/dispatcher.d.ts b/node_modules/undici-types/dispatcher.d.ts new file mode 100644 index 0000000..816db19 --- /dev/null +++ b/node_modules/undici-types/dispatcher.d.ts @@ -0,0 +1,241 @@ +import { URL } from 'url' +import { Duplex, Readable, Writable } from 'stream' +import { EventEmitter } from 'events' +import { Blob } from 'buffer' +import { IncomingHttpHeaders } from './header' +import BodyReadable from './readable' +import { FormData } from './formdata' +import Errors from './errors' + +type AbortSignal = unknown; + +export default Dispatcher + +/** Dispatcher is the core API used to dispatch requests. */ +declare class Dispatcher extends EventEmitter { + /** Dispatches a request. This API is expected to evolve through semver-major versions and is less stable than the preceding higher level APIs. It is primarily intended for library developers who implement higher level APIs on top of this. */ + dispatch(options: Dispatcher.DispatchOptions, handler: Dispatcher.DispatchHandlers): boolean; + /** Starts two-way communications with the requested resource. */ + connect(options: Dispatcher.ConnectOptions): Promise; + connect(options: Dispatcher.ConnectOptions, callback: (err: Error | null, data: Dispatcher.ConnectData) => void): void; + /** Performs an HTTP request. */ + request(options: Dispatcher.RequestOptions): Promise; + request(options: Dispatcher.RequestOptions, callback: (err: Error | null, data: Dispatcher.ResponseData) => void): void; + /** For easy use with `stream.pipeline`. */ + pipeline(options: Dispatcher.PipelineOptions, handler: Dispatcher.PipelineHandler): Duplex; + /** A faster version of `Dispatcher.request`. */ + stream(options: Dispatcher.RequestOptions, factory: Dispatcher.StreamFactory): Promise; + stream(options: Dispatcher.RequestOptions, factory: Dispatcher.StreamFactory, callback: (err: Error | null, data: Dispatcher.StreamData) => void): void; + /** Upgrade to a different protocol. */ + upgrade(options: Dispatcher.UpgradeOptions): Promise; + upgrade(options: Dispatcher.UpgradeOptions, callback: (err: Error | null, data: Dispatcher.UpgradeData) => void): void; + /** Closes the client and gracefully waits for enqueued requests to complete before invoking the callback (or returning a promise if no callback is provided). */ + close(): Promise; + close(callback: () => void): void; + /** Destroy the client abruptly with the given err. All the pending and running requests will be asynchronously aborted and error. Waits until socket is closed before invoking the callback (or returning a promise if no callback is provided). Since this operation is asynchronously dispatched there might still be some progress on dispatched requests. */ + destroy(): Promise; + destroy(err: Error | null): Promise; + destroy(callback: () => void): void; + destroy(err: Error | null, callback: () => void): void; + + on(eventName: 'connect', callback: (origin: URL, targets: readonly Dispatcher[]) => void): this; + on(eventName: 'disconnect', callback: (origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void): this; + on(eventName: 'connectionError', callback: (origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void): this; + on(eventName: 'drain', callback: (origin: URL) => void): this; + + + once(eventName: 'connect', callback: (origin: URL, targets: readonly Dispatcher[]) => void): this; + once(eventName: 'disconnect', callback: (origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void): this; + once(eventName: 'connectionError', callback: (origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void): this; + once(eventName: 'drain', callback: (origin: URL) => void): this; + + + off(eventName: 'connect', callback: (origin: URL, targets: readonly Dispatcher[]) => void): this; + off(eventName: 'disconnect', callback: (origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void): this; + off(eventName: 'connectionError', callback: (origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void): this; + off(eventName: 'drain', callback: (origin: URL) => void): this; + + + addListener(eventName: 'connect', callback: (origin: URL, targets: readonly Dispatcher[]) => void): this; + addListener(eventName: 'disconnect', callback: (origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void): this; + addListener(eventName: 'connectionError', callback: (origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void): this; + addListener(eventName: 'drain', callback: (origin: URL) => void): this; + + removeListener(eventName: 'connect', callback: (origin: URL, targets: readonly Dispatcher[]) => void): this; + removeListener(eventName: 'disconnect', callback: (origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void): this; + removeListener(eventName: 'connectionError', callback: (origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void): this; + removeListener(eventName: 'drain', callback: (origin: URL) => void): this; + + prependListener(eventName: 'connect', callback: (origin: URL, targets: readonly Dispatcher[]) => void): this; + prependListener(eventName: 'disconnect', callback: (origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void): this; + prependListener(eventName: 'connectionError', callback: (origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void): this; + prependListener(eventName: 'drain', callback: (origin: URL) => void): this; + + prependOnceListener(eventName: 'connect', callback: (origin: URL, targets: readonly Dispatcher[]) => void): this; + prependOnceListener(eventName: 'disconnect', callback: (origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void): this; + prependOnceListener(eventName: 'connectionError', callback: (origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void): this; + prependOnceListener(eventName: 'drain', callback: (origin: URL) => void): this; + + listeners(eventName: 'connect'): ((origin: URL, targets: readonly Dispatcher[]) => void)[] + listeners(eventName: 'disconnect'): ((origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void)[]; + listeners(eventName: 'connectionError'): ((origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void)[]; + listeners(eventName: 'drain'): ((origin: URL) => void)[]; + + rawListeners(eventName: 'connect'): ((origin: URL, targets: readonly Dispatcher[]) => void)[] + rawListeners(eventName: 'disconnect'): ((origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void)[]; + rawListeners(eventName: 'connectionError'): ((origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError) => void)[]; + rawListeners(eventName: 'drain'): ((origin: URL) => void)[]; + + emit(eventName: 'connect', origin: URL, targets: readonly Dispatcher[]): boolean; + emit(eventName: 'disconnect', origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError): boolean; + emit(eventName: 'connectionError', origin: URL, targets: readonly Dispatcher[], error: Errors.UndiciError): boolean; + emit(eventName: 'drain', origin: URL): boolean; +} + +declare namespace Dispatcher { + export interface DispatchOptions { + origin?: string | URL; + path: string; + method: HttpMethod; + /** Default: `null` */ + body?: string | Buffer | Uint8Array | Readable | null | FormData; + /** Default: `null` */ + headers?: IncomingHttpHeaders | string[] | null; + /** Query string params to be embedded in the request URL. Default: `null` */ + query?: Record; + /** Whether the requests can be safely retried or not. If `false` the request won't be sent until all preceding requests in the pipeline have completed. Default: `true` if `method` is `HEAD` or `GET`. */ + idempotent?: boolean; + /** Whether the response is expected to take a long time and would end up blocking the pipeline. When this is set to `true` further pipelining will be avoided on the same connection until headers have been received. */ + blocking?: boolean; + /** Upgrade the request. Should be used to specify the kind of upgrade i.e. `'Websocket'`. Default: `method === 'CONNECT' || null`. */ + upgrade?: boolean | string | null; + /** The amount of time, in milliseconds, the parser will wait to receive the complete HTTP headers. Defaults to 300 seconds. */ + headersTimeout?: number | null; + /** The timeout after which a request will time out, in milliseconds. Monitors time between receiving body data. Use 0 to disable it entirely. Defaults to 300 seconds. */ + bodyTimeout?: number | null; + /** Whether the request should stablish a keep-alive or not. Default `false` */ + reset?: boolean; + /** Whether Undici should throw an error upon receiving a 4xx or 5xx response from the server. Defaults to false */ + throwOnError?: boolean; + /** For H2, it appends the expect: 100-continue header, and halts the request body until a 100-continue is received from the remote server*/ + expectContinue?: boolean; + } + export interface ConnectOptions { + path: string; + /** Default: `null` */ + headers?: IncomingHttpHeaders | string[] | null; + /** Default: `null` */ + signal?: AbortSignal | EventEmitter | null; + /** This argument parameter is passed through to `ConnectData` */ + opaque?: unknown; + /** Default: 0 */ + maxRedirections?: number; + /** Default: `null` */ + responseHeader?: 'raw' | null; + } + export interface RequestOptions extends DispatchOptions { + /** Default: `null` */ + opaque?: unknown; + /** Default: `null` */ + signal?: AbortSignal | EventEmitter | null; + /** Default: 0 */ + maxRedirections?: number; + /** Default: `null` */ + onInfo?: (info: { statusCode: number, headers: Record }) => void; + /** Default: `null` */ + responseHeader?: 'raw' | null; + /** Default: `64 KiB` */ + highWaterMark?: number; + } + export interface PipelineOptions extends RequestOptions { + /** `true` if the `handler` will return an object stream. Default: `false` */ + objectMode?: boolean; + } + export interface UpgradeOptions { + path: string; + /** Default: `'GET'` */ + method?: string; + /** Default: `null` */ + headers?: IncomingHttpHeaders | string[] | null; + /** A string of comma separated protocols, in descending preference order. Default: `'Websocket'` */ + protocol?: string; + /** Default: `null` */ + signal?: AbortSignal | EventEmitter | null; + /** Default: 0 */ + maxRedirections?: number; + /** Default: `null` */ + responseHeader?: 'raw' | null; + } + export interface ConnectData { + statusCode: number; + headers: IncomingHttpHeaders; + socket: Duplex; + opaque: unknown; + } + export interface ResponseData { + statusCode: number; + headers: IncomingHttpHeaders; + body: BodyReadable & BodyMixin; + trailers: Record; + opaque: unknown; + context: object; + } + export interface PipelineHandlerData { + statusCode: number; + headers: IncomingHttpHeaders; + opaque: unknown; + body: BodyReadable; + context: object; + } + export interface StreamData { + opaque: unknown; + trailers: Record; + } + export interface UpgradeData { + headers: IncomingHttpHeaders; + socket: Duplex; + opaque: unknown; + } + export interface StreamFactoryData { + statusCode: number; + headers: IncomingHttpHeaders; + opaque: unknown; + context: object; + } + export type StreamFactory = (data: StreamFactoryData) => Writable; + export interface DispatchHandlers { + /** Invoked before request is dispatched on socket. May be invoked multiple times when a request is retried when the request at the head of the pipeline fails. */ + onConnect?(abort: () => void): void; + /** Invoked when an error has occurred. */ + onError?(err: Error): void; + /** Invoked when request is upgraded either due to a `Upgrade` header or `CONNECT` method. */ + onUpgrade?(statusCode: number, headers: Buffer[] | string[] | null, socket: Duplex): void; + /** Invoked when statusCode and headers have been received. May be invoked multiple times due to 1xx informational headers. */ + onHeaders?(statusCode: number, headers: Buffer[] | string[] | null, resume: () => void): boolean; + /** Invoked when response payload data is received. */ + onData?(chunk: Buffer): boolean; + /** Invoked when response payload and trailers have been received and the request has completed. */ + onComplete?(trailers: string[] | null): void; + /** Invoked when a body chunk is sent to the server. May be invoked multiple times for chunked requests */ + onBodySent?(chunkSize: number, totalBytesSent: number): void; + } + export type PipelineHandler = (data: PipelineHandlerData) => Readable; + export type HttpMethod = 'GET' | 'HEAD' | 'POST' | 'PUT' | 'DELETE' | 'CONNECT' | 'OPTIONS' | 'TRACE' | 'PATCH'; + + /** + * @link https://fetch.spec.whatwg.org/#body-mixin + */ + interface BodyMixin { + readonly body?: never; // throws on node v16.6.0 + readonly bodyUsed: boolean; + arrayBuffer(): Promise; + blob(): Promise; + formData(): Promise; + json(): Promise; + text(): Promise; + } + + export interface DispatchInterceptor { + (dispatch: Dispatcher['dispatch']): Dispatcher['dispatch'] + } +} diff --git a/node_modules/undici-types/errors.d.ts b/node_modules/undici-types/errors.d.ts new file mode 100644 index 0000000..7923ddd --- /dev/null +++ b/node_modules/undici-types/errors.d.ts @@ -0,0 +1,128 @@ +import { IncomingHttpHeaders } from "./header"; +import Client from './client' + +export default Errors + +declare namespace Errors { + export class UndiciError extends Error { + name: string; + code: string; + } + + /** Connect timeout error. */ + export class ConnectTimeoutError extends UndiciError { + name: 'ConnectTimeoutError'; + code: 'UND_ERR_CONNECT_TIMEOUT'; + } + + /** A header exceeds the `headersTimeout` option. */ + export class HeadersTimeoutError extends UndiciError { + name: 'HeadersTimeoutError'; + code: 'UND_ERR_HEADERS_TIMEOUT'; + } + + /** Headers overflow error. */ + export class HeadersOverflowError extends UndiciError { + name: 'HeadersOverflowError' + code: 'UND_ERR_HEADERS_OVERFLOW' + } + + /** A body exceeds the `bodyTimeout` option. */ + export class BodyTimeoutError extends UndiciError { + name: 'BodyTimeoutError'; + code: 'UND_ERR_BODY_TIMEOUT'; + } + + export class ResponseStatusCodeError extends UndiciError { + constructor ( + message?: string, + statusCode?: number, + headers?: IncomingHttpHeaders | string[] | null, + body?: null | Record | string + ); + name: 'ResponseStatusCodeError'; + code: 'UND_ERR_RESPONSE_STATUS_CODE'; + body: null | Record | string + status: number + statusCode: number + headers: IncomingHttpHeaders | string[] | null; + } + + /** Passed an invalid argument. */ + export class InvalidArgumentError extends UndiciError { + name: 'InvalidArgumentError'; + code: 'UND_ERR_INVALID_ARG'; + } + + /** Returned an invalid value. */ + export class InvalidReturnValueError extends UndiciError { + name: 'InvalidReturnValueError'; + code: 'UND_ERR_INVALID_RETURN_VALUE'; + } + + /** The request has been aborted by the user. */ + export class RequestAbortedError extends UndiciError { + name: 'AbortError'; + code: 'UND_ERR_ABORTED'; + } + + /** Expected error with reason. */ + export class InformationalError extends UndiciError { + name: 'InformationalError'; + code: 'UND_ERR_INFO'; + } + + /** Request body length does not match content-length header. */ + export class RequestContentLengthMismatchError extends UndiciError { + name: 'RequestContentLengthMismatchError'; + code: 'UND_ERR_REQ_CONTENT_LENGTH_MISMATCH'; + } + + /** Response body length does not match content-length header. */ + export class ResponseContentLengthMismatchError extends UndiciError { + name: 'ResponseContentLengthMismatchError'; + code: 'UND_ERR_RES_CONTENT_LENGTH_MISMATCH'; + } + + /** Trying to use a destroyed client. */ + export class ClientDestroyedError extends UndiciError { + name: 'ClientDestroyedError'; + code: 'UND_ERR_DESTROYED'; + } + + /** Trying to use a closed client. */ + export class ClientClosedError extends UndiciError { + name: 'ClientClosedError'; + code: 'UND_ERR_CLOSED'; + } + + /** There is an error with the socket. */ + export class SocketError extends UndiciError { + name: 'SocketError'; + code: 'UND_ERR_SOCKET'; + socket: Client.SocketInfo | null + } + + /** Encountered unsupported functionality. */ + export class NotSupportedError extends UndiciError { + name: 'NotSupportedError'; + code: 'UND_ERR_NOT_SUPPORTED'; + } + + /** No upstream has been added to the BalancedPool. */ + export class BalancedPoolMissingUpstreamError extends UndiciError { + name: 'MissingUpstreamError'; + code: 'UND_ERR_BPL_MISSING_UPSTREAM'; + } + + export class HTTPParserError extends UndiciError { + name: 'HTTPParserError'; + code: string; + } + + /** The response exceed the length allowed. */ + export class ResponseExceededMaxSizeError extends UndiciError { + name: 'ResponseExceededMaxSizeError'; + code: 'UND_ERR_RES_EXCEEDED_MAX_SIZE'; + } +} diff --git a/node_modules/undici-types/fetch.d.ts b/node_modules/undici-types/fetch.d.ts new file mode 100644 index 0000000..fa4619c --- /dev/null +++ b/node_modules/undici-types/fetch.d.ts @@ -0,0 +1,209 @@ +// based on https://github.com/Ethan-Arrowood/undici-fetch/blob/249269714db874351589d2d364a0645d5160ae71/index.d.ts (MIT license) +// and https://github.com/node-fetch/node-fetch/blob/914ce6be5ec67a8bab63d68510aabf07cb818b6d/index.d.ts (MIT license) +/// + +import { Blob } from 'buffer' +import { URL, URLSearchParams } from 'url' +import { ReadableStream } from 'stream/web' +import { FormData } from './formdata' + +import Dispatcher from './dispatcher' + +export type RequestInfo = string | URL | Request + +export declare function fetch ( + input: RequestInfo, + init?: RequestInit +): Promise + +export type BodyInit = + | ArrayBuffer + | AsyncIterable + | Blob + | FormData + | Iterable + | NodeJS.ArrayBufferView + | URLSearchParams + | null + | string + +export interface BodyMixin { + readonly body: ReadableStream | null + readonly bodyUsed: boolean + + readonly arrayBuffer: () => Promise + readonly blob: () => Promise + readonly formData: () => Promise + readonly json: () => Promise + readonly text: () => Promise +} + +export interface SpecIterator { + next(...args: [] | [TNext]): IteratorResult; +} + +export interface SpecIterableIterator extends SpecIterator { + [Symbol.iterator](): SpecIterableIterator; +} + +export interface SpecIterable { + [Symbol.iterator](): SpecIterator; +} + +export type HeadersInit = string[][] | Record> | Headers + +export declare class Headers implements SpecIterable<[string, string]> { + constructor (init?: HeadersInit) + readonly append: (name: string, value: string) => void + readonly delete: (name: string) => void + readonly get: (name: string) => string | null + readonly has: (name: string) => boolean + readonly set: (name: string, value: string) => void + readonly getSetCookie: () => string[] + readonly forEach: ( + callbackfn: (value: string, key: string, iterable: Headers) => void, + thisArg?: unknown + ) => void + + readonly keys: () => SpecIterableIterator + readonly values: () => SpecIterableIterator + readonly entries: () => SpecIterableIterator<[string, string]> + readonly [Symbol.iterator]: () => SpecIterator<[string, string]> +} + +export type RequestCache = + | 'default' + | 'force-cache' + | 'no-cache' + | 'no-store' + | 'only-if-cached' + | 'reload' + +export type RequestCredentials = 'omit' | 'include' | 'same-origin' + +type RequestDestination = + | '' + | 'audio' + | 'audioworklet' + | 'document' + | 'embed' + | 'font' + | 'image' + | 'manifest' + | 'object' + | 'paintworklet' + | 'report' + | 'script' + | 'sharedworker' + | 'style' + | 'track' + | 'video' + | 'worker' + | 'xslt' + +export interface RequestInit { + method?: string + keepalive?: boolean + headers?: HeadersInit + body?: BodyInit + redirect?: RequestRedirect + integrity?: string + signal?: AbortSignal + credentials?: RequestCredentials + mode?: RequestMode + referrer?: string + referrerPolicy?: ReferrerPolicy + window?: null + dispatcher?: Dispatcher + duplex?: RequestDuplex +} + +export type ReferrerPolicy = + | '' + | 'no-referrer' + | 'no-referrer-when-downgrade' + | 'origin' + | 'origin-when-cross-origin' + | 'same-origin' + | 'strict-origin' + | 'strict-origin-when-cross-origin' + | 'unsafe-url'; + +export type RequestMode = 'cors' | 'navigate' | 'no-cors' | 'same-origin' + +export type RequestRedirect = 'error' | 'follow' | 'manual' + +export type RequestDuplex = 'half' + +export declare class Request implements BodyMixin { + constructor (input: RequestInfo, init?: RequestInit) + + readonly cache: RequestCache + readonly credentials: RequestCredentials + readonly destination: RequestDestination + readonly headers: Headers + readonly integrity: string + readonly method: string + readonly mode: RequestMode + readonly redirect: RequestRedirect + readonly referrerPolicy: string + readonly url: string + + readonly keepalive: boolean + readonly signal: AbortSignal + readonly duplex: RequestDuplex + + readonly body: ReadableStream | null + readonly bodyUsed: boolean + + readonly arrayBuffer: () => Promise + readonly blob: () => Promise + readonly formData: () => Promise + readonly json: () => Promise + readonly text: () => Promise + + readonly clone: () => Request +} + +export interface ResponseInit { + readonly status?: number + readonly statusText?: string + readonly headers?: HeadersInit +} + +export type ResponseType = + | 'basic' + | 'cors' + | 'default' + | 'error' + | 'opaque' + | 'opaqueredirect' + +export type ResponseRedirectStatus = 301 | 302 | 303 | 307 | 308 + +export declare class Response implements BodyMixin { + constructor (body?: BodyInit, init?: ResponseInit) + + readonly headers: Headers + readonly ok: boolean + readonly status: number + readonly statusText: string + readonly type: ResponseType + readonly url: string + readonly redirected: boolean + + readonly body: ReadableStream | null + readonly bodyUsed: boolean + + readonly arrayBuffer: () => Promise + readonly blob: () => Promise + readonly formData: () => Promise + readonly json: () => Promise + readonly text: () => Promise + + readonly clone: () => Response + + static error (): Response + static json(data: any, init?: ResponseInit): Response + static redirect (url: string | URL, status: ResponseRedirectStatus): Response +} diff --git a/node_modules/undici-types/file.d.ts b/node_modules/undici-types/file.d.ts new file mode 100644 index 0000000..c695b7a --- /dev/null +++ b/node_modules/undici-types/file.d.ts @@ -0,0 +1,39 @@ +// Based on https://github.com/octet-stream/form-data/blob/2d0f0dc371517444ce1f22cdde13f51995d0953a/lib/File.ts (MIT) +/// + +import { Blob } from 'buffer' + +export interface BlobPropertyBag { + type?: string + endings?: 'native' | 'transparent' +} + +export interface FilePropertyBag extends BlobPropertyBag { + /** + * The last modified date of the file as the number of milliseconds since the Unix epoch (January 1, 1970 at midnight). Files without a known last modified date return the current date. + */ + lastModified?: number +} + +export declare class File extends Blob { + /** + * Creates a new File instance. + * + * @param fileBits An `Array` strings, or [`ArrayBuffer`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/ArrayBuffer), [`ArrayBufferView`](https://developer.mozilla.org/en-US/docs/Web/API/ArrayBufferView), [`Blob`](https://developer.mozilla.org/en-US/docs/Web/API/Blob) objects, or a mix of any of such objects, that will be put inside the [`File`](https://developer.mozilla.org/en-US/docs/Web/API/File). + * @param fileName The name of the file. + * @param options An options object containing optional attributes for the file. + */ + constructor(fileBits: ReadonlyArray, fileName: string, options?: FilePropertyBag) + + /** + * Name of the file referenced by the File object. + */ + readonly name: string + + /** + * The last modified date of the file as the number of milliseconds since the Unix epoch (January 1, 1970 at midnight). Files without a known last modified date return the current date. + */ + readonly lastModified: number + + readonly [Symbol.toStringTag]: string +} diff --git a/node_modules/undici-types/filereader.d.ts b/node_modules/undici-types/filereader.d.ts new file mode 100644 index 0000000..f05d231 --- /dev/null +++ b/node_modules/undici-types/filereader.d.ts @@ -0,0 +1,54 @@ +/// + +import { Blob } from 'buffer' +import { DOMException, Event, EventInit, EventTarget } from './patch' + +export declare class FileReader { + __proto__: EventTarget & FileReader + + constructor () + + readAsArrayBuffer (blob: Blob): void + readAsBinaryString (blob: Blob): void + readAsText (blob: Blob, encoding?: string): void + readAsDataURL (blob: Blob): void + + abort (): void + + static readonly EMPTY = 0 + static readonly LOADING = 1 + static readonly DONE = 2 + + readonly EMPTY = 0 + readonly LOADING = 1 + readonly DONE = 2 + + readonly readyState: number + + readonly result: string | ArrayBuffer | null + + readonly error: DOMException | null + + onloadstart: null | ((this: FileReader, event: ProgressEvent) => void) + onprogress: null | ((this: FileReader, event: ProgressEvent) => void) + onload: null | ((this: FileReader, event: ProgressEvent) => void) + onabort: null | ((this: FileReader, event: ProgressEvent) => void) + onerror: null | ((this: FileReader, event: ProgressEvent) => void) + onloadend: null | ((this: FileReader, event: ProgressEvent) => void) +} + +export interface ProgressEventInit extends EventInit { + lengthComputable?: boolean + loaded?: number + total?: number +} + +export declare class ProgressEvent { + __proto__: Event & ProgressEvent + + constructor (type: string, eventInitDict?: ProgressEventInit) + + readonly lengthComputable: boolean + readonly loaded: number + readonly total: number +} diff --git a/node_modules/undici-types/formdata.d.ts b/node_modules/undici-types/formdata.d.ts new file mode 100644 index 0000000..df29a57 --- /dev/null +++ b/node_modules/undici-types/formdata.d.ts @@ -0,0 +1,108 @@ +// Based on https://github.com/octet-stream/form-data/blob/2d0f0dc371517444ce1f22cdde13f51995d0953a/lib/FormData.ts (MIT) +/// + +import { File } from './file' +import { SpecIterator, SpecIterableIterator } from './fetch' + +/** + * A `string` or `File` that represents a single value from a set of `FormData` key-value pairs. + */ +declare type FormDataEntryValue = string | File + +/** + * Provides a way to easily construct a set of key/value pairs representing form fields and their values, which can then be easily sent using fetch(). + */ +export declare class FormData { + /** + * Appends a new value onto an existing key inside a FormData object, + * or adds the key if it does not already exist. + * + * The difference between `set()` and `append()` is that if the specified key already exists, `set()` will overwrite all existing values with the new one, whereas `append()` will append the new value onto the end of the existing set of values. + * + * @param name The name of the field whose data is contained in `value`. + * @param value The field's value. This can be [`Blob`](https://developer.mozilla.org/en-US/docs/Web/API/Blob) + or [`File`](https://developer.mozilla.org/en-US/docs/Web/API/File). If none of these are specified the value is converted to a string. + * @param fileName The filename reported to the server, when a Blob or File is passed as the second parameter. The default filename for Blob objects is "blob". The default filename for File objects is the file's filename. + */ + append(name: string, value: unknown, fileName?: string): void + + /** + * Set a new value for an existing key inside FormData, + * or add the new field if it does not already exist. + * + * @param name The name of the field whose data is contained in `value`. + * @param value The field's value. This can be [`Blob`](https://developer.mozilla.org/en-US/docs/Web/API/Blob) + or [`File`](https://developer.mozilla.org/en-US/docs/Web/API/File). If none of these are specified the value is converted to a string. + * @param fileName The filename reported to the server, when a Blob or File is passed as the second parameter. The default filename for Blob objects is "blob". The default filename for File objects is the file's filename. + * + */ + set(name: string, value: unknown, fileName?: string): void + + /** + * Returns the first value associated with a given key from within a `FormData` object. + * If you expect multiple values and want all of them, use the `getAll()` method instead. + * + * @param {string} name A name of the value you want to retrieve. + * + * @returns A `FormDataEntryValue` containing the value. If the key doesn't exist, the method returns null. + */ + get(name: string): FormDataEntryValue | null + + /** + * Returns all the values associated with a given key from within a `FormData` object. + * + * @param {string} name A name of the value you want to retrieve. + * + * @returns An array of `FormDataEntryValue` whose key matches the value passed in the `name` parameter. If the key doesn't exist, the method returns an empty list. + */ + getAll(name: string): FormDataEntryValue[] + + /** + * Returns a boolean stating whether a `FormData` object contains a certain key. + * + * @param name A string representing the name of the key you want to test for. + * + * @return A boolean value. + */ + has(name: string): boolean + + /** + * Deletes a key and its value(s) from a `FormData` object. + * + * @param name The name of the key you want to delete. + */ + delete(name: string): void + + /** + * Executes given callback function for each field of the FormData instance + */ + forEach: ( + callbackfn: (value: FormDataEntryValue, key: string, iterable: FormData) => void, + thisArg?: unknown + ) => void + + /** + * Returns an [`iterator`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols) allowing to go through all keys contained in this `FormData` object. + * Each key is a `string`. + */ + keys: () => SpecIterableIterator + + /** + * Returns an [`iterator`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols) allowing to go through all values contained in this object `FormData` object. + * Each value is a [`FormDataValue`](https://developer.mozilla.org/en-US/docs/Web/API/FormDataEntryValue). + */ + values: () => SpecIterableIterator + + /** + * Returns an [`iterator`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols) allowing to go through the `FormData` key/value pairs. + * The key of each pair is a string; the value is a [`FormDataValue`](https://developer.mozilla.org/en-US/docs/Web/API/FormDataEntryValue). + */ + entries: () => SpecIterableIterator<[string, FormDataEntryValue]> + + /** + * An alias for FormData#entries() + */ + [Symbol.iterator]: () => SpecIterableIterator<[string, FormDataEntryValue]> + + readonly [Symbol.toStringTag]: string +} diff --git a/node_modules/undici-types/global-dispatcher.d.ts b/node_modules/undici-types/global-dispatcher.d.ts new file mode 100644 index 0000000..728f95c --- /dev/null +++ b/node_modules/undici-types/global-dispatcher.d.ts @@ -0,0 +1,9 @@ +import Dispatcher from "./dispatcher"; + +export { + getGlobalDispatcher, + setGlobalDispatcher +} + +declare function setGlobalDispatcher(dispatcher: DispatcherImplementation): void; +declare function getGlobalDispatcher(): Dispatcher; diff --git a/node_modules/undici-types/global-origin.d.ts b/node_modules/undici-types/global-origin.d.ts new file mode 100644 index 0000000..322542d --- /dev/null +++ b/node_modules/undici-types/global-origin.d.ts @@ -0,0 +1,7 @@ +export { + setGlobalOrigin, + getGlobalOrigin +} + +declare function setGlobalOrigin(origin: string | URL | undefined): void; +declare function getGlobalOrigin(): URL | undefined; \ No newline at end of file diff --git a/node_modules/undici-types/handlers.d.ts b/node_modules/undici-types/handlers.d.ts new file mode 100644 index 0000000..eb4f5a9 --- /dev/null +++ b/node_modules/undici-types/handlers.d.ts @@ -0,0 +1,9 @@ +import Dispatcher from "./dispatcher"; + +export declare class RedirectHandler implements Dispatcher.DispatchHandlers{ + constructor (dispatch: Dispatcher, maxRedirections: number, opts: Dispatcher.DispatchOptions, handler: Dispatcher.DispatchHandlers) +} + +export declare class DecoratorHandler implements Dispatcher.DispatchHandlers{ + constructor (handler: Dispatcher.DispatchHandlers) +} diff --git a/node_modules/undici-types/header.d.ts b/node_modules/undici-types/header.d.ts new file mode 100644 index 0000000..bfdb329 --- /dev/null +++ b/node_modules/undici-types/header.d.ts @@ -0,0 +1,4 @@ +/** + * The header type declaration of `undici`. + */ +export type IncomingHttpHeaders = Record; diff --git a/node_modules/undici-types/index.d.ts b/node_modules/undici-types/index.d.ts new file mode 100644 index 0000000..4589845 --- /dev/null +++ b/node_modules/undici-types/index.d.ts @@ -0,0 +1,63 @@ +import Dispatcher from'./dispatcher' +import { setGlobalDispatcher, getGlobalDispatcher } from './global-dispatcher' +import { setGlobalOrigin, getGlobalOrigin } from './global-origin' +import Pool from'./pool' +import { RedirectHandler, DecoratorHandler } from './handlers' + +import BalancedPool from './balanced-pool' +import Client from'./client' +import buildConnector from'./connector' +import errors from'./errors' +import Agent from'./agent' +import MockClient from'./mock-client' +import MockPool from'./mock-pool' +import MockAgent from'./mock-agent' +import mockErrors from'./mock-errors' +import ProxyAgent from'./proxy-agent' +import { request, pipeline, stream, connect, upgrade } from './api' + +export * from './cookies' +export * from './fetch' +export * from './file' +export * from './filereader' +export * from './formdata' +export * from './diagnostics-channel' +export * from './websocket' +export * from './content-type' +export * from './cache' +export { Interceptable } from './mock-interceptor' + +export { Dispatcher, BalancedPool, Pool, Client, buildConnector, errors, Agent, request, stream, pipeline, connect, upgrade, setGlobalDispatcher, getGlobalDispatcher, setGlobalOrigin, getGlobalOrigin, MockClient, MockPool, MockAgent, mockErrors, ProxyAgent, RedirectHandler, DecoratorHandler } +export default Undici + +declare namespace Undici { + var Dispatcher: typeof import('./dispatcher').default + var Pool: typeof import('./pool').default; + var RedirectHandler: typeof import ('./handlers').RedirectHandler + var DecoratorHandler: typeof import ('./handlers').DecoratorHandler + var createRedirectInterceptor: typeof import ('./interceptors').createRedirectInterceptor + var BalancedPool: typeof import('./balanced-pool').default; + var Client: typeof import('./client').default; + var buildConnector: typeof import('./connector').default; + var errors: typeof import('./errors').default; + var Agent: typeof import('./agent').default; + var setGlobalDispatcher: typeof import('./global-dispatcher').setGlobalDispatcher; + var getGlobalDispatcher: typeof import('./global-dispatcher').getGlobalDispatcher; + var request: typeof import('./api').request; + var stream: typeof import('./api').stream; + var pipeline: typeof import('./api').pipeline; + var connect: typeof import('./api').connect; + var upgrade: typeof import('./api').upgrade; + var MockClient: typeof import('./mock-client').default; + var MockPool: typeof import('./mock-pool').default; + var MockAgent: typeof import('./mock-agent').default; + var mockErrors: typeof import('./mock-errors').default; + var fetch: typeof import('./fetch').fetch; + var Headers: typeof import('./fetch').Headers; + var Response: typeof import('./fetch').Response; + var Request: typeof import('./fetch').Request; + var FormData: typeof import('./formdata').FormData; + var File: typeof import('./file').File; + var FileReader: typeof import('./filereader').FileReader; + var caches: typeof import('./cache').caches; +} diff --git a/node_modules/undici-types/interceptors.d.ts b/node_modules/undici-types/interceptors.d.ts new file mode 100644 index 0000000..047ac17 --- /dev/null +++ b/node_modules/undici-types/interceptors.d.ts @@ -0,0 +1,5 @@ +import Dispatcher from "./dispatcher"; + +type RedirectInterceptorOpts = { maxRedirections?: number } + +export declare function createRedirectInterceptor (opts: RedirectInterceptorOpts): Dispatcher.DispatchInterceptor diff --git a/node_modules/undici-types/mock-agent.d.ts b/node_modules/undici-types/mock-agent.d.ts new file mode 100644 index 0000000..98cd645 --- /dev/null +++ b/node_modules/undici-types/mock-agent.d.ts @@ -0,0 +1,50 @@ +import Agent from './agent' +import Dispatcher from './dispatcher' +import { Interceptable, MockInterceptor } from './mock-interceptor' +import MockDispatch = MockInterceptor.MockDispatch; + +export default MockAgent + +interface PendingInterceptor extends MockDispatch { + origin: string; +} + +/** A mocked Agent class that implements the Agent API. It allows one to intercept HTTP requests made through undici and return mocked responses instead. */ +declare class MockAgent extends Dispatcher { + constructor(options?: MockAgent.Options) + /** Creates and retrieves mock Dispatcher instances which can then be used to intercept HTTP requests. If the number of connections on the mock agent is set to 1, a MockClient instance is returned. Otherwise a MockPool instance is returned. */ + get(origin: string): TInterceptable; + get(origin: RegExp): TInterceptable; + get(origin: ((origin: string) => boolean)): TInterceptable; + /** Dispatches a mocked request. */ + dispatch(options: Agent.DispatchOptions, handler: Dispatcher.DispatchHandlers): boolean; + /** Closes the mock agent and waits for registered mock pools and clients to also close before resolving. */ + close(): Promise; + /** Disables mocking in MockAgent. */ + deactivate(): void; + /** Enables mocking in a MockAgent instance. When instantiated, a MockAgent is automatically activated. Therefore, this method is only effective after `MockAgent.deactivate` has been called. */ + activate(): void; + /** Define host matchers so only matching requests that aren't intercepted by the mock dispatchers will be attempted. */ + enableNetConnect(): void; + enableNetConnect(host: string): void; + enableNetConnect(host: RegExp): void; + enableNetConnect(host: ((host: string) => boolean)): void; + /** Causes all requests to throw when requests are not matched in a MockAgent intercept. */ + disableNetConnect(): void; + pendingInterceptors(): PendingInterceptor[]; + assertNoPendingInterceptors(options?: { + pendingInterceptorsFormatter?: PendingInterceptorsFormatter; + }): void; +} + +interface PendingInterceptorsFormatter { + format(pendingInterceptors: readonly PendingInterceptor[]): string; +} + +declare namespace MockAgent { + /** MockAgent options. */ + export interface Options extends Agent.Options { + /** A custom agent to be encapsulated by the MockAgent. */ + agent?: Agent; + } +} diff --git a/node_modules/undici-types/mock-client.d.ts b/node_modules/undici-types/mock-client.d.ts new file mode 100644 index 0000000..51d008c --- /dev/null +++ b/node_modules/undici-types/mock-client.d.ts @@ -0,0 +1,25 @@ +import Client from './client' +import Dispatcher from './dispatcher' +import MockAgent from './mock-agent' +import { MockInterceptor, Interceptable } from './mock-interceptor' + +export default MockClient + +/** MockClient extends the Client API and allows one to mock requests. */ +declare class MockClient extends Client implements Interceptable { + constructor(origin: string, options: MockClient.Options); + /** Intercepts any matching requests that use the same origin as this mock client. */ + intercept(options: MockInterceptor.Options): MockInterceptor; + /** Dispatches a mocked request. */ + dispatch(options: Dispatcher.DispatchOptions, handlers: Dispatcher.DispatchHandlers): boolean; + /** Closes the mock client and gracefully waits for enqueued requests to complete. */ + close(): Promise; +} + +declare namespace MockClient { + /** MockClient options. */ + export interface Options extends Client.Options { + /** The agent to associate this MockClient with. */ + agent: MockAgent; + } +} diff --git a/node_modules/undici-types/mock-errors.d.ts b/node_modules/undici-types/mock-errors.d.ts new file mode 100644 index 0000000..3d9e727 --- /dev/null +++ b/node_modules/undici-types/mock-errors.d.ts @@ -0,0 +1,12 @@ +import Errors from './errors' + +export default MockErrors + +declare namespace MockErrors { + /** The request does not match any registered mock dispatches. */ + export class MockNotMatchedError extends Errors.UndiciError { + constructor(message?: string); + name: 'MockNotMatchedError'; + code: 'UND_MOCK_ERR_MOCK_NOT_MATCHED'; + } +} diff --git a/node_modules/undici-types/mock-interceptor.d.ts b/node_modules/undici-types/mock-interceptor.d.ts new file mode 100644 index 0000000..6b3961c --- /dev/null +++ b/node_modules/undici-types/mock-interceptor.d.ts @@ -0,0 +1,93 @@ +import { IncomingHttpHeaders } from './header' +import Dispatcher from './dispatcher'; +import { BodyInit, Headers } from './fetch' + +export { + Interceptable, + MockInterceptor, + MockScope +} + +/** The scope associated with a mock dispatch. */ +declare class MockScope { + constructor(mockDispatch: MockInterceptor.MockDispatch); + /** Delay a reply by a set amount of time in ms. */ + delay(waitInMs: number): MockScope; + /** Persist the defined mock data for the associated reply. It will return the defined mock data indefinitely. */ + persist(): MockScope; + /** Define a reply for a set amount of matching requests. */ + times(repeatTimes: number): MockScope; +} + +/** The interceptor for a Mock. */ +declare class MockInterceptor { + constructor(options: MockInterceptor.Options, mockDispatches: MockInterceptor.MockDispatch[]); + /** Mock an undici request with the defined reply. */ + reply(replyOptionsCallback: MockInterceptor.MockReplyOptionsCallback): MockScope; + reply( + statusCode: number, + data?: TData | Buffer | string | MockInterceptor.MockResponseDataHandler, + responseOptions?: MockInterceptor.MockResponseOptions + ): MockScope; + /** Mock an undici request by throwing the defined reply error. */ + replyWithError(error: TError): MockScope; + /** Set default reply headers on the interceptor for subsequent mocked replies. */ + defaultReplyHeaders(headers: IncomingHttpHeaders): MockInterceptor; + /** Set default reply trailers on the interceptor for subsequent mocked replies. */ + defaultReplyTrailers(trailers: Record): MockInterceptor; + /** Set automatically calculated content-length header on subsequent mocked replies. */ + replyContentLength(): MockInterceptor; +} + +declare namespace MockInterceptor { + /** MockInterceptor options. */ + export interface Options { + /** Path to intercept on. */ + path: string | RegExp | ((path: string) => boolean); + /** Method to intercept on. Defaults to GET. */ + method?: string | RegExp | ((method: string) => boolean); + /** Body to intercept on. */ + body?: string | RegExp | ((body: string) => boolean); + /** Headers to intercept on. */ + headers?: Record boolean)> | ((headers: Record) => boolean); + /** Query params to intercept on */ + query?: Record; + } + export interface MockDispatch extends Options { + times: number | null; + persist: boolean; + consumed: boolean; + data: MockDispatchData; + } + export interface MockDispatchData extends MockResponseOptions { + error: TError | null; + statusCode?: number; + data?: TData | string; + } + export interface MockResponseOptions { + headers?: IncomingHttpHeaders; + trailers?: Record; + } + + export interface MockResponseCallbackOptions { + path: string; + origin: string; + method: string; + body?: BodyInit | Dispatcher.DispatchOptions['body']; + headers: Headers | Record; + maxRedirections: number; + } + + export type MockResponseDataHandler = ( + opts: MockResponseCallbackOptions + ) => TData | Buffer | string; + + export type MockReplyOptionsCallback = ( + opts: MockResponseCallbackOptions + ) => { statusCode: number, data?: TData | Buffer | string, responseOptions?: MockResponseOptions } +} + +interface Interceptable extends Dispatcher { + /** Intercepts any matching requests that use the same origin as this mock client. */ + intercept(options: MockInterceptor.Options): MockInterceptor; +} diff --git a/node_modules/undici-types/mock-pool.d.ts b/node_modules/undici-types/mock-pool.d.ts new file mode 100644 index 0000000..39e709a --- /dev/null +++ b/node_modules/undici-types/mock-pool.d.ts @@ -0,0 +1,25 @@ +import Pool from './pool' +import MockAgent from './mock-agent' +import { Interceptable, MockInterceptor } from './mock-interceptor' +import Dispatcher from './dispatcher' + +export default MockPool + +/** MockPool extends the Pool API and allows one to mock requests. */ +declare class MockPool extends Pool implements Interceptable { + constructor(origin: string, options: MockPool.Options); + /** Intercepts any matching requests that use the same origin as this mock pool. */ + intercept(options: MockInterceptor.Options): MockInterceptor; + /** Dispatches a mocked request. */ + dispatch(options: Dispatcher.DispatchOptions, handlers: Dispatcher.DispatchHandlers): boolean; + /** Closes the mock pool and gracefully waits for enqueued requests to complete. */ + close(): Promise; +} + +declare namespace MockPool { + /** MockPool options. */ + export interface Options extends Pool.Options { + /** The agent to associate this MockPool with. */ + agent: MockAgent; + } +} diff --git a/node_modules/undici-types/package.json b/node_modules/undici-types/package.json new file mode 100644 index 0000000..be7aa4c --- /dev/null +++ b/node_modules/undici-types/package.json @@ -0,0 +1,55 @@ +{ + "name": "undici-types", + "version": "5.26.5", + "description": "A stand-alone types package for Undici", + "homepage": "https://undici.nodejs.org", + "bugs": { + "url": "https://github.com/nodejs/undici/issues" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/nodejs/undici.git" + }, + "license": "MIT", + "types": "index.d.ts", + "files": [ + "*.d.ts" + ], + "contributors": [ + { + "name": "Daniele Belardi", + "url": "https://github.com/dnlup", + "author": true + }, + { + "name": "Ethan Arrowood", + "url": "https://github.com/ethan-arrowood", + "author": true + }, + { + "name": "Matteo Collina", + "url": "https://github.com/mcollina", + "author": true + }, + { + "name": "Matthew Aitken", + "url": "https://github.com/KhafraDev", + "author": true + }, + { + "name": "Robert Nagy", + "url": "https://github.com/ronag", + "author": true + }, + { + "name": "Szymon Marczak", + "url": "https://github.com/szmarczak", + "author": true + }, + { + "name": "Tomas Della Vedova", + "url": "https://github.com/delvedor", + "author": true + } + ] +} \ No newline at end of file diff --git a/node_modules/undici-types/patch.d.ts b/node_modules/undici-types/patch.d.ts new file mode 100644 index 0000000..3871acf --- /dev/null +++ b/node_modules/undici-types/patch.d.ts @@ -0,0 +1,71 @@ +/// + +// See https://github.com/nodejs/undici/issues/1740 + +export type DOMException = typeof globalThis extends { DOMException: infer T } + ? T + : any + +export type EventTarget = typeof globalThis extends { EventTarget: infer T } + ? T + : { + addEventListener( + type: string, + listener: any, + options?: any, + ): void + dispatchEvent(event: Event): boolean + removeEventListener( + type: string, + listener: any, + options?: any | boolean, + ): void + } + +export type Event = typeof globalThis extends { Event: infer T } + ? T + : { + readonly bubbles: boolean + cancelBubble: () => void + readonly cancelable: boolean + readonly composed: boolean + composedPath(): [EventTarget?] + readonly currentTarget: EventTarget | null + readonly defaultPrevented: boolean + readonly eventPhase: 0 | 2 + readonly isTrusted: boolean + preventDefault(): void + returnValue: boolean + readonly srcElement: EventTarget | null + stopImmediatePropagation(): void + stopPropagation(): void + readonly target: EventTarget | null + readonly timeStamp: number + readonly type: string + } + +export interface EventInit { + bubbles?: boolean + cancelable?: boolean + composed?: boolean +} + +export interface EventListenerOptions { + capture?: boolean +} + +export interface AddEventListenerOptions extends EventListenerOptions { + once?: boolean + passive?: boolean + signal?: AbortSignal +} + +export type EventListenerOrEventListenerObject = EventListener | EventListenerObject + +export interface EventListenerObject { + handleEvent (object: Event): void +} + +export interface EventListener { + (evt: Event): void +} diff --git a/node_modules/undici-types/pool-stats.d.ts b/node_modules/undici-types/pool-stats.d.ts new file mode 100644 index 0000000..8b6d2bf --- /dev/null +++ b/node_modules/undici-types/pool-stats.d.ts @@ -0,0 +1,19 @@ +import Pool from "./pool" + +export default PoolStats + +declare class PoolStats { + constructor(pool: Pool); + /** Number of open socket connections in this pool. */ + connected: number; + /** Number of open socket connections in this pool that do not have an active request. */ + free: number; + /** Number of pending requests across all clients in this pool. */ + pending: number; + /** Number of queued requests across all clients in this pool. */ + queued: number; + /** Number of currently active requests across all clients in this pool. */ + running: number; + /** Number of active, pending, or queued requests across all clients in this pool. */ + size: number; +} diff --git a/node_modules/undici-types/pool.d.ts b/node_modules/undici-types/pool.d.ts new file mode 100644 index 0000000..7747d48 --- /dev/null +++ b/node_modules/undici-types/pool.d.ts @@ -0,0 +1,28 @@ +import Client from './client' +import TPoolStats from './pool-stats' +import { URL } from 'url' +import Dispatcher from "./dispatcher"; + +export default Pool + +declare class Pool extends Dispatcher { + constructor(url: string | URL, options?: Pool.Options) + /** `true` after `pool.close()` has been called. */ + closed: boolean; + /** `true` after `pool.destroyed()` has been called or `pool.close()` has been called and the pool shutdown has completed. */ + destroyed: boolean; + /** Aggregate stats for a Pool. */ + readonly stats: TPoolStats; +} + +declare namespace Pool { + export type PoolStats = TPoolStats; + export interface Options extends Client.Options { + /** Default: `(origin, opts) => new Client(origin, opts)`. */ + factory?(origin: URL, opts: object): Dispatcher; + /** The max number of clients to create. `null` if no limit. Default `null`. */ + connections?: number | null; + + interceptors?: { Pool?: readonly Dispatcher.DispatchInterceptor[] } & Client.Options["interceptors"] + } +} diff --git a/node_modules/undici-types/proxy-agent.d.ts b/node_modules/undici-types/proxy-agent.d.ts new file mode 100644 index 0000000..96b2638 --- /dev/null +++ b/node_modules/undici-types/proxy-agent.d.ts @@ -0,0 +1,30 @@ +import Agent from './agent' +import buildConnector from './connector'; +import Client from './client' +import Dispatcher from './dispatcher' +import { IncomingHttpHeaders } from './header' +import Pool from './pool' + +export default ProxyAgent + +declare class ProxyAgent extends Dispatcher { + constructor(options: ProxyAgent.Options | string) + + dispatch(options: Agent.DispatchOptions, handler: Dispatcher.DispatchHandlers): boolean; + close(): Promise; +} + +declare namespace ProxyAgent { + export interface Options extends Agent.Options { + uri: string; + /** + * @deprecated use opts.token + */ + auth?: string; + token?: string; + headers?: IncomingHttpHeaders; + requestTls?: buildConnector.BuildOptions; + proxyTls?: buildConnector.BuildOptions; + clientFactory?(origin: URL, opts: object): Dispatcher; + } +} diff --git a/node_modules/undici-types/readable.d.ts b/node_modules/undici-types/readable.d.ts new file mode 100644 index 0000000..4549a8c --- /dev/null +++ b/node_modules/undici-types/readable.d.ts @@ -0,0 +1,61 @@ +import { Readable } from "stream"; +import { Blob } from 'buffer' + +export default BodyReadable + +declare class BodyReadable extends Readable { + constructor( + resume?: (this: Readable, size: number) => void | null, + abort?: () => void | null, + contentType?: string + ) + + /** Consumes and returns the body as a string + * https://fetch.spec.whatwg.org/#dom-body-text + */ + text(): Promise + + /** Consumes and returns the body as a JavaScript Object + * https://fetch.spec.whatwg.org/#dom-body-json + */ + json(): Promise + + /** Consumes and returns the body as a Blob + * https://fetch.spec.whatwg.org/#dom-body-blob + */ + blob(): Promise + + /** Consumes and returns the body as an ArrayBuffer + * https://fetch.spec.whatwg.org/#dom-body-arraybuffer + */ + arrayBuffer(): Promise + + /** Not implemented + * + * https://fetch.spec.whatwg.org/#dom-body-formdata + */ + formData(): Promise + + /** Returns true if the body is not null and the body has been consumed + * + * Otherwise, returns false + * + * https://fetch.spec.whatwg.org/#dom-body-bodyused + */ + readonly bodyUsed: boolean + + /** Throws on node 16.6.0 + * + * If body is null, it should return null as the body + * + * If body is not null, should return the body as a ReadableStream + * + * https://fetch.spec.whatwg.org/#dom-body-body + */ + readonly body: never | undefined + + /** Dumps the response body by reading `limit` number of bytes. + * @param opts.limit Number of bytes to read (optional) - Default: 262144 + */ + dump(opts?: { limit: number }): Promise +} diff --git a/node_modules/undici-types/webidl.d.ts b/node_modules/undici-types/webidl.d.ts new file mode 100644 index 0000000..40cfe06 --- /dev/null +++ b/node_modules/undici-types/webidl.d.ts @@ -0,0 +1,220 @@ +// These types are not exported, and are only used internally + +/** + * Take in an unknown value and return one that is of type T + */ +type Converter = (object: unknown) => T + +type SequenceConverter = (object: unknown) => T[] + +type RecordConverter = (object: unknown) => Record + +interface ConvertToIntOpts { + clamp?: boolean + enforceRange?: boolean +} + +interface WebidlErrors { + exception (opts: { header: string, message: string }): TypeError + /** + * @description Throw an error when conversion from one type to another has failed + */ + conversionFailed (opts: { + prefix: string + argument: string + types: string[] + }): TypeError + /** + * @description Throw an error when an invalid argument is provided + */ + invalidArgument (opts: { + prefix: string + value: string + type: string + }): TypeError +} + +interface WebidlUtil { + /** + * @see https://tc39.es/ecma262/#sec-ecmascript-data-types-and-values + */ + Type (object: unknown): + | 'Undefined' + | 'Boolean' + | 'String' + | 'Symbol' + | 'Number' + | 'BigInt' + | 'Null' + | 'Object' + + /** + * @see https://webidl.spec.whatwg.org/#abstract-opdef-converttoint + */ + ConvertToInt ( + V: unknown, + bitLength: number, + signedness: 'signed' | 'unsigned', + opts?: ConvertToIntOpts + ): number + + /** + * @see https://webidl.spec.whatwg.org/#abstract-opdef-converttoint + */ + IntegerPart (N: number): number +} + +interface WebidlConverters { + /** + * @see https://webidl.spec.whatwg.org/#es-DOMString + */ + DOMString (V: unknown, opts?: { + legacyNullToEmptyString: boolean + }): string + + /** + * @see https://webidl.spec.whatwg.org/#es-ByteString + */ + ByteString (V: unknown): string + + /** + * @see https://webidl.spec.whatwg.org/#es-USVString + */ + USVString (V: unknown): string + + /** + * @see https://webidl.spec.whatwg.org/#es-boolean + */ + boolean (V: unknown): boolean + + /** + * @see https://webidl.spec.whatwg.org/#es-any + */ + any (V: Value): Value + + /** + * @see https://webidl.spec.whatwg.org/#es-long-long + */ + ['long long'] (V: unknown): number + + /** + * @see https://webidl.spec.whatwg.org/#es-unsigned-long-long + */ + ['unsigned long long'] (V: unknown): number + + /** + * @see https://webidl.spec.whatwg.org/#es-unsigned-long + */ + ['unsigned long'] (V: unknown): number + + /** + * @see https://webidl.spec.whatwg.org/#es-unsigned-short + */ + ['unsigned short'] (V: unknown, opts?: ConvertToIntOpts): number + + /** + * @see https://webidl.spec.whatwg.org/#idl-ArrayBuffer + */ + ArrayBuffer (V: unknown): ArrayBufferLike + ArrayBuffer (V: unknown, opts: { allowShared: false }): ArrayBuffer + + /** + * @see https://webidl.spec.whatwg.org/#es-buffer-source-types + */ + TypedArray ( + V: unknown, + TypedArray: NodeJS.TypedArray | ArrayBufferLike + ): NodeJS.TypedArray | ArrayBufferLike + TypedArray ( + V: unknown, + TypedArray: NodeJS.TypedArray | ArrayBufferLike, + opts?: { allowShared: false } + ): NodeJS.TypedArray | ArrayBuffer + + /** + * @see https://webidl.spec.whatwg.org/#es-buffer-source-types + */ + DataView (V: unknown, opts?: { allowShared: boolean }): DataView + + /** + * @see https://webidl.spec.whatwg.org/#BufferSource + */ + BufferSource ( + V: unknown, + opts?: { allowShared: boolean } + ): NodeJS.TypedArray | ArrayBufferLike | DataView + + ['sequence']: SequenceConverter + + ['sequence>']: SequenceConverter + + ['record']: RecordConverter + + [Key: string]: (...args: any[]) => unknown +} + +export interface Webidl { + errors: WebidlErrors + util: WebidlUtil + converters: WebidlConverters + + /** + * @description Performs a brand-check on {@param V} to ensure it is a + * {@param cls} object. + */ + brandCheck (V: unknown, cls: Interface, opts?: { strict?: boolean }): asserts V is Interface + + /** + * @see https://webidl.spec.whatwg.org/#es-sequence + * @description Convert a value, V, to a WebIDL sequence type. + */ + sequenceConverter (C: Converter): SequenceConverter + + illegalConstructor (): never + + /** + * @see https://webidl.spec.whatwg.org/#es-to-record + * @description Convert a value, V, to a WebIDL record type. + */ + recordConverter ( + keyConverter: Converter, + valueConverter: Converter + ): RecordConverter + + /** + * Similar to {@link Webidl.brandCheck} but allows skipping the check if third party + * interfaces are allowed. + */ + interfaceConverter (cls: Interface): ( + V: unknown, + opts?: { strict: boolean } + ) => asserts V is typeof cls + + // TODO(@KhafraDev): a type could likely be implemented that can infer the return type + // from the converters given? + /** + * Converts a value, V, to a WebIDL dictionary types. Allows limiting which keys are + * allowed, values allowed, optional and required keys. Auto converts the value to + * a type given a converter. + */ + dictionaryConverter (converters: { + key: string, + defaultValue?: unknown, + required?: boolean, + converter: (...args: unknown[]) => unknown, + allowedValues?: unknown[] + }[]): (V: unknown) => Record + + /** + * @see https://webidl.spec.whatwg.org/#idl-nullable-type + * @description allows a type, V, to be null + */ + nullableConverter ( + converter: Converter + ): (V: unknown) => ReturnType | null + + argumentLengthCheck (args: { length: number }, min: number, context: { + header: string + message?: string + }): void +} diff --git a/node_modules/undici-types/websocket.d.ts b/node_modules/undici-types/websocket.d.ts new file mode 100644 index 0000000..15a357d --- /dev/null +++ b/node_modules/undici-types/websocket.d.ts @@ -0,0 +1,131 @@ +/// + +import type { Blob } from 'buffer' +import type { MessagePort } from 'worker_threads' +import { + EventTarget, + Event, + EventInit, + EventListenerOptions, + AddEventListenerOptions, + EventListenerOrEventListenerObject +} from './patch' +import Dispatcher from './dispatcher' +import { HeadersInit } from './fetch' + +export type BinaryType = 'blob' | 'arraybuffer' + +interface WebSocketEventMap { + close: CloseEvent + error: Event + message: MessageEvent + open: Event +} + +interface WebSocket extends EventTarget { + binaryType: BinaryType + + readonly bufferedAmount: number + readonly extensions: string + + onclose: ((this: WebSocket, ev: WebSocketEventMap['close']) => any) | null + onerror: ((this: WebSocket, ev: WebSocketEventMap['error']) => any) | null + onmessage: ((this: WebSocket, ev: WebSocketEventMap['message']) => any) | null + onopen: ((this: WebSocket, ev: WebSocketEventMap['open']) => any) | null + + readonly protocol: string + readonly readyState: number + readonly url: string + + close(code?: number, reason?: string): void + send(data: string | ArrayBufferLike | Blob | ArrayBufferView): void + + readonly CLOSED: number + readonly CLOSING: number + readonly CONNECTING: number + readonly OPEN: number + + addEventListener( + type: K, + listener: (this: WebSocket, ev: WebSocketEventMap[K]) => any, + options?: boolean | AddEventListenerOptions + ): void + addEventListener( + type: string, + listener: EventListenerOrEventListenerObject, + options?: boolean | AddEventListenerOptions + ): void + removeEventListener( + type: K, + listener: (this: WebSocket, ev: WebSocketEventMap[K]) => any, + options?: boolean | EventListenerOptions + ): void + removeEventListener( + type: string, + listener: EventListenerOrEventListenerObject, + options?: boolean | EventListenerOptions + ): void +} + +export declare const WebSocket: { + prototype: WebSocket + new (url: string | URL, protocols?: string | string[] | WebSocketInit): WebSocket + readonly CLOSED: number + readonly CLOSING: number + readonly CONNECTING: number + readonly OPEN: number +} + +interface CloseEventInit extends EventInit { + code?: number + reason?: string + wasClean?: boolean +} + +interface CloseEvent extends Event { + readonly code: number + readonly reason: string + readonly wasClean: boolean +} + +export declare const CloseEvent: { + prototype: CloseEvent + new (type: string, eventInitDict?: CloseEventInit): CloseEvent +} + +interface MessageEventInit extends EventInit { + data?: T + lastEventId?: string + origin?: string + ports?: (typeof MessagePort)[] + source?: typeof MessagePort | null +} + +interface MessageEvent extends Event { + readonly data: T + readonly lastEventId: string + readonly origin: string + readonly ports: ReadonlyArray + readonly source: typeof MessagePort | null + initMessageEvent( + type: string, + bubbles?: boolean, + cancelable?: boolean, + data?: any, + origin?: string, + lastEventId?: string, + source?: typeof MessagePort | null, + ports?: (typeof MessagePort)[] + ): void; +} + +export declare const MessageEvent: { + prototype: MessageEvent + new(type: string, eventInitDict?: MessageEventInit): MessageEvent +} + +interface WebSocketInit { + protocols?: string | string[], + dispatcher?: Dispatcher, + headers?: HeadersInit +} diff --git a/node_modules/wrap-ansi/index.js b/node_modules/wrap-ansi/index.js new file mode 100755 index 0000000..d502255 --- /dev/null +++ b/node_modules/wrap-ansi/index.js @@ -0,0 +1,216 @@ +'use strict'; +const stringWidth = require('string-width'); +const stripAnsi = require('strip-ansi'); +const ansiStyles = require('ansi-styles'); + +const ESCAPES = new Set([ + '\u001B', + '\u009B' +]); + +const END_CODE = 39; + +const ANSI_ESCAPE_BELL = '\u0007'; +const ANSI_CSI = '['; +const ANSI_OSC = ']'; +const ANSI_SGR_TERMINATOR = 'm'; +const ANSI_ESCAPE_LINK = `${ANSI_OSC}8;;`; + +const wrapAnsi = code => `${ESCAPES.values().next().value}${ANSI_CSI}${code}${ANSI_SGR_TERMINATOR}`; +const wrapAnsiHyperlink = uri => `${ESCAPES.values().next().value}${ANSI_ESCAPE_LINK}${uri}${ANSI_ESCAPE_BELL}`; + +// Calculate the length of words split on ' ', ignoring +// the extra characters added by ansi escape codes +const wordLengths = string => string.split(' ').map(character => stringWidth(character)); + +// Wrap a long word across multiple rows +// Ansi escape codes do not count towards length +const wrapWord = (rows, word, columns) => { + const characters = [...word]; + + let isInsideEscape = false; + let isInsideLinkEscape = false; + let visible = stringWidth(stripAnsi(rows[rows.length - 1])); + + for (const [index, character] of characters.entries()) { + const characterLength = stringWidth(character); + + if (visible + characterLength <= columns) { + rows[rows.length - 1] += character; + } else { + rows.push(character); + visible = 0; + } + + if (ESCAPES.has(character)) { + isInsideEscape = true; + isInsideLinkEscape = characters.slice(index + 1).join('').startsWith(ANSI_ESCAPE_LINK); + } + + if (isInsideEscape) { + if (isInsideLinkEscape) { + if (character === ANSI_ESCAPE_BELL) { + isInsideEscape = false; + isInsideLinkEscape = false; + } + } else if (character === ANSI_SGR_TERMINATOR) { + isInsideEscape = false; + } + + continue; + } + + visible += characterLength; + + if (visible === columns && index < characters.length - 1) { + rows.push(''); + visible = 0; + } + } + + // It's possible that the last row we copy over is only + // ansi escape characters, handle this edge-case + if (!visible && rows[rows.length - 1].length > 0 && rows.length > 1) { + rows[rows.length - 2] += rows.pop(); + } +}; + +// Trims spaces from a string ignoring invisible sequences +const stringVisibleTrimSpacesRight = string => { + const words = string.split(' '); + let last = words.length; + + while (last > 0) { + if (stringWidth(words[last - 1]) > 0) { + break; + } + + last--; + } + + if (last === words.length) { + return string; + } + + return words.slice(0, last).join(' ') + words.slice(last).join(''); +}; + +// The wrap-ansi module can be invoked in either 'hard' or 'soft' wrap mode +// +// 'hard' will never allow a string to take up more than columns characters +// +// 'soft' allows long words to expand past the column length +const exec = (string, columns, options = {}) => { + if (options.trim !== false && string.trim() === '') { + return ''; + } + + let returnValue = ''; + let escapeCode; + let escapeUrl; + + const lengths = wordLengths(string); + let rows = ['']; + + for (const [index, word] of string.split(' ').entries()) { + if (options.trim !== false) { + rows[rows.length - 1] = rows[rows.length - 1].trimStart(); + } + + let rowLength = stringWidth(rows[rows.length - 1]); + + if (index !== 0) { + if (rowLength >= columns && (options.wordWrap === false || options.trim === false)) { + // If we start with a new word but the current row length equals the length of the columns, add a new row + rows.push(''); + rowLength = 0; + } + + if (rowLength > 0 || options.trim === false) { + rows[rows.length - 1] += ' '; + rowLength++; + } + } + + // In 'hard' wrap mode, the length of a line is never allowed to extend past 'columns' + if (options.hard && lengths[index] > columns) { + const remainingColumns = (columns - rowLength); + const breaksStartingThisLine = 1 + Math.floor((lengths[index] - remainingColumns - 1) / columns); + const breaksStartingNextLine = Math.floor((lengths[index] - 1) / columns); + if (breaksStartingNextLine < breaksStartingThisLine) { + rows.push(''); + } + + wrapWord(rows, word, columns); + continue; + } + + if (rowLength + lengths[index] > columns && rowLength > 0 && lengths[index] > 0) { + if (options.wordWrap === false && rowLength < columns) { + wrapWord(rows, word, columns); + continue; + } + + rows.push(''); + } + + if (rowLength + lengths[index] > columns && options.wordWrap === false) { + wrapWord(rows, word, columns); + continue; + } + + rows[rows.length - 1] += word; + } + + if (options.trim !== false) { + rows = rows.map(stringVisibleTrimSpacesRight); + } + + const pre = [...rows.join('\n')]; + + for (const [index, character] of pre.entries()) { + returnValue += character; + + if (ESCAPES.has(character)) { + const {groups} = new RegExp(`(?:\\${ANSI_CSI}(?\\d+)m|\\${ANSI_ESCAPE_LINK}(?.*)${ANSI_ESCAPE_BELL})`).exec(pre.slice(index).join('')) || {groups: {}}; + if (groups.code !== undefined) { + const code = Number.parseFloat(groups.code); + escapeCode = code === END_CODE ? undefined : code; + } else if (groups.uri !== undefined) { + escapeUrl = groups.uri.length === 0 ? undefined : groups.uri; + } + } + + const code = ansiStyles.codes.get(Number(escapeCode)); + + if (pre[index + 1] === '\n') { + if (escapeUrl) { + returnValue += wrapAnsiHyperlink(''); + } + + if (escapeCode && code) { + returnValue += wrapAnsi(code); + } + } else if (character === '\n') { + if (escapeCode && code) { + returnValue += wrapAnsi(escapeCode); + } + + if (escapeUrl) { + returnValue += wrapAnsiHyperlink(escapeUrl); + } + } + } + + return returnValue; +}; + +// For each newline, invoke the method separately +module.exports = (string, columns, options) => { + return String(string) + .normalize() + .replace(/\r\n/g, '\n') + .split('\n') + .map(line => exec(line, columns, options)) + .join('\n'); +}; diff --git a/node_modules/wrap-ansi/license b/node_modules/wrap-ansi/license new file mode 100644 index 0000000..fa7ceba --- /dev/null +++ b/node_modules/wrap-ansi/license @@ -0,0 +1,9 @@ +MIT License + +Copyright (c) Sindre Sorhus (https://sindresorhus.com) + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/node_modules/wrap-ansi/package.json b/node_modules/wrap-ansi/package.json new file mode 100644 index 0000000..dfb2f4f --- /dev/null +++ b/node_modules/wrap-ansi/package.json @@ -0,0 +1,62 @@ +{ + "name": "wrap-ansi", + "version": "7.0.0", + "description": "Wordwrap a string with ANSI escape codes", + "license": "MIT", + "repository": "chalk/wrap-ansi", + "funding": "https://github.com/chalk/wrap-ansi?sponsor=1", + "author": { + "name": "Sindre Sorhus", + "email": "sindresorhus@gmail.com", + "url": "https://sindresorhus.com" + }, + "engines": { + "node": ">=10" + }, + "scripts": { + "test": "xo && nyc ava" + }, + "files": [ + "index.js" + ], + "keywords": [ + "wrap", + "break", + "wordwrap", + "wordbreak", + "linewrap", + "ansi", + "styles", + "color", + "colour", + "colors", + "terminal", + "console", + "cli", + "string", + "tty", + "escape", + "formatting", + "rgb", + "256", + "shell", + "xterm", + "log", + "logging", + "command-line", + "text" + ], + "dependencies": { + "ansi-styles": "^4.0.0", + "string-width": "^4.1.0", + "strip-ansi": "^6.0.0" + }, + "devDependencies": { + "ava": "^2.1.0", + "chalk": "^4.0.0", + "coveralls": "^3.0.3", + "has-ansi": "^4.0.0", + "nyc": "^15.0.1", + "xo": "^0.29.1" + } +} diff --git a/node_modules/wrap-ansi/readme.md b/node_modules/wrap-ansi/readme.md new file mode 100644 index 0000000..68779ba --- /dev/null +++ b/node_modules/wrap-ansi/readme.md @@ -0,0 +1,91 @@ +# wrap-ansi [![Build Status](https://travis-ci.com/chalk/wrap-ansi.svg?branch=master)](https://travis-ci.com/chalk/wrap-ansi) [![Coverage Status](https://coveralls.io/repos/github/chalk/wrap-ansi/badge.svg?branch=master)](https://coveralls.io/github/chalk/wrap-ansi?branch=master) + +> Wordwrap a string with [ANSI escape codes](https://en.wikipedia.org/wiki/ANSI_escape_code#Colors_and_Styles) + +## Install + +``` +$ npm install wrap-ansi +``` + +## Usage + +```js +const chalk = require('chalk'); +const wrapAnsi = require('wrap-ansi'); + +const input = 'The quick brown ' + chalk.red('fox jumped over ') + + 'the lazy ' + chalk.green('dog and then ran away with the unicorn.'); + +console.log(wrapAnsi(input, 20)); +``` + + + +## API + +### wrapAnsi(string, columns, options?) + +Wrap words to the specified column width. + +#### string + +Type: `string` + +String with ANSI escape codes. Like one styled by [`chalk`](https://github.com/chalk/chalk). Newline characters will be normalized to `\n`. + +#### columns + +Type: `number` + +Number of columns to wrap the text to. + +#### options + +Type: `object` + +##### hard + +Type: `boolean`\ +Default: `false` + +By default the wrap is soft, meaning long words may extend past the column width. Setting this to `true` will make it hard wrap at the column width. + +##### wordWrap + +Type: `boolean`\ +Default: `true` + +By default, an attempt is made to split words at spaces, ensuring that they don't extend past the configured columns. If wordWrap is `false`, each column will instead be completely filled splitting words as necessary. + +##### trim + +Type: `boolean`\ +Default: `true` + +Whitespace on all lines is removed by default. Set this option to `false` if you don't want to trim. + +## Related + +- [slice-ansi](https://github.com/chalk/slice-ansi) - Slice a string with ANSI escape codes +- [cli-truncate](https://github.com/sindresorhus/cli-truncate) - Truncate a string to a specific width in the terminal +- [chalk](https://github.com/chalk/chalk) - Terminal string styling done right +- [jsesc](https://github.com/mathiasbynens/jsesc) - Generate ASCII-only output from Unicode strings. Useful for creating test fixtures. + +## Maintainers + +- [Sindre Sorhus](https://github.com/sindresorhus) +- [Josh Junon](https://github.com/qix-) +- [Benjamin Coe](https://github.com/bcoe) + +--- + +
+ + Get professional support for this package with a Tidelift subscription + +
+ + Tidelift helps make open source sustainable for maintainers while giving companies
assurances about security, maintenance, and licensing for their dependencies. +
+
diff --git a/node_modules/y18n/CHANGELOG.md b/node_modules/y18n/CHANGELOG.md new file mode 100644 index 0000000..244d838 --- /dev/null +++ b/node_modules/y18n/CHANGELOG.md @@ -0,0 +1,100 @@ +# Change Log + +All notable changes to this project will be documented in this file. See [standard-version](https://github.com/conventional-changelog/standard-version) for commit guidelines. + +### [5.0.8](https://www.github.com/yargs/y18n/compare/v5.0.7...v5.0.8) (2021-04-07) + + +### Bug Fixes + +* **deno:** force modern release for Deno ([b1c215a](https://www.github.com/yargs/y18n/commit/b1c215aed714bee5830e76de3e335504dc2c4dab)) + +### [5.0.7](https://www.github.com/yargs/y18n/compare/v5.0.6...v5.0.7) (2021-04-07) + + +### Bug Fixes + +* **deno:** force release for deno ([#121](https://www.github.com/yargs/y18n/issues/121)) ([d3f2560](https://www.github.com/yargs/y18n/commit/d3f2560e6cedf2bfa2352e9eec044da53f9a06b2)) + +### [5.0.6](https://www.github.com/yargs/y18n/compare/v5.0.5...v5.0.6) (2021-04-05) + + +### Bug Fixes + +* **webpack:** skip readFileSync if not defined ([#117](https://www.github.com/yargs/y18n/issues/117)) ([6966fa9](https://www.github.com/yargs/y18n/commit/6966fa91d2881cc6a6c531e836099e01f4da1616)) + +### [5.0.5](https://www.github.com/yargs/y18n/compare/v5.0.4...v5.0.5) (2020-10-25) + + +### Bug Fixes + +* address prototype pollution issue ([#108](https://www.github.com/yargs/y18n/issues/108)) ([a9ac604](https://www.github.com/yargs/y18n/commit/a9ac604abf756dec9687be3843e2c93bfe581f25)) + +### [5.0.4](https://www.github.com/yargs/y18n/compare/v5.0.3...v5.0.4) (2020-10-16) + + +### Bug Fixes + +* **exports:** node 13.0 and 13.1 require the dotted object form _with_ a string fallback ([#105](https://www.github.com/yargs/y18n/issues/105)) ([4f85d80](https://www.github.com/yargs/y18n/commit/4f85d80dbaae6d2c7899ae394f7ad97805df4886)) + +### [5.0.3](https://www.github.com/yargs/y18n/compare/v5.0.2...v5.0.3) (2020-10-16) + + +### Bug Fixes + +* **exports:** node 13.0-13.6 require a string fallback ([#103](https://www.github.com/yargs/y18n/issues/103)) ([e39921e](https://www.github.com/yargs/y18n/commit/e39921e1017f88f5d8ea97ddea854ffe92d68e74)) + +### [5.0.2](https://www.github.com/yargs/y18n/compare/v5.0.1...v5.0.2) (2020-10-01) + + +### Bug Fixes + +* **deno:** update types for deno ^1.4.0 ([#100](https://www.github.com/yargs/y18n/issues/100)) ([3834d9a](https://www.github.com/yargs/y18n/commit/3834d9ab1332f2937c935ada5e76623290efae81)) + +### [5.0.1](https://www.github.com/yargs/y18n/compare/v5.0.0...v5.0.1) (2020-09-05) + + +### Bug Fixes + +* main had old index path ([#98](https://www.github.com/yargs/y18n/issues/98)) ([124f7b0](https://www.github.com/yargs/y18n/commit/124f7b047ba9596bdbdf64459988304e77f3de1b)) + +## [5.0.0](https://www.github.com/yargs/y18n/compare/v4.0.0...v5.0.0) (2020-09-05) + + +### ⚠ BREAKING CHANGES + +* exports maps are now used, which modifies import behavior. +* drops Node 6 and 4. begin following Node.js LTS schedule (#89) + +### Features + +* add support for ESM and Deno [#95](https://www.github.com/yargs/y18n/issues/95)) ([4d7ae94](https://www.github.com/yargs/y18n/commit/4d7ae94bcb42e84164e2180366474b1cd321ed94)) + + +### Build System + +* drops Node 6 and 4. begin following Node.js LTS schedule ([#89](https://www.github.com/yargs/y18n/issues/89)) ([3cc0c28](https://www.github.com/yargs/y18n/commit/3cc0c287240727b84eaf1927f903612ec80f5e43)) + +### 4.0.1 (2020-10-25) + + +### Bug Fixes + +* address prototype pollution issue ([#108](https://www.github.com/yargs/y18n/issues/108)) ([a9ac604](https://www.github.com/yargs/y18n/commit/7de58ca0d315990cdb38234e97fc66254cdbcd71)) + +## [4.0.0](https://github.com/yargs/y18n/compare/v3.2.1...v4.0.0) (2017-10-10) + + +### Bug Fixes + +* allow support for falsy values like 0 in tagged literal ([#45](https://github.com/yargs/y18n/issues/45)) ([c926123](https://github.com/yargs/y18n/commit/c926123)) + + +### Features + +* **__:** added tagged template literal support ([#44](https://github.com/yargs/y18n/issues/44)) ([0598daf](https://github.com/yargs/y18n/commit/0598daf)) + + +### BREAKING CHANGES + +* **__:** dropping Node 0.10/Node 0.12 support diff --git a/node_modules/y18n/LICENSE b/node_modules/y18n/LICENSE new file mode 100644 index 0000000..3c157f0 --- /dev/null +++ b/node_modules/y18n/LICENSE @@ -0,0 +1,13 @@ +Copyright (c) 2015, 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. diff --git a/node_modules/y18n/README.md b/node_modules/y18n/README.md new file mode 100644 index 0000000..5102bb1 --- /dev/null +++ b/node_modules/y18n/README.md @@ -0,0 +1,127 @@ +# y18n + +[![NPM version][npm-image]][npm-url] +[![js-standard-style][standard-image]][standard-url] +[![Conventional Commits](https://img.shields.io/badge/Conventional%20Commits-1.0.0-yellow.svg)](https://conventionalcommits.org) + +The bare-bones internationalization library used by yargs. + +Inspired by [i18n](https://www.npmjs.com/package/i18n). + +## Examples + +_simple string translation:_ + +```js +const __ = require('y18n')().__; + +console.log(__('my awesome string %s', 'foo')); +``` + +output: + +`my awesome string foo` + +_using tagged template literals_ + +```js +const __ = require('y18n')().__; + +const str = 'foo'; + +console.log(__`my awesome string ${str}`); +``` + +output: + +`my awesome string foo` + +_pluralization support:_ + +```js +const __n = require('y18n')().__n; + +console.log(__n('one fish %s', '%d fishes %s', 2, 'foo')); +``` + +output: + +`2 fishes foo` + +## Deno Example + +As of `v5` `y18n` supports [Deno](https://github.com/denoland/deno): + +```typescript +import y18n from "https://deno.land/x/y18n/deno.ts"; + +const __ = y18n({ + locale: 'pirate', + directory: './test/locales' +}).__ + +console.info(__`Hi, ${'Ben'} ${'Coe'}!`) +``` + +You will need to run with `--allow-read` to load alternative locales. + +## JSON Language Files + +The JSON language files should be stored in a `./locales` folder. +File names correspond to locales, e.g., `en.json`, `pirate.json`. + +When strings are observed for the first time they will be +added to the JSON file corresponding to the current locale. + +## Methods + +### require('y18n')(config) + +Create an instance of y18n with the config provided, options include: + +* `directory`: the locale directory, default `./locales`. +* `updateFiles`: should newly observed strings be updated in file, default `true`. +* `locale`: what locale should be used. +* `fallbackToLanguage`: should fallback to a language-only file (e.g. `en.json`) + be allowed if a file matching the locale does not exist (e.g. `en_US.json`), + default `true`. + +### y18n.\_\_(str, arg, arg, arg) + +Print a localized string, `%s` will be replaced with `arg`s. + +This function can also be used as a tag for a template literal. You can use it +like this: __`hello ${'world'}`. This will be equivalent to +`__('hello %s', 'world')`. + +### y18n.\_\_n(singularString, pluralString, count, arg, arg, arg) + +Print a localized string with appropriate pluralization. If `%d` is provided +in the string, the `count` will replace this placeholder. + +### y18n.setLocale(str) + +Set the current locale being used. + +### y18n.getLocale() + +What locale is currently being used? + +### y18n.updateLocale(obj) + +Update the current locale with the key value pairs in `obj`. + +## Supported Node.js Versions + +Libraries in this ecosystem make a best effort to track +[Node.js' release schedule](https://nodejs.org/en/about/releases/). Here's [a +post on why we think this is important](https://medium.com/the-node-js-collection/maintainers-should-consider-following-node-js-release-schedule-ab08ed4de71a). + +## License + +ISC + +[npm-url]: https://npmjs.org/package/y18n +[npm-image]: https://img.shields.io/npm/v/y18n.svg +[standard-image]: https://img.shields.io/badge/code%20style-standard-brightgreen.svg +[standard-url]: https://github.com/feross/standard diff --git a/node_modules/y18n/build/index.cjs b/node_modules/y18n/build/index.cjs new file mode 100644 index 0000000..b2731e1 --- /dev/null +++ b/node_modules/y18n/build/index.cjs @@ -0,0 +1,203 @@ +'use strict'; + +var fs = require('fs'); +var util = require('util'); +var path = require('path'); + +let shim; +class Y18N { + constructor(opts) { + // configurable options. + opts = opts || {}; + this.directory = opts.directory || './locales'; + this.updateFiles = typeof opts.updateFiles === 'boolean' ? opts.updateFiles : true; + this.locale = opts.locale || 'en'; + this.fallbackToLanguage = typeof opts.fallbackToLanguage === 'boolean' ? opts.fallbackToLanguage : true; + // internal stuff. + this.cache = Object.create(null); + this.writeQueue = []; + } + __(...args) { + if (typeof arguments[0] !== 'string') { + return this._taggedLiteral(arguments[0], ...arguments); + } + const str = args.shift(); + let cb = function () { }; // start with noop. + if (typeof args[args.length - 1] === 'function') + cb = args.pop(); + cb = cb || function () { }; // noop. + if (!this.cache[this.locale]) + this._readLocaleFile(); + // we've observed a new string, update the language file. + if (!this.cache[this.locale][str] && this.updateFiles) { + this.cache[this.locale][str] = str; + // include the current directory and locale, + // since these values could change before the + // write is performed. + this._enqueueWrite({ + directory: this.directory, + locale: this.locale, + cb + }); + } + else { + cb(); + } + return shim.format.apply(shim.format, [this.cache[this.locale][str] || str].concat(args)); + } + __n() { + const args = Array.prototype.slice.call(arguments); + const singular = args.shift(); + const plural = args.shift(); + const quantity = args.shift(); + let cb = function () { }; // start with noop. + if (typeof args[args.length - 1] === 'function') + cb = args.pop(); + if (!this.cache[this.locale]) + this._readLocaleFile(); + let str = quantity === 1 ? singular : plural; + if (this.cache[this.locale][singular]) { + const entry = this.cache[this.locale][singular]; + str = entry[quantity === 1 ? 'one' : 'other']; + } + // we've observed a new string, update the language file. + if (!this.cache[this.locale][singular] && this.updateFiles) { + this.cache[this.locale][singular] = { + one: singular, + other: plural + }; + // include the current directory and locale, + // since these values could change before the + // write is performed. + this._enqueueWrite({ + directory: this.directory, + locale: this.locale, + cb + }); + } + else { + cb(); + } + // if a %d placeholder is provided, add quantity + // to the arguments expanded by util.format. + const values = [str]; + if (~str.indexOf('%d')) + values.push(quantity); + return shim.format.apply(shim.format, values.concat(args)); + } + setLocale(locale) { + this.locale = locale; + } + getLocale() { + return this.locale; + } + updateLocale(obj) { + if (!this.cache[this.locale]) + this._readLocaleFile(); + for (const key in obj) { + if (Object.prototype.hasOwnProperty.call(obj, key)) { + this.cache[this.locale][key] = obj[key]; + } + } + } + _taggedLiteral(parts, ...args) { + let str = ''; + parts.forEach(function (part, i) { + const arg = args[i + 1]; + str += part; + if (typeof arg !== 'undefined') { + str += '%s'; + } + }); + return this.__.apply(this, [str].concat([].slice.call(args, 1))); + } + _enqueueWrite(work) { + this.writeQueue.push(work); + if (this.writeQueue.length === 1) + this._processWriteQueue(); + } + _processWriteQueue() { + const _this = this; + const work = this.writeQueue[0]; + // destructure the enqueued work. + const directory = work.directory; + const locale = work.locale; + const cb = work.cb; + const languageFile = this._resolveLocaleFile(directory, locale); + const serializedLocale = JSON.stringify(this.cache[locale], null, 2); + shim.fs.writeFile(languageFile, serializedLocale, 'utf-8', function (err) { + _this.writeQueue.shift(); + if (_this.writeQueue.length > 0) + _this._processWriteQueue(); + cb(err); + }); + } + _readLocaleFile() { + let localeLookup = {}; + const languageFile = this._resolveLocaleFile(this.directory, this.locale); + try { + // When using a bundler such as webpack, readFileSync may not be defined: + if (shim.fs.readFileSync) { + localeLookup = JSON.parse(shim.fs.readFileSync(languageFile, 'utf-8')); + } + } + catch (err) { + if (err instanceof SyntaxError) { + err.message = 'syntax error in ' + languageFile; + } + if (err.code === 'ENOENT') + localeLookup = {}; + else + throw err; + } + this.cache[this.locale] = localeLookup; + } + _resolveLocaleFile(directory, locale) { + let file = shim.resolve(directory, './', locale + '.json'); + if (this.fallbackToLanguage && !this._fileExistsSync(file) && ~locale.lastIndexOf('_')) { + // attempt fallback to language only + const languageFile = shim.resolve(directory, './', locale.split('_')[0] + '.json'); + if (this._fileExistsSync(languageFile)) + file = languageFile; + } + return file; + } + _fileExistsSync(file) { + return shim.exists(file); + } +} +function y18n$1(opts, _shim) { + shim = _shim; + const y18n = new Y18N(opts); + return { + __: y18n.__.bind(y18n), + __n: y18n.__n.bind(y18n), + setLocale: y18n.setLocale.bind(y18n), + getLocale: y18n.getLocale.bind(y18n), + updateLocale: y18n.updateLocale.bind(y18n), + locale: y18n.locale + }; +} + +var nodePlatformShim = { + fs: { + readFileSync: fs.readFileSync, + writeFile: fs.writeFile + }, + format: util.format, + resolve: path.resolve, + exists: (file) => { + try { + return fs.statSync(file).isFile(); + } + catch (err) { + return false; + } + } +}; + +const y18n = (opts) => { + return y18n$1(opts, nodePlatformShim); +}; + +module.exports = y18n; diff --git a/node_modules/y18n/build/lib/cjs.js b/node_modules/y18n/build/lib/cjs.js new file mode 100644 index 0000000..ff58470 --- /dev/null +++ b/node_modules/y18n/build/lib/cjs.js @@ -0,0 +1,6 @@ +import { y18n as _y18n } from './index.js'; +import nodePlatformShim from './platform-shims/node.js'; +const y18n = (opts) => { + return _y18n(opts, nodePlatformShim); +}; +export default y18n; diff --git a/node_modules/y18n/build/lib/index.js b/node_modules/y18n/build/lib/index.js new file mode 100644 index 0000000..e38f335 --- /dev/null +++ b/node_modules/y18n/build/lib/index.js @@ -0,0 +1,174 @@ +let shim; +class Y18N { + constructor(opts) { + // configurable options. + opts = opts || {}; + this.directory = opts.directory || './locales'; + this.updateFiles = typeof opts.updateFiles === 'boolean' ? opts.updateFiles : true; + this.locale = opts.locale || 'en'; + this.fallbackToLanguage = typeof opts.fallbackToLanguage === 'boolean' ? opts.fallbackToLanguage : true; + // internal stuff. + this.cache = Object.create(null); + this.writeQueue = []; + } + __(...args) { + if (typeof arguments[0] !== 'string') { + return this._taggedLiteral(arguments[0], ...arguments); + } + const str = args.shift(); + let cb = function () { }; // start with noop. + if (typeof args[args.length - 1] === 'function') + cb = args.pop(); + cb = cb || function () { }; // noop. + if (!this.cache[this.locale]) + this._readLocaleFile(); + // we've observed a new string, update the language file. + if (!this.cache[this.locale][str] && this.updateFiles) { + this.cache[this.locale][str] = str; + // include the current directory and locale, + // since these values could change before the + // write is performed. + this._enqueueWrite({ + directory: this.directory, + locale: this.locale, + cb + }); + } + else { + cb(); + } + return shim.format.apply(shim.format, [this.cache[this.locale][str] || str].concat(args)); + } + __n() { + const args = Array.prototype.slice.call(arguments); + const singular = args.shift(); + const plural = args.shift(); + const quantity = args.shift(); + let cb = function () { }; // start with noop. + if (typeof args[args.length - 1] === 'function') + cb = args.pop(); + if (!this.cache[this.locale]) + this._readLocaleFile(); + let str = quantity === 1 ? singular : plural; + if (this.cache[this.locale][singular]) { + const entry = this.cache[this.locale][singular]; + str = entry[quantity === 1 ? 'one' : 'other']; + } + // we've observed a new string, update the language file. + if (!this.cache[this.locale][singular] && this.updateFiles) { + this.cache[this.locale][singular] = { + one: singular, + other: plural + }; + // include the current directory and locale, + // since these values could change before the + // write is performed. + this._enqueueWrite({ + directory: this.directory, + locale: this.locale, + cb + }); + } + else { + cb(); + } + // if a %d placeholder is provided, add quantity + // to the arguments expanded by util.format. + const values = [str]; + if (~str.indexOf('%d')) + values.push(quantity); + return shim.format.apply(shim.format, values.concat(args)); + } + setLocale(locale) { + this.locale = locale; + } + getLocale() { + return this.locale; + } + updateLocale(obj) { + if (!this.cache[this.locale]) + this._readLocaleFile(); + for (const key in obj) { + if (Object.prototype.hasOwnProperty.call(obj, key)) { + this.cache[this.locale][key] = obj[key]; + } + } + } + _taggedLiteral(parts, ...args) { + let str = ''; + parts.forEach(function (part, i) { + const arg = args[i + 1]; + str += part; + if (typeof arg !== 'undefined') { + str += '%s'; + } + }); + return this.__.apply(this, [str].concat([].slice.call(args, 1))); + } + _enqueueWrite(work) { + this.writeQueue.push(work); + if (this.writeQueue.length === 1) + this._processWriteQueue(); + } + _processWriteQueue() { + const _this = this; + const work = this.writeQueue[0]; + // destructure the enqueued work. + const directory = work.directory; + const locale = work.locale; + const cb = work.cb; + const languageFile = this._resolveLocaleFile(directory, locale); + const serializedLocale = JSON.stringify(this.cache[locale], null, 2); + shim.fs.writeFile(languageFile, serializedLocale, 'utf-8', function (err) { + _this.writeQueue.shift(); + if (_this.writeQueue.length > 0) + _this._processWriteQueue(); + cb(err); + }); + } + _readLocaleFile() { + let localeLookup = {}; + const languageFile = this._resolveLocaleFile(this.directory, this.locale); + try { + // When using a bundler such as webpack, readFileSync may not be defined: + if (shim.fs.readFileSync) { + localeLookup = JSON.parse(shim.fs.readFileSync(languageFile, 'utf-8')); + } + } + catch (err) { + if (err instanceof SyntaxError) { + err.message = 'syntax error in ' + languageFile; + } + if (err.code === 'ENOENT') + localeLookup = {}; + else + throw err; + } + this.cache[this.locale] = localeLookup; + } + _resolveLocaleFile(directory, locale) { + let file = shim.resolve(directory, './', locale + '.json'); + if (this.fallbackToLanguage && !this._fileExistsSync(file) && ~locale.lastIndexOf('_')) { + // attempt fallback to language only + const languageFile = shim.resolve(directory, './', locale.split('_')[0] + '.json'); + if (this._fileExistsSync(languageFile)) + file = languageFile; + } + return file; + } + _fileExistsSync(file) { + return shim.exists(file); + } +} +export function y18n(opts, _shim) { + shim = _shim; + const y18n = new Y18N(opts); + return { + __: y18n.__.bind(y18n), + __n: y18n.__n.bind(y18n), + setLocale: y18n.setLocale.bind(y18n), + getLocale: y18n.getLocale.bind(y18n), + updateLocale: y18n.updateLocale.bind(y18n), + locale: y18n.locale + }; +} diff --git a/node_modules/y18n/build/lib/platform-shims/node.js b/node_modules/y18n/build/lib/platform-shims/node.js new file mode 100644 index 0000000..181208b --- /dev/null +++ b/node_modules/y18n/build/lib/platform-shims/node.js @@ -0,0 +1,19 @@ +import { readFileSync, statSync, writeFile } from 'fs'; +import { format } from 'util'; +import { resolve } from 'path'; +export default { + fs: { + readFileSync, + writeFile + }, + format, + resolve, + exists: (file) => { + try { + return statSync(file).isFile(); + } + catch (err) { + return false; + } + } +}; diff --git a/node_modules/y18n/index.mjs b/node_modules/y18n/index.mjs new file mode 100644 index 0000000..46c8213 --- /dev/null +++ b/node_modules/y18n/index.mjs @@ -0,0 +1,8 @@ +import shim from './build/lib/platform-shims/node.js' +import { y18n as _y18n } from './build/lib/index.js' + +const y18n = (opts) => { + return _y18n(opts, shim) +} + +export default y18n diff --git a/node_modules/y18n/package.json b/node_modules/y18n/package.json new file mode 100644 index 0000000..4e5c1ca --- /dev/null +++ b/node_modules/y18n/package.json @@ -0,0 +1,70 @@ +{ + "name": "y18n", + "version": "5.0.8", + "description": "the bare-bones internationalization library used by yargs", + "exports": { + ".": [ + { + "import": "./index.mjs", + "require": "./build/index.cjs" + }, + "./build/index.cjs" + ] + }, + "type": "module", + "module": "./build/lib/index.js", + "keywords": [ + "i18n", + "internationalization", + "yargs" + ], + "homepage": "https://github.com/yargs/y18n", + "bugs": { + "url": "https://github.com/yargs/y18n/issues" + }, + "repository": "yargs/y18n", + "license": "ISC", + "author": "Ben Coe ", + "main": "./build/index.cjs", + "scripts": { + "check": "standardx **/*.ts **/*.cjs **/*.mjs", + "fix": "standardx --fix **/*.ts **/*.cjs **/*.mjs", + "pretest": "rimraf build && tsc -p tsconfig.test.json && cross-env NODE_ENV=test npm run build:cjs", + "test": "c8 --reporter=text --reporter=html mocha test/*.cjs", + "test:esm": "c8 --reporter=text --reporter=html mocha test/esm/*.mjs", + "posttest": "npm run check", + "coverage": "c8 report --check-coverage", + "precompile": "rimraf build", + "compile": "tsc", + "postcompile": "npm run build:cjs", + "build:cjs": "rollup -c", + "prepare": "npm run compile" + }, + "devDependencies": { + "@types/node": "^14.6.4", + "@wessberg/rollup-plugin-ts": "^1.3.1", + "c8": "^7.3.0", + "chai": "^4.0.1", + "cross-env": "^7.0.2", + "gts": "^3.0.0", + "mocha": "^8.0.0", + "rimraf": "^3.0.2", + "rollup": "^2.26.10", + "standardx": "^7.0.0", + "ts-transform-default-export": "^1.0.2", + "typescript": "^4.0.0" + }, + "files": [ + "build", + "index.mjs", + "!*.d.ts" + ], + "engines": { + "node": ">=10" + }, + "standardx": { + "ignore": [ + "build" + ] + } +} diff --git a/node_modules/yargs-parser/CHANGELOG.md b/node_modules/yargs-parser/CHANGELOG.md new file mode 100644 index 0000000..584eb86 --- /dev/null +++ b/node_modules/yargs-parser/CHANGELOG.md @@ -0,0 +1,308 @@ +# Changelog + +All notable changes to this project will be documented in this file. See [standard-version](https://github.com/conventional-changelog/standard-version) for commit guidelines. + +## [21.1.1](https://github.com/yargs/yargs-parser/compare/yargs-parser-v21.1.0...yargs-parser-v21.1.1) (2022-08-04) + + +### Bug Fixes + +* **typescript:** ignore .cts files during publish ([#454](https://github.com/yargs/yargs-parser/issues/454)) ([d69f9c3](https://github.com/yargs/yargs-parser/commit/d69f9c3a91c3ad2f9494d0a94e29a8b76c41b81b)), closes [#452](https://github.com/yargs/yargs-parser/issues/452) + +## [21.1.0](https://github.com/yargs/yargs-parser/compare/yargs-parser-v21.0.1...yargs-parser-v21.1.0) (2022-08-03) + + +### Features + +* allow the browser build to be imported ([#443](https://github.com/yargs/yargs-parser/issues/443)) ([a89259f](https://github.com/yargs/yargs-parser/commit/a89259ff41d6f5312b3ce8a30bef343a993f395a)) + + +### Bug Fixes + +* **halt-at-non-option:** prevent known args from being parsed when "unknown-options-as-args" is enabled ([#438](https://github.com/yargs/yargs-parser/issues/438)) ([c474bc1](https://github.com/yargs/yargs-parser/commit/c474bc10c3aa0ae864b95e5722730114ef15f573)) +* node version check now uses process.versions.node ([#450](https://github.com/yargs/yargs-parser/issues/450)) ([d07bcdb](https://github.com/yargs/yargs-parser/commit/d07bcdbe43075f7201fbe8a08e491217247fe1f1)) +* parse options ending with 3+ hyphens ([#434](https://github.com/yargs/yargs-parser/issues/434)) ([4f1060b](https://github.com/yargs/yargs-parser/commit/4f1060b50759fadbac3315c5117b0c3d65b0a7d8)) + +### [21.0.1](https://github.com/yargs/yargs-parser/compare/yargs-parser-v21.0.0...yargs-parser-v21.0.1) (2022-02-27) + + +### Bug Fixes + +* return deno env object ([#432](https://github.com/yargs/yargs-parser/issues/432)) ([b00eb87](https://github.com/yargs/yargs-parser/commit/b00eb87b4860a890dd2dab0d6058241bbfd2b3ec)) + +## [21.0.0](https://www.github.com/yargs/yargs-parser/compare/yargs-parser-v20.2.9...yargs-parser-v21.0.0) (2021-11-15) + + +### ⚠ BREAKING CHANGES + +* drops support for 10 (#421) + +### Bug Fixes + +* esm json import ([#416](https://www.github.com/yargs/yargs-parser/issues/416)) ([90f970a](https://www.github.com/yargs/yargs-parser/commit/90f970a6482dd4f5b5eb18d38596dd6f02d73edf)) +* parser should preserve inner quotes ([#407](https://www.github.com/yargs/yargs-parser/issues/407)) ([ae11f49](https://www.github.com/yargs/yargs-parser/commit/ae11f496a8318ea8885aa25015d429b33713c314)) + + +### Code Refactoring + +* drops support for 10 ([#421](https://www.github.com/yargs/yargs-parser/issues/421)) ([3aaf878](https://www.github.com/yargs/yargs-parser/commit/3aaf8784f5c7f2aec6108c1c6a55537fa7e3b5c1)) + +### [20.2.9](https://www.github.com/yargs/yargs-parser/compare/yargs-parser-v20.2.8...yargs-parser-v20.2.9) (2021-06-20) + + +### Bug Fixes + +* **build:** fixed automated release pipeline ([1fe9135](https://www.github.com/yargs/yargs-parser/commit/1fe9135884790a083615419b2861683e2597dac3)) + +### [20.2.8](https://www.github.com/yargs/yargs-parser/compare/yargs-parser-v20.2.7...yargs-parser-v20.2.8) (2021-06-20) + + +### Bug Fixes + +* **locale:** Turkish camelize and decamelize issues with toLocaleLowerCase/toLocaleUpperCase ([2617303](https://www.github.com/yargs/yargs-parser/commit/261730383e02448562f737b94bbd1f164aed5143)) +* **perf:** address slow parse when using unknown-options-as-args ([#394](https://www.github.com/yargs/yargs-parser/issues/394)) ([441f059](https://www.github.com/yargs/yargs-parser/commit/441f059d585d446551068ad213db79ac91daf83a)) +* **string-utils:** detect [0,1] ranged values as numbers ([#388](https://www.github.com/yargs/yargs-parser/issues/388)) ([efcc32c](https://www.github.com/yargs/yargs-parser/commit/efcc32c2d6b09aba31abfa2db9bd947befe5586b)) + +### [20.2.7](https://www.github.com/yargs/yargs-parser/compare/v20.2.6...v20.2.7) (2021-03-10) + + +### Bug Fixes + +* **deno:** force release for Deno ([6687c97](https://www.github.com/yargs/yargs-parser/commit/6687c972d0f3ca7865a97908dde3080b05f8b026)) + +### [20.2.6](https://www.github.com/yargs/yargs-parser/compare/v20.2.5...v20.2.6) (2021-02-22) + + +### Bug Fixes + +* **populate--:** -- should always be array ([#354](https://www.github.com/yargs/yargs-parser/issues/354)) ([585ae8f](https://www.github.com/yargs/yargs-parser/commit/585ae8ffad74cc02974f92d788e750137fd65146)) + +### [20.2.5](https://www.github.com/yargs/yargs-parser/compare/v20.2.4...v20.2.5) (2021-02-13) + + +### Bug Fixes + +* do not lowercase camel cased string ([#348](https://www.github.com/yargs/yargs-parser/issues/348)) ([5f4da1f](https://www.github.com/yargs/yargs-parser/commit/5f4da1f17d9d50542d2aaa206c9806ce3e320335)) + +### [20.2.4](https://www.github.com/yargs/yargs-parser/compare/v20.2.3...v20.2.4) (2020-11-09) + + +### Bug Fixes + +* **deno:** address import issues in Deno ([#339](https://www.github.com/yargs/yargs-parser/issues/339)) ([3b54e5e](https://www.github.com/yargs/yargs-parser/commit/3b54e5eef6e9a7b7c6eec7c12bab3ba3b8ba8306)) + +### [20.2.3](https://www.github.com/yargs/yargs-parser/compare/v20.2.2...v20.2.3) (2020-10-16) + + +### Bug Fixes + +* **exports:** node 13.0 and 13.1 require the dotted object form _with_ a string fallback ([#336](https://www.github.com/yargs/yargs-parser/issues/336)) ([3ae7242](https://www.github.com/yargs/yargs-parser/commit/3ae7242040ff876d28dabded60ac226e00150c88)) + +### [20.2.2](https://www.github.com/yargs/yargs-parser/compare/v20.2.1...v20.2.2) (2020-10-14) + + +### Bug Fixes + +* **exports:** node 13.0-13.6 require a string fallback ([#333](https://www.github.com/yargs/yargs-parser/issues/333)) ([291aeda](https://www.github.com/yargs/yargs-parser/commit/291aeda06b685b7a015d83bdf2558e180b37388d)) + +### [20.2.1](https://www.github.com/yargs/yargs-parser/compare/v20.2.0...v20.2.1) (2020-10-01) + + +### Bug Fixes + +* **deno:** update types for deno ^1.4.0 ([#330](https://www.github.com/yargs/yargs-parser/issues/330)) ([0ab92e5](https://www.github.com/yargs/yargs-parser/commit/0ab92e50b090f11196334c048c9c92cecaddaf56)) + +## [20.2.0](https://www.github.com/yargs/yargs-parser/compare/v20.1.0...v20.2.0) (2020-09-21) + + +### Features + +* **string-utils:** export looksLikeNumber helper ([#324](https://www.github.com/yargs/yargs-parser/issues/324)) ([c8580a2](https://www.github.com/yargs/yargs-parser/commit/c8580a2327b55f6342acecb6e72b62963d506750)) + + +### Bug Fixes + +* **unknown-options-as-args:** convert positionals that look like numbers ([#326](https://www.github.com/yargs/yargs-parser/issues/326)) ([f85ebb4](https://www.github.com/yargs/yargs-parser/commit/f85ebb4face9d4b0f56147659404cbe0002f3dad)) + +## [20.1.0](https://www.github.com/yargs/yargs-parser/compare/v20.0.0...v20.1.0) (2020-09-20) + + +### Features + +* adds parse-positional-numbers configuration ([#321](https://www.github.com/yargs/yargs-parser/issues/321)) ([9cec00a](https://www.github.com/yargs/yargs-parser/commit/9cec00a622251292ffb7dce6f78f5353afaa0d4c)) + + +### Bug Fixes + +* **build:** update release-please; make labels kick off builds ([#323](https://www.github.com/yargs/yargs-parser/issues/323)) ([09f448b](https://www.github.com/yargs/yargs-parser/commit/09f448b4cd66e25d2872544718df46dab8af062a)) + +## [20.0.0](https://www.github.com/yargs/yargs-parser/compare/v19.0.4...v20.0.0) (2020-09-09) + + +### ⚠ BREAKING CHANGES + +* do not ship type definitions (#318) + +### Bug Fixes + +* only strip camel case if hyphenated ([#316](https://www.github.com/yargs/yargs-parser/issues/316)) ([95a9e78](https://www.github.com/yargs/yargs-parser/commit/95a9e785127b9bbf2d1db1f1f808ca1fb100e82a)), closes [#315](https://www.github.com/yargs/yargs-parser/issues/315) + + +### Code Refactoring + +* do not ship type definitions ([#318](https://www.github.com/yargs/yargs-parser/issues/318)) ([8fbd56f](https://www.github.com/yargs/yargs-parser/commit/8fbd56f1d0b6c44c30fca62708812151ca0ce330)) + +### [19.0.4](https://www.github.com/yargs/yargs-parser/compare/v19.0.3...v19.0.4) (2020-08-27) + + +### Bug Fixes + +* **build:** fixing publication ([#310](https://www.github.com/yargs/yargs-parser/issues/310)) ([5d3c6c2](https://www.github.com/yargs/yargs-parser/commit/5d3c6c29a9126248ba601920d9cf87c78e161ff5)) + +### [19.0.3](https://www.github.com/yargs/yargs-parser/compare/v19.0.2...v19.0.3) (2020-08-27) + + +### Bug Fixes + +* **build:** switch to action for publish ([#308](https://www.github.com/yargs/yargs-parser/issues/308)) ([5c2f305](https://www.github.com/yargs/yargs-parser/commit/5c2f30585342bcd8aaf926407c863099d256d174)) + +### [19.0.2](https://www.github.com/yargs/yargs-parser/compare/v19.0.1...v19.0.2) (2020-08-27) + + +### Bug Fixes + +* **types:** envPrefix should be optional ([#305](https://www.github.com/yargs/yargs-parser/issues/305)) ([ae3f180](https://www.github.com/yargs/yargs-parser/commit/ae3f180e14df2de2fd962145f4518f9aa0e76523)) + +### [19.0.1](https://www.github.com/yargs/yargs-parser/compare/v19.0.0...v19.0.1) (2020-08-09) + + +### Bug Fixes + +* **build:** push tag created for deno ([2186a14](https://www.github.com/yargs/yargs-parser/commit/2186a14989749887d56189867602e39e6679f8b0)) + +## [19.0.0](https://www.github.com/yargs/yargs-parser/compare/v18.1.3...v19.0.0) (2020-08-09) + + +### ⚠ BREAKING CHANGES + +* adds support for ESM and Deno (#295) +* **ts:** projects using `@types/yargs-parser` may see variations in type definitions. +* drops Node 6. begin following Node.js LTS schedule (#278) + +### Features + +* adds support for ESM and Deno ([#295](https://www.github.com/yargs/yargs-parser/issues/295)) ([195bc4a](https://www.github.com/yargs/yargs-parser/commit/195bc4a7f20c2a8f8e33fbb6ba96ef6e9a0120a1)) +* expose camelCase and decamelize helpers ([#296](https://www.github.com/yargs/yargs-parser/issues/296)) ([39154ce](https://www.github.com/yargs/yargs-parser/commit/39154ceb5bdcf76b5f59a9219b34cedb79b67f26)) +* **deps:** update to latest camelcase/decamelize ([#281](https://www.github.com/yargs/yargs-parser/issues/281)) ([8931ab0](https://www.github.com/yargs/yargs-parser/commit/8931ab08f686cc55286f33a95a83537da2be5516)) + + +### Bug Fixes + +* boolean numeric short option ([#294](https://www.github.com/yargs/yargs-parser/issues/294)) ([f600082](https://www.github.com/yargs/yargs-parser/commit/f600082c959e092076caf420bbbc9d7a231e2418)) +* raise permission error for Deno if config load fails ([#298](https://www.github.com/yargs/yargs-parser/issues/298)) ([1174e2b](https://www.github.com/yargs/yargs-parser/commit/1174e2b3f0c845a1cd64e14ffc3703e730567a84)) +* **deps:** update dependency decamelize to v3 ([#274](https://www.github.com/yargs/yargs-parser/issues/274)) ([4d98698](https://www.github.com/yargs/yargs-parser/commit/4d98698bc6767e84ec54a0842908191739be73b7)) +* **types:** switch back to using Partial types ([#293](https://www.github.com/yargs/yargs-parser/issues/293)) ([bdc80ba](https://www.github.com/yargs/yargs-parser/commit/bdc80ba59fa13bc3025ce0a85e8bad9f9da24ea7)) + + +### Build System + +* drops Node 6. begin following Node.js LTS schedule ([#278](https://www.github.com/yargs/yargs-parser/issues/278)) ([9014ed7](https://www.github.com/yargs/yargs-parser/commit/9014ed722a32768b96b829e65a31705db5c1458a)) + + +### Code Refactoring + +* **ts:** move index.js to TypeScript ([#292](https://www.github.com/yargs/yargs-parser/issues/292)) ([f78d2b9](https://www.github.com/yargs/yargs-parser/commit/f78d2b97567ac4828624406e420b4047c710b789)) + +### [18.1.3](https://www.github.com/yargs/yargs-parser/compare/v18.1.2...v18.1.3) (2020-04-16) + + +### Bug Fixes + +* **setArg:** options using camel-case and dot-notation populated twice ([#268](https://www.github.com/yargs/yargs-parser/issues/268)) ([f7e15b9](https://www.github.com/yargs/yargs-parser/commit/f7e15b9800900b9856acac1a830a5f35847be73e)) + +### [18.1.2](https://www.github.com/yargs/yargs-parser/compare/v18.1.1...v18.1.2) (2020-03-26) + + +### Bug Fixes + +* **array, nargs:** support -o=--value and --option=--value format ([#262](https://www.github.com/yargs/yargs-parser/issues/262)) ([41d3f81](https://www.github.com/yargs/yargs-parser/commit/41d3f8139e116706b28de9b0de3433feb08d2f13)) + +### [18.1.1](https://www.github.com/yargs/yargs-parser/compare/v18.1.0...v18.1.1) (2020-03-16) + + +### Bug Fixes + +* \_\_proto\_\_ will now be replaced with \_\_\_proto\_\_\_ in parse ([#258](https://www.github.com/yargs/yargs-parser/issues/258)), patching a potential +prototype pollution vulnerability. This was reported by the Snyk Security Research Team.([63810ca](https://www.github.com/yargs/yargs-parser/commit/63810ca1ae1a24b08293a4d971e70e058c7a41e2)) + +## [18.1.0](https://www.github.com/yargs/yargs-parser/compare/v18.0.0...v18.1.0) (2020-03-07) + + +### Features + +* introduce single-digit boolean aliases ([#255](https://www.github.com/yargs/yargs-parser/issues/255)) ([9c60265](https://www.github.com/yargs/yargs-parser/commit/9c60265fd7a03cb98e6df3e32c8c5e7508d9f56f)) + +## [18.0.0](https://www.github.com/yargs/yargs-parser/compare/v17.1.0...v18.0.0) (2020-03-02) + + +### ⚠ BREAKING CHANGES + +* the narg count is now enforced when parsing arrays. + +### Features + +* NaN can now be provided as a value for nargs, indicating "at least" one value is expected for array ([#251](https://www.github.com/yargs/yargs-parser/issues/251)) ([9db4be8](https://www.github.com/yargs/yargs-parser/commit/9db4be81417a2c7097128db34d86fe70ef4af70c)) + +## [17.1.0](https://www.github.com/yargs/yargs-parser/compare/v17.0.1...v17.1.0) (2020-03-01) + + +### Features + +* introduce greedy-arrays config, for specifying whether arrays consume multiple positionals ([#249](https://www.github.com/yargs/yargs-parser/issues/249)) ([60e880a](https://www.github.com/yargs/yargs-parser/commit/60e880a837046314d89fa4725f923837fd33a9eb)) + +### [17.0.1](https://www.github.com/yargs/yargs-parser/compare/v17.0.0...v17.0.1) (2020-02-29) + + +### Bug Fixes + +* normalized keys were not enumerable ([#247](https://www.github.com/yargs/yargs-parser/issues/247)) ([57119f9](https://www.github.com/yargs/yargs-parser/commit/57119f9f17cf27499bd95e61c2f72d18314f11ba)) + +## [17.0.0](https://www.github.com/yargs/yargs-parser/compare/v16.1.0...v17.0.0) (2020-02-10) + + +### ⚠ BREAKING CHANGES + +* this reverts parsing behavior of booleans to that of yargs@14 +* objects used during parsing are now created with a null +prototype. There may be some scenarios where this change in behavior +leaks externally. + +### Features + +* boolean arguments will not be collected into an implicit array ([#236](https://www.github.com/yargs/yargs-parser/issues/236)) ([34c4e19](https://www.github.com/yargs/yargs-parser/commit/34c4e19bae4e7af63e3cb6fa654a97ed476e5eb5)) +* introduce nargs-eats-options config option ([#246](https://www.github.com/yargs/yargs-parser/issues/246)) ([d50822a](https://www.github.com/yargs/yargs-parser/commit/d50822ac10e1b05f2e9643671ca131ac251b6732)) + + +### Bug Fixes + +* address bugs with "uknown-options-as-args" ([bc023e3](https://www.github.com/yargs/yargs-parser/commit/bc023e3b13e20a118353f9507d1c999bf388a346)) +* array should take precedence over nargs, but enforce nargs ([#243](https://www.github.com/yargs/yargs-parser/issues/243)) ([4cbc188](https://www.github.com/yargs/yargs-parser/commit/4cbc188b7abb2249529a19c090338debdad2fe6c)) +* support keys that collide with object prototypes ([#234](https://www.github.com/yargs/yargs-parser/issues/234)) ([1587b6d](https://www.github.com/yargs/yargs-parser/commit/1587b6d91db853a9109f1be6b209077993fee4de)) +* unknown options terminated with digits now handled by unknown-options-as-args ([#238](https://www.github.com/yargs/yargs-parser/issues/238)) ([d36cdfa](https://www.github.com/yargs/yargs-parser/commit/d36cdfa854254d7c7e0fe1d583818332ac46c2a5)) + +## [16.1.0](https://www.github.com/yargs/yargs-parser/compare/v16.0.0...v16.1.0) (2019-11-01) + + +### ⚠ BREAKING CHANGES + +* populate error if incompatible narg/count or array/count options are used (#191) + +### Features + +* options that have had their default value used are now tracked ([#211](https://www.github.com/yargs/yargs-parser/issues/211)) ([a525234](https://www.github.com/yargs/yargs-parser/commit/a525234558c847deedd73f8792e0a3b77b26e2c0)) +* populate error if incompatible narg/count or array/count options are used ([#191](https://www.github.com/yargs/yargs-parser/issues/191)) ([84a401f](https://www.github.com/yargs/yargs-parser/commit/84a401f0fa3095e0a19661670d1570d0c3b9d3c9)) + + +### Reverts + +* revert 16.0.0 CHANGELOG entry ([920320a](https://www.github.com/yargs/yargs-parser/commit/920320ad9861bbfd58eda39221ae211540fc1daf)) diff --git a/node_modules/yargs-parser/LICENSE.txt b/node_modules/yargs-parser/LICENSE.txt new file mode 100644 index 0000000..836440b --- /dev/null +++ b/node_modules/yargs-parser/LICENSE.txt @@ -0,0 +1,14 @@ +Copyright (c) 2016, 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. diff --git a/node_modules/yargs-parser/README.md b/node_modules/yargs-parser/README.md new file mode 100644 index 0000000..2614840 --- /dev/null +++ b/node_modules/yargs-parser/README.md @@ -0,0 +1,518 @@ +# yargs-parser + +![ci](https://github.com/yargs/yargs-parser/workflows/ci/badge.svg) +[![NPM version](https://img.shields.io/npm/v/yargs-parser.svg)](https://www.npmjs.com/package/yargs-parser) +[![Conventional Commits](https://img.shields.io/badge/Conventional%20Commits-1.0.0-yellow.svg)](https://conventionalcommits.org) +![nycrc config on GitHub](https://img.shields.io/nycrc/yargs/yargs-parser) + +The mighty option parser used by [yargs](https://github.com/yargs/yargs). + +visit the [yargs website](http://yargs.js.org/) for more examples, and thorough usage instructions. + + + +## Example + +```sh +npm i yargs-parser --save +``` + +```js +const argv = require('yargs-parser')(process.argv.slice(2)) +console.log(argv) +``` + +```console +$ node example.js --foo=33 --bar hello +{ _: [], foo: 33, bar: 'hello' } +``` + +_or parse a string!_ + +```js +const argv = require('yargs-parser')('--foo=99 --bar=33') +console.log(argv) +``` + +```console +{ _: [], foo: 99, bar: 33 } +``` + +Convert an array of mixed types before passing to `yargs-parser`: + +```js +const parse = require('yargs-parser') +parse(['-f', 11, '--zoom', 55].join(' ')) // <-- array to string +parse(['-f', 11, '--zoom', 55].map(String)) // <-- array of strings +``` + +## Deno Example + +As of `v19` `yargs-parser` supports [Deno](https://github.com/denoland/deno): + +```typescript +import parser from "https://deno.land/x/yargs_parser/deno.ts"; + +const argv = parser('--foo=99 --bar=9987930', { + string: ['bar'] +}) +console.log(argv) +``` + +## ESM Example + +As of `v19` `yargs-parser` supports ESM (_both in Node.js and in the browser_): + +**Node.js:** + +```js +import parser from 'yargs-parser' + +const argv = parser('--foo=99 --bar=9987930', { + string: ['bar'] +}) +console.log(argv) +``` + +**Browsers:** + +```html + + + + +``` + +## API + +### parser(args, opts={}) + +Parses command line arguments returning a simple mapping of keys and values. + +**expects:** + +* `args`: a string or array of strings representing the options to parse. +* `opts`: provide a set of hints indicating how `args` should be parsed: + * `opts.alias`: an object representing the set of aliases for a key: `{alias: {foo: ['f']}}`. + * `opts.array`: indicate that keys should be parsed as an array: `{array: ['foo', 'bar']}`.
+ Indicate that keys should be parsed as an array and coerced to booleans / numbers:
+ `{array: [{ key: 'foo', boolean: true }, {key: 'bar', number: true}]}`. + * `opts.boolean`: arguments should be parsed as booleans: `{boolean: ['x', 'y']}`. + * `opts.coerce`: provide a custom synchronous function that returns a coerced value from the argument provided + (or throws an error). For arrays the function is called only once for the entire array:
+ `{coerce: {foo: function (arg) {return modifiedArg}}}`. + * `opts.config`: indicate a key that represents a path to a configuration file (this file will be loaded and parsed). + * `opts.configObjects`: configuration objects to parse, their properties will be set as arguments:
+ `{configObjects: [{'x': 5, 'y': 33}, {'z': 44}]}`. + * `opts.configuration`: provide configuration options to the yargs-parser (see: [configuration](#configuration)). + * `opts.count`: indicate a key that should be used as a counter, e.g., `-vvv` = `{v: 3}`. + * `opts.default`: provide default values for keys: `{default: {x: 33, y: 'hello world!'}}`. + * `opts.envPrefix`: environment variables (`process.env`) with the prefix provided should be parsed. + * `opts.narg`: specify that a key requires `n` arguments: `{narg: {x: 2}}`. + * `opts.normalize`: `path.normalize()` will be applied to values set to this key. + * `opts.number`: keys should be treated as numbers. + * `opts.string`: keys should be treated as strings (even if they resemble a number `-x 33`). + +**returns:** + +* `obj`: an object representing the parsed value of `args` + * `key/value`: key value pairs for each argument and their aliases. + * `_`: an array representing the positional arguments. + * [optional] `--`: an array with arguments after the end-of-options flag `--`. + +### require('yargs-parser').detailed(args, opts={}) + +Parses a command line string, returning detailed information required by the +yargs engine. + +**expects:** + +* `args`: a string or array of strings representing options to parse. +* `opts`: provide a set of hints indicating how `args`, inputs are identical to `require('yargs-parser')(args, opts={})`. + +**returns:** + +* `argv`: an object representing the parsed value of `args` + * `key/value`: key value pairs for each argument and their aliases. + * `_`: an array representing the positional arguments. + * [optional] `--`: an array with arguments after the end-of-options flag `--`. +* `error`: populated with an error object if an exception occurred during parsing. +* `aliases`: the inferred list of aliases built by combining lists in `opts.alias`. +* `newAliases`: any new aliases added via camel-case expansion: + * `boolean`: `{ fooBar: true }` +* `defaulted`: any new argument created by `opts.default`, no aliases included. + * `boolean`: `{ foo: true }` +* `configuration`: given by default settings and `opts.configuration`. + + + +### Configuration + +The yargs-parser applies several automated transformations on the keys provided +in `args`. These features can be turned on and off using the `configuration` field +of `opts`. + +```js +var parsed = parser(['--no-dice'], { + configuration: { + 'boolean-negation': false + } +}) +``` + +### short option groups + +* default: `true`. +* key: `short-option-groups`. + +Should a group of short-options be treated as boolean flags? + +```console +$ node example.js -abc +{ _: [], a: true, b: true, c: true } +``` + +_if disabled:_ + +```console +$ node example.js -abc +{ _: [], abc: true } +``` + +### camel-case expansion + +* default: `true`. +* key: `camel-case-expansion`. + +Should hyphenated arguments be expanded into camel-case aliases? + +```console +$ node example.js --foo-bar +{ _: [], 'foo-bar': true, fooBar: true } +``` + +_if disabled:_ + +```console +$ node example.js --foo-bar +{ _: [], 'foo-bar': true } +``` + +### dot-notation + +* default: `true` +* key: `dot-notation` + +Should keys that contain `.` be treated as objects? + +```console +$ node example.js --foo.bar +{ _: [], foo: { bar: true } } +``` + +_if disabled:_ + +```console +$ node example.js --foo.bar +{ _: [], "foo.bar": true } +``` + +### parse numbers + +* default: `true` +* key: `parse-numbers` + +Should keys that look like numbers be treated as such? + +```console +$ node example.js --foo=99.3 +{ _: [], foo: 99.3 } +``` + +_if disabled:_ + +```console +$ node example.js --foo=99.3 +{ _: [], foo: "99.3" } +``` + +### parse positional numbers + +* default: `true` +* key: `parse-positional-numbers` + +Should positional keys that look like numbers be treated as such. + +```console +$ node example.js 99.3 +{ _: [99.3] } +``` + +_if disabled:_ + +```console +$ node example.js 99.3 +{ _: ['99.3'] } +``` + +### boolean negation + +* default: `true` +* key: `boolean-negation` + +Should variables prefixed with `--no` be treated as negations? + +```console +$ node example.js --no-foo +{ _: [], foo: false } +``` + +_if disabled:_ + +```console +$ node example.js --no-foo +{ _: [], "no-foo": true } +``` + +### combine arrays + +* default: `false` +* key: `combine-arrays` + +Should arrays be combined when provided by both command line arguments and +a configuration file. + +### duplicate arguments array + +* default: `true` +* key: `duplicate-arguments-array` + +Should arguments be coerced into an array when duplicated: + +```console +$ node example.js -x 1 -x 2 +{ _: [], x: [1, 2] } +``` + +_if disabled:_ + +```console +$ node example.js -x 1 -x 2 +{ _: [], x: 2 } +``` + +### flatten duplicate arrays + +* default: `true` +* key: `flatten-duplicate-arrays` + +Should array arguments be coerced into a single array when duplicated: + +```console +$ node example.js -x 1 2 -x 3 4 +{ _: [], x: [1, 2, 3, 4] } +``` + +_if disabled:_ + +```console +$ node example.js -x 1 2 -x 3 4 +{ _: [], x: [[1, 2], [3, 4]] } +``` + +### greedy arrays + +* default: `true` +* key: `greedy-arrays` + +Should arrays consume more than one positional argument following their flag. + +```console +$ node example --arr 1 2 +{ _: [], arr: [1, 2] } +``` + +_if disabled:_ + +```console +$ node example --arr 1 2 +{ _: [2], arr: [1] } +``` + +**Note: in `v18.0.0` we are considering defaulting greedy arrays to `false`.** + +### nargs eats options + +* default: `false` +* key: `nargs-eats-options` + +Should nargs consume dash options as well as positional arguments. + +### negation prefix + +* default: `no-` +* key: `negation-prefix` + +The prefix to use for negated boolean variables. + +```console +$ node example.js --no-foo +{ _: [], foo: false } +``` + +_if set to `quux`:_ + +```console +$ node example.js --quuxfoo +{ _: [], foo: false } +``` + +### populate -- + +* default: `false`. +* key: `populate--` + +Should unparsed flags be stored in `--` or `_`. + +_If disabled:_ + +```console +$ node example.js a -b -- x y +{ _: [ 'a', 'x', 'y' ], b: true } +``` + +_If enabled:_ + +```console +$ node example.js a -b -- x y +{ _: [ 'a' ], '--': [ 'x', 'y' ], b: true } +``` + +### set placeholder key + +* default: `false`. +* key: `set-placeholder-key`. + +Should a placeholder be added for keys not set via the corresponding CLI argument? + +_If disabled:_ + +```console +$ node example.js -a 1 -c 2 +{ _: [], a: 1, c: 2 } +``` + +_If enabled:_ + +```console +$ node example.js -a 1 -c 2 +{ _: [], a: 1, b: undefined, c: 2 } +``` + +### halt at non-option + +* default: `false`. +* key: `halt-at-non-option`. + +Should parsing stop at the first positional argument? This is similar to how e.g. `ssh` parses its command line. + +_If disabled:_ + +```console +$ node example.js -a run b -x y +{ _: [ 'b' ], a: 'run', x: 'y' } +``` + +_If enabled:_ + +```console +$ node example.js -a run b -x y +{ _: [ 'b', '-x', 'y' ], a: 'run' } +``` + +### strip aliased + +* default: `false` +* key: `strip-aliased` + +Should aliases be removed before returning results? + +_If disabled:_ + +```console +$ node example.js --test-field 1 +{ _: [], 'test-field': 1, testField: 1, 'test-alias': 1, testAlias: 1 } +``` + +_If enabled:_ + +```console +$ node example.js --test-field 1 +{ _: [], 'test-field': 1, testField: 1 } +``` + +### strip dashed + +* default: `false` +* key: `strip-dashed` + +Should dashed keys be removed before returning results? This option has no effect if +`camel-case-expansion` is disabled. + +_If disabled:_ + +```console +$ node example.js --test-field 1 +{ _: [], 'test-field': 1, testField: 1 } +``` + +_If enabled:_ + +```console +$ node example.js --test-field 1 +{ _: [], testField: 1 } +``` + +### unknown options as args + +* default: `false` +* key: `unknown-options-as-args` + +Should unknown options be treated like regular arguments? An unknown option is one that is not +configured in `opts`. + +_If disabled_ + +```console +$ node example.js --unknown-option --known-option 2 --string-option --unknown-option2 +{ _: [], unknownOption: true, knownOption: 2, stringOption: '', unknownOption2: true } +``` + +_If enabled_ + +```console +$ node example.js --unknown-option --known-option 2 --string-option --unknown-option2 +{ _: ['--unknown-option'], knownOption: 2, stringOption: '--unknown-option2' } +``` + +## Supported Node.js Versions + +Libraries in this ecosystem make a best effort to track +[Node.js' release schedule](https://nodejs.org/en/about/releases/). Here's [a +post on why we think this is important](https://medium.com/the-node-js-collection/maintainers-should-consider-following-node-js-release-schedule-ab08ed4de71a). + +## Special Thanks + +The yargs project evolves from optimist and minimist. It owes its +existence to a lot of James Halliday's hard work. Thanks [substack](https://github.com/substack) **beep** **boop** \o/ + +## License + +ISC diff --git a/node_modules/yargs-parser/browser.js b/node_modules/yargs-parser/browser.js new file mode 100644 index 0000000..241202c --- /dev/null +++ b/node_modules/yargs-parser/browser.js @@ -0,0 +1,29 @@ +// Main entrypoint for ESM web browser environments. Avoids using Node.js +// specific libraries, such as "path". +// +// TODO: figure out reasonable web equivalents for "resolve", "normalize", etc. +import { camelCase, decamelize, looksLikeNumber } from './build/lib/string-utils.js' +import { YargsParser } from './build/lib/yargs-parser.js' +const parser = new YargsParser({ + cwd: () => { return '' }, + format: (str, arg) => { return str.replace('%s', arg) }, + normalize: (str) => { return str }, + resolve: (str) => { return str }, + require: () => { + throw Error('loading config from files not currently supported in browser') + }, + env: () => {} +}) + +const yargsParser = function Parser (args, opts) { + const result = parser.parse(args.slice(), opts) + return result.argv +} +yargsParser.detailed = function (args, opts) { + return parser.parse(args.slice(), opts) +} +yargsParser.camelCase = camelCase +yargsParser.decamelize = decamelize +yargsParser.looksLikeNumber = looksLikeNumber + +export default yargsParser diff --git a/node_modules/yargs-parser/build/index.cjs b/node_modules/yargs-parser/build/index.cjs new file mode 100644 index 0000000..cf6f50f --- /dev/null +++ b/node_modules/yargs-parser/build/index.cjs @@ -0,0 +1,1050 @@ +'use strict'; + +var util = require('util'); +var path = require('path'); +var fs = require('fs'); + +function camelCase(str) { + const isCamelCase = str !== str.toLowerCase() && str !== str.toUpperCase(); + if (!isCamelCase) { + str = str.toLowerCase(); + } + if (str.indexOf('-') === -1 && str.indexOf('_') === -1) { + return str; + } + else { + let camelcase = ''; + let nextChrUpper = false; + const leadingHyphens = str.match(/^-+/); + for (let i = leadingHyphens ? leadingHyphens[0].length : 0; i < str.length; i++) { + let chr = str.charAt(i); + if (nextChrUpper) { + nextChrUpper = false; + chr = chr.toUpperCase(); + } + if (i !== 0 && (chr === '-' || chr === '_')) { + nextChrUpper = true; + } + else if (chr !== '-' && chr !== '_') { + camelcase += chr; + } + } + return camelcase; + } +} +function decamelize(str, joinString) { + const lowercase = str.toLowerCase(); + joinString = joinString || '-'; + let notCamelcase = ''; + for (let i = 0; i < str.length; i++) { + const chrLower = lowercase.charAt(i); + const chrString = str.charAt(i); + if (chrLower !== chrString && i > 0) { + notCamelcase += `${joinString}${lowercase.charAt(i)}`; + } + else { + notCamelcase += chrString; + } + } + return notCamelcase; +} +function looksLikeNumber(x) { + if (x === null || x === undefined) + return false; + if (typeof x === 'number') + return true; + if (/^0x[0-9a-f]+$/i.test(x)) + return true; + if (/^0[^.]/.test(x)) + return false; + return /^[-]?(?:\d+(?:\.\d*)?|\.\d+)(e[-+]?\d+)?$/.test(x); +} + +function tokenizeArgString(argString) { + if (Array.isArray(argString)) { + return argString.map(e => typeof e !== 'string' ? e + '' : e); + } + argString = argString.trim(); + let i = 0; + let prevC = null; + let c = null; + let opening = null; + const args = []; + for (let ii = 0; ii < argString.length; ii++) { + prevC = c; + c = argString.charAt(ii); + if (c === ' ' && !opening) { + if (!(prevC === ' ')) { + i++; + } + continue; + } + if (c === opening) { + opening = null; + } + else if ((c === "'" || c === '"') && !opening) { + opening = c; + } + if (!args[i]) + args[i] = ''; + args[i] += c; + } + return args; +} + +var DefaultValuesForTypeKey; +(function (DefaultValuesForTypeKey) { + DefaultValuesForTypeKey["BOOLEAN"] = "boolean"; + DefaultValuesForTypeKey["STRING"] = "string"; + DefaultValuesForTypeKey["NUMBER"] = "number"; + DefaultValuesForTypeKey["ARRAY"] = "array"; +})(DefaultValuesForTypeKey || (DefaultValuesForTypeKey = {})); + +let mixin; +class YargsParser { + constructor(_mixin) { + mixin = _mixin; + } + parse(argsInput, options) { + const opts = Object.assign({ + alias: undefined, + array: undefined, + boolean: undefined, + config: undefined, + configObjects: undefined, + configuration: undefined, + coerce: undefined, + count: undefined, + default: undefined, + envPrefix: undefined, + narg: undefined, + normalize: undefined, + string: undefined, + number: undefined, + __: undefined, + key: undefined + }, options); + const args = tokenizeArgString(argsInput); + const inputIsString = typeof argsInput === 'string'; + const aliases = combineAliases(Object.assign(Object.create(null), opts.alias)); + const configuration = Object.assign({ + 'boolean-negation': true, + 'camel-case-expansion': true, + 'combine-arrays': false, + 'dot-notation': true, + 'duplicate-arguments-array': true, + 'flatten-duplicate-arrays': true, + 'greedy-arrays': true, + 'halt-at-non-option': false, + 'nargs-eats-options': false, + 'negation-prefix': 'no-', + 'parse-numbers': true, + 'parse-positional-numbers': true, + 'populate--': false, + 'set-placeholder-key': false, + 'short-option-groups': true, + 'strip-aliased': false, + 'strip-dashed': false, + 'unknown-options-as-args': false + }, opts.configuration); + const defaults = Object.assign(Object.create(null), opts.default); + const configObjects = opts.configObjects || []; + const envPrefix = opts.envPrefix; + const notFlagsOption = configuration['populate--']; + const notFlagsArgv = notFlagsOption ? '--' : '_'; + const newAliases = Object.create(null); + const defaulted = Object.create(null); + const __ = opts.__ || mixin.format; + const flags = { + aliases: Object.create(null), + arrays: Object.create(null), + bools: Object.create(null), + strings: Object.create(null), + numbers: Object.create(null), + counts: Object.create(null), + normalize: Object.create(null), + configs: Object.create(null), + nargs: Object.create(null), + coercions: Object.create(null), + keys: [] + }; + const negative = /^-([0-9]+(\.[0-9]+)?|\.[0-9]+)$/; + const negatedBoolean = new RegExp('^--' + configuration['negation-prefix'] + '(.+)'); + [].concat(opts.array || []).filter(Boolean).forEach(function (opt) { + const key = typeof opt === 'object' ? opt.key : opt; + const assignment = Object.keys(opt).map(function (key) { + const arrayFlagKeys = { + boolean: 'bools', + string: 'strings', + number: 'numbers' + }; + return arrayFlagKeys[key]; + }).filter(Boolean).pop(); + if (assignment) { + flags[assignment][key] = true; + } + flags.arrays[key] = true; + flags.keys.push(key); + }); + [].concat(opts.boolean || []).filter(Boolean).forEach(function (key) { + flags.bools[key] = true; + flags.keys.push(key); + }); + [].concat(opts.string || []).filter(Boolean).forEach(function (key) { + flags.strings[key] = true; + flags.keys.push(key); + }); + [].concat(opts.number || []).filter(Boolean).forEach(function (key) { + flags.numbers[key] = true; + flags.keys.push(key); + }); + [].concat(opts.count || []).filter(Boolean).forEach(function (key) { + flags.counts[key] = true; + flags.keys.push(key); + }); + [].concat(opts.normalize || []).filter(Boolean).forEach(function (key) { + flags.normalize[key] = true; + flags.keys.push(key); + }); + if (typeof opts.narg === 'object') { + Object.entries(opts.narg).forEach(([key, value]) => { + if (typeof value === 'number') { + flags.nargs[key] = value; + flags.keys.push(key); + } + }); + } + if (typeof opts.coerce === 'object') { + Object.entries(opts.coerce).forEach(([key, value]) => { + if (typeof value === 'function') { + flags.coercions[key] = value; + flags.keys.push(key); + } + }); + } + if (typeof opts.config !== 'undefined') { + if (Array.isArray(opts.config) || typeof opts.config === 'string') { + [].concat(opts.config).filter(Boolean).forEach(function (key) { + flags.configs[key] = true; + }); + } + else if (typeof opts.config === 'object') { + Object.entries(opts.config).forEach(([key, value]) => { + if (typeof value === 'boolean' || typeof value === 'function') { + flags.configs[key] = value; + } + }); + } + } + extendAliases(opts.key, aliases, opts.default, flags.arrays); + Object.keys(defaults).forEach(function (key) { + (flags.aliases[key] || []).forEach(function (alias) { + defaults[alias] = defaults[key]; + }); + }); + let error = null; + checkConfiguration(); + let notFlags = []; + const argv = Object.assign(Object.create(null), { _: [] }); + const argvReturn = {}; + for (let i = 0; i < args.length; i++) { + const arg = args[i]; + const truncatedArg = arg.replace(/^-{3,}/, '---'); + let broken; + let key; + let letters; + let m; + let next; + let value; + if (arg !== '--' && /^-/.test(arg) && isUnknownOptionAsArg(arg)) { + pushPositional(arg); + } + else if (truncatedArg.match(/^---+(=|$)/)) { + pushPositional(arg); + continue; + } + else if (arg.match(/^--.+=/) || (!configuration['short-option-groups'] && arg.match(/^-.+=/))) { + m = arg.match(/^--?([^=]+)=([\s\S]*)$/); + if (m !== null && Array.isArray(m) && m.length >= 3) { + if (checkAllAliases(m[1], flags.arrays)) { + i = eatArray(i, m[1], args, m[2]); + } + else if (checkAllAliases(m[1], flags.nargs) !== false) { + i = eatNargs(i, m[1], args, m[2]); + } + else { + setArg(m[1], m[2], true); + } + } + } + else if (arg.match(negatedBoolean) && configuration['boolean-negation']) { + m = arg.match(negatedBoolean); + if (m !== null && Array.isArray(m) && m.length >= 2) { + key = m[1]; + setArg(key, checkAllAliases(key, flags.arrays) ? [false] : false); + } + } + else if (arg.match(/^--.+/) || (!configuration['short-option-groups'] && arg.match(/^-[^-]+/))) { + m = arg.match(/^--?(.+)/); + if (m !== null && Array.isArray(m) && m.length >= 2) { + key = m[1]; + if (checkAllAliases(key, flags.arrays)) { + i = eatArray(i, key, args); + } + else if (checkAllAliases(key, flags.nargs) !== false) { + i = eatNargs(i, key, args); + } + else { + next = args[i + 1]; + if (next !== undefined && (!next.match(/^-/) || + next.match(negative)) && + !checkAllAliases(key, flags.bools) && + !checkAllAliases(key, flags.counts)) { + setArg(key, next); + i++; + } + else if (/^(true|false)$/.test(next)) { + setArg(key, next); + i++; + } + else { + setArg(key, defaultValue(key)); + } + } + } + } + else if (arg.match(/^-.\..+=/)) { + m = arg.match(/^-([^=]+)=([\s\S]*)$/); + if (m !== null && Array.isArray(m) && m.length >= 3) { + setArg(m[1], m[2]); + } + } + else if (arg.match(/^-.\..+/) && !arg.match(negative)) { + next = args[i + 1]; + m = arg.match(/^-(.\..+)/); + if (m !== null && Array.isArray(m) && m.length >= 2) { + key = m[1]; + if (next !== undefined && !next.match(/^-/) && + !checkAllAliases(key, flags.bools) && + !checkAllAliases(key, flags.counts)) { + setArg(key, next); + i++; + } + else { + setArg(key, defaultValue(key)); + } + } + } + else if (arg.match(/^-[^-]+/) && !arg.match(negative)) { + letters = arg.slice(1, -1).split(''); + broken = false; + for (let j = 0; j < letters.length; j++) { + next = arg.slice(j + 2); + if (letters[j + 1] && letters[j + 1] === '=') { + value = arg.slice(j + 3); + key = letters[j]; + if (checkAllAliases(key, flags.arrays)) { + i = eatArray(i, key, args, value); + } + else if (checkAllAliases(key, flags.nargs) !== false) { + i = eatNargs(i, key, args, value); + } + else { + setArg(key, value); + } + broken = true; + break; + } + if (next === '-') { + setArg(letters[j], next); + continue; + } + if (/[A-Za-z]/.test(letters[j]) && + /^-?\d+(\.\d*)?(e-?\d+)?$/.test(next) && + checkAllAliases(next, flags.bools) === false) { + setArg(letters[j], next); + broken = true; + break; + } + if (letters[j + 1] && letters[j + 1].match(/\W/)) { + setArg(letters[j], next); + broken = true; + break; + } + else { + setArg(letters[j], defaultValue(letters[j])); + } + } + key = arg.slice(-1)[0]; + if (!broken && key !== '-') { + if (checkAllAliases(key, flags.arrays)) { + i = eatArray(i, key, args); + } + else if (checkAllAliases(key, flags.nargs) !== false) { + i = eatNargs(i, key, args); + } + else { + next = args[i + 1]; + if (next !== undefined && (!/^(-|--)[^-]/.test(next) || + next.match(negative)) && + !checkAllAliases(key, flags.bools) && + !checkAllAliases(key, flags.counts)) { + setArg(key, next); + i++; + } + else if (/^(true|false)$/.test(next)) { + setArg(key, next); + i++; + } + else { + setArg(key, defaultValue(key)); + } + } + } + } + else if (arg.match(/^-[0-9]$/) && + arg.match(negative) && + checkAllAliases(arg.slice(1), flags.bools)) { + key = arg.slice(1); + setArg(key, defaultValue(key)); + } + else if (arg === '--') { + notFlags = args.slice(i + 1); + break; + } + else if (configuration['halt-at-non-option']) { + notFlags = args.slice(i); + break; + } + else { + pushPositional(arg); + } + } + applyEnvVars(argv, true); + applyEnvVars(argv, false); + setConfig(argv); + setConfigObjects(); + applyDefaultsAndAliases(argv, flags.aliases, defaults, true); + applyCoercions(argv); + if (configuration['set-placeholder-key']) + setPlaceholderKeys(argv); + Object.keys(flags.counts).forEach(function (key) { + if (!hasKey(argv, key.split('.'))) + setArg(key, 0); + }); + if (notFlagsOption && notFlags.length) + argv[notFlagsArgv] = []; + notFlags.forEach(function (key) { + argv[notFlagsArgv].push(key); + }); + if (configuration['camel-case-expansion'] && configuration['strip-dashed']) { + Object.keys(argv).filter(key => key !== '--' && key.includes('-')).forEach(key => { + delete argv[key]; + }); + } + if (configuration['strip-aliased']) { + [].concat(...Object.keys(aliases).map(k => aliases[k])).forEach(alias => { + if (configuration['camel-case-expansion'] && alias.includes('-')) { + delete argv[alias.split('.').map(prop => camelCase(prop)).join('.')]; + } + delete argv[alias]; + }); + } + function pushPositional(arg) { + const maybeCoercedNumber = maybeCoerceNumber('_', arg); + if (typeof maybeCoercedNumber === 'string' || typeof maybeCoercedNumber === 'number') { + argv._.push(maybeCoercedNumber); + } + } + function eatNargs(i, key, args, argAfterEqualSign) { + let ii; + let toEat = checkAllAliases(key, flags.nargs); + toEat = typeof toEat !== 'number' || isNaN(toEat) ? 1 : toEat; + if (toEat === 0) { + if (!isUndefined(argAfterEqualSign)) { + error = Error(__('Argument unexpected for: %s', key)); + } + setArg(key, defaultValue(key)); + return i; + } + let available = isUndefined(argAfterEqualSign) ? 0 : 1; + if (configuration['nargs-eats-options']) { + if (args.length - (i + 1) + available < toEat) { + error = Error(__('Not enough arguments following: %s', key)); + } + available = toEat; + } + else { + for (ii = i + 1; ii < args.length; ii++) { + if (!args[ii].match(/^-[^0-9]/) || args[ii].match(negative) || isUnknownOptionAsArg(args[ii])) + available++; + else + break; + } + if (available < toEat) + error = Error(__('Not enough arguments following: %s', key)); + } + let consumed = Math.min(available, toEat); + if (!isUndefined(argAfterEqualSign) && consumed > 0) { + setArg(key, argAfterEqualSign); + consumed--; + } + for (ii = i + 1; ii < (consumed + i + 1); ii++) { + setArg(key, args[ii]); + } + return (i + consumed); + } + function eatArray(i, key, args, argAfterEqualSign) { + let argsToSet = []; + let next = argAfterEqualSign || args[i + 1]; + const nargsCount = checkAllAliases(key, flags.nargs); + if (checkAllAliases(key, flags.bools) && !(/^(true|false)$/.test(next))) { + argsToSet.push(true); + } + else if (isUndefined(next) || + (isUndefined(argAfterEqualSign) && /^-/.test(next) && !negative.test(next) && !isUnknownOptionAsArg(next))) { + if (defaults[key] !== undefined) { + const defVal = defaults[key]; + argsToSet = Array.isArray(defVal) ? defVal : [defVal]; + } + } + else { + if (!isUndefined(argAfterEqualSign)) { + argsToSet.push(processValue(key, argAfterEqualSign, true)); + } + for (let ii = i + 1; ii < args.length; ii++) { + if ((!configuration['greedy-arrays'] && argsToSet.length > 0) || + (nargsCount && typeof nargsCount === 'number' && argsToSet.length >= nargsCount)) + break; + next = args[ii]; + if (/^-/.test(next) && !negative.test(next) && !isUnknownOptionAsArg(next)) + break; + i = ii; + argsToSet.push(processValue(key, next, inputIsString)); + } + } + if (typeof nargsCount === 'number' && ((nargsCount && argsToSet.length < nargsCount) || + (isNaN(nargsCount) && argsToSet.length === 0))) { + error = Error(__('Not enough arguments following: %s', key)); + } + setArg(key, argsToSet); + return i; + } + function setArg(key, val, shouldStripQuotes = inputIsString) { + if (/-/.test(key) && configuration['camel-case-expansion']) { + const alias = key.split('.').map(function (prop) { + return camelCase(prop); + }).join('.'); + addNewAlias(key, alias); + } + const value = processValue(key, val, shouldStripQuotes); + const splitKey = key.split('.'); + setKey(argv, splitKey, value); + if (flags.aliases[key]) { + flags.aliases[key].forEach(function (x) { + const keyProperties = x.split('.'); + setKey(argv, keyProperties, value); + }); + } + if (splitKey.length > 1 && configuration['dot-notation']) { + (flags.aliases[splitKey[0]] || []).forEach(function (x) { + let keyProperties = x.split('.'); + const a = [].concat(splitKey); + a.shift(); + keyProperties = keyProperties.concat(a); + if (!(flags.aliases[key] || []).includes(keyProperties.join('.'))) { + setKey(argv, keyProperties, value); + } + }); + } + if (checkAllAliases(key, flags.normalize) && !checkAllAliases(key, flags.arrays)) { + const keys = [key].concat(flags.aliases[key] || []); + keys.forEach(function (key) { + Object.defineProperty(argvReturn, key, { + enumerable: true, + get() { + return val; + }, + set(value) { + val = typeof value === 'string' ? mixin.normalize(value) : value; + } + }); + }); + } + } + function addNewAlias(key, alias) { + if (!(flags.aliases[key] && flags.aliases[key].length)) { + flags.aliases[key] = [alias]; + newAliases[alias] = true; + } + if (!(flags.aliases[alias] && flags.aliases[alias].length)) { + addNewAlias(alias, key); + } + } + function processValue(key, val, shouldStripQuotes) { + if (shouldStripQuotes) { + val = stripQuotes(val); + } + if (checkAllAliases(key, flags.bools) || checkAllAliases(key, flags.counts)) { + if (typeof val === 'string') + val = val === 'true'; + } + let value = Array.isArray(val) + ? val.map(function (v) { return maybeCoerceNumber(key, v); }) + : maybeCoerceNumber(key, val); + if (checkAllAliases(key, flags.counts) && (isUndefined(value) || typeof value === 'boolean')) { + value = increment(); + } + if (checkAllAliases(key, flags.normalize) && checkAllAliases(key, flags.arrays)) { + if (Array.isArray(val)) + value = val.map((val) => { return mixin.normalize(val); }); + else + value = mixin.normalize(val); + } + return value; + } + function maybeCoerceNumber(key, value) { + if (!configuration['parse-positional-numbers'] && key === '_') + return value; + if (!checkAllAliases(key, flags.strings) && !checkAllAliases(key, flags.bools) && !Array.isArray(value)) { + const shouldCoerceNumber = looksLikeNumber(value) && configuration['parse-numbers'] && (Number.isSafeInteger(Math.floor(parseFloat(`${value}`)))); + if (shouldCoerceNumber || (!isUndefined(value) && checkAllAliases(key, flags.numbers))) { + value = Number(value); + } + } + return value; + } + function setConfig(argv) { + const configLookup = Object.create(null); + applyDefaultsAndAliases(configLookup, flags.aliases, defaults); + Object.keys(flags.configs).forEach(function (configKey) { + const configPath = argv[configKey] || configLookup[configKey]; + if (configPath) { + try { + let config = null; + const resolvedConfigPath = mixin.resolve(mixin.cwd(), configPath); + const resolveConfig = flags.configs[configKey]; + if (typeof resolveConfig === 'function') { + try { + config = resolveConfig(resolvedConfigPath); + } + catch (e) { + config = e; + } + if (config instanceof Error) { + error = config; + return; + } + } + else { + config = mixin.require(resolvedConfigPath); + } + setConfigObject(config); + } + catch (ex) { + if (ex.name === 'PermissionDenied') + error = ex; + else if (argv[configKey]) + error = Error(__('Invalid JSON config file: %s', configPath)); + } + } + }); + } + function setConfigObject(config, prev) { + Object.keys(config).forEach(function (key) { + const value = config[key]; + const fullKey = prev ? prev + '.' + key : key; + if (typeof value === 'object' && value !== null && !Array.isArray(value) && configuration['dot-notation']) { + setConfigObject(value, fullKey); + } + else { + if (!hasKey(argv, fullKey.split('.')) || (checkAllAliases(fullKey, flags.arrays) && configuration['combine-arrays'])) { + setArg(fullKey, value); + } + } + }); + } + function setConfigObjects() { + if (typeof configObjects !== 'undefined') { + configObjects.forEach(function (configObject) { + setConfigObject(configObject); + }); + } + } + function applyEnvVars(argv, configOnly) { + if (typeof envPrefix === 'undefined') + return; + const prefix = typeof envPrefix === 'string' ? envPrefix : ''; + const env = mixin.env(); + Object.keys(env).forEach(function (envVar) { + if (prefix === '' || envVar.lastIndexOf(prefix, 0) === 0) { + const keys = envVar.split('__').map(function (key, i) { + if (i === 0) { + key = key.substring(prefix.length); + } + return camelCase(key); + }); + if (((configOnly && flags.configs[keys.join('.')]) || !configOnly) && !hasKey(argv, keys)) { + setArg(keys.join('.'), env[envVar]); + } + } + }); + } + function applyCoercions(argv) { + let coerce; + const applied = new Set(); + Object.keys(argv).forEach(function (key) { + if (!applied.has(key)) { + coerce = checkAllAliases(key, flags.coercions); + if (typeof coerce === 'function') { + try { + const value = maybeCoerceNumber(key, coerce(argv[key])); + ([].concat(flags.aliases[key] || [], key)).forEach(ali => { + applied.add(ali); + argv[ali] = value; + }); + } + catch (err) { + error = err; + } + } + } + }); + } + function setPlaceholderKeys(argv) { + flags.keys.forEach((key) => { + if (~key.indexOf('.')) + return; + if (typeof argv[key] === 'undefined') + argv[key] = undefined; + }); + return argv; + } + function applyDefaultsAndAliases(obj, aliases, defaults, canLog = false) { + Object.keys(defaults).forEach(function (key) { + if (!hasKey(obj, key.split('.'))) { + setKey(obj, key.split('.'), defaults[key]); + if (canLog) + defaulted[key] = true; + (aliases[key] || []).forEach(function (x) { + if (hasKey(obj, x.split('.'))) + return; + setKey(obj, x.split('.'), defaults[key]); + }); + } + }); + } + function hasKey(obj, keys) { + let o = obj; + if (!configuration['dot-notation']) + keys = [keys.join('.')]; + keys.slice(0, -1).forEach(function (key) { + o = (o[key] || {}); + }); + const key = keys[keys.length - 1]; + if (typeof o !== 'object') + return false; + else + return key in o; + } + function setKey(obj, keys, value) { + let o = obj; + if (!configuration['dot-notation']) + keys = [keys.join('.')]; + keys.slice(0, -1).forEach(function (key) { + key = sanitizeKey(key); + if (typeof o === 'object' && o[key] === undefined) { + o[key] = {}; + } + if (typeof o[key] !== 'object' || Array.isArray(o[key])) { + if (Array.isArray(o[key])) { + o[key].push({}); + } + else { + o[key] = [o[key], {}]; + } + o = o[key][o[key].length - 1]; + } + else { + o = o[key]; + } + }); + const key = sanitizeKey(keys[keys.length - 1]); + const isTypeArray = checkAllAliases(keys.join('.'), flags.arrays); + const isValueArray = Array.isArray(value); + let duplicate = configuration['duplicate-arguments-array']; + if (!duplicate && checkAllAliases(key, flags.nargs)) { + duplicate = true; + if ((!isUndefined(o[key]) && flags.nargs[key] === 1) || (Array.isArray(o[key]) && o[key].length === flags.nargs[key])) { + o[key] = undefined; + } + } + if (value === increment()) { + o[key] = increment(o[key]); + } + else if (Array.isArray(o[key])) { + if (duplicate && isTypeArray && isValueArray) { + o[key] = configuration['flatten-duplicate-arrays'] ? o[key].concat(value) : (Array.isArray(o[key][0]) ? o[key] : [o[key]]).concat([value]); + } + else if (!duplicate && Boolean(isTypeArray) === Boolean(isValueArray)) { + o[key] = value; + } + else { + o[key] = o[key].concat([value]); + } + } + else if (o[key] === undefined && isTypeArray) { + o[key] = isValueArray ? value : [value]; + } + else if (duplicate && !(o[key] === undefined || + checkAllAliases(key, flags.counts) || + checkAllAliases(key, flags.bools))) { + o[key] = [o[key], value]; + } + else { + o[key] = value; + } + } + function extendAliases(...args) { + args.forEach(function (obj) { + Object.keys(obj || {}).forEach(function (key) { + if (flags.aliases[key]) + return; + flags.aliases[key] = [].concat(aliases[key] || []); + flags.aliases[key].concat(key).forEach(function (x) { + if (/-/.test(x) && configuration['camel-case-expansion']) { + const c = camelCase(x); + if (c !== key && flags.aliases[key].indexOf(c) === -1) { + flags.aliases[key].push(c); + newAliases[c] = true; + } + } + }); + flags.aliases[key].concat(key).forEach(function (x) { + if (x.length > 1 && /[A-Z]/.test(x) && configuration['camel-case-expansion']) { + const c = decamelize(x, '-'); + if (c !== key && flags.aliases[key].indexOf(c) === -1) { + flags.aliases[key].push(c); + newAliases[c] = true; + } + } + }); + flags.aliases[key].forEach(function (x) { + flags.aliases[x] = [key].concat(flags.aliases[key].filter(function (y) { + return x !== y; + })); + }); + }); + }); + } + function checkAllAliases(key, flag) { + const toCheck = [].concat(flags.aliases[key] || [], key); + const keys = Object.keys(flag); + const setAlias = toCheck.find(key => keys.includes(key)); + return setAlias ? flag[setAlias] : false; + } + function hasAnyFlag(key) { + const flagsKeys = Object.keys(flags); + const toCheck = [].concat(flagsKeys.map(k => flags[k])); + return toCheck.some(function (flag) { + return Array.isArray(flag) ? flag.includes(key) : flag[key]; + }); + } + function hasFlagsMatching(arg, ...patterns) { + const toCheck = [].concat(...patterns); + return toCheck.some(function (pattern) { + const match = arg.match(pattern); + return match && hasAnyFlag(match[1]); + }); + } + function hasAllShortFlags(arg) { + if (arg.match(negative) || !arg.match(/^-[^-]+/)) { + return false; + } + let hasAllFlags = true; + let next; + const letters = arg.slice(1).split(''); + for (let j = 0; j < letters.length; j++) { + next = arg.slice(j + 2); + if (!hasAnyFlag(letters[j])) { + hasAllFlags = false; + break; + } + if ((letters[j + 1] && letters[j + 1] === '=') || + next === '-' || + (/[A-Za-z]/.test(letters[j]) && /^-?\d+(\.\d*)?(e-?\d+)?$/.test(next)) || + (letters[j + 1] && letters[j + 1].match(/\W/))) { + break; + } + } + return hasAllFlags; + } + function isUnknownOptionAsArg(arg) { + return configuration['unknown-options-as-args'] && isUnknownOption(arg); + } + function isUnknownOption(arg) { + arg = arg.replace(/^-{3,}/, '--'); + if (arg.match(negative)) { + return false; + } + if (hasAllShortFlags(arg)) { + return false; + } + const flagWithEquals = /^-+([^=]+?)=[\s\S]*$/; + const normalFlag = /^-+([^=]+?)$/; + const flagEndingInHyphen = /^-+([^=]+?)-$/; + const flagEndingInDigits = /^-+([^=]+?\d+)$/; + const flagEndingInNonWordCharacters = /^-+([^=]+?)\W+.*$/; + return !hasFlagsMatching(arg, flagWithEquals, negatedBoolean, normalFlag, flagEndingInHyphen, flagEndingInDigits, flagEndingInNonWordCharacters); + } + function defaultValue(key) { + if (!checkAllAliases(key, flags.bools) && + !checkAllAliases(key, flags.counts) && + `${key}` in defaults) { + return defaults[key]; + } + else { + return defaultForType(guessType(key)); + } + } + function defaultForType(type) { + const def = { + [DefaultValuesForTypeKey.BOOLEAN]: true, + [DefaultValuesForTypeKey.STRING]: '', + [DefaultValuesForTypeKey.NUMBER]: undefined, + [DefaultValuesForTypeKey.ARRAY]: [] + }; + return def[type]; + } + function guessType(key) { + let type = DefaultValuesForTypeKey.BOOLEAN; + if (checkAllAliases(key, flags.strings)) + type = DefaultValuesForTypeKey.STRING; + else if (checkAllAliases(key, flags.numbers)) + type = DefaultValuesForTypeKey.NUMBER; + else if (checkAllAliases(key, flags.bools)) + type = DefaultValuesForTypeKey.BOOLEAN; + else if (checkAllAliases(key, flags.arrays)) + type = DefaultValuesForTypeKey.ARRAY; + return type; + } + function isUndefined(num) { + return num === undefined; + } + function checkConfiguration() { + Object.keys(flags.counts).find(key => { + if (checkAllAliases(key, flags.arrays)) { + error = Error(__('Invalid configuration: %s, opts.count excludes opts.array.', key)); + return true; + } + else if (checkAllAliases(key, flags.nargs)) { + error = Error(__('Invalid configuration: %s, opts.count excludes opts.narg.', key)); + return true; + } + return false; + }); + } + return { + aliases: Object.assign({}, flags.aliases), + argv: Object.assign(argvReturn, argv), + configuration: configuration, + defaulted: Object.assign({}, defaulted), + error: error, + newAliases: Object.assign({}, newAliases) + }; + } +} +function combineAliases(aliases) { + const aliasArrays = []; + const combined = Object.create(null); + let change = true; + Object.keys(aliases).forEach(function (key) { + aliasArrays.push([].concat(aliases[key], key)); + }); + while (change) { + change = false; + for (let i = 0; i < aliasArrays.length; i++) { + for (let ii = i + 1; ii < aliasArrays.length; ii++) { + const intersect = aliasArrays[i].filter(function (v) { + return aliasArrays[ii].indexOf(v) !== -1; + }); + if (intersect.length) { + aliasArrays[i] = aliasArrays[i].concat(aliasArrays[ii]); + aliasArrays.splice(ii, 1); + change = true; + break; + } + } + } + } + aliasArrays.forEach(function (aliasArray) { + aliasArray = aliasArray.filter(function (v, i, self) { + return self.indexOf(v) === i; + }); + const lastAlias = aliasArray.pop(); + if (lastAlias !== undefined && typeof lastAlias === 'string') { + combined[lastAlias] = aliasArray; + } + }); + return combined; +} +function increment(orig) { + return orig !== undefined ? orig + 1 : 1; +} +function sanitizeKey(key) { + if (key === '__proto__') + return '___proto___'; + return key; +} +function stripQuotes(val) { + return (typeof val === 'string' && + (val[0] === "'" || val[0] === '"') && + val[val.length - 1] === val[0]) + ? val.substring(1, val.length - 1) + : val; +} + +var _a, _b, _c; +const minNodeVersion = (process && process.env && process.env.YARGS_MIN_NODE_VERSION) + ? Number(process.env.YARGS_MIN_NODE_VERSION) + : 12; +const nodeVersion = (_b = (_a = process === null || process === void 0 ? void 0 : process.versions) === null || _a === void 0 ? void 0 : _a.node) !== null && _b !== void 0 ? _b : (_c = process === null || process === void 0 ? void 0 : process.version) === null || _c === void 0 ? void 0 : _c.slice(1); +if (nodeVersion) { + const major = Number(nodeVersion.match(/^([^.]+)/)[1]); + if (major < minNodeVersion) { + throw Error(`yargs parser supports a minimum Node.js version of ${minNodeVersion}. Read our version support policy: https://github.com/yargs/yargs-parser#supported-nodejs-versions`); + } +} +const env = process ? process.env : {}; +const parser = new YargsParser({ + cwd: process.cwd, + env: () => { + return env; + }, + format: util.format, + normalize: path.normalize, + resolve: path.resolve, + require: (path) => { + if (typeof require !== 'undefined') { + return require(path); + } + else if (path.match(/\.json$/)) { + return JSON.parse(fs.readFileSync(path, 'utf8')); + } + else { + throw Error('only .json config files are supported in ESM'); + } + } +}); +const yargsParser = function Parser(args, opts) { + const result = parser.parse(args.slice(), opts); + return result.argv; +}; +yargsParser.detailed = function (args, opts) { + return parser.parse(args.slice(), opts); +}; +yargsParser.camelCase = camelCase; +yargsParser.decamelize = decamelize; +yargsParser.looksLikeNumber = looksLikeNumber; + +module.exports = yargsParser; diff --git a/node_modules/yargs-parser/build/lib/index.js b/node_modules/yargs-parser/build/lib/index.js new file mode 100644 index 0000000..43ef485 --- /dev/null +++ b/node_modules/yargs-parser/build/lib/index.js @@ -0,0 +1,62 @@ +/** + * @fileoverview Main entrypoint for libraries using yargs-parser in Node.js + * CJS and ESM environments. + * + * @license + * Copyright (c) 2016, Contributors + * SPDX-License-Identifier: ISC + */ +var _a, _b, _c; +import { format } from 'util'; +import { normalize, resolve } from 'path'; +import { camelCase, decamelize, looksLikeNumber } from './string-utils.js'; +import { YargsParser } from './yargs-parser.js'; +import { readFileSync } from 'fs'; +// See https://github.com/yargs/yargs-parser#supported-nodejs-versions for our +// version support policy. The YARGS_MIN_NODE_VERSION is used for testing only. +const minNodeVersion = (process && process.env && process.env.YARGS_MIN_NODE_VERSION) + ? Number(process.env.YARGS_MIN_NODE_VERSION) + : 12; +const nodeVersion = (_b = (_a = process === null || process === void 0 ? void 0 : process.versions) === null || _a === void 0 ? void 0 : _a.node) !== null && _b !== void 0 ? _b : (_c = process === null || process === void 0 ? void 0 : process.version) === null || _c === void 0 ? void 0 : _c.slice(1); +if (nodeVersion) { + const major = Number(nodeVersion.match(/^([^.]+)/)[1]); + if (major < minNodeVersion) { + throw Error(`yargs parser supports a minimum Node.js version of ${minNodeVersion}. Read our version support policy: https://github.com/yargs/yargs-parser#supported-nodejs-versions`); + } +} +// Creates a yargs-parser instance using Node.js standard libraries: +const env = process ? process.env : {}; +const parser = new YargsParser({ + cwd: process.cwd, + env: () => { + return env; + }, + format, + normalize, + resolve, + // TODO: figure out a way to combine ESM and CJS coverage, such that + // we can exercise all the lines below: + require: (path) => { + if (typeof require !== 'undefined') { + return require(path); + } + else if (path.match(/\.json$/)) { + // Addresses: https://github.com/yargs/yargs/issues/2040 + return JSON.parse(readFileSync(path, 'utf8')); + } + else { + throw Error('only .json config files are supported in ESM'); + } + } +}); +const yargsParser = function Parser(args, opts) { + const result = parser.parse(args.slice(), opts); + return result.argv; +}; +yargsParser.detailed = function (args, opts) { + return parser.parse(args.slice(), opts); +}; +yargsParser.camelCase = camelCase; +yargsParser.decamelize = decamelize; +yargsParser.looksLikeNumber = looksLikeNumber; +export default yargsParser; diff --git a/node_modules/yargs-parser/build/lib/string-utils.js b/node_modules/yargs-parser/build/lib/string-utils.js new file mode 100644 index 0000000..4e8bd99 --- /dev/null +++ b/node_modules/yargs-parser/build/lib/string-utils.js @@ -0,0 +1,65 @@ +/** + * @license + * Copyright (c) 2016, Contributors + * SPDX-License-Identifier: ISC + */ +export function camelCase(str) { + // Handle the case where an argument is provided as camel case, e.g., fooBar. + // by ensuring that the string isn't already mixed case: + const isCamelCase = str !== str.toLowerCase() && str !== str.toUpperCase(); + if (!isCamelCase) { + str = str.toLowerCase(); + } + if (str.indexOf('-') === -1 && str.indexOf('_') === -1) { + return str; + } + else { + let camelcase = ''; + let nextChrUpper = false; + const leadingHyphens = str.match(/^-+/); + for (let i = leadingHyphens ? leadingHyphens[0].length : 0; i < str.length; i++) { + let chr = str.charAt(i); + if (nextChrUpper) { + nextChrUpper = false; + chr = chr.toUpperCase(); + } + if (i !== 0 && (chr === '-' || chr === '_')) { + nextChrUpper = true; + } + else if (chr !== '-' && chr !== '_') { + camelcase += chr; + } + } + return camelcase; + } +} +export function decamelize(str, joinString) { + const lowercase = str.toLowerCase(); + joinString = joinString || '-'; + let notCamelcase = ''; + for (let i = 0; i < str.length; i++) { + const chrLower = lowercase.charAt(i); + const chrString = str.charAt(i); + if (chrLower !== chrString && i > 0) { + notCamelcase += `${joinString}${lowercase.charAt(i)}`; + } + else { + notCamelcase += chrString; + } + } + return notCamelcase; +} +export function looksLikeNumber(x) { + if (x === null || x === undefined) + return false; + // if loaded from config, may already be a number. + if (typeof x === 'number') + return true; + // hexadecimal. + if (/^0x[0-9a-f]+$/i.test(x)) + return true; + // don't treat 0123 as a number; as it drops the leading '0'. + if (/^0[^.]/.test(x)) + return false; + return /^[-]?(?:\d+(?:\.\d*)?|\.\d+)(e[-+]?\d+)?$/.test(x); +} diff --git a/node_modules/yargs-parser/build/lib/tokenize-arg-string.js b/node_modules/yargs-parser/build/lib/tokenize-arg-string.js new file mode 100644 index 0000000..5e732ef --- /dev/null +++ b/node_modules/yargs-parser/build/lib/tokenize-arg-string.js @@ -0,0 +1,40 @@ +/** + * @license + * Copyright (c) 2016, Contributors + * SPDX-License-Identifier: ISC + */ +// take an un-split argv string and tokenize it. +export function tokenizeArgString(argString) { + if (Array.isArray(argString)) { + return argString.map(e => typeof e !== 'string' ? e + '' : e); + } + argString = argString.trim(); + let i = 0; + let prevC = null; + let c = null; + let opening = null; + const args = []; + for (let ii = 0; ii < argString.length; ii++) { + prevC = c; + c = argString.charAt(ii); + // split on spaces unless we're in quotes. + if (c === ' ' && !opening) { + if (!(prevC === ' ')) { + i++; + } + continue; + } + // don't split the string if we're in matching + // opening or closing single and double quotes. + if (c === opening) { + opening = null; + } + else if ((c === "'" || c === '"') && !opening) { + opening = c; + } + if (!args[i]) + args[i] = ''; + args[i] += c; + } + return args; +} diff --git a/node_modules/yargs-parser/build/lib/yargs-parser-types.js b/node_modules/yargs-parser/build/lib/yargs-parser-types.js new file mode 100644 index 0000000..63b7c31 --- /dev/null +++ b/node_modules/yargs-parser/build/lib/yargs-parser-types.js @@ -0,0 +1,12 @@ +/** + * @license + * Copyright (c) 2016, Contributors + * SPDX-License-Identifier: ISC + */ +export var DefaultValuesForTypeKey; +(function (DefaultValuesForTypeKey) { + DefaultValuesForTypeKey["BOOLEAN"] = "boolean"; + DefaultValuesForTypeKey["STRING"] = "string"; + DefaultValuesForTypeKey["NUMBER"] = "number"; + DefaultValuesForTypeKey["ARRAY"] = "array"; +})(DefaultValuesForTypeKey || (DefaultValuesForTypeKey = {})); diff --git a/node_modules/yargs-parser/build/lib/yargs-parser.js b/node_modules/yargs-parser/build/lib/yargs-parser.js new file mode 100644 index 0000000..415d4bc --- /dev/null +++ b/node_modules/yargs-parser/build/lib/yargs-parser.js @@ -0,0 +1,1045 @@ +/** + * @license + * Copyright (c) 2016, Contributors + * SPDX-License-Identifier: ISC + */ +import { tokenizeArgString } from './tokenize-arg-string.js'; +import { DefaultValuesForTypeKey } from './yargs-parser-types.js'; +import { camelCase, decamelize, looksLikeNumber } from './string-utils.js'; +let mixin; +export class YargsParser { + constructor(_mixin) { + mixin = _mixin; + } + parse(argsInput, options) { + const opts = Object.assign({ + alias: undefined, + array: undefined, + boolean: undefined, + config: undefined, + configObjects: undefined, + configuration: undefined, + coerce: undefined, + count: undefined, + default: undefined, + envPrefix: undefined, + narg: undefined, + normalize: undefined, + string: undefined, + number: undefined, + __: undefined, + key: undefined + }, options); + // allow a string argument to be passed in rather + // than an argv array. + const args = tokenizeArgString(argsInput); + // tokenizeArgString adds extra quotes to args if argsInput is a string + // only strip those extra quotes in processValue if argsInput is a string + const inputIsString = typeof argsInput === 'string'; + // aliases might have transitive relationships, normalize this. + const aliases = combineAliases(Object.assign(Object.create(null), opts.alias)); + const configuration = Object.assign({ + 'boolean-negation': true, + 'camel-case-expansion': true, + 'combine-arrays': false, + 'dot-notation': true, + 'duplicate-arguments-array': true, + 'flatten-duplicate-arrays': true, + 'greedy-arrays': true, + 'halt-at-non-option': false, + 'nargs-eats-options': false, + 'negation-prefix': 'no-', + 'parse-numbers': true, + 'parse-positional-numbers': true, + 'populate--': false, + 'set-placeholder-key': false, + 'short-option-groups': true, + 'strip-aliased': false, + 'strip-dashed': false, + 'unknown-options-as-args': false + }, opts.configuration); + const defaults = Object.assign(Object.create(null), opts.default); + const configObjects = opts.configObjects || []; + const envPrefix = opts.envPrefix; + const notFlagsOption = configuration['populate--']; + const notFlagsArgv = notFlagsOption ? '--' : '_'; + const newAliases = Object.create(null); + const defaulted = Object.create(null); + // allow a i18n handler to be passed in, default to a fake one (util.format). + const __ = opts.__ || mixin.format; + const flags = { + aliases: Object.create(null), + arrays: Object.create(null), + bools: Object.create(null), + strings: Object.create(null), + numbers: Object.create(null), + counts: Object.create(null), + normalize: Object.create(null), + configs: Object.create(null), + nargs: Object.create(null), + coercions: Object.create(null), + keys: [] + }; + const negative = /^-([0-9]+(\.[0-9]+)?|\.[0-9]+)$/; + const negatedBoolean = new RegExp('^--' + configuration['negation-prefix'] + '(.+)'); + [].concat(opts.array || []).filter(Boolean).forEach(function (opt) { + const key = typeof opt === 'object' ? opt.key : opt; + // assign to flags[bools|strings|numbers] + const assignment = Object.keys(opt).map(function (key) { + const arrayFlagKeys = { + boolean: 'bools', + string: 'strings', + number: 'numbers' + }; + return arrayFlagKeys[key]; + }).filter(Boolean).pop(); + // assign key to be coerced + if (assignment) { + flags[assignment][key] = true; + } + flags.arrays[key] = true; + flags.keys.push(key); + }); + [].concat(opts.boolean || []).filter(Boolean).forEach(function (key) { + flags.bools[key] = true; + flags.keys.push(key); + }); + [].concat(opts.string || []).filter(Boolean).forEach(function (key) { + flags.strings[key] = true; + flags.keys.push(key); + }); + [].concat(opts.number || []).filter(Boolean).forEach(function (key) { + flags.numbers[key] = true; + flags.keys.push(key); + }); + [].concat(opts.count || []).filter(Boolean).forEach(function (key) { + flags.counts[key] = true; + flags.keys.push(key); + }); + [].concat(opts.normalize || []).filter(Boolean).forEach(function (key) { + flags.normalize[key] = true; + flags.keys.push(key); + }); + if (typeof opts.narg === 'object') { + Object.entries(opts.narg).forEach(([key, value]) => { + if (typeof value === 'number') { + flags.nargs[key] = value; + flags.keys.push(key); + } + }); + } + if (typeof opts.coerce === 'object') { + Object.entries(opts.coerce).forEach(([key, value]) => { + if (typeof value === 'function') { + flags.coercions[key] = value; + flags.keys.push(key); + } + }); + } + if (typeof opts.config !== 'undefined') { + if (Array.isArray(opts.config) || typeof opts.config === 'string') { + ; + [].concat(opts.config).filter(Boolean).forEach(function (key) { + flags.configs[key] = true; + }); + } + else if (typeof opts.config === 'object') { + Object.entries(opts.config).forEach(([key, value]) => { + if (typeof value === 'boolean' || typeof value === 'function') { + flags.configs[key] = value; + } + }); + } + } + // create a lookup table that takes into account all + // combinations of aliases: {f: ['foo'], foo: ['f']} + extendAliases(opts.key, aliases, opts.default, flags.arrays); + // apply default values to all aliases. + Object.keys(defaults).forEach(function (key) { + (flags.aliases[key] || []).forEach(function (alias) { + defaults[alias] = defaults[key]; + }); + }); + let error = null; + checkConfiguration(); + let notFlags = []; + const argv = Object.assign(Object.create(null), { _: [] }); + // TODO(bcoe): for the first pass at removing object prototype we didn't + // remove all prototypes from objects returned by this API, we might want + // to gradually move towards doing so. + const argvReturn = {}; + for (let i = 0; i < args.length; i++) { + const arg = args[i]; + const truncatedArg = arg.replace(/^-{3,}/, '---'); + let broken; + let key; + let letters; + let m; + let next; + let value; + // any unknown option (except for end-of-options, "--") + if (arg !== '--' && /^-/.test(arg) && isUnknownOptionAsArg(arg)) { + pushPositional(arg); + // ---, ---=, ----, etc, + } + else if (truncatedArg.match(/^---+(=|$)/)) { + // options without key name are invalid. + pushPositional(arg); + continue; + // -- separated by = + } + else if (arg.match(/^--.+=/) || (!configuration['short-option-groups'] && arg.match(/^-.+=/))) { + // Using [\s\S] instead of . because js doesn't support the + // 'dotall' regex modifier. See: + // http://stackoverflow.com/a/1068308/13216 + m = arg.match(/^--?([^=]+)=([\s\S]*)$/); + // arrays format = '--f=a b c' + if (m !== null && Array.isArray(m) && m.length >= 3) { + if (checkAllAliases(m[1], flags.arrays)) { + i = eatArray(i, m[1], args, m[2]); + } + else if (checkAllAliases(m[1], flags.nargs) !== false) { + // nargs format = '--f=monkey washing cat' + i = eatNargs(i, m[1], args, m[2]); + } + else { + setArg(m[1], m[2], true); + } + } + } + else if (arg.match(negatedBoolean) && configuration['boolean-negation']) { + m = arg.match(negatedBoolean); + if (m !== null && Array.isArray(m) && m.length >= 2) { + key = m[1]; + setArg(key, checkAllAliases(key, flags.arrays) ? [false] : false); + } + // -- separated by space. + } + else if (arg.match(/^--.+/) || (!configuration['short-option-groups'] && arg.match(/^-[^-]+/))) { + m = arg.match(/^--?(.+)/); + if (m !== null && Array.isArray(m) && m.length >= 2) { + key = m[1]; + if (checkAllAliases(key, flags.arrays)) { + // array format = '--foo a b c' + i = eatArray(i, key, args); + } + else if (checkAllAliases(key, flags.nargs) !== false) { + // nargs format = '--foo a b c' + // should be truthy even if: flags.nargs[key] === 0 + i = eatNargs(i, key, args); + } + else { + next = args[i + 1]; + if (next !== undefined && (!next.match(/^-/) || + next.match(negative)) && + !checkAllAliases(key, flags.bools) && + !checkAllAliases(key, flags.counts)) { + setArg(key, next); + i++; + } + else if (/^(true|false)$/.test(next)) { + setArg(key, next); + i++; + } + else { + setArg(key, defaultValue(key)); + } + } + } + // dot-notation flag separated by '='. + } + else if (arg.match(/^-.\..+=/)) { + m = arg.match(/^-([^=]+)=([\s\S]*)$/); + if (m !== null && Array.isArray(m) && m.length >= 3) { + setArg(m[1], m[2]); + } + // dot-notation flag separated by space. + } + else if (arg.match(/^-.\..+/) && !arg.match(negative)) { + next = args[i + 1]; + m = arg.match(/^-(.\..+)/); + if (m !== null && Array.isArray(m) && m.length >= 2) { + key = m[1]; + if (next !== undefined && !next.match(/^-/) && + !checkAllAliases(key, flags.bools) && + !checkAllAliases(key, flags.counts)) { + setArg(key, next); + i++; + } + else { + setArg(key, defaultValue(key)); + } + } + } + else if (arg.match(/^-[^-]+/) && !arg.match(negative)) { + letters = arg.slice(1, -1).split(''); + broken = false; + for (let j = 0; j < letters.length; j++) { + next = arg.slice(j + 2); + if (letters[j + 1] && letters[j + 1] === '=') { + value = arg.slice(j + 3); + key = letters[j]; + if (checkAllAliases(key, flags.arrays)) { + // array format = '-f=a b c' + i = eatArray(i, key, args, value); + } + else if (checkAllAliases(key, flags.nargs) !== false) { + // nargs format = '-f=monkey washing cat' + i = eatNargs(i, key, args, value); + } + else { + setArg(key, value); + } + broken = true; + break; + } + if (next === '-') { + setArg(letters[j], next); + continue; + } + // current letter is an alphabetic character and next value is a number + if (/[A-Za-z]/.test(letters[j]) && + /^-?\d+(\.\d*)?(e-?\d+)?$/.test(next) && + checkAllAliases(next, flags.bools) === false) { + setArg(letters[j], next); + broken = true; + break; + } + if (letters[j + 1] && letters[j + 1].match(/\W/)) { + setArg(letters[j], next); + broken = true; + break; + } + else { + setArg(letters[j], defaultValue(letters[j])); + } + } + key = arg.slice(-1)[0]; + if (!broken && key !== '-') { + if (checkAllAliases(key, flags.arrays)) { + // array format = '-f a b c' + i = eatArray(i, key, args); + } + else if (checkAllAliases(key, flags.nargs) !== false) { + // nargs format = '-f a b c' + // should be truthy even if: flags.nargs[key] === 0 + i = eatNargs(i, key, args); + } + else { + next = args[i + 1]; + if (next !== undefined && (!/^(-|--)[^-]/.test(next) || + next.match(negative)) && + !checkAllAliases(key, flags.bools) && + !checkAllAliases(key, flags.counts)) { + setArg(key, next); + i++; + } + else if (/^(true|false)$/.test(next)) { + setArg(key, next); + i++; + } + else { + setArg(key, defaultValue(key)); + } + } + } + } + else if (arg.match(/^-[0-9]$/) && + arg.match(negative) && + checkAllAliases(arg.slice(1), flags.bools)) { + // single-digit boolean alias, e.g: xargs -0 + key = arg.slice(1); + setArg(key, defaultValue(key)); + } + else if (arg === '--') { + notFlags = args.slice(i + 1); + break; + } + else if (configuration['halt-at-non-option']) { + notFlags = args.slice(i); + break; + } + else { + pushPositional(arg); + } + } + // order of precedence: + // 1. command line arg + // 2. value from env var + // 3. value from config file + // 4. value from config objects + // 5. configured default value + applyEnvVars(argv, true); // special case: check env vars that point to config file + applyEnvVars(argv, false); + setConfig(argv); + setConfigObjects(); + applyDefaultsAndAliases(argv, flags.aliases, defaults, true); + applyCoercions(argv); + if (configuration['set-placeholder-key']) + setPlaceholderKeys(argv); + // for any counts either not in args or without an explicit default, set to 0 + Object.keys(flags.counts).forEach(function (key) { + if (!hasKey(argv, key.split('.'))) + setArg(key, 0); + }); + // '--' defaults to undefined. + if (notFlagsOption && notFlags.length) + argv[notFlagsArgv] = []; + notFlags.forEach(function (key) { + argv[notFlagsArgv].push(key); + }); + if (configuration['camel-case-expansion'] && configuration['strip-dashed']) { + Object.keys(argv).filter(key => key !== '--' && key.includes('-')).forEach(key => { + delete argv[key]; + }); + } + if (configuration['strip-aliased']) { + ; + [].concat(...Object.keys(aliases).map(k => aliases[k])).forEach(alias => { + if (configuration['camel-case-expansion'] && alias.includes('-')) { + delete argv[alias.split('.').map(prop => camelCase(prop)).join('.')]; + } + delete argv[alias]; + }); + } + // Push argument into positional array, applying numeric coercion: + function pushPositional(arg) { + const maybeCoercedNumber = maybeCoerceNumber('_', arg); + if (typeof maybeCoercedNumber === 'string' || typeof maybeCoercedNumber === 'number') { + argv._.push(maybeCoercedNumber); + } + } + // how many arguments should we consume, based + // on the nargs option? + function eatNargs(i, key, args, argAfterEqualSign) { + let ii; + let toEat = checkAllAliases(key, flags.nargs); + // NaN has a special meaning for the array type, indicating that one or + // more values are expected. + toEat = typeof toEat !== 'number' || isNaN(toEat) ? 1 : toEat; + if (toEat === 0) { + if (!isUndefined(argAfterEqualSign)) { + error = Error(__('Argument unexpected for: %s', key)); + } + setArg(key, defaultValue(key)); + return i; + } + let available = isUndefined(argAfterEqualSign) ? 0 : 1; + if (configuration['nargs-eats-options']) { + // classic behavior, yargs eats positional and dash arguments. + if (args.length - (i + 1) + available < toEat) { + error = Error(__('Not enough arguments following: %s', key)); + } + available = toEat; + } + else { + // nargs will not consume flag arguments, e.g., -abc, --foo, + // and terminates when one is observed. + for (ii = i + 1; ii < args.length; ii++) { + if (!args[ii].match(/^-[^0-9]/) || args[ii].match(negative) || isUnknownOptionAsArg(args[ii])) + available++; + else + break; + } + if (available < toEat) + error = Error(__('Not enough arguments following: %s', key)); + } + let consumed = Math.min(available, toEat); + if (!isUndefined(argAfterEqualSign) && consumed > 0) { + setArg(key, argAfterEqualSign); + consumed--; + } + for (ii = i + 1; ii < (consumed + i + 1); ii++) { + setArg(key, args[ii]); + } + return (i + consumed); + } + // if an option is an array, eat all non-hyphenated arguments + // following it... YUM! + // e.g., --foo apple banana cat becomes ["apple", "banana", "cat"] + function eatArray(i, key, args, argAfterEqualSign) { + let argsToSet = []; + let next = argAfterEqualSign || args[i + 1]; + // If both array and nargs are configured, enforce the nargs count: + const nargsCount = checkAllAliases(key, flags.nargs); + if (checkAllAliases(key, flags.bools) && !(/^(true|false)$/.test(next))) { + argsToSet.push(true); + } + else if (isUndefined(next) || + (isUndefined(argAfterEqualSign) && /^-/.test(next) && !negative.test(next) && !isUnknownOptionAsArg(next))) { + // for keys without value ==> argsToSet remains an empty [] + // set user default value, if available + if (defaults[key] !== undefined) { + const defVal = defaults[key]; + argsToSet = Array.isArray(defVal) ? defVal : [defVal]; + } + } + else { + // value in --option=value is eaten as is + if (!isUndefined(argAfterEqualSign)) { + argsToSet.push(processValue(key, argAfterEqualSign, true)); + } + for (let ii = i + 1; ii < args.length; ii++) { + if ((!configuration['greedy-arrays'] && argsToSet.length > 0) || + (nargsCount && typeof nargsCount === 'number' && argsToSet.length >= nargsCount)) + break; + next = args[ii]; + if (/^-/.test(next) && !negative.test(next) && !isUnknownOptionAsArg(next)) + break; + i = ii; + argsToSet.push(processValue(key, next, inputIsString)); + } + } + // If both array and nargs are configured, create an error if less than + // nargs positionals were found. NaN has special meaning, indicating + // that at least one value is required (more are okay). + if (typeof nargsCount === 'number' && ((nargsCount && argsToSet.length < nargsCount) || + (isNaN(nargsCount) && argsToSet.length === 0))) { + error = Error(__('Not enough arguments following: %s', key)); + } + setArg(key, argsToSet); + return i; + } + function setArg(key, val, shouldStripQuotes = inputIsString) { + if (/-/.test(key) && configuration['camel-case-expansion']) { + const alias = key.split('.').map(function (prop) { + return camelCase(prop); + }).join('.'); + addNewAlias(key, alias); + } + const value = processValue(key, val, shouldStripQuotes); + const splitKey = key.split('.'); + setKey(argv, splitKey, value); + // handle populating aliases of the full key + if (flags.aliases[key]) { + flags.aliases[key].forEach(function (x) { + const keyProperties = x.split('.'); + setKey(argv, keyProperties, value); + }); + } + // handle populating aliases of the first element of the dot-notation key + if (splitKey.length > 1 && configuration['dot-notation']) { + ; + (flags.aliases[splitKey[0]] || []).forEach(function (x) { + let keyProperties = x.split('.'); + // expand alias with nested objects in key + const a = [].concat(splitKey); + a.shift(); // nuke the old key. + keyProperties = keyProperties.concat(a); + // populate alias only if is not already an alias of the full key + // (already populated above) + if (!(flags.aliases[key] || []).includes(keyProperties.join('.'))) { + setKey(argv, keyProperties, value); + } + }); + } + // Set normalize getter and setter when key is in 'normalize' but isn't an array + if (checkAllAliases(key, flags.normalize) && !checkAllAliases(key, flags.arrays)) { + const keys = [key].concat(flags.aliases[key] || []); + keys.forEach(function (key) { + Object.defineProperty(argvReturn, key, { + enumerable: true, + get() { + return val; + }, + set(value) { + val = typeof value === 'string' ? mixin.normalize(value) : value; + } + }); + }); + } + } + function addNewAlias(key, alias) { + if (!(flags.aliases[key] && flags.aliases[key].length)) { + flags.aliases[key] = [alias]; + newAliases[alias] = true; + } + if (!(flags.aliases[alias] && flags.aliases[alias].length)) { + addNewAlias(alias, key); + } + } + function processValue(key, val, shouldStripQuotes) { + // strings may be quoted, clean this up as we assign values. + if (shouldStripQuotes) { + val = stripQuotes(val); + } + // handle parsing boolean arguments --foo=true --bar false. + if (checkAllAliases(key, flags.bools) || checkAllAliases(key, flags.counts)) { + if (typeof val === 'string') + val = val === 'true'; + } + let value = Array.isArray(val) + ? val.map(function (v) { return maybeCoerceNumber(key, v); }) + : maybeCoerceNumber(key, val); + // increment a count given as arg (either no value or value parsed as boolean) + if (checkAllAliases(key, flags.counts) && (isUndefined(value) || typeof value === 'boolean')) { + value = increment(); + } + // Set normalized value when key is in 'normalize' and in 'arrays' + if (checkAllAliases(key, flags.normalize) && checkAllAliases(key, flags.arrays)) { + if (Array.isArray(val)) + value = val.map((val) => { return mixin.normalize(val); }); + else + value = mixin.normalize(val); + } + return value; + } + function maybeCoerceNumber(key, value) { + if (!configuration['parse-positional-numbers'] && key === '_') + return value; + if (!checkAllAliases(key, flags.strings) && !checkAllAliases(key, flags.bools) && !Array.isArray(value)) { + const shouldCoerceNumber = looksLikeNumber(value) && configuration['parse-numbers'] && (Number.isSafeInteger(Math.floor(parseFloat(`${value}`)))); + if (shouldCoerceNumber || (!isUndefined(value) && checkAllAliases(key, flags.numbers))) { + value = Number(value); + } + } + return value; + } + // set args from config.json file, this should be + // applied last so that defaults can be applied. + function setConfig(argv) { + const configLookup = Object.create(null); + // expand defaults/aliases, in-case any happen to reference + // the config.json file. + applyDefaultsAndAliases(configLookup, flags.aliases, defaults); + Object.keys(flags.configs).forEach(function (configKey) { + const configPath = argv[configKey] || configLookup[configKey]; + if (configPath) { + try { + let config = null; + const resolvedConfigPath = mixin.resolve(mixin.cwd(), configPath); + const resolveConfig = flags.configs[configKey]; + if (typeof resolveConfig === 'function') { + try { + config = resolveConfig(resolvedConfigPath); + } + catch (e) { + config = e; + } + if (config instanceof Error) { + error = config; + return; + } + } + else { + config = mixin.require(resolvedConfigPath); + } + setConfigObject(config); + } + catch (ex) { + // Deno will receive a PermissionDenied error if an attempt is + // made to load config without the --allow-read flag: + if (ex.name === 'PermissionDenied') + error = ex; + else if (argv[configKey]) + error = Error(__('Invalid JSON config file: %s', configPath)); + } + } + }); + } + // set args from config object. + // it recursively checks nested objects. + function setConfigObject(config, prev) { + Object.keys(config).forEach(function (key) { + const value = config[key]; + const fullKey = prev ? prev + '.' + key : key; + // if the value is an inner object and we have dot-notation + // enabled, treat inner objects in config the same as + // heavily nested dot notations (foo.bar.apple). + if (typeof value === 'object' && value !== null && !Array.isArray(value) && configuration['dot-notation']) { + // if the value is an object but not an array, check nested object + setConfigObject(value, fullKey); + } + else { + // setting arguments via CLI takes precedence over + // values within the config file. + if (!hasKey(argv, fullKey.split('.')) || (checkAllAliases(fullKey, flags.arrays) && configuration['combine-arrays'])) { + setArg(fullKey, value); + } + } + }); + } + // set all config objects passed in opts + function setConfigObjects() { + if (typeof configObjects !== 'undefined') { + configObjects.forEach(function (configObject) { + setConfigObject(configObject); + }); + } + } + function applyEnvVars(argv, configOnly) { + if (typeof envPrefix === 'undefined') + return; + const prefix = typeof envPrefix === 'string' ? envPrefix : ''; + const env = mixin.env(); + Object.keys(env).forEach(function (envVar) { + if (prefix === '' || envVar.lastIndexOf(prefix, 0) === 0) { + // get array of nested keys and convert them to camel case + const keys = envVar.split('__').map(function (key, i) { + if (i === 0) { + key = key.substring(prefix.length); + } + return camelCase(key); + }); + if (((configOnly && flags.configs[keys.join('.')]) || !configOnly) && !hasKey(argv, keys)) { + setArg(keys.join('.'), env[envVar]); + } + } + }); + } + function applyCoercions(argv) { + let coerce; + const applied = new Set(); + Object.keys(argv).forEach(function (key) { + if (!applied.has(key)) { // If we haven't already coerced this option via one of its aliases + coerce = checkAllAliases(key, flags.coercions); + if (typeof coerce === 'function') { + try { + const value = maybeCoerceNumber(key, coerce(argv[key])); + ([].concat(flags.aliases[key] || [], key)).forEach(ali => { + applied.add(ali); + argv[ali] = value; + }); + } + catch (err) { + error = err; + } + } + } + }); + } + function setPlaceholderKeys(argv) { + flags.keys.forEach((key) => { + // don't set placeholder keys for dot notation options 'foo.bar'. + if (~key.indexOf('.')) + return; + if (typeof argv[key] === 'undefined') + argv[key] = undefined; + }); + return argv; + } + function applyDefaultsAndAliases(obj, aliases, defaults, canLog = false) { + Object.keys(defaults).forEach(function (key) { + if (!hasKey(obj, key.split('.'))) { + setKey(obj, key.split('.'), defaults[key]); + if (canLog) + defaulted[key] = true; + (aliases[key] || []).forEach(function (x) { + if (hasKey(obj, x.split('.'))) + return; + setKey(obj, x.split('.'), defaults[key]); + }); + } + }); + } + function hasKey(obj, keys) { + let o = obj; + if (!configuration['dot-notation']) + keys = [keys.join('.')]; + keys.slice(0, -1).forEach(function (key) { + o = (o[key] || {}); + }); + const key = keys[keys.length - 1]; + if (typeof o !== 'object') + return false; + else + return key in o; + } + function setKey(obj, keys, value) { + let o = obj; + if (!configuration['dot-notation']) + keys = [keys.join('.')]; + keys.slice(0, -1).forEach(function (key) { + // TODO(bcoe): in the next major version of yargs, switch to + // Object.create(null) for dot notation: + key = sanitizeKey(key); + if (typeof o === 'object' && o[key] === undefined) { + o[key] = {}; + } + if (typeof o[key] !== 'object' || Array.isArray(o[key])) { + // ensure that o[key] is an array, and that the last item is an empty object. + if (Array.isArray(o[key])) { + o[key].push({}); + } + else { + o[key] = [o[key], {}]; + } + // we want to update the empty object at the end of the o[key] array, so set o to that object + o = o[key][o[key].length - 1]; + } + else { + o = o[key]; + } + }); + // TODO(bcoe): in the next major version of yargs, switch to + // Object.create(null) for dot notation: + const key = sanitizeKey(keys[keys.length - 1]); + const isTypeArray = checkAllAliases(keys.join('.'), flags.arrays); + const isValueArray = Array.isArray(value); + let duplicate = configuration['duplicate-arguments-array']; + // nargs has higher priority than duplicate + if (!duplicate && checkAllAliases(key, flags.nargs)) { + duplicate = true; + if ((!isUndefined(o[key]) && flags.nargs[key] === 1) || (Array.isArray(o[key]) && o[key].length === flags.nargs[key])) { + o[key] = undefined; + } + } + if (value === increment()) { + o[key] = increment(o[key]); + } + else if (Array.isArray(o[key])) { + if (duplicate && isTypeArray && isValueArray) { + o[key] = configuration['flatten-duplicate-arrays'] ? o[key].concat(value) : (Array.isArray(o[key][0]) ? o[key] : [o[key]]).concat([value]); + } + else if (!duplicate && Boolean(isTypeArray) === Boolean(isValueArray)) { + o[key] = value; + } + else { + o[key] = o[key].concat([value]); + } + } + else if (o[key] === undefined && isTypeArray) { + o[key] = isValueArray ? value : [value]; + } + else if (duplicate && !(o[key] === undefined || + checkAllAliases(key, flags.counts) || + checkAllAliases(key, flags.bools))) { + o[key] = [o[key], value]; + } + else { + o[key] = value; + } + } + // extend the aliases list with inferred aliases. + function extendAliases(...args) { + args.forEach(function (obj) { + Object.keys(obj || {}).forEach(function (key) { + // short-circuit if we've already added a key + // to the aliases array, for example it might + // exist in both 'opts.default' and 'opts.key'. + if (flags.aliases[key]) + return; + flags.aliases[key] = [].concat(aliases[key] || []); + // For "--option-name", also set argv.optionName + flags.aliases[key].concat(key).forEach(function (x) { + if (/-/.test(x) && configuration['camel-case-expansion']) { + const c = camelCase(x); + if (c !== key && flags.aliases[key].indexOf(c) === -1) { + flags.aliases[key].push(c); + newAliases[c] = true; + } + } + }); + // For "--optionName", also set argv['option-name'] + flags.aliases[key].concat(key).forEach(function (x) { + if (x.length > 1 && /[A-Z]/.test(x) && configuration['camel-case-expansion']) { + const c = decamelize(x, '-'); + if (c !== key && flags.aliases[key].indexOf(c) === -1) { + flags.aliases[key].push(c); + newAliases[c] = true; + } + } + }); + flags.aliases[key].forEach(function (x) { + flags.aliases[x] = [key].concat(flags.aliases[key].filter(function (y) { + return x !== y; + })); + }); + }); + }); + } + function checkAllAliases(key, flag) { + const toCheck = [].concat(flags.aliases[key] || [], key); + const keys = Object.keys(flag); + const setAlias = toCheck.find(key => keys.includes(key)); + return setAlias ? flag[setAlias] : false; + } + function hasAnyFlag(key) { + const flagsKeys = Object.keys(flags); + const toCheck = [].concat(flagsKeys.map(k => flags[k])); + return toCheck.some(function (flag) { + return Array.isArray(flag) ? flag.includes(key) : flag[key]; + }); + } + function hasFlagsMatching(arg, ...patterns) { + const toCheck = [].concat(...patterns); + return toCheck.some(function (pattern) { + const match = arg.match(pattern); + return match && hasAnyFlag(match[1]); + }); + } + // based on a simplified version of the short flag group parsing logic + function hasAllShortFlags(arg) { + // if this is a negative number, or doesn't start with a single hyphen, it's not a short flag group + if (arg.match(negative) || !arg.match(/^-[^-]+/)) { + return false; + } + let hasAllFlags = true; + let next; + const letters = arg.slice(1).split(''); + for (let j = 0; j < letters.length; j++) { + next = arg.slice(j + 2); + if (!hasAnyFlag(letters[j])) { + hasAllFlags = false; + break; + } + if ((letters[j + 1] && letters[j + 1] === '=') || + next === '-' || + (/[A-Za-z]/.test(letters[j]) && /^-?\d+(\.\d*)?(e-?\d+)?$/.test(next)) || + (letters[j + 1] && letters[j + 1].match(/\W/))) { + break; + } + } + return hasAllFlags; + } + function isUnknownOptionAsArg(arg) { + return configuration['unknown-options-as-args'] && isUnknownOption(arg); + } + function isUnknownOption(arg) { + arg = arg.replace(/^-{3,}/, '--'); + // ignore negative numbers + if (arg.match(negative)) { + return false; + } + // if this is a short option group and all of them are configured, it isn't unknown + if (hasAllShortFlags(arg)) { + return false; + } + // e.g. '--count=2' + const flagWithEquals = /^-+([^=]+?)=[\s\S]*$/; + // e.g. '-a' or '--arg' + const normalFlag = /^-+([^=]+?)$/; + // e.g. '-a-' + const flagEndingInHyphen = /^-+([^=]+?)-$/; + // e.g. '-abc123' + const flagEndingInDigits = /^-+([^=]+?\d+)$/; + // e.g. '-a/usr/local' + const flagEndingInNonWordCharacters = /^-+([^=]+?)\W+.*$/; + // check the different types of flag styles, including negatedBoolean, a pattern defined near the start of the parse method + return !hasFlagsMatching(arg, flagWithEquals, negatedBoolean, normalFlag, flagEndingInHyphen, flagEndingInDigits, flagEndingInNonWordCharacters); + } + // make a best effort to pick a default value + // for an option based on name and type. + function defaultValue(key) { + if (!checkAllAliases(key, flags.bools) && + !checkAllAliases(key, flags.counts) && + `${key}` in defaults) { + return defaults[key]; + } + else { + return defaultForType(guessType(key)); + } + } + // return a default value, given the type of a flag., + function defaultForType(type) { + const def = { + [DefaultValuesForTypeKey.BOOLEAN]: true, + [DefaultValuesForTypeKey.STRING]: '', + [DefaultValuesForTypeKey.NUMBER]: undefined, + [DefaultValuesForTypeKey.ARRAY]: [] + }; + return def[type]; + } + // given a flag, enforce a default type. + function guessType(key) { + let type = DefaultValuesForTypeKey.BOOLEAN; + if (checkAllAliases(key, flags.strings)) + type = DefaultValuesForTypeKey.STRING; + else if (checkAllAliases(key, flags.numbers)) + type = DefaultValuesForTypeKey.NUMBER; + else if (checkAllAliases(key, flags.bools)) + type = DefaultValuesForTypeKey.BOOLEAN; + else if (checkAllAliases(key, flags.arrays)) + type = DefaultValuesForTypeKey.ARRAY; + return type; + } + function isUndefined(num) { + return num === undefined; + } + // check user configuration settings for inconsistencies + function checkConfiguration() { + // count keys should not be set as array/narg + Object.keys(flags.counts).find(key => { + if (checkAllAliases(key, flags.arrays)) { + error = Error(__('Invalid configuration: %s, opts.count excludes opts.array.', key)); + return true; + } + else if (checkAllAliases(key, flags.nargs)) { + error = Error(__('Invalid configuration: %s, opts.count excludes opts.narg.', key)); + return true; + } + return false; + }); + } + return { + aliases: Object.assign({}, flags.aliases), + argv: Object.assign(argvReturn, argv), + configuration: configuration, + defaulted: Object.assign({}, defaulted), + error: error, + newAliases: Object.assign({}, newAliases) + }; + } +} +// if any aliases reference each other, we should +// merge them together. +function combineAliases(aliases) { + const aliasArrays = []; + const combined = Object.create(null); + let change = true; + // turn alias lookup hash {key: ['alias1', 'alias2']} into + // a simple array ['key', 'alias1', 'alias2'] + Object.keys(aliases).forEach(function (key) { + aliasArrays.push([].concat(aliases[key], key)); + }); + // combine arrays until zero changes are + // made in an iteration. + while (change) { + change = false; + for (let i = 0; i < aliasArrays.length; i++) { + for (let ii = i + 1; ii < aliasArrays.length; ii++) { + const intersect = aliasArrays[i].filter(function (v) { + return aliasArrays[ii].indexOf(v) !== -1; + }); + if (intersect.length) { + aliasArrays[i] = aliasArrays[i].concat(aliasArrays[ii]); + aliasArrays.splice(ii, 1); + change = true; + break; + } + } + } + } + // map arrays back to the hash-lookup (de-dupe while + // we're at it). + aliasArrays.forEach(function (aliasArray) { + aliasArray = aliasArray.filter(function (v, i, self) { + return self.indexOf(v) === i; + }); + const lastAlias = aliasArray.pop(); + if (lastAlias !== undefined && typeof lastAlias === 'string') { + combined[lastAlias] = aliasArray; + } + }); + return combined; +} +// this function should only be called when a count is given as an arg +// it is NOT called to set a default value +// thus we can start the count at 1 instead of 0 +function increment(orig) { + return orig !== undefined ? orig + 1 : 1; +} +// TODO(bcoe): in the next major version of yargs, switch to +// Object.create(null) for dot notation: +function sanitizeKey(key) { + if (key === '__proto__') + return '___proto___'; + return key; +} +function stripQuotes(val) { + return (typeof val === 'string' && + (val[0] === "'" || val[0] === '"') && + val[val.length - 1] === val[0]) + ? val.substring(1, val.length - 1) + : val; +} diff --git a/node_modules/yargs-parser/package.json b/node_modules/yargs-parser/package.json new file mode 100644 index 0000000..decd0c3 --- /dev/null +++ b/node_modules/yargs-parser/package.json @@ -0,0 +1,92 @@ +{ + "name": "yargs-parser", + "version": "21.1.1", + "description": "the mighty option parser used by yargs", + "main": "build/index.cjs", + "exports": { + ".": [ + { + "import": "./build/lib/index.js", + "require": "./build/index.cjs" + }, + "./build/index.cjs" + ], + "./browser": [ + "./browser.js" + ] + }, + "type": "module", + "module": "./build/lib/index.js", + "scripts": { + "check": "standardx '**/*.ts' && standardx '**/*.js' && standardx '**/*.cjs'", + "fix": "standardx --fix '**/*.ts' && standardx --fix '**/*.js' && standardx --fix '**/*.cjs'", + "pretest": "rimraf build && tsc -p tsconfig.test.json && cross-env NODE_ENV=test npm run build:cjs", + "test": "c8 --reporter=text --reporter=html mocha test/*.cjs", + "test:esm": "c8 --reporter=text --reporter=html mocha test/*.mjs", + "test:browser": "start-server-and-test 'serve ./ -p 8080' http://127.0.0.1:8080/package.json 'node ./test/browser/yargs-test.cjs'", + "pretest:typescript": "npm run pretest", + "test:typescript": "c8 mocha ./build/test/typescript/*.js", + "coverage": "c8 report --check-coverage", + "precompile": "rimraf build", + "compile": "tsc", + "postcompile": "npm run build:cjs", + "build:cjs": "rollup -c", + "prepare": "npm run compile" + }, + "repository": { + "type": "git", + "url": "https://github.com/yargs/yargs-parser.git" + }, + "keywords": [ + "argument", + "parser", + "yargs", + "command", + "cli", + "parsing", + "option", + "args", + "argument" + ], + "author": "Ben Coe ", + "license": "ISC", + "devDependencies": { + "@types/chai": "^4.2.11", + "@types/mocha": "^9.0.0", + "@types/node": "^16.11.4", + "@typescript-eslint/eslint-plugin": "^3.10.1", + "@typescript-eslint/parser": "^3.10.1", + "c8": "^7.3.0", + "chai": "^4.2.0", + "cross-env": "^7.0.2", + "eslint": "^7.0.0", + "eslint-plugin-import": "^2.20.1", + "eslint-plugin-node": "^11.0.0", + "gts": "^3.0.0", + "mocha": "^10.0.0", + "puppeteer": "^16.0.0", + "rimraf": "^3.0.2", + "rollup": "^2.22.1", + "rollup-plugin-cleanup": "^3.1.1", + "rollup-plugin-ts": "^3.0.2", + "serve": "^14.0.0", + "standardx": "^7.0.0", + "start-server-and-test": "^1.11.2", + "ts-transform-default-export": "^1.0.2", + "typescript": "^4.0.0" + }, + "files": [ + "browser.js", + "build", + "!*.d.ts", + "!*.d.cts" + ], + "engines": { + "node": ">=12" + }, + "standardx": { + "ignore": [ + "build" + ] + } +} diff --git a/node_modules/yargs/LICENSE b/node_modules/yargs/LICENSE new file mode 100644 index 0000000..b0145ca --- /dev/null +++ b/node_modules/yargs/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright 2010 James Halliday (mail@substack.net); Modified work Copyright 2014 Contributors (ben@npmjs.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. diff --git a/node_modules/yargs/README.md b/node_modules/yargs/README.md new file mode 100644 index 0000000..51f5b22 --- /dev/null +++ b/node_modules/yargs/README.md @@ -0,0 +1,204 @@ +

+ +

+

Yargs

+

+ Yargs be a node.js library fer hearties tryin' ter parse optstrings +

+ +
+ +![ci](https://github.com/yargs/yargs/workflows/ci/badge.svg) +[![NPM version][npm-image]][npm-url] +[![js-standard-style][standard-image]][standard-url] +[![Coverage][coverage-image]][coverage-url] +[![Conventional Commits][conventional-commits-image]][conventional-commits-url] +[![Slack][slack-image]][slack-url] + +## Description +Yargs helps you build interactive command line tools, by parsing arguments and generating an elegant user interface. + +It gives you: + +* commands and (grouped) options (`my-program.js serve --port=5000`). +* a dynamically generated help menu based on your arguments: + +``` +mocha [spec..] + +Run tests with Mocha + +Commands + mocha inspect [spec..] Run tests with Mocha [default] + mocha init create a client-side Mocha setup at + +Rules & Behavior + --allow-uncaught Allow uncaught errors to propagate [boolean] + --async-only, -A Require all tests to use a callback (async) or + return a Promise [boolean] +``` + +* bash-completion shortcuts for commands and options. +* and [tons more](/docs/api.md). + +## Installation + +Stable version: +```bash +npm i yargs +``` + +Bleeding edge version with the most recent features: +```bash +npm i yargs@next +``` + +## Usage + +### Simple Example + +```javascript +#!/usr/bin/env node +const yargs = require('yargs/yargs') +const { hideBin } = require('yargs/helpers') +const argv = yargs(hideBin(process.argv)).argv + +if (argv.ships > 3 && argv.distance < 53.5) { + console.log('Plunder more riffiwobbles!') +} else { + console.log('Retreat from the xupptumblers!') +} +``` + +```bash +$ ./plunder.js --ships=4 --distance=22 +Plunder more riffiwobbles! + +$ ./plunder.js --ships 12 --distance 98.7 +Retreat from the xupptumblers! +``` + +> Note: `hideBin` is a shorthand for [`process.argv.slice(2)`](https://nodejs.org/en/knowledge/command-line/how-to-parse-command-line-arguments/). It has the benefit that it takes into account variations in some environments, e.g., [Electron](https://github.com/electron/electron/issues/4690). + +### Complex Example + +```javascript +#!/usr/bin/env node +const yargs = require('yargs/yargs') +const { hideBin } = require('yargs/helpers') + +yargs(hideBin(process.argv)) + .command('serve [port]', 'start the server', (yargs) => { + return yargs + .positional('port', { + describe: 'port to bind on', + default: 5000 + }) + }, (argv) => { + if (argv.verbose) console.info(`start server on :${argv.port}`) + serve(argv.port) + }) + .option('verbose', { + alias: 'v', + type: 'boolean', + description: 'Run with verbose logging' + }) + .parse() +``` + +Run the example above with `--help` to see the help for the application. + +## Supported Platforms + +### TypeScript + +yargs has type definitions at [@types/yargs][type-definitions]. + +``` +npm i @types/yargs --save-dev +``` + +See usage examples in [docs](/docs/typescript.md). + +### Deno + +As of `v16`, `yargs` supports [Deno](https://github.com/denoland/deno): + +```typescript +import yargs from 'https://deno.land/x/yargs/deno.ts' +import { Arguments } from 'https://deno.land/x/yargs/deno-types.ts' + +yargs(Deno.args) + .command('download ', 'download a list of files', (yargs: any) => { + return yargs.positional('files', { + describe: 'a list of files to do something with' + }) + }, (argv: Arguments) => { + console.info(argv) + }) + .strictCommands() + .demandCommand(1) + .parse() +``` + +### ESM + +As of `v16`,`yargs` supports ESM imports: + +```js +import yargs from 'yargs' +import { hideBin } from 'yargs/helpers' + +yargs(hideBin(process.argv)) + .command('curl ', 'fetch the contents of the URL', () => {}, (argv) => { + console.info(argv) + }) + .demandCommand(1) + .parse() +``` + +### Usage in Browser + +See examples of using yargs in the browser in [docs](/docs/browser.md). + +## Community + +Having problems? want to contribute? join our [community slack](http://devtoolscommunity.herokuapp.com). + +## Documentation + +### Table of Contents + +* [Yargs' API](/docs/api.md) +* [Examples](/docs/examples.md) +* [Parsing Tricks](/docs/tricks.md) + * [Stop the Parser](/docs/tricks.md#stop) + * [Negating Boolean Arguments](/docs/tricks.md#negate) + * [Numbers](/docs/tricks.md#numbers) + * [Arrays](/docs/tricks.md#arrays) + * [Objects](/docs/tricks.md#objects) + * [Quotes](/docs/tricks.md#quotes) +* [Advanced Topics](/docs/advanced.md) + * [Composing Your App Using Commands](/docs/advanced.md#commands) + * [Building Configurable CLI Apps](/docs/advanced.md#configuration) + * [Customizing Yargs' Parser](/docs/advanced.md#customizing) + * [Bundling yargs](/docs/bundling.md) +* [Contributing](/contributing.md) + +## Supported Node.js Versions + +Libraries in this ecosystem make a best effort to track +[Node.js' release schedule](https://nodejs.org/en/about/releases/). Here's [a +post on why we think this is important](https://medium.com/the-node-js-collection/maintainers-should-consider-following-node-js-release-schedule-ab08ed4de71a). + +[npm-url]: https://www.npmjs.com/package/yargs +[npm-image]: https://img.shields.io/npm/v/yargs.svg +[standard-image]: https://img.shields.io/badge/code%20style-standard-brightgreen.svg +[standard-url]: http://standardjs.com/ +[conventional-commits-image]: https://img.shields.io/badge/Conventional%20Commits-1.0.0-yellow.svg +[conventional-commits-url]: https://conventionalcommits.org/ +[slack-image]: http://devtoolscommunity.herokuapp.com/badge.svg +[slack-url]: http://devtoolscommunity.herokuapp.com +[type-definitions]: https://github.com/DefinitelyTyped/DefinitelyTyped/tree/master/types/yargs +[coverage-image]: https://img.shields.io/nycrc/yargs/yargs +[coverage-url]: https://github.com/yargs/yargs/blob/main/.nycrc diff --git a/node_modules/yargs/browser.d.ts b/node_modules/yargs/browser.d.ts new file mode 100644 index 0000000..21f3fc6 --- /dev/null +++ b/node_modules/yargs/browser.d.ts @@ -0,0 +1,5 @@ +import {YargsFactory} from './build/lib/yargs-factory'; + +declare const Yargs: ReturnType; + +export default Yargs; diff --git a/node_modules/yargs/browser.mjs b/node_modules/yargs/browser.mjs new file mode 100644 index 0000000..2d0d6e9 --- /dev/null +++ b/node_modules/yargs/browser.mjs @@ -0,0 +1,7 @@ +// Bootstrap yargs for browser: +import browserPlatformShim from './lib/platform-shims/browser.mjs'; +import {YargsFactory} from './build/lib/yargs-factory.js'; + +const Yargs = YargsFactory(browserPlatformShim); + +export default Yargs; diff --git a/node_modules/yargs/build/index.cjs b/node_modules/yargs/build/index.cjs new file mode 100644 index 0000000..e9cf013 --- /dev/null +++ b/node_modules/yargs/build/index.cjs @@ -0,0 +1 @@ +"use strict";var t=require("assert");class e extends Error{constructor(t){super(t||"yargs error"),this.name="YError",Error.captureStackTrace&&Error.captureStackTrace(this,e)}}let s,i=[];function n(t,o,a,h){s=h;let l={};if(Object.prototype.hasOwnProperty.call(t,"extends")){if("string"!=typeof t.extends)return l;const r=/\.json|\..*rc$/.test(t.extends);let h=null;if(r)h=function(t,e){return s.path.resolve(t,e)}(o,t.extends);else try{h=require.resolve(t.extends)}catch(e){return t}!function(t){if(i.indexOf(t)>-1)throw new e(`Circular extended configurations: '${t}'.`)}(h),i.push(h),l=r?JSON.parse(s.readFileSync(h,"utf8")):require(t.extends),delete t.extends,l=n(l,s.path.dirname(h),a,s)}return i=[],a?r(l,t):Object.assign({},l,t)}function r(t,e){const s={};function i(t){return t&&"object"==typeof t&&!Array.isArray(t)}Object.assign(s,t);for(const n of Object.keys(e))i(e[n])&&i(s[n])?s[n]=r(t[n],e[n]):s[n]=e[n];return s}function o(t){const e=t.replace(/\s{2,}/g," ").split(/\s+(?![^[]*]|[^<]*>)/),s=/\.*[\][<>]/g,i=e.shift();if(!i)throw new Error(`No command found in: ${t}`);const n={cmd:i.replace(s,""),demanded:[],optional:[]};return e.forEach(((t,i)=>{let r=!1;t=t.replace(/\s/g,""),/\.+[\]>]/.test(t)&&i===e.length-1&&(r=!0),/^\[/.test(t)?n.optional.push({cmd:t.replace(s,"").split("|"),variadic:r}):n.demanded.push({cmd:t.replace(s,"").split("|"),variadic:r})})),n}const a=["first","second","third","fourth","fifth","sixth"];function h(t,s,i){try{let n=0;const[r,a,h]="object"==typeof t?[{demanded:[],optional:[]},t,s]:[o(`cmd ${t}`),s,i],f=[].slice.call(a);for(;f.length&&void 0===f[f.length-1];)f.pop();const d=h||f.length;if(du)throw new e(`Too many arguments provided. Expected max ${u} but received ${d}.`);r.demanded.forEach((t=>{const e=l(f.shift());0===t.cmd.filter((t=>t===e||"*"===t)).length&&c(e,t.cmd,n),n+=1})),r.optional.forEach((t=>{if(0===f.length)return;const e=l(f.shift());0===t.cmd.filter((t=>t===e||"*"===t)).length&&c(e,t.cmd,n),n+=1}))}catch(t){console.warn(t.stack)}}function l(t){return Array.isArray(t)?"array":null===t?"null":typeof t}function c(t,s,i){throw new e(`Invalid ${a[i]||"manyith"} argument. Expected ${s.join(" or ")} but received ${t}.`)}function f(t){return!!t&&!!t.then&&"function"==typeof t.then}function d(t,e,s,i){s.assert.notStrictEqual(t,e,i)}function u(t,e){e.assert.strictEqual(typeof t,"string")}function p(t){return Object.keys(t)}function g(t={},e=(()=>!0)){const s={};return p(t).forEach((i=>{e(i,t[i])&&(s[i]=t[i])})),s}function m(){return process.versions.electron&&!process.defaultApp?0:1}function y(){return process.argv[m()]}var b=Object.freeze({__proto__:null,hideBin:function(t){return t.slice(m()+1)},getProcessArgvBin:y});function v(t,e,s,i){if("a"===s&&!i)throw new TypeError("Private accessor was defined without a getter");if("function"==typeof e?t!==e||!i:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return"m"===s?i:"a"===s?i.call(t):i?i.value:e.get(t)}function O(t,e,s,i,n){if("m"===i)throw new TypeError("Private method is not writable");if("a"===i&&!n)throw new TypeError("Private accessor was defined without a setter");if("function"==typeof e?t!==e||!n:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return"a"===i?n.call(t,s):n?n.value=s:e.set(t,s),s}class w{constructor(t){this.globalMiddleware=[],this.frozens=[],this.yargs=t}addMiddleware(t,e,s=!0,i=!1){if(h(" [boolean] [boolean] [boolean]",[t,e,s],arguments.length),Array.isArray(t)){for(let i=0;i{const i=[...s[e]||[],e];return!t.option||!i.includes(t.option)})),t.option=e,this.addMiddleware(t,!0,!0,!0)}getMiddleware(){return this.globalMiddleware}freeze(){this.frozens.push([...this.globalMiddleware])}unfreeze(){const t=this.frozens.pop();void 0!==t&&(this.globalMiddleware=t)}reset(){this.globalMiddleware=this.globalMiddleware.filter((t=>t.global))}}function C(t,e,s,i){return s.reduce(((t,s)=>{if(s.applyBeforeValidation!==i)return t;if(s.mutates){if(s.applied)return t;s.applied=!0}if(f(t))return t.then((t=>Promise.all([t,s(t,e)]))).then((([t,e])=>Object.assign(t,e)));{const i=s(t,e);return f(i)?i.then((e=>Object.assign(t,e))):Object.assign(t,i)}}),t)}function j(t,e,s=(t=>{throw t})){try{const s="function"==typeof t?t():t;return f(s)?s.then((t=>e(t))):e(s)}catch(t){return s(t)}}const M=/(^\*)|(^\$0)/;class _{constructor(t,e,s,i){this.requireCache=new Set,this.handlers={},this.aliasMap={},this.frozens=[],this.shim=i,this.usage=t,this.globalMiddleware=s,this.validation=e}addDirectory(t,e,s,i){"boolean"!=typeof(i=i||{}).recurse&&(i.recurse=!1),Array.isArray(i.extensions)||(i.extensions=["js"]);const n="function"==typeof i.visit?i.visit:t=>t;i.visit=(t,e,s)=>{const i=n(t,e,s);if(i){if(this.requireCache.has(e))return i;this.requireCache.add(e),this.addHandler(i)}return i},this.shim.requireDirectory({require:e,filename:s},t,i)}addHandler(t,e,s,i,n,r){let a=[];const h=function(t){return t?t.map((t=>(t.applyBeforeValidation=!1,t))):[]}(n);if(i=i||(()=>{}),Array.isArray(t))if(function(t){return t.every((t=>"string"==typeof t))}(t))[t,...a]=t;else for(const e of t)this.addHandler(e);else{if(function(t){return"object"==typeof t&&!Array.isArray(t)}(t)){let e=Array.isArray(t.command)||"string"==typeof t.command?t.command:this.moduleName(t);return t.aliases&&(e=[].concat(e).concat(t.aliases)),void this.addHandler(e,this.extractDesc(t),t.builder,t.handler,t.middlewares,t.deprecated)}if(k(s))return void this.addHandler([t].concat(a),e,s.builder,s.handler,s.middlewares,s.deprecated)}if("string"==typeof t){const n=o(t);a=a.map((t=>o(t).cmd));let l=!1;const c=[n.cmd].concat(a).filter((t=>!M.test(t)||(l=!0,!1)));0===c.length&&l&&c.push("$0"),l&&(n.cmd=c[0],a=c.slice(1),t=t.replace(M,n.cmd)),a.forEach((t=>{this.aliasMap[t]=n.cmd})),!1!==e&&this.usage.command(t,e,l,a,r),this.handlers[n.cmd]={original:t,description:e,handler:i,builder:s||{},middlewares:h,deprecated:r,demanded:n.demanded,optional:n.optional},l&&(this.defaultCommand=this.handlers[n.cmd])}}getCommandHandlers(){return this.handlers}getCommands(){return Object.keys(this.handlers).concat(Object.keys(this.aliasMap))}hasDefaultCommand(){return!!this.defaultCommand}runCommand(t,e,s,i,n,r){const o=this.handlers[t]||this.handlers[this.aliasMap[t]]||this.defaultCommand,a=e.getInternalMethods().getContext(),h=a.commands.slice(),l=!t;t&&(a.commands.push(t),a.fullCommands.push(o.original));const c=this.applyBuilderUpdateUsageAndParse(l,o,e,s.aliases,h,i,n,r);return f(c)?c.then((t=>this.applyMiddlewareAndGetResult(l,o,t.innerArgv,a,n,t.aliases,e))):this.applyMiddlewareAndGetResult(l,o,c.innerArgv,a,n,c.aliases,e)}applyBuilderUpdateUsageAndParse(t,e,s,i,n,r,o,a){const h=e.builder;let l=s;if(x(h)){s.getInternalMethods().getUsageInstance().freeze();const c=h(s.getInternalMethods().reset(i),a);if(f(c))return c.then((i=>{var a;return l=(a=i)&&"function"==typeof a.getInternalMethods?i:s,this.parseAndUpdateUsage(t,e,l,n,r,o)}))}else(function(t){return"object"==typeof t})(h)&&(s.getInternalMethods().getUsageInstance().freeze(),l=s.getInternalMethods().reset(i),Object.keys(e.builder).forEach((t=>{l.option(t,h[t])})));return this.parseAndUpdateUsage(t,e,l,n,r,o)}parseAndUpdateUsage(t,e,s,i,n,r){t&&s.getInternalMethods().getUsageInstance().unfreeze(!0),this.shouldUpdateUsage(s)&&s.getInternalMethods().getUsageInstance().usage(this.usageFromParentCommandsCommandHandler(i,e),e.description);const o=s.getInternalMethods().runYargsParserAndExecuteCommands(null,void 0,!0,n,r);return f(o)?o.then((t=>({aliases:s.parsed.aliases,innerArgv:t}))):{aliases:s.parsed.aliases,innerArgv:o}}shouldUpdateUsage(t){return!t.getInternalMethods().getUsageInstance().getUsageDisabled()&&0===t.getInternalMethods().getUsageInstance().getUsage().length}usageFromParentCommandsCommandHandler(t,e){const s=M.test(e.original)?e.original.replace(M,"").trim():e.original,i=t.filter((t=>!M.test(t)));return i.push(s),`$0 ${i.join(" ")}`}handleValidationAndGetResult(t,e,s,i,n,r,o,a){if(!r.getInternalMethods().getHasOutput()){const e=r.getInternalMethods().runValidation(n,a,r.parsed.error,t);s=j(s,(t=>(e(t),t)))}if(e.handler&&!r.getInternalMethods().getHasOutput()){r.getInternalMethods().setHasOutput();const i=!!r.getOptions().configuration["populate--"];r.getInternalMethods().postProcess(s,i,!1,!1),s=j(s=C(s,r,o,!1),(t=>{const s=e.handler(t);return f(s)?s.then((()=>t)):t})),t||r.getInternalMethods().getUsageInstance().cacheHelpMessage(),f(s)&&!r.getInternalMethods().hasParseCallback()&&s.catch((t=>{try{r.getInternalMethods().getUsageInstance().fail(null,t)}catch(t){}}))}return t||(i.commands.pop(),i.fullCommands.pop()),s}applyMiddlewareAndGetResult(t,e,s,i,n,r,o){let a={};if(n)return s;o.getInternalMethods().getHasOutput()||(a=this.populatePositionals(e,s,i,o));const h=this.globalMiddleware.getMiddleware().slice(0).concat(e.middlewares),l=C(s,o,h,!0);return f(l)?l.then((s=>this.handleValidationAndGetResult(t,e,s,i,r,o,h,a))):this.handleValidationAndGetResult(t,e,l,i,r,o,h,a)}populatePositionals(t,e,s,i){e._=e._.slice(s.commands.length);const n=t.demanded.slice(0),r=t.optional.slice(0),o={};for(this.validation.positionalCount(n.length,e._.length);n.length;){const t=n.shift();this.populatePositional(t,e,o)}for(;r.length;){const t=r.shift();this.populatePositional(t,e,o)}return e._=s.commands.concat(e._.map((t=>""+t))),this.postProcessPositionals(e,o,this.cmdToParseOptions(t.original),i),o}populatePositional(t,e,s){const i=t.cmd[0];t.variadic?s[i]=e._.splice(0).map(String):e._.length&&(s[i]=[String(e._.shift())])}cmdToParseOptions(t){const e={array:[],default:{},alias:{},demand:{}},s=o(t);return s.demanded.forEach((t=>{const[s,...i]=t.cmd;t.variadic&&(e.array.push(s),e.default[s]=[]),e.alias[s]=i,e.demand[s]=!0})),s.optional.forEach((t=>{const[s,...i]=t.cmd;t.variadic&&(e.array.push(s),e.default[s]=[]),e.alias[s]=i})),e}postProcessPositionals(t,e,s,i){const n=Object.assign({},i.getOptions());n.default=Object.assign(s.default,n.default);for(const t of Object.keys(s.alias))n.alias[t]=(n.alias[t]||[]).concat(s.alias[t]);n.array=n.array.concat(s.array),n.config={};const r=[];if(Object.keys(e).forEach((t=>{e[t].map((e=>{n.configuration["unknown-options-as-args"]&&(n.key[t]=!0),r.push(`--${t}`),r.push(e)}))})),!r.length)return;const o=Object.assign({},n.configuration,{"populate--":!1}),a=this.shim.Parser.detailed(r,Object.assign({},n,{configuration:o}));if(a.error)i.getInternalMethods().getUsageInstance().fail(a.error.message,a.error);else{const s=Object.keys(e);Object.keys(e).forEach((t=>{s.push(...a.aliases[t])})),Object.keys(a.argv).forEach((n=>{s.includes(n)&&(e[n]||(e[n]=a.argv[n]),!this.isInConfigs(i,n)&&!this.isDefaulted(i,n)&&Object.prototype.hasOwnProperty.call(t,n)&&Object.prototype.hasOwnProperty.call(a.argv,n)&&(Array.isArray(t[n])||Array.isArray(a.argv[n]))?t[n]=[].concat(t[n],a.argv[n]):t[n]=a.argv[n])}))}}isDefaulted(t,e){const{default:s}=t.getOptions();return Object.prototype.hasOwnProperty.call(s,e)||Object.prototype.hasOwnProperty.call(s,this.shim.Parser.camelCase(e))}isInConfigs(t,e){const{configObjects:s}=t.getOptions();return s.some((t=>Object.prototype.hasOwnProperty.call(t,e)))||s.some((t=>Object.prototype.hasOwnProperty.call(t,this.shim.Parser.camelCase(e))))}runDefaultBuilderOn(t){if(!this.defaultCommand)return;if(this.shouldUpdateUsage(t)){const e=M.test(this.defaultCommand.original)?this.defaultCommand.original:this.defaultCommand.original.replace(/^[^[\]<>]*/,"$0 ");t.getInternalMethods().getUsageInstance().usage(e,this.defaultCommand.description)}const e=this.defaultCommand.builder;if(x(e))return e(t,!0);k(e)||Object.keys(e).forEach((s=>{t.option(s,e[s])}))}moduleName(t){const e=function(t){if("undefined"==typeof require)return null;for(let e,s=0,i=Object.keys(require.cache);s{const s=e;s._handle&&s.isTTY&&"function"==typeof s._handle.setBlocking&&s._handle.setBlocking(t)}))}function A(t){return"boolean"==typeof t}function P(t,s){const i=s.y18n.__,n={},r=[];n.failFn=function(t){r.push(t)};let o=null,a=null,h=!0;n.showHelpOnFail=function(e=!0,s){const[i,r]="string"==typeof e?[!0,e]:[e,s];return t.getInternalMethods().isGlobalContext()&&(a=r),o=r,h=i,n};let l=!1;n.fail=function(s,i){const c=t.getInternalMethods().getLoggerInstance();if(!r.length){if(t.getExitProcess()&&E(!0),!l){l=!0,h&&(t.showHelp("error"),c.error()),(s||i)&&c.error(s||i);const e=o||a;e&&((s||i)&&c.error(""),c.error(e))}if(i=i||new e(s),t.getExitProcess())return t.exit(1);if(t.getInternalMethods().hasParseCallback())return t.exit(1,i);throw i}for(let t=r.length-1;t>=0;--t){const e=r[t];if(A(e)){if(i)throw i;if(s)throw Error(s)}else e(s,i,n)}};let c=[],f=!1;n.usage=(t,e)=>null===t?(f=!0,c=[],n):(f=!1,c.push([t,e||""]),n),n.getUsage=()=>c,n.getUsageDisabled=()=>f,n.getPositionalGroupName=()=>i("Positionals:");let d=[];n.example=(t,e)=>{d.push([t,e||""])};let u=[];n.command=function(t,e,s,i,n=!1){s&&(u=u.map((t=>(t[2]=!1,t)))),u.push([t,e||"",s,i,n])},n.getCommands=()=>u;let p={};n.describe=function(t,e){Array.isArray(t)?t.forEach((t=>{n.describe(t,e)})):"object"==typeof t?Object.keys(t).forEach((e=>{n.describe(e,t[e])})):p[t]=e},n.getDescriptions=()=>p;let m=[];n.epilog=t=>{m.push(t)};let y,b=!1;n.wrap=t=>{b=!0,y=t},n.getWrap=()=>s.getEnv("YARGS_DISABLE_WRAP")?null:(b||(y=function(){const t=80;return s.process.stdColumns?Math.min(t,s.process.stdColumns):t}(),b=!0),y);const v="__yargsString__:";function O(t,e,i){let n=0;return Array.isArray(t)||(t=Object.values(t).map((t=>[t]))),t.forEach((t=>{n=Math.max(s.stringWidth(i?`${i} ${I(t[0])}`:I(t[0]))+$(t[0]),n)})),e&&(n=Math.min(n,parseInt((.5*e).toString(),10))),n}let w;function C(e){return t.getOptions().hiddenOptions.indexOf(e)<0||t.parsed.argv[t.getOptions().showHiddenOpt]}function j(t,e){let s=`[${i("default:")} `;if(void 0===t&&!e)return null;if(e)s+=e;else switch(typeof t){case"string":s+=`"${t}"`;break;case"object":s+=JSON.stringify(t);break;default:s+=t}return`${s}]`}n.deferY18nLookup=t=>v+t,n.help=function(){if(w)return w;!function(){const e=t.getDemandedOptions(),s=t.getOptions();(Object.keys(s.alias)||[]).forEach((i=>{s.alias[i].forEach((r=>{p[r]&&n.describe(i,p[r]),r in e&&t.demandOption(i,e[r]),s.boolean.includes(r)&&t.boolean(i),s.count.includes(r)&&t.count(i),s.string.includes(r)&&t.string(i),s.normalize.includes(r)&&t.normalize(i),s.array.includes(r)&&t.array(i),s.number.includes(r)&&t.number(i)}))}))}();const e=t.customScriptName?t.$0:s.path.basename(t.$0),r=t.getDemandedOptions(),o=t.getDemandedCommands(),a=t.getDeprecatedOptions(),h=t.getGroups(),l=t.getOptions();let g=[];g=g.concat(Object.keys(p)),g=g.concat(Object.keys(r)),g=g.concat(Object.keys(o)),g=g.concat(Object.keys(l.default)),g=g.filter(C),g=Object.keys(g.reduce(((t,e)=>("_"!==e&&(t[e]=!0),t)),{}));const y=n.getWrap(),b=s.cliui({width:y,wrap:!!y});if(!f)if(c.length)c.forEach((t=>{b.div({text:`${t[0].replace(/\$0/g,e)}`}),t[1]&&b.div({text:`${t[1]}`,padding:[1,0,0,0]})})),b.div();else if(u.length){let t=null;t=o._?`${e} <${i("command")}>\n`:`${e} [${i("command")}]\n`,b.div(`${t}`)}if(u.length>1||1===u.length&&!u[0][2]){b.div(i("Commands:"));const s=t.getInternalMethods().getContext(),n=s.commands.length?`${s.commands.join(" ")} `:"";!0===t.getInternalMethods().getParserConfiguration()["sort-commands"]&&(u=u.sort(((t,e)=>t[0].localeCompare(e[0]))));const r=e?`${e} `:"";u.forEach((t=>{const s=`${r}${n}${t[0].replace(/^\$0 ?/,"")}`;b.span({text:s,padding:[0,2,0,2],width:O(u,y,`${e}${n}`)+4},{text:t[1]});const o=[];t[2]&&o.push(`[${i("default")}]`),t[3]&&t[3].length&&o.push(`[${i("aliases:")} ${t[3].join(", ")}]`),t[4]&&("string"==typeof t[4]?o.push(`[${i("deprecated: %s",t[4])}]`):o.push(`[${i("deprecated")}]`)),o.length?b.div({text:o.join(" "),padding:[0,0,0,2],align:"right"}):b.div()})),b.div()}const M=(Object.keys(l.alias)||[]).concat(Object.keys(t.parsed.newAliases)||[]);g=g.filter((e=>!t.parsed.newAliases[e]&&M.every((t=>-1===(l.alias[t]||[]).indexOf(e)))));const _=i("Options:");h[_]||(h[_]=[]),function(t,e,s,i){let n=[],r=null;Object.keys(s).forEach((t=>{n=n.concat(s[t])})),t.forEach((t=>{r=[t].concat(e[t]),r.some((t=>-1!==n.indexOf(t)))||s[i].push(t)}))}(g,l.alias,h,_);const k=t=>/^--/.test(I(t)),x=Object.keys(h).filter((t=>h[t].length>0)).map((t=>({groupName:t,normalizedKeys:h[t].filter(C).map((t=>{if(M.includes(t))return t;for(let e,s=0;void 0!==(e=M[s]);s++)if((l.alias[e]||[]).includes(t))return e;return t}))}))).filter((({normalizedKeys:t})=>t.length>0)).map((({groupName:t,normalizedKeys:e})=>{const s=e.reduce(((e,s)=>(e[s]=[s].concat(l.alias[s]||[]).map((e=>t===n.getPositionalGroupName()?e:(/^[0-9]$/.test(e)?l.boolean.includes(s)?"-":"--":e.length>1?"--":"-")+e)).sort(((t,e)=>k(t)===k(e)?0:k(t)?1:-1)).join(", "),e)),{});return{groupName:t,normalizedKeys:e,switches:s}}));if(x.filter((({groupName:t})=>t!==n.getPositionalGroupName())).some((({normalizedKeys:t,switches:e})=>!t.every((t=>k(e[t])))))&&x.filter((({groupName:t})=>t!==n.getPositionalGroupName())).forEach((({normalizedKeys:t,switches:e})=>{t.forEach((t=>{var s,i;k(e[t])&&(e[t]=(s=e[t],i=4,S(s)?{text:s.text,indentation:s.indentation+i}:{text:s,indentation:i}))}))})),x.forEach((({groupName:e,normalizedKeys:s,switches:o})=>{b.div(e),s.forEach((e=>{const s=o[e];let h=p[e]||"",c=null;h.includes(v)&&(h=i(h.substring(16))),l.boolean.includes(e)&&(c=`[${i("boolean")}]`),l.count.includes(e)&&(c=`[${i("count")}]`),l.string.includes(e)&&(c=`[${i("string")}]`),l.normalize.includes(e)&&(c=`[${i("string")}]`),l.array.includes(e)&&(c=`[${i("array")}]`),l.number.includes(e)&&(c=`[${i("number")}]`);const f=[e in a?(d=a[e],"string"==typeof d?`[${i("deprecated: %s",d)}]`:`[${i("deprecated")}]`):null,c,e in r?`[${i("required")}]`:null,l.choices&&l.choices[e]?`[${i("choices:")} ${n.stringifiedValues(l.choices[e])}]`:null,j(l.default[e],l.defaultDescription[e])].filter(Boolean).join(" ");var d;b.span({text:I(s),padding:[0,2,0,2+$(s)],width:O(o,y)+4},h);const u=!0===t.getInternalMethods().getUsageConfiguration()["hide-types"];f&&!u?b.div({text:f,padding:[0,0,0,2],align:"right"}):b.div()})),b.div()})),d.length&&(b.div(i("Examples:")),d.forEach((t=>{t[0]=t[0].replace(/\$0/g,e)})),d.forEach((t=>{""===t[1]?b.div({text:t[0],padding:[0,2,0,2]}):b.div({text:t[0],padding:[0,2,0,2],width:O(d,y)+4},{text:t[1]})})),b.div()),m.length>0){const t=m.map((t=>t.replace(/\$0/g,e))).join("\n");b.div(`${t}\n`)}return b.toString().replace(/\s*$/,"")},n.cacheHelpMessage=function(){w=this.help()},n.clearCachedHelpMessage=function(){w=void 0},n.hasCachedHelpMessage=function(){return!!w},n.showHelp=e=>{const s=t.getInternalMethods().getLoggerInstance();e||(e="error");("function"==typeof e?e:s[e])(n.help())},n.functionDescription=t=>["(",t.name?s.Parser.decamelize(t.name,"-"):i("generated-value"),")"].join(""),n.stringifiedValues=function(t,e){let s="";const i=e||", ",n=[].concat(t);return t&&n.length?(n.forEach((t=>{s.length&&(s+=i),s+=JSON.stringify(t)})),s):s};let M=null;n.version=t=>{M=t},n.showVersion=e=>{const s=t.getInternalMethods().getLoggerInstance();e||(e="error");("function"==typeof e?e:s[e])(M)},n.reset=function(t){return o=null,l=!1,c=[],f=!1,m=[],d=[],u=[],p=g(p,(e=>!t[e])),n};const _=[];return n.freeze=function(){_.push({failMessage:o,failureOutput:l,usages:c,usageDisabled:f,epilogs:m,examples:d,commands:u,descriptions:p})},n.unfreeze=function(t=!1){const e=_.pop();e&&(t?(p={...e.descriptions,...p},u=[...e.commands,...u],c=[...e.usages,...c],d=[...e.examples,...d],m=[...e.epilogs,...m]):({failMessage:o,failureOutput:l,usages:c,usageDisabled:f,epilogs:m,examples:d,commands:u,descriptions:p}=e))},n}function S(t){return"object"==typeof t}function $(t){return S(t)?t.indentation:0}function I(t){return S(t)?t.text:t}class D{constructor(t,e,s,i){var n,r,o;this.yargs=t,this.usage=e,this.command=s,this.shim=i,this.completionKey="get-yargs-completions",this.aliases=null,this.customCompletionFunction=null,this.indexAfterLastReset=0,this.zshShell=null!==(o=(null===(n=this.shim.getEnv("SHELL"))||void 0===n?void 0:n.includes("zsh"))||(null===(r=this.shim.getEnv("ZSH_NAME"))||void 0===r?void 0:r.includes("zsh")))&&void 0!==o&&o}defaultCompletion(t,e,s,i){const n=this.command.getCommandHandlers();for(let e=0,s=t.length;e{const i=o(s[0]).cmd;if(-1===e.indexOf(i))if(this.zshShell){const e=s[1]||"";t.push(i.replace(/:/g,"\\:")+":"+e)}else t.push(i)}))}optionCompletions(t,e,s,i){if((i.match(/^-/)||""===i&&0===t.length)&&!this.previousArgHasChoices(e)){const s=this.yargs.getOptions(),n=this.yargs.getGroups()[this.usage.getPositionalGroupName()]||[];Object.keys(s.key).forEach((r=>{const o=!!s.configuration["boolean-negation"]&&s.boolean.includes(r);n.includes(r)||s.hiddenOptions.includes(r)||this.argsContainKey(e,r,o)||this.completeOptionKey(r,t,i,o&&!!s.default[r])}))}}choicesFromOptionsCompletions(t,e,s,i){if(this.previousArgHasChoices(e)){const s=this.getPreviousArgChoices(e);s&&s.length>0&&t.push(...s.map((t=>t.replace(/:/g,"\\:"))))}}choicesFromPositionalsCompletions(t,e,s,i){if(""===i&&t.length>0&&this.previousArgHasChoices(e))return;const n=this.yargs.getGroups()[this.usage.getPositionalGroupName()]||[],r=Math.max(this.indexAfterLastReset,this.yargs.getInternalMethods().getContext().commands.length+1),o=n[s._.length-r-1];if(!o)return;const a=this.yargs.getOptions().choices[o]||[];for(const e of a)e.startsWith(i)&&t.push(e.replace(/:/g,"\\:"))}getPreviousArgChoices(t){if(t.length<1)return;let e=t[t.length-1],s="";if(!e.startsWith("-")&&t.length>1&&(s=e,e=t[t.length-2]),!e.startsWith("-"))return;const i=e.replace(/^-+/,""),n=this.yargs.getOptions(),r=[i,...this.yargs.getAliases()[i]||[]];let o;for(const t of r)if(Object.prototype.hasOwnProperty.call(n.key,t)&&Array.isArray(n.choices[t])){o=n.choices[t];break}return o?o.filter((t=>!s||t.startsWith(s))):void 0}previousArgHasChoices(t){const e=this.getPreviousArgChoices(t);return void 0!==e&&e.length>0}argsContainKey(t,e,s){const i=e=>-1!==t.indexOf((/^[^0-9]$/.test(e)?"-":"--")+e);if(i(e))return!0;if(s&&i(`no-${e}`))return!0;if(this.aliases)for(const t of this.aliases[e])if(i(t))return!0;return!1}completeOptionKey(t,e,s,i){var n,r,o,a;let h=t;if(this.zshShell){const e=this.usage.getDescriptions(),s=null===(r=null===(n=null==this?void 0:this.aliases)||void 0===n?void 0:n[t])||void 0===r?void 0:r.find((t=>{const s=e[t];return"string"==typeof s&&s.length>0})),i=s?e[s]:void 0,l=null!==(a=null!==(o=e[t])&&void 0!==o?o:i)&&void 0!==a?a:"";h=`${t.replace(/:/g,"\\:")}:${l.replace("__yargsString__:","").replace(/(\r\n|\n|\r)/gm," ")}`}const l=!/^--/.test(s)&&(t=>/^[^0-9]$/.test(t))(t)?"-":"--";e.push(l+h),i&&e.push(l+"no-"+h)}customCompletion(t,e,s,i){if(d(this.customCompletionFunction,null,this.shim),this.customCompletionFunction.length<3){const t=this.customCompletionFunction(s,e);return f(t)?t.then((t=>{this.shim.process.nextTick((()=>{i(null,t)}))})).catch((t=>{this.shim.process.nextTick((()=>{i(t,void 0)}))})):i(null,t)}return function(t){return t.length>3}(this.customCompletionFunction)?this.customCompletionFunction(s,e,((n=i)=>this.defaultCompletion(t,e,s,n)),(t=>{i(null,t)})):this.customCompletionFunction(s,e,(t=>{i(null,t)}))}getCompletion(t,e){const s=t.length?t[t.length-1]:"",i=this.yargs.parse(t,!0),n=this.customCompletionFunction?i=>this.customCompletion(t,i,s,e):i=>this.defaultCompletion(t,i,s,e);return f(i)?i.then(n):n(i)}generateCompletionScript(t,e){let s=this.zshShell?'#compdef {{app_name}}\n###-begin-{{app_name}}-completions-###\n#\n# yargs command completion script\n#\n# Installation: {{app_path}} {{completion_command}} >> ~/.zshrc\n# or {{app_path}} {{completion_command}} >> ~/.zprofile on OSX.\n#\n_{{app_name}}_yargs_completions()\n{\n local reply\n local si=$IFS\n IFS=$\'\n\' reply=($(COMP_CWORD="$((CURRENT-1))" COMP_LINE="$BUFFER" COMP_POINT="$CURSOR" {{app_path}} --get-yargs-completions "${words[@]}"))\n IFS=$si\n _describe \'values\' reply\n}\ncompdef _{{app_name}}_yargs_completions {{app_name}}\n###-end-{{app_name}}-completions-###\n':'###-begin-{{app_name}}-completions-###\n#\n# yargs command completion script\n#\n# Installation: {{app_path}} {{completion_command}} >> ~/.bashrc\n# or {{app_path}} {{completion_command}} >> ~/.bash_profile on OSX.\n#\n_{{app_name}}_yargs_completions()\n{\n local cur_word args type_list\n\n cur_word="${COMP_WORDS[COMP_CWORD]}"\n args=("${COMP_WORDS[@]}")\n\n # ask yargs to generate completions.\n type_list=$({{app_path}} --get-yargs-completions "${args[@]}")\n\n COMPREPLY=( $(compgen -W "${type_list}" -- ${cur_word}) )\n\n # if no match was found, fall back to filename completion\n if [ ${#COMPREPLY[@]} -eq 0 ]; then\n COMPREPLY=()\n fi\n\n return 0\n}\ncomplete -o bashdefault -o default -F _{{app_name}}_yargs_completions {{app_name}}\n###-end-{{app_name}}-completions-###\n';const i=this.shim.path.basename(t);return t.match(/\.js$/)&&(t=`./${t}`),s=s.replace(/{{app_name}}/g,i),s=s.replace(/{{completion_command}}/g,e),s.replace(/{{app_path}}/g,t)}registerFunction(t){this.customCompletionFunction=t}setParsed(t){this.aliases=t.aliases}}function N(t,e){if(0===t.length)return e.length;if(0===e.length)return t.length;const s=[];let i,n;for(i=0;i<=e.length;i++)s[i]=[i];for(n=0;n<=t.length;n++)s[0][n]=n;for(i=1;i<=e.length;i++)for(n=1;n<=t.length;n++)e.charAt(i-1)===t.charAt(n-1)?s[i][n]=s[i-1][n-1]:i>1&&n>1&&e.charAt(i-2)===t.charAt(n-1)&&e.charAt(i-1)===t.charAt(n-2)?s[i][n]=s[i-2][n-2]+1:s[i][n]=Math.min(s[i-1][n-1]+1,Math.min(s[i][n-1]+1,s[i-1][n]+1));return s[e.length][t.length]}const H=["$0","--","_"];var z,W,q,U,F,L,V,G,R,T,B,Y,K,J,Z,X,Q,tt,et,st,it,nt,rt,ot,at,ht,lt,ct,ft,dt,ut,pt,gt,mt,yt;const bt=Symbol("copyDoubleDash"),vt=Symbol("copyDoubleDash"),Ot=Symbol("deleteFromParserHintObject"),wt=Symbol("emitWarning"),Ct=Symbol("freeze"),jt=Symbol("getDollarZero"),Mt=Symbol("getParserConfiguration"),_t=Symbol("getUsageConfiguration"),kt=Symbol("guessLocale"),xt=Symbol("guessVersion"),Et=Symbol("parsePositionalNumbers"),At=Symbol("pkgUp"),Pt=Symbol("populateParserHintArray"),St=Symbol("populateParserHintSingleValueDictionary"),$t=Symbol("populateParserHintArrayDictionary"),It=Symbol("populateParserHintDictionary"),Dt=Symbol("sanitizeKey"),Nt=Symbol("setKey"),Ht=Symbol("unfreeze"),zt=Symbol("validateAsync"),Wt=Symbol("getCommandInstance"),qt=Symbol("getContext"),Ut=Symbol("getHasOutput"),Ft=Symbol("getLoggerInstance"),Lt=Symbol("getParseContext"),Vt=Symbol("getUsageInstance"),Gt=Symbol("getValidationInstance"),Rt=Symbol("hasParseCallback"),Tt=Symbol("isGlobalContext"),Bt=Symbol("postProcess"),Yt=Symbol("rebase"),Kt=Symbol("reset"),Jt=Symbol("runYargsParserAndExecuteCommands"),Zt=Symbol("runValidation"),Xt=Symbol("setHasOutput"),Qt=Symbol("kTrackManuallySetKeys");class te{constructor(t=[],e,s,i){this.customScriptName=!1,this.parsed=!1,z.set(this,void 0),W.set(this,void 0),q.set(this,{commands:[],fullCommands:[]}),U.set(this,null),F.set(this,null),L.set(this,"show-hidden"),V.set(this,null),G.set(this,!0),R.set(this,{}),T.set(this,!0),B.set(this,[]),Y.set(this,void 0),K.set(this,{}),J.set(this,!1),Z.set(this,null),X.set(this,!0),Q.set(this,void 0),tt.set(this,""),et.set(this,void 0),st.set(this,void 0),it.set(this,{}),nt.set(this,null),rt.set(this,null),ot.set(this,{}),at.set(this,{}),ht.set(this,void 0),lt.set(this,!1),ct.set(this,void 0),ft.set(this,!1),dt.set(this,!1),ut.set(this,!1),pt.set(this,void 0),gt.set(this,{}),mt.set(this,null),yt.set(this,void 0),O(this,ct,i,"f"),O(this,ht,t,"f"),O(this,W,e,"f"),O(this,st,s,"f"),O(this,Y,new w(this),"f"),this.$0=this[jt](),this[Kt](),O(this,z,v(this,z,"f"),"f"),O(this,pt,v(this,pt,"f"),"f"),O(this,yt,v(this,yt,"f"),"f"),O(this,et,v(this,et,"f"),"f"),v(this,et,"f").showHiddenOpt=v(this,L,"f"),O(this,Q,this[vt](),"f")}addHelpOpt(t,e){return h("[string|boolean] [string]",[t,e],arguments.length),v(this,Z,"f")&&(this[Ot](v(this,Z,"f")),O(this,Z,null,"f")),!1===t&&void 0===e||(O(this,Z,"string"==typeof t?t:"help","f"),this.boolean(v(this,Z,"f")),this.describe(v(this,Z,"f"),e||v(this,pt,"f").deferY18nLookup("Show help"))),this}help(t,e){return this.addHelpOpt(t,e)}addShowHiddenOpt(t,e){if(h("[string|boolean] [string]",[t,e],arguments.length),!1===t&&void 0===e)return this;const s="string"==typeof t?t:v(this,L,"f");return this.boolean(s),this.describe(s,e||v(this,pt,"f").deferY18nLookup("Show hidden options")),v(this,et,"f").showHiddenOpt=s,this}showHidden(t,e){return this.addShowHiddenOpt(t,e)}alias(t,e){return h(" [string|array]",[t,e],arguments.length),this[$t](this.alias.bind(this),"alias",t,e),this}array(t){return h("",[t],arguments.length),this[Pt]("array",t),this[Qt](t),this}boolean(t){return h("",[t],arguments.length),this[Pt]("boolean",t),this[Qt](t),this}check(t,e){return h(" [boolean]",[t,e],arguments.length),this.middleware(((e,s)=>j((()=>t(e,s.getOptions())),(s=>(s?("string"==typeof s||s instanceof Error)&&v(this,pt,"f").fail(s.toString(),s):v(this,pt,"f").fail(v(this,ct,"f").y18n.__("Argument check failed: %s",t.toString())),e)),(t=>(v(this,pt,"f").fail(t.message?t.message:t.toString(),t),e)))),!1,e),this}choices(t,e){return h(" [string|array]",[t,e],arguments.length),this[$t](this.choices.bind(this),"choices",t,e),this}coerce(t,s){if(h(" [function]",[t,s],arguments.length),Array.isArray(t)){if(!s)throw new e("coerce callback must be provided");for(const e of t)this.coerce(e,s);return this}if("object"==typeof t){for(const e of Object.keys(t))this.coerce(e,t[e]);return this}if(!s)throw new e("coerce callback must be provided");return v(this,et,"f").key[t]=!0,v(this,Y,"f").addCoerceMiddleware(((i,n)=>{let r;return Object.prototype.hasOwnProperty.call(i,t)?j((()=>(r=n.getAliases(),s(i[t]))),(e=>{i[t]=e;const s=n.getInternalMethods().getParserConfiguration()["strip-aliased"];if(r[t]&&!0!==s)for(const s of r[t])i[s]=e;return i}),(t=>{throw new e(t.message)})):i}),t),this}conflicts(t,e){return h(" [string|array]",[t,e],arguments.length),v(this,yt,"f").conflicts(t,e),this}config(t="config",e,s){return h("[object|string] [string|function] [function]",[t,e,s],arguments.length),"object"!=typeof t||Array.isArray(t)?("function"==typeof e&&(s=e,e=void 0),this.describe(t,e||v(this,pt,"f").deferY18nLookup("Path to JSON config file")),(Array.isArray(t)?t:[t]).forEach((t=>{v(this,et,"f").config[t]=s||!0})),this):(t=n(t,v(this,W,"f"),this[Mt]()["deep-merge-config"]||!1,v(this,ct,"f")),v(this,et,"f").configObjects=(v(this,et,"f").configObjects||[]).concat(t),this)}completion(t,e,s){return h("[string] [string|boolean|function] [function]",[t,e,s],arguments.length),"function"==typeof e&&(s=e,e=void 0),O(this,F,t||v(this,F,"f")||"completion","f"),e||!1===e||(e="generate completion script"),this.command(v(this,F,"f"),e),s&&v(this,U,"f").registerFunction(s),this}command(t,e,s,i,n,r){return h(" [string|boolean] [function|object] [function] [array] [boolean|string]",[t,e,s,i,n,r],arguments.length),v(this,z,"f").addHandler(t,e,s,i,n,r),this}commands(t,e,s,i,n,r){return this.command(t,e,s,i,n,r)}commandDir(t,e){h(" [object]",[t,e],arguments.length);const s=v(this,st,"f")||v(this,ct,"f").require;return v(this,z,"f").addDirectory(t,s,v(this,ct,"f").getCallerFile(),e),this}count(t){return h("",[t],arguments.length),this[Pt]("count",t),this[Qt](t),this}default(t,e,s){return h(" [*] [string]",[t,e,s],arguments.length),s&&(u(t,v(this,ct,"f")),v(this,et,"f").defaultDescription[t]=s),"function"==typeof e&&(u(t,v(this,ct,"f")),v(this,et,"f").defaultDescription[t]||(v(this,et,"f").defaultDescription[t]=v(this,pt,"f").functionDescription(e)),e=e.call()),this[St](this.default.bind(this),"default",t,e),this}defaults(t,e,s){return this.default(t,e,s)}demandCommand(t=1,e,s,i){return h("[number] [number|string] [string|null|undefined] [string|null|undefined]",[t,e,s,i],arguments.length),"number"!=typeof e&&(s=e,e=1/0),this.global("_",!1),v(this,et,"f").demandedCommands._={min:t,max:e,minMsg:s,maxMsg:i},this}demand(t,e,s){return Array.isArray(e)?(e.forEach((t=>{d(s,!0,v(this,ct,"f")),this.demandOption(t,s)})),e=1/0):"number"!=typeof e&&(s=e,e=1/0),"number"==typeof t?(d(s,!0,v(this,ct,"f")),this.demandCommand(t,e,s,s)):Array.isArray(t)?t.forEach((t=>{d(s,!0,v(this,ct,"f")),this.demandOption(t,s)})):"string"==typeof s?this.demandOption(t,s):!0!==s&&void 0!==s||this.demandOption(t),this}demandOption(t,e){return h(" [string]",[t,e],arguments.length),this[St](this.demandOption.bind(this),"demandedOptions",t,e),this}deprecateOption(t,e){return h(" [string|boolean]",[t,e],arguments.length),v(this,et,"f").deprecatedOptions[t]=e,this}describe(t,e){return h(" [string]",[t,e],arguments.length),this[Nt](t,!0),v(this,pt,"f").describe(t,e),this}detectLocale(t){return h("",[t],arguments.length),O(this,G,t,"f"),this}env(t){return h("[string|boolean]",[t],arguments.length),!1===t?delete v(this,et,"f").envPrefix:v(this,et,"f").envPrefix=t||"",this}epilogue(t){return h("",[t],arguments.length),v(this,pt,"f").epilog(t),this}epilog(t){return this.epilogue(t)}example(t,e){return h(" [string]",[t,e],arguments.length),Array.isArray(t)?t.forEach((t=>this.example(...t))):v(this,pt,"f").example(t,e),this}exit(t,e){O(this,J,!0,"f"),O(this,V,e,"f"),v(this,T,"f")&&v(this,ct,"f").process.exit(t)}exitProcess(t=!0){return h("[boolean]",[t],arguments.length),O(this,T,t,"f"),this}fail(t){if(h("",[t],arguments.length),"boolean"==typeof t&&!1!==t)throw new e("Invalid first argument. Expected function or boolean 'false'");return v(this,pt,"f").failFn(t),this}getAliases(){return this.parsed?this.parsed.aliases:{}}async getCompletion(t,e){return h(" [function]",[t,e],arguments.length),e?v(this,U,"f").getCompletion(t,e):new Promise(((e,s)=>{v(this,U,"f").getCompletion(t,((t,i)=>{t?s(t):e(i)}))}))}getDemandedOptions(){return h([],0),v(this,et,"f").demandedOptions}getDemandedCommands(){return h([],0),v(this,et,"f").demandedCommands}getDeprecatedOptions(){return h([],0),v(this,et,"f").deprecatedOptions}getDetectLocale(){return v(this,G,"f")}getExitProcess(){return v(this,T,"f")}getGroups(){return Object.assign({},v(this,K,"f"),v(this,at,"f"))}getHelp(){if(O(this,J,!0,"f"),!v(this,pt,"f").hasCachedHelpMessage()){if(!this.parsed){const t=this[Jt](v(this,ht,"f"),void 0,void 0,0,!0);if(f(t))return t.then((()=>v(this,pt,"f").help()))}const t=v(this,z,"f").runDefaultBuilderOn(this);if(f(t))return t.then((()=>v(this,pt,"f").help()))}return Promise.resolve(v(this,pt,"f").help())}getOptions(){return v(this,et,"f")}getStrict(){return v(this,ft,"f")}getStrictCommands(){return v(this,dt,"f")}getStrictOptions(){return v(this,ut,"f")}global(t,e){return h(" [boolean]",[t,e],arguments.length),t=[].concat(t),!1!==e?v(this,et,"f").local=v(this,et,"f").local.filter((e=>-1===t.indexOf(e))):t.forEach((t=>{v(this,et,"f").local.includes(t)||v(this,et,"f").local.push(t)})),this}group(t,e){h(" ",[t,e],arguments.length);const s=v(this,at,"f")[e]||v(this,K,"f")[e];v(this,at,"f")[e]&&delete v(this,at,"f")[e];const i={};return v(this,K,"f")[e]=(s||[]).concat(t).filter((t=>!i[t]&&(i[t]=!0))),this}hide(t){return h("",[t],arguments.length),v(this,et,"f").hiddenOptions.push(t),this}implies(t,e){return h(" [number|string|array]",[t,e],arguments.length),v(this,yt,"f").implies(t,e),this}locale(t){return h("[string]",[t],arguments.length),void 0===t?(this[kt](),v(this,ct,"f").y18n.getLocale()):(O(this,G,!1,"f"),v(this,ct,"f").y18n.setLocale(t),this)}middleware(t,e,s){return v(this,Y,"f").addMiddleware(t,!!e,s)}nargs(t,e){return h(" [number]",[t,e],arguments.length),this[St](this.nargs.bind(this),"narg",t,e),this}normalize(t){return h("",[t],arguments.length),this[Pt]("normalize",t),this}number(t){return h("",[t],arguments.length),this[Pt]("number",t),this[Qt](t),this}option(t,e){if(h(" [object]",[t,e],arguments.length),"object"==typeof t)Object.keys(t).forEach((e=>{this.options(e,t[e])}));else{"object"!=typeof e&&(e={}),this[Qt](t),!v(this,mt,"f")||"version"!==t&&"version"!==(null==e?void 0:e.alias)||this[wt](['"version" is a reserved word.',"Please do one of the following:",'- Disable version with `yargs.version(false)` if using "version" as an option',"- Use the built-in `yargs.version` method instead (if applicable)","- Use a different option key","https://yargs.js.org/docs/#api-reference-version"].join("\n"),void 0,"versionWarning"),v(this,et,"f").key[t]=!0,e.alias&&this.alias(t,e.alias);const s=e.deprecate||e.deprecated;s&&this.deprecateOption(t,s);const i=e.demand||e.required||e.require;i&&this.demand(t,i),e.demandOption&&this.demandOption(t,"string"==typeof e.demandOption?e.demandOption:void 0),e.conflicts&&this.conflicts(t,e.conflicts),"default"in e&&this.default(t,e.default),void 0!==e.implies&&this.implies(t,e.implies),void 0!==e.nargs&&this.nargs(t,e.nargs),e.config&&this.config(t,e.configParser),e.normalize&&this.normalize(t),e.choices&&this.choices(t,e.choices),e.coerce&&this.coerce(t,e.coerce),e.group&&this.group(t,e.group),(e.boolean||"boolean"===e.type)&&(this.boolean(t),e.alias&&this.boolean(e.alias)),(e.array||"array"===e.type)&&(this.array(t),e.alias&&this.array(e.alias)),(e.number||"number"===e.type)&&(this.number(t),e.alias&&this.number(e.alias)),(e.string||"string"===e.type)&&(this.string(t),e.alias&&this.string(e.alias)),(e.count||"count"===e.type)&&this.count(t),"boolean"==typeof e.global&&this.global(t,e.global),e.defaultDescription&&(v(this,et,"f").defaultDescription[t]=e.defaultDescription),e.skipValidation&&this.skipValidation(t);const n=e.describe||e.description||e.desc,r=v(this,pt,"f").getDescriptions();Object.prototype.hasOwnProperty.call(r,t)&&"string"!=typeof n||this.describe(t,n),e.hidden&&this.hide(t),e.requiresArg&&this.requiresArg(t)}return this}options(t,e){return this.option(t,e)}parse(t,e,s){h("[string|array] [function|boolean|object] [function]",[t,e,s],arguments.length),this[Ct](),void 0===t&&(t=v(this,ht,"f")),"object"==typeof e&&(O(this,rt,e,"f"),e=s),"function"==typeof e&&(O(this,nt,e,"f"),e=!1),e||O(this,ht,t,"f"),v(this,nt,"f")&&O(this,T,!1,"f");const i=this[Jt](t,!!e),n=this.parsed;return v(this,U,"f").setParsed(this.parsed),f(i)?i.then((t=>(v(this,nt,"f")&&v(this,nt,"f").call(this,v(this,V,"f"),t,v(this,tt,"f")),t))).catch((t=>{throw v(this,nt,"f")&&v(this,nt,"f")(t,this.parsed.argv,v(this,tt,"f")),t})).finally((()=>{this[Ht](),this.parsed=n})):(v(this,nt,"f")&&v(this,nt,"f").call(this,v(this,V,"f"),i,v(this,tt,"f")),this[Ht](),this.parsed=n,i)}parseAsync(t,e,s){const i=this.parse(t,e,s);return f(i)?i:Promise.resolve(i)}parseSync(t,s,i){const n=this.parse(t,s,i);if(f(n))throw new e(".parseSync() must not be used with asynchronous builders, handlers, or middleware");return n}parserConfiguration(t){return h("",[t],arguments.length),O(this,it,t,"f"),this}pkgConf(t,e){h(" [string]",[t,e],arguments.length);let s=null;const i=this[At](e||v(this,W,"f"));return i[t]&&"object"==typeof i[t]&&(s=n(i[t],e||v(this,W,"f"),this[Mt]()["deep-merge-config"]||!1,v(this,ct,"f")),v(this,et,"f").configObjects=(v(this,et,"f").configObjects||[]).concat(s)),this}positional(t,e){h(" ",[t,e],arguments.length);const s=["default","defaultDescription","implies","normalize","choices","conflicts","coerce","type","describe","desc","description","alias"];e=g(e,((t,e)=>!("type"===t&&!["string","number","boolean"].includes(e))&&s.includes(t)));const i=v(this,q,"f").fullCommands[v(this,q,"f").fullCommands.length-1],n=i?v(this,z,"f").cmdToParseOptions(i):{array:[],alias:{},default:{},demand:{}};return p(n).forEach((s=>{const i=n[s];Array.isArray(i)?-1!==i.indexOf(t)&&(e[s]=!0):i[t]&&!(s in e)&&(e[s]=i[t])})),this.group(t,v(this,pt,"f").getPositionalGroupName()),this.option(t,e)}recommendCommands(t=!0){return h("[boolean]",[t],arguments.length),O(this,lt,t,"f"),this}required(t,e,s){return this.demand(t,e,s)}require(t,e,s){return this.demand(t,e,s)}requiresArg(t){return h(" [number]",[t],arguments.length),"string"==typeof t&&v(this,et,"f").narg[t]||this[St](this.requiresArg.bind(this),"narg",t,NaN),this}showCompletionScript(t,e){return h("[string] [string]",[t,e],arguments.length),t=t||this.$0,v(this,Q,"f").log(v(this,U,"f").generateCompletionScript(t,e||v(this,F,"f")||"completion")),this}showHelp(t){if(h("[string|function]",[t],arguments.length),O(this,J,!0,"f"),!v(this,pt,"f").hasCachedHelpMessage()){if(!this.parsed){const e=this[Jt](v(this,ht,"f"),void 0,void 0,0,!0);if(f(e))return e.then((()=>{v(this,pt,"f").showHelp(t)})),this}const e=v(this,z,"f").runDefaultBuilderOn(this);if(f(e))return e.then((()=>{v(this,pt,"f").showHelp(t)})),this}return v(this,pt,"f").showHelp(t),this}scriptName(t){return this.customScriptName=!0,this.$0=t,this}showHelpOnFail(t,e){return h("[boolean|string] [string]",[t,e],arguments.length),v(this,pt,"f").showHelpOnFail(t,e),this}showVersion(t){return h("[string|function]",[t],arguments.length),v(this,pt,"f").showVersion(t),this}skipValidation(t){return h("",[t],arguments.length),this[Pt]("skipValidation",t),this}strict(t){return h("[boolean]",[t],arguments.length),O(this,ft,!1!==t,"f"),this}strictCommands(t){return h("[boolean]",[t],arguments.length),O(this,dt,!1!==t,"f"),this}strictOptions(t){return h("[boolean]",[t],arguments.length),O(this,ut,!1!==t,"f"),this}string(t){return h("",[t],arguments.length),this[Pt]("string",t),this[Qt](t),this}terminalWidth(){return h([],0),v(this,ct,"f").process.stdColumns}updateLocale(t){return this.updateStrings(t)}updateStrings(t){return h("",[t],arguments.length),O(this,G,!1,"f"),v(this,ct,"f").y18n.updateLocale(t),this}usage(t,s,i,n){if(h(" [string|boolean] [function|object] [function]",[t,s,i,n],arguments.length),void 0!==s){if(d(t,null,v(this,ct,"f")),(t||"").match(/^\$0( |$)/))return this.command(t,s,i,n);throw new e(".usage() description must start with $0 if being used as alias for .command()")}return v(this,pt,"f").usage(t),this}usageConfiguration(t){return h("",[t],arguments.length),O(this,gt,t,"f"),this}version(t,e,s){const i="version";if(h("[boolean|string] [string] [string]",[t,e,s],arguments.length),v(this,mt,"f")&&(this[Ot](v(this,mt,"f")),v(this,pt,"f").version(void 0),O(this,mt,null,"f")),0===arguments.length)s=this[xt](),t=i;else if(1===arguments.length){if(!1===t)return this;s=t,t=i}else 2===arguments.length&&(s=e,e=void 0);return O(this,mt,"string"==typeof t?t:i,"f"),e=e||v(this,pt,"f").deferY18nLookup("Show version number"),v(this,pt,"f").version(s||void 0),this.boolean(v(this,mt,"f")),this.describe(v(this,mt,"f"),e),this}wrap(t){return h("",[t],arguments.length),v(this,pt,"f").wrap(t),this}[(z=new WeakMap,W=new WeakMap,q=new WeakMap,U=new WeakMap,F=new WeakMap,L=new WeakMap,V=new WeakMap,G=new WeakMap,R=new WeakMap,T=new WeakMap,B=new WeakMap,Y=new WeakMap,K=new WeakMap,J=new WeakMap,Z=new WeakMap,X=new WeakMap,Q=new WeakMap,tt=new WeakMap,et=new WeakMap,st=new WeakMap,it=new WeakMap,nt=new WeakMap,rt=new WeakMap,ot=new WeakMap,at=new WeakMap,ht=new WeakMap,lt=new WeakMap,ct=new WeakMap,ft=new WeakMap,dt=new WeakMap,ut=new WeakMap,pt=new WeakMap,gt=new WeakMap,mt=new WeakMap,yt=new WeakMap,bt)](t){if(!t._||!t["--"])return t;t._.push.apply(t._,t["--"]);try{delete t["--"]}catch(t){}return t}[vt](){return{log:(...t)=>{this[Rt]()||console.log(...t),O(this,J,!0,"f"),v(this,tt,"f").length&&O(this,tt,v(this,tt,"f")+"\n","f"),O(this,tt,v(this,tt,"f")+t.join(" "),"f")},error:(...t)=>{this[Rt]()||console.error(...t),O(this,J,!0,"f"),v(this,tt,"f").length&&O(this,tt,v(this,tt,"f")+"\n","f"),O(this,tt,v(this,tt,"f")+t.join(" "),"f")}}}[Ot](t){p(v(this,et,"f")).forEach((e=>{if("configObjects"===e)return;const s=v(this,et,"f")[e];Array.isArray(s)?s.includes(t)&&s.splice(s.indexOf(t),1):"object"==typeof s&&delete s[t]})),delete v(this,pt,"f").getDescriptions()[t]}[wt](t,e,s){v(this,R,"f")[s]||(v(this,ct,"f").process.emitWarning(t,e),v(this,R,"f")[s]=!0)}[Ct](){v(this,B,"f").push({options:v(this,et,"f"),configObjects:v(this,et,"f").configObjects.slice(0),exitProcess:v(this,T,"f"),groups:v(this,K,"f"),strict:v(this,ft,"f"),strictCommands:v(this,dt,"f"),strictOptions:v(this,ut,"f"),completionCommand:v(this,F,"f"),output:v(this,tt,"f"),exitError:v(this,V,"f"),hasOutput:v(this,J,"f"),parsed:this.parsed,parseFn:v(this,nt,"f"),parseContext:v(this,rt,"f")}),v(this,pt,"f").freeze(),v(this,yt,"f").freeze(),v(this,z,"f").freeze(),v(this,Y,"f").freeze()}[jt](){let t,e="";return t=/\b(node|iojs|electron)(\.exe)?$/.test(v(this,ct,"f").process.argv()[0])?v(this,ct,"f").process.argv().slice(1,2):v(this,ct,"f").process.argv().slice(0,1),e=t.map((t=>{const e=this[Yt](v(this,W,"f"),t);return t.match(/^(\/|([a-zA-Z]:)?\\)/)&&e.lengthe.includes("package.json")?"package.json":void 0));d(i,void 0,v(this,ct,"f")),s=JSON.parse(v(this,ct,"f").readFileSync(i,"utf8"))}catch(t){}return v(this,ot,"f")[e]=s||{},v(this,ot,"f")[e]}[Pt](t,e){(e=[].concat(e)).forEach((e=>{e=this[Dt](e),v(this,et,"f")[t].push(e)}))}[St](t,e,s,i){this[It](t,e,s,i,((t,e,s)=>{v(this,et,"f")[t][e]=s}))}[$t](t,e,s,i){this[It](t,e,s,i,((t,e,s)=>{v(this,et,"f")[t][e]=(v(this,et,"f")[t][e]||[]).concat(s)}))}[It](t,e,s,i,n){if(Array.isArray(s))s.forEach((e=>{t(e,i)}));else if((t=>"object"==typeof t)(s))for(const e of p(s))t(e,s[e]);else n(e,this[Dt](s),i)}[Dt](t){return"__proto__"===t?"___proto___":t}[Nt](t,e){return this[St](this[Nt].bind(this),"key",t,e),this}[Ht](){var t,e,s,i,n,r,o,a,h,l,c,f;const u=v(this,B,"f").pop();let p;d(u,void 0,v(this,ct,"f")),t=this,e=this,s=this,i=this,n=this,r=this,o=this,a=this,h=this,l=this,c=this,f=this,({options:{set value(e){O(t,et,e,"f")}}.value,configObjects:p,exitProcess:{set value(t){O(e,T,t,"f")}}.value,groups:{set value(t){O(s,K,t,"f")}}.value,output:{set value(t){O(i,tt,t,"f")}}.value,exitError:{set value(t){O(n,V,t,"f")}}.value,hasOutput:{set value(t){O(r,J,t,"f")}}.value,parsed:this.parsed,strict:{set value(t){O(o,ft,t,"f")}}.value,strictCommands:{set value(t){O(a,dt,t,"f")}}.value,strictOptions:{set value(t){O(h,ut,t,"f")}}.value,completionCommand:{set value(t){O(l,F,t,"f")}}.value,parseFn:{set value(t){O(c,nt,t,"f")}}.value,parseContext:{set value(t){O(f,rt,t,"f")}}.value}=u),v(this,et,"f").configObjects=p,v(this,pt,"f").unfreeze(),v(this,yt,"f").unfreeze(),v(this,z,"f").unfreeze(),v(this,Y,"f").unfreeze()}[zt](t,e){return j(e,(e=>(t(e),e)))}getInternalMethods(){return{getCommandInstance:this[Wt].bind(this),getContext:this[qt].bind(this),getHasOutput:this[Ut].bind(this),getLoggerInstance:this[Ft].bind(this),getParseContext:this[Lt].bind(this),getParserConfiguration:this[Mt].bind(this),getUsageConfiguration:this[_t].bind(this),getUsageInstance:this[Vt].bind(this),getValidationInstance:this[Gt].bind(this),hasParseCallback:this[Rt].bind(this),isGlobalContext:this[Tt].bind(this),postProcess:this[Bt].bind(this),reset:this[Kt].bind(this),runValidation:this[Zt].bind(this),runYargsParserAndExecuteCommands:this[Jt].bind(this),setHasOutput:this[Xt].bind(this)}}[Wt](){return v(this,z,"f")}[qt](){return v(this,q,"f")}[Ut](){return v(this,J,"f")}[Ft](){return v(this,Q,"f")}[Lt](){return v(this,rt,"f")||{}}[Vt](){return v(this,pt,"f")}[Gt](){return v(this,yt,"f")}[Rt](){return!!v(this,nt,"f")}[Tt](){return v(this,X,"f")}[Bt](t,e,s,i){if(s)return t;if(f(t))return t;e||(t=this[bt](t));return(this[Mt]()["parse-positional-numbers"]||void 0===this[Mt]()["parse-positional-numbers"])&&(t=this[Et](t)),i&&(t=C(t,this,v(this,Y,"f").getMiddleware(),!1)),t}[Kt](t={}){O(this,et,v(this,et,"f")||{},"f");const e={};e.local=v(this,et,"f").local||[],e.configObjects=v(this,et,"f").configObjects||[];const s={};e.local.forEach((e=>{s[e]=!0,(t[e]||[]).forEach((t=>{s[t]=!0}))})),Object.assign(v(this,at,"f"),Object.keys(v(this,K,"f")).reduce(((t,e)=>{const i=v(this,K,"f")[e].filter((t=>!(t in s)));return i.length>0&&(t[e]=i),t}),{})),O(this,K,{},"f");return["array","boolean","string","skipValidation","count","normalize","number","hiddenOptions"].forEach((t=>{e[t]=(v(this,et,"f")[t]||[]).filter((t=>!s[t]))})),["narg","key","alias","default","defaultDescription","config","choices","demandedOptions","demandedCommands","deprecatedOptions"].forEach((t=>{e[t]=g(v(this,et,"f")[t],(t=>!s[t]))})),e.envPrefix=v(this,et,"f").envPrefix,O(this,et,e,"f"),O(this,pt,v(this,pt,"f")?v(this,pt,"f").reset(s):P(this,v(this,ct,"f")),"f"),O(this,yt,v(this,yt,"f")?v(this,yt,"f").reset(s):function(t,e,s){const i=s.y18n.__,n=s.y18n.__n,r={nonOptionCount:function(s){const i=t.getDemandedCommands(),r=s._.length+(s["--"]?s["--"].length:0)-t.getInternalMethods().getContext().commands.length;i._&&(ri._.max)&&(ri._.max&&(void 0!==i._.maxMsg?e.fail(i._.maxMsg?i._.maxMsg.replace(/\$0/g,r.toString()).replace(/\$1/,i._.max.toString()):null):e.fail(n("Too many non-option arguments: got %s, maximum of %s","Too many non-option arguments: got %s, maximum of %s",r,r.toString(),i._.max.toString()))))},positionalCount:function(t,s){s{H.includes(e)||Object.prototype.hasOwnProperty.call(o,e)||Object.prototype.hasOwnProperty.call(t.getInternalMethods().getParseContext(),e)||r.isValidAndSomeAliasIsNotNew(e,i)||f.push(e)})),h&&(d.commands.length>0||c.length>0||a)&&s._.slice(d.commands.length).forEach((t=>{c.includes(""+t)||f.push(""+t)})),h){const e=(null===(l=t.getDemandedCommands()._)||void 0===l?void 0:l.max)||0,i=d.commands.length+e;i{t=String(t),d.commands.includes(t)||f.includes(t)||f.push(t)}))}f.length&&e.fail(n("Unknown argument: %s","Unknown arguments: %s",f.length,f.map((t=>t.trim()?t:`"${t}"`)).join(", ")))},unknownCommands:function(s){const i=t.getInternalMethods().getCommandInstance().getCommands(),r=[],o=t.getInternalMethods().getContext();return(o.commands.length>0||i.length>0)&&s._.slice(o.commands.length).forEach((t=>{i.includes(""+t)||r.push(""+t)})),r.length>0&&(e.fail(n("Unknown command: %s","Unknown commands: %s",r.length,r.join(", "))),!0)},isValidAndSomeAliasIsNotNew:function(e,s){if(!Object.prototype.hasOwnProperty.call(s,e))return!1;const i=t.parsed.newAliases;return[e,...s[e]].some((t=>!Object.prototype.hasOwnProperty.call(i,t)||!i[e]))},limitedChoices:function(s){const n=t.getOptions(),r={};if(!Object.keys(n.choices).length)return;Object.keys(s).forEach((t=>{-1===H.indexOf(t)&&Object.prototype.hasOwnProperty.call(n.choices,t)&&[].concat(s[t]).forEach((e=>{-1===n.choices[t].indexOf(e)&&void 0!==e&&(r[t]=(r[t]||[]).concat(e))}))}));const o=Object.keys(r);if(!o.length)return;let a=i("Invalid values:");o.forEach((t=>{a+=`\n ${i("Argument: %s, Given: %s, Choices: %s",t,e.stringifiedValues(r[t]),e.stringifiedValues(n.choices[t]))}`})),e.fail(a)}};let o={};function a(t,e){const s=Number(e);return"number"==typeof(e=isNaN(s)?e:s)?e=t._.length>=e:e.match(/^--no-.+/)?(e=e.match(/^--no-(.+)/)[1],e=!Object.prototype.hasOwnProperty.call(t,e)):e=Object.prototype.hasOwnProperty.call(t,e),e}r.implies=function(e,i){h(" [array|number|string]",[e,i],arguments.length),"object"==typeof e?Object.keys(e).forEach((t=>{r.implies(t,e[t])})):(t.global(e),o[e]||(o[e]=[]),Array.isArray(i)?i.forEach((t=>r.implies(e,t))):(d(i,void 0,s),o[e].push(i)))},r.getImplied=function(){return o},r.implications=function(t){const s=[];if(Object.keys(o).forEach((e=>{const i=e;(o[e]||[]).forEach((e=>{let n=i;const r=e;n=a(t,n),e=a(t,e),n&&!e&&s.push(` ${i} -> ${r}`)}))})),s.length){let t=`${i("Implications failed:")}\n`;s.forEach((e=>{t+=e})),e.fail(t)}};let l={};r.conflicts=function(e,s){h(" [array|string]",[e,s],arguments.length),"object"==typeof e?Object.keys(e).forEach((t=>{r.conflicts(t,e[t])})):(t.global(e),l[e]||(l[e]=[]),Array.isArray(s)?s.forEach((t=>r.conflicts(e,t))):l[e].push(s))},r.getConflicting=()=>l,r.conflicting=function(n){Object.keys(n).forEach((t=>{l[t]&&l[t].forEach((s=>{s&&void 0!==n[t]&&void 0!==n[s]&&e.fail(i("Arguments %s and %s are mutually exclusive",t,s))}))})),t.getInternalMethods().getParserConfiguration()["strip-dashed"]&&Object.keys(l).forEach((t=>{l[t].forEach((r=>{r&&void 0!==n[s.Parser.camelCase(t)]&&void 0!==n[s.Parser.camelCase(r)]&&e.fail(i("Arguments %s and %s are mutually exclusive",t,r))}))}))},r.recommendCommands=function(t,s){s=s.sort(((t,e)=>e.length-t.length));let n=null,r=1/0;for(let e,i=0;void 0!==(e=s[i]);i++){const s=N(t,e);s<=3&&s!t[e])),l=g(l,(e=>!t[e])),r};const c=[];return r.freeze=function(){c.push({implied:o,conflicting:l})},r.unfreeze=function(){const t=c.pop();d(t,void 0,s),({implied:o,conflicting:l}=t)},r}(this,v(this,pt,"f"),v(this,ct,"f")),"f"),O(this,z,v(this,z,"f")?v(this,z,"f").reset():function(t,e,s,i){return new _(t,e,s,i)}(v(this,pt,"f"),v(this,yt,"f"),v(this,Y,"f"),v(this,ct,"f")),"f"),v(this,U,"f")||O(this,U,function(t,e,s,i){return new D(t,e,s,i)}(this,v(this,pt,"f"),v(this,z,"f"),v(this,ct,"f")),"f"),v(this,Y,"f").reset(),O(this,F,null,"f"),O(this,tt,"","f"),O(this,V,null,"f"),O(this,J,!1,"f"),this.parsed=!1,this}[Yt](t,e){return v(this,ct,"f").path.relative(t,e)}[Jt](t,s,i,n=0,r=!1){let o=!!i||r;t=t||v(this,ht,"f"),v(this,et,"f").__=v(this,ct,"f").y18n.__,v(this,et,"f").configuration=this[Mt]();const a=!!v(this,et,"f").configuration["populate--"],h=Object.assign({},v(this,et,"f").configuration,{"populate--":!0}),l=v(this,ct,"f").Parser.detailed(t,Object.assign({},v(this,et,"f"),{configuration:{"parse-positional-numbers":!1,...h}})),c=Object.assign(l.argv,v(this,rt,"f"));let d;const u=l.aliases;let p=!1,g=!1;Object.keys(c).forEach((t=>{t===v(this,Z,"f")&&c[t]?p=!0:t===v(this,mt,"f")&&c[t]&&(g=!0)})),c.$0=this.$0,this.parsed=l,0===n&&v(this,pt,"f").clearCachedHelpMessage();try{if(this[kt](),s)return this[Bt](c,a,!!i,!1);if(v(this,Z,"f")){[v(this,Z,"f")].concat(u[v(this,Z,"f")]||[]).filter((t=>t.length>1)).includes(""+c._[c._.length-1])&&(c._.pop(),p=!0)}O(this,X,!1,"f");const h=v(this,z,"f").getCommands(),m=v(this,U,"f").completionKey in c,y=p||m||r;if(c._.length){if(h.length){let t;for(let e,s=n||0;void 0!==c._[s];s++){if(e=String(c._[s]),h.includes(e)&&e!==v(this,F,"f")){const t=v(this,z,"f").runCommand(e,this,l,s+1,r,p||g||r);return this[Bt](t,a,!!i,!1)}if(!t&&e!==v(this,F,"f")){t=e;break}}!v(this,z,"f").hasDefaultCommand()&&v(this,lt,"f")&&t&&!y&&v(this,yt,"f").recommendCommands(t,h)}v(this,F,"f")&&c._.includes(v(this,F,"f"))&&!m&&(v(this,T,"f")&&E(!0),this.showCompletionScript(),this.exit(0))}if(v(this,z,"f").hasDefaultCommand()&&!y){const t=v(this,z,"f").runCommand(null,this,l,0,r,p||g||r);return this[Bt](t,a,!!i,!1)}if(m){v(this,T,"f")&&E(!0);const s=(t=[].concat(t)).slice(t.indexOf(`--${v(this,U,"f").completionKey}`)+1);return v(this,U,"f").getCompletion(s,((t,s)=>{if(t)throw new e(t.message);(s||[]).forEach((t=>{v(this,Q,"f").log(t)})),this.exit(0)})),this[Bt](c,!a,!!i,!1)}if(v(this,J,"f")||(p?(v(this,T,"f")&&E(!0),o=!0,this.showHelp("log"),this.exit(0)):g&&(v(this,T,"f")&&E(!0),o=!0,v(this,pt,"f").showVersion("log"),this.exit(0))),!o&&v(this,et,"f").skipValidation.length>0&&(o=Object.keys(c).some((t=>v(this,et,"f").skipValidation.indexOf(t)>=0&&!0===c[t]))),!o){if(l.error)throw new e(l.error.message);if(!m){const t=this[Zt](u,{},l.error);i||(d=C(c,this,v(this,Y,"f").getMiddleware(),!0)),d=this[zt](t,null!=d?d:c),f(d)&&!i&&(d=d.then((()=>C(c,this,v(this,Y,"f").getMiddleware(),!1))))}}}catch(t){if(!(t instanceof e))throw t;v(this,pt,"f").fail(t.message,t)}return this[Bt](null!=d?d:c,a,!!i,!0)}[Zt](t,s,i,n){const r={...this.getDemandedOptions()};return o=>{if(i)throw new e(i.message);v(this,yt,"f").nonOptionCount(o),v(this,yt,"f").requiredArguments(o,r);let a=!1;v(this,dt,"f")&&(a=v(this,yt,"f").unknownCommands(o)),v(this,ft,"f")&&!a?v(this,yt,"f").unknownArguments(o,t,s,!!n):v(this,ut,"f")&&v(this,yt,"f").unknownArguments(o,t,{},!1,!1),v(this,yt,"f").limitedChoices(o),v(this,yt,"f").implications(o),v(this,yt,"f").conflicting(o)}}[Xt](){O(this,J,!0,"f")}[Qt](t){if("string"==typeof t)v(this,et,"f").key[t]=!0;else for(const e of t)v(this,et,"f").key[e]=!0}}var ee,se;const{readFileSync:ie}=require("fs"),{inspect:ne}=require("util"),{resolve:re}=require("path"),oe=require("y18n"),ae=require("yargs-parser");var he,le={assert:{notStrictEqual:t.notStrictEqual,strictEqual:t.strictEqual},cliui:require("cliui"),findUp:require("escalade/sync"),getEnv:t=>process.env[t],getCallerFile:require("get-caller-file"),getProcessArgvBin:y,inspect:ne,mainFilename:null!==(se=null===(ee=null===require||void 0===require?void 0:require.main)||void 0===ee?void 0:ee.filename)&&void 0!==se?se:process.cwd(),Parser:ae,path:require("path"),process:{argv:()=>process.argv,cwd:process.cwd,emitWarning:(t,e)=>process.emitWarning(t,e),execPath:()=>process.execPath,exit:t=>{process.exit(t)},nextTick:process.nextTick,stdColumns:void 0!==process.stdout.columns?process.stdout.columns:null},readFileSync:ie,require:require,requireDirectory:require("require-directory"),stringWidth:require("string-width"),y18n:oe({directory:re(__dirname,"../locales"),updateFiles:!1})};const ce=(null===(he=null===process||void 0===process?void 0:process.env)||void 0===he?void 0:he.YARGS_MIN_NODE_VERSION)?Number(process.env.YARGS_MIN_NODE_VERSION):12;if(process&&process.version){if(Number(process.version.match(/v([^.]+)/)[1]){const i=new te(t,e,s,de);return Object.defineProperty(i,"argv",{get:()=>i.parse(),enumerable:!0}),i.help(),i.version(),i}),argsert:h,isPromise:f,objFilter:g,parseCommand:o,Parser:fe,processArgv:b,YError:e};module.exports=ue; diff --git a/node_modules/yargs/build/lib/argsert.js b/node_modules/yargs/build/lib/argsert.js new file mode 100644 index 0000000..be5b3aa --- /dev/null +++ b/node_modules/yargs/build/lib/argsert.js @@ -0,0 +1,62 @@ +import { YError } from './yerror.js'; +import { parseCommand } from './parse-command.js'; +const positionName = ['first', 'second', 'third', 'fourth', 'fifth', 'sixth']; +export function argsert(arg1, arg2, arg3) { + function parseArgs() { + return typeof arg1 === 'object' + ? [{ demanded: [], optional: [] }, arg1, arg2] + : [ + parseCommand(`cmd ${arg1}`), + arg2, + arg3, + ]; + } + try { + let position = 0; + const [parsed, callerArguments, _length] = parseArgs(); + const args = [].slice.call(callerArguments); + while (args.length && args[args.length - 1] === undefined) + args.pop(); + const length = _length || args.length; + if (length < parsed.demanded.length) { + throw new YError(`Not enough arguments provided. Expected ${parsed.demanded.length} but received ${args.length}.`); + } + const totalCommands = parsed.demanded.length + parsed.optional.length; + if (length > totalCommands) { + throw new YError(`Too many arguments provided. Expected max ${totalCommands} but received ${length}.`); + } + parsed.demanded.forEach(demanded => { + const arg = args.shift(); + const observedType = guessType(arg); + const matchingTypes = demanded.cmd.filter(type => type === observedType || type === '*'); + if (matchingTypes.length === 0) + argumentTypeError(observedType, demanded.cmd, position); + position += 1; + }); + parsed.optional.forEach(optional => { + if (args.length === 0) + return; + const arg = args.shift(); + const observedType = guessType(arg); + const matchingTypes = optional.cmd.filter(type => type === observedType || type === '*'); + if (matchingTypes.length === 0) + argumentTypeError(observedType, optional.cmd, position); + position += 1; + }); + } + catch (err) { + console.warn(err.stack); + } +} +function guessType(arg) { + if (Array.isArray(arg)) { + return 'array'; + } + else if (arg === null) { + return 'null'; + } + return typeof arg; +} +function argumentTypeError(observedType, allowedTypes, position) { + throw new YError(`Invalid ${positionName[position] || 'manyith'} argument. Expected ${allowedTypes.join(' or ')} but received ${observedType}.`); +} diff --git a/node_modules/yargs/build/lib/command.js b/node_modules/yargs/build/lib/command.js new file mode 100644 index 0000000..47c1ed6 --- /dev/null +++ b/node_modules/yargs/build/lib/command.js @@ -0,0 +1,449 @@ +import { assertNotStrictEqual, } from './typings/common-types.js'; +import { isPromise } from './utils/is-promise.js'; +import { applyMiddleware, commandMiddlewareFactory, } from './middleware.js'; +import { parseCommand } from './parse-command.js'; +import { isYargsInstance, } from './yargs-factory.js'; +import { maybeAsyncResult } from './utils/maybe-async-result.js'; +import whichModule from './utils/which-module.js'; +const DEFAULT_MARKER = /(^\*)|(^\$0)/; +export class CommandInstance { + constructor(usage, validation, globalMiddleware, shim) { + this.requireCache = new Set(); + this.handlers = {}; + this.aliasMap = {}; + this.frozens = []; + this.shim = shim; + this.usage = usage; + this.globalMiddleware = globalMiddleware; + this.validation = validation; + } + addDirectory(dir, req, callerFile, opts) { + opts = opts || {}; + if (typeof opts.recurse !== 'boolean') + opts.recurse = false; + if (!Array.isArray(opts.extensions)) + opts.extensions = ['js']; + const parentVisit = typeof opts.visit === 'function' ? opts.visit : (o) => o; + opts.visit = (obj, joined, filename) => { + const visited = parentVisit(obj, joined, filename); + if (visited) { + if (this.requireCache.has(joined)) + return visited; + else + this.requireCache.add(joined); + this.addHandler(visited); + } + return visited; + }; + this.shim.requireDirectory({ require: req, filename: callerFile }, dir, opts); + } + addHandler(cmd, description, builder, handler, commandMiddleware, deprecated) { + let aliases = []; + const middlewares = commandMiddlewareFactory(commandMiddleware); + handler = handler || (() => { }); + if (Array.isArray(cmd)) { + if (isCommandAndAliases(cmd)) { + [cmd, ...aliases] = cmd; + } + else { + for (const command of cmd) { + this.addHandler(command); + } + } + } + else if (isCommandHandlerDefinition(cmd)) { + let command = Array.isArray(cmd.command) || typeof cmd.command === 'string' + ? cmd.command + : this.moduleName(cmd); + if (cmd.aliases) + command = [].concat(command).concat(cmd.aliases); + this.addHandler(command, this.extractDesc(cmd), cmd.builder, cmd.handler, cmd.middlewares, cmd.deprecated); + return; + } + else if (isCommandBuilderDefinition(builder)) { + this.addHandler([cmd].concat(aliases), description, builder.builder, builder.handler, builder.middlewares, builder.deprecated); + return; + } + if (typeof cmd === 'string') { + const parsedCommand = parseCommand(cmd); + aliases = aliases.map(alias => parseCommand(alias).cmd); + let isDefault = false; + const parsedAliases = [parsedCommand.cmd].concat(aliases).filter(c => { + if (DEFAULT_MARKER.test(c)) { + isDefault = true; + return false; + } + return true; + }); + if (parsedAliases.length === 0 && isDefault) + parsedAliases.push('$0'); + if (isDefault) { + parsedCommand.cmd = parsedAliases[0]; + aliases = parsedAliases.slice(1); + cmd = cmd.replace(DEFAULT_MARKER, parsedCommand.cmd); + } + aliases.forEach(alias => { + this.aliasMap[alias] = parsedCommand.cmd; + }); + if (description !== false) { + this.usage.command(cmd, description, isDefault, aliases, deprecated); + } + this.handlers[parsedCommand.cmd] = { + original: cmd, + description, + handler, + builder: builder || {}, + middlewares, + deprecated, + demanded: parsedCommand.demanded, + optional: parsedCommand.optional, + }; + if (isDefault) + this.defaultCommand = this.handlers[parsedCommand.cmd]; + } + } + getCommandHandlers() { + return this.handlers; + } + getCommands() { + return Object.keys(this.handlers).concat(Object.keys(this.aliasMap)); + } + hasDefaultCommand() { + return !!this.defaultCommand; + } + runCommand(command, yargs, parsed, commandIndex, helpOnly, helpOrVersionSet) { + const commandHandler = this.handlers[command] || + this.handlers[this.aliasMap[command]] || + this.defaultCommand; + const currentContext = yargs.getInternalMethods().getContext(); + const parentCommands = currentContext.commands.slice(); + const isDefaultCommand = !command; + if (command) { + currentContext.commands.push(command); + currentContext.fullCommands.push(commandHandler.original); + } + const builderResult = this.applyBuilderUpdateUsageAndParse(isDefaultCommand, commandHandler, yargs, parsed.aliases, parentCommands, commandIndex, helpOnly, helpOrVersionSet); + return isPromise(builderResult) + ? builderResult.then(result => this.applyMiddlewareAndGetResult(isDefaultCommand, commandHandler, result.innerArgv, currentContext, helpOnly, result.aliases, yargs)) + : this.applyMiddlewareAndGetResult(isDefaultCommand, commandHandler, builderResult.innerArgv, currentContext, helpOnly, builderResult.aliases, yargs); + } + applyBuilderUpdateUsageAndParse(isDefaultCommand, commandHandler, yargs, aliases, parentCommands, commandIndex, helpOnly, helpOrVersionSet) { + const builder = commandHandler.builder; + let innerYargs = yargs; + if (isCommandBuilderCallback(builder)) { + yargs.getInternalMethods().getUsageInstance().freeze(); + const builderOutput = builder(yargs.getInternalMethods().reset(aliases), helpOrVersionSet); + if (isPromise(builderOutput)) { + return builderOutput.then(output => { + innerYargs = isYargsInstance(output) ? output : yargs; + return this.parseAndUpdateUsage(isDefaultCommand, commandHandler, innerYargs, parentCommands, commandIndex, helpOnly); + }); + } + } + else if (isCommandBuilderOptionDefinitions(builder)) { + yargs.getInternalMethods().getUsageInstance().freeze(); + innerYargs = yargs.getInternalMethods().reset(aliases); + Object.keys(commandHandler.builder).forEach(key => { + innerYargs.option(key, builder[key]); + }); + } + return this.parseAndUpdateUsage(isDefaultCommand, commandHandler, innerYargs, parentCommands, commandIndex, helpOnly); + } + parseAndUpdateUsage(isDefaultCommand, commandHandler, innerYargs, parentCommands, commandIndex, helpOnly) { + if (isDefaultCommand) + innerYargs.getInternalMethods().getUsageInstance().unfreeze(true); + if (this.shouldUpdateUsage(innerYargs)) { + innerYargs + .getInternalMethods() + .getUsageInstance() + .usage(this.usageFromParentCommandsCommandHandler(parentCommands, commandHandler), commandHandler.description); + } + const innerArgv = innerYargs + .getInternalMethods() + .runYargsParserAndExecuteCommands(null, undefined, true, commandIndex, helpOnly); + return isPromise(innerArgv) + ? innerArgv.then(argv => ({ + aliases: innerYargs.parsed.aliases, + innerArgv: argv, + })) + : { + aliases: innerYargs.parsed.aliases, + innerArgv: innerArgv, + }; + } + shouldUpdateUsage(yargs) { + return (!yargs.getInternalMethods().getUsageInstance().getUsageDisabled() && + yargs.getInternalMethods().getUsageInstance().getUsage().length === 0); + } + usageFromParentCommandsCommandHandler(parentCommands, commandHandler) { + const c = DEFAULT_MARKER.test(commandHandler.original) + ? commandHandler.original.replace(DEFAULT_MARKER, '').trim() + : commandHandler.original; + const pc = parentCommands.filter(c => { + return !DEFAULT_MARKER.test(c); + }); + pc.push(c); + return `$0 ${pc.join(' ')}`; + } + handleValidationAndGetResult(isDefaultCommand, commandHandler, innerArgv, currentContext, aliases, yargs, middlewares, positionalMap) { + if (!yargs.getInternalMethods().getHasOutput()) { + const validation = yargs + .getInternalMethods() + .runValidation(aliases, positionalMap, yargs.parsed.error, isDefaultCommand); + innerArgv = maybeAsyncResult(innerArgv, result => { + validation(result); + return result; + }); + } + if (commandHandler.handler && !yargs.getInternalMethods().getHasOutput()) { + yargs.getInternalMethods().setHasOutput(); + const populateDoubleDash = !!yargs.getOptions().configuration['populate--']; + yargs + .getInternalMethods() + .postProcess(innerArgv, populateDoubleDash, false, false); + innerArgv = applyMiddleware(innerArgv, yargs, middlewares, false); + innerArgv = maybeAsyncResult(innerArgv, result => { + const handlerResult = commandHandler.handler(result); + return isPromise(handlerResult) + ? handlerResult.then(() => result) + : result; + }); + if (!isDefaultCommand) { + yargs.getInternalMethods().getUsageInstance().cacheHelpMessage(); + } + if (isPromise(innerArgv) && + !yargs.getInternalMethods().hasParseCallback()) { + innerArgv.catch(error => { + try { + yargs.getInternalMethods().getUsageInstance().fail(null, error); + } + catch (_err) { + } + }); + } + } + if (!isDefaultCommand) { + currentContext.commands.pop(); + currentContext.fullCommands.pop(); + } + return innerArgv; + } + applyMiddlewareAndGetResult(isDefaultCommand, commandHandler, innerArgv, currentContext, helpOnly, aliases, yargs) { + let positionalMap = {}; + if (helpOnly) + return innerArgv; + if (!yargs.getInternalMethods().getHasOutput()) { + positionalMap = this.populatePositionals(commandHandler, innerArgv, currentContext, yargs); + } + const middlewares = this.globalMiddleware + .getMiddleware() + .slice(0) + .concat(commandHandler.middlewares); + const maybePromiseArgv = applyMiddleware(innerArgv, yargs, middlewares, true); + return isPromise(maybePromiseArgv) + ? maybePromiseArgv.then(resolvedInnerArgv => this.handleValidationAndGetResult(isDefaultCommand, commandHandler, resolvedInnerArgv, currentContext, aliases, yargs, middlewares, positionalMap)) + : this.handleValidationAndGetResult(isDefaultCommand, commandHandler, maybePromiseArgv, currentContext, aliases, yargs, middlewares, positionalMap); + } + populatePositionals(commandHandler, argv, context, yargs) { + argv._ = argv._.slice(context.commands.length); + const demanded = commandHandler.demanded.slice(0); + const optional = commandHandler.optional.slice(0); + const positionalMap = {}; + this.validation.positionalCount(demanded.length, argv._.length); + while (demanded.length) { + const demand = demanded.shift(); + this.populatePositional(demand, argv, positionalMap); + } + while (optional.length) { + const maybe = optional.shift(); + this.populatePositional(maybe, argv, positionalMap); + } + argv._ = context.commands.concat(argv._.map(a => '' + a)); + this.postProcessPositionals(argv, positionalMap, this.cmdToParseOptions(commandHandler.original), yargs); + return positionalMap; + } + populatePositional(positional, argv, positionalMap) { + const cmd = positional.cmd[0]; + if (positional.variadic) { + positionalMap[cmd] = argv._.splice(0).map(String); + } + else { + if (argv._.length) + positionalMap[cmd] = [String(argv._.shift())]; + } + } + cmdToParseOptions(cmdString) { + const parseOptions = { + array: [], + default: {}, + alias: {}, + demand: {}, + }; + const parsed = parseCommand(cmdString); + parsed.demanded.forEach(d => { + const [cmd, ...aliases] = d.cmd; + if (d.variadic) { + parseOptions.array.push(cmd); + parseOptions.default[cmd] = []; + } + parseOptions.alias[cmd] = aliases; + parseOptions.demand[cmd] = true; + }); + parsed.optional.forEach(o => { + const [cmd, ...aliases] = o.cmd; + if (o.variadic) { + parseOptions.array.push(cmd); + parseOptions.default[cmd] = []; + } + parseOptions.alias[cmd] = aliases; + }); + return parseOptions; + } + postProcessPositionals(argv, positionalMap, parseOptions, yargs) { + const options = Object.assign({}, yargs.getOptions()); + options.default = Object.assign(parseOptions.default, options.default); + for (const key of Object.keys(parseOptions.alias)) { + options.alias[key] = (options.alias[key] || []).concat(parseOptions.alias[key]); + } + options.array = options.array.concat(parseOptions.array); + options.config = {}; + const unparsed = []; + Object.keys(positionalMap).forEach(key => { + positionalMap[key].map(value => { + if (options.configuration['unknown-options-as-args']) + options.key[key] = true; + unparsed.push(`--${key}`); + unparsed.push(value); + }); + }); + if (!unparsed.length) + return; + const config = Object.assign({}, options.configuration, { + 'populate--': false, + }); + const parsed = this.shim.Parser.detailed(unparsed, Object.assign({}, options, { + configuration: config, + })); + if (parsed.error) { + yargs + .getInternalMethods() + .getUsageInstance() + .fail(parsed.error.message, parsed.error); + } + else { + const positionalKeys = Object.keys(positionalMap); + Object.keys(positionalMap).forEach(key => { + positionalKeys.push(...parsed.aliases[key]); + }); + Object.keys(parsed.argv).forEach(key => { + if (positionalKeys.includes(key)) { + if (!positionalMap[key]) + positionalMap[key] = parsed.argv[key]; + if (!this.isInConfigs(yargs, key) && + !this.isDefaulted(yargs, key) && + Object.prototype.hasOwnProperty.call(argv, key) && + Object.prototype.hasOwnProperty.call(parsed.argv, key) && + (Array.isArray(argv[key]) || Array.isArray(parsed.argv[key]))) { + argv[key] = [].concat(argv[key], parsed.argv[key]); + } + else { + argv[key] = parsed.argv[key]; + } + } + }); + } + } + isDefaulted(yargs, key) { + const { default: defaults } = yargs.getOptions(); + return (Object.prototype.hasOwnProperty.call(defaults, key) || + Object.prototype.hasOwnProperty.call(defaults, this.shim.Parser.camelCase(key))); + } + isInConfigs(yargs, key) { + const { configObjects } = yargs.getOptions(); + return (configObjects.some(c => Object.prototype.hasOwnProperty.call(c, key)) || + configObjects.some(c => Object.prototype.hasOwnProperty.call(c, this.shim.Parser.camelCase(key)))); + } + runDefaultBuilderOn(yargs) { + if (!this.defaultCommand) + return; + if (this.shouldUpdateUsage(yargs)) { + const commandString = DEFAULT_MARKER.test(this.defaultCommand.original) + ? this.defaultCommand.original + : this.defaultCommand.original.replace(/^[^[\]<>]*/, '$0 '); + yargs + .getInternalMethods() + .getUsageInstance() + .usage(commandString, this.defaultCommand.description); + } + const builder = this.defaultCommand.builder; + if (isCommandBuilderCallback(builder)) { + return builder(yargs, true); + } + else if (!isCommandBuilderDefinition(builder)) { + Object.keys(builder).forEach(key => { + yargs.option(key, builder[key]); + }); + } + return undefined; + } + moduleName(obj) { + const mod = whichModule(obj); + if (!mod) + throw new Error(`No command name given for module: ${this.shim.inspect(obj)}`); + return this.commandFromFilename(mod.filename); + } + commandFromFilename(filename) { + return this.shim.path.basename(filename, this.shim.path.extname(filename)); + } + extractDesc({ describe, description, desc }) { + for (const test of [describe, description, desc]) { + if (typeof test === 'string' || test === false) + return test; + assertNotStrictEqual(test, true, this.shim); + } + return false; + } + freeze() { + this.frozens.push({ + handlers: this.handlers, + aliasMap: this.aliasMap, + defaultCommand: this.defaultCommand, + }); + } + unfreeze() { + const frozen = this.frozens.pop(); + assertNotStrictEqual(frozen, undefined, this.shim); + ({ + handlers: this.handlers, + aliasMap: this.aliasMap, + defaultCommand: this.defaultCommand, + } = frozen); + } + reset() { + this.handlers = {}; + this.aliasMap = {}; + this.defaultCommand = undefined; + this.requireCache = new Set(); + return this; + } +} +export function command(usage, validation, globalMiddleware, shim) { + return new CommandInstance(usage, validation, globalMiddleware, shim); +} +export function isCommandBuilderDefinition(builder) { + return (typeof builder === 'object' && + !!builder.builder && + typeof builder.handler === 'function'); +} +function isCommandAndAliases(cmd) { + return cmd.every(c => typeof c === 'string'); +} +export function isCommandBuilderCallback(builder) { + return typeof builder === 'function'; +} +function isCommandBuilderOptionDefinitions(builder) { + return typeof builder === 'object'; +} +export function isCommandHandlerDefinition(cmd) { + return typeof cmd === 'object' && !Array.isArray(cmd); +} diff --git a/node_modules/yargs/build/lib/completion-templates.js b/node_modules/yargs/build/lib/completion-templates.js new file mode 100644 index 0000000..2c4dcb5 --- /dev/null +++ b/node_modules/yargs/build/lib/completion-templates.js @@ -0,0 +1,48 @@ +export const completionShTemplate = `###-begin-{{app_name}}-completions-### +# +# yargs command completion script +# +# Installation: {{app_path}} {{completion_command}} >> ~/.bashrc +# or {{app_path}} {{completion_command}} >> ~/.bash_profile on OSX. +# +_{{app_name}}_yargs_completions() +{ + local cur_word args type_list + + cur_word="\${COMP_WORDS[COMP_CWORD]}" + args=("\${COMP_WORDS[@]}") + + # ask yargs to generate completions. + type_list=$({{app_path}} --get-yargs-completions "\${args[@]}") + + COMPREPLY=( $(compgen -W "\${type_list}" -- \${cur_word}) ) + + # if no match was found, fall back to filename completion + if [ \${#COMPREPLY[@]} -eq 0 ]; then + COMPREPLY=() + fi + + return 0 +} +complete -o bashdefault -o default -F _{{app_name}}_yargs_completions {{app_name}} +###-end-{{app_name}}-completions-### +`; +export const completionZshTemplate = `#compdef {{app_name}} +###-begin-{{app_name}}-completions-### +# +# yargs command completion script +# +# Installation: {{app_path}} {{completion_command}} >> ~/.zshrc +# or {{app_path}} {{completion_command}} >> ~/.zprofile on OSX. +# +_{{app_name}}_yargs_completions() +{ + local reply + local si=$IFS + IFS=$'\n' reply=($(COMP_CWORD="$((CURRENT-1))" COMP_LINE="$BUFFER" COMP_POINT="$CURSOR" {{app_path}} --get-yargs-completions "\${words[@]}")) + IFS=$si + _describe 'values' reply +} +compdef _{{app_name}}_yargs_completions {{app_name}} +###-end-{{app_name}}-completions-### +`; diff --git a/node_modules/yargs/build/lib/completion.js b/node_modules/yargs/build/lib/completion.js new file mode 100644 index 0000000..cef2bbe --- /dev/null +++ b/node_modules/yargs/build/lib/completion.js @@ -0,0 +1,243 @@ +import { isCommandBuilderCallback } from './command.js'; +import { assertNotStrictEqual } from './typings/common-types.js'; +import * as templates from './completion-templates.js'; +import { isPromise } from './utils/is-promise.js'; +import { parseCommand } from './parse-command.js'; +export class Completion { + constructor(yargs, usage, command, shim) { + var _a, _b, _c; + this.yargs = yargs; + this.usage = usage; + this.command = command; + this.shim = shim; + this.completionKey = 'get-yargs-completions'; + this.aliases = null; + this.customCompletionFunction = null; + this.indexAfterLastReset = 0; + this.zshShell = + (_c = (((_a = this.shim.getEnv('SHELL')) === null || _a === void 0 ? void 0 : _a.includes('zsh')) || + ((_b = this.shim.getEnv('ZSH_NAME')) === null || _b === void 0 ? void 0 : _b.includes('zsh')))) !== null && _c !== void 0 ? _c : false; + } + defaultCompletion(args, argv, current, done) { + const handlers = this.command.getCommandHandlers(); + for (let i = 0, ii = args.length; i < ii; ++i) { + if (handlers[args[i]] && handlers[args[i]].builder) { + const builder = handlers[args[i]].builder; + if (isCommandBuilderCallback(builder)) { + this.indexAfterLastReset = i + 1; + const y = this.yargs.getInternalMethods().reset(); + builder(y, true); + return y.argv; + } + } + } + const completions = []; + this.commandCompletions(completions, args, current); + this.optionCompletions(completions, args, argv, current); + this.choicesFromOptionsCompletions(completions, args, argv, current); + this.choicesFromPositionalsCompletions(completions, args, argv, current); + done(null, completions); + } + commandCompletions(completions, args, current) { + const parentCommands = this.yargs + .getInternalMethods() + .getContext().commands; + if (!current.match(/^-/) && + parentCommands[parentCommands.length - 1] !== current && + !this.previousArgHasChoices(args)) { + this.usage.getCommands().forEach(usageCommand => { + const commandName = parseCommand(usageCommand[0]).cmd; + if (args.indexOf(commandName) === -1) { + if (!this.zshShell) { + completions.push(commandName); + } + else { + const desc = usageCommand[1] || ''; + completions.push(commandName.replace(/:/g, '\\:') + ':' + desc); + } + } + }); + } + } + optionCompletions(completions, args, argv, current) { + if ((current.match(/^-/) || (current === '' && completions.length === 0)) && + !this.previousArgHasChoices(args)) { + const options = this.yargs.getOptions(); + const positionalKeys = this.yargs.getGroups()[this.usage.getPositionalGroupName()] || []; + Object.keys(options.key).forEach(key => { + const negable = !!options.configuration['boolean-negation'] && + options.boolean.includes(key); + const isPositionalKey = positionalKeys.includes(key); + if (!isPositionalKey && + !options.hiddenOptions.includes(key) && + !this.argsContainKey(args, key, negable)) { + this.completeOptionKey(key, completions, current, negable && !!options.default[key]); + } + }); + } + } + choicesFromOptionsCompletions(completions, args, argv, current) { + if (this.previousArgHasChoices(args)) { + const choices = this.getPreviousArgChoices(args); + if (choices && choices.length > 0) { + completions.push(...choices.map(c => c.replace(/:/g, '\\:'))); + } + } + } + choicesFromPositionalsCompletions(completions, args, argv, current) { + if (current === '' && + completions.length > 0 && + this.previousArgHasChoices(args)) { + return; + } + const positionalKeys = this.yargs.getGroups()[this.usage.getPositionalGroupName()] || []; + const offset = Math.max(this.indexAfterLastReset, this.yargs.getInternalMethods().getContext().commands.length + + 1); + const positionalKey = positionalKeys[argv._.length - offset - 1]; + if (!positionalKey) { + return; + } + const choices = this.yargs.getOptions().choices[positionalKey] || []; + for (const choice of choices) { + if (choice.startsWith(current)) { + completions.push(choice.replace(/:/g, '\\:')); + } + } + } + getPreviousArgChoices(args) { + if (args.length < 1) + return; + let previousArg = args[args.length - 1]; + let filter = ''; + if (!previousArg.startsWith('-') && args.length > 1) { + filter = previousArg; + previousArg = args[args.length - 2]; + } + if (!previousArg.startsWith('-')) + return; + const previousArgKey = previousArg.replace(/^-+/, ''); + const options = this.yargs.getOptions(); + const possibleAliases = [ + previousArgKey, + ...(this.yargs.getAliases()[previousArgKey] || []), + ]; + let choices; + for (const possibleAlias of possibleAliases) { + if (Object.prototype.hasOwnProperty.call(options.key, possibleAlias) && + Array.isArray(options.choices[possibleAlias])) { + choices = options.choices[possibleAlias]; + break; + } + } + if (choices) { + return choices.filter(choice => !filter || choice.startsWith(filter)); + } + } + previousArgHasChoices(args) { + const choices = this.getPreviousArgChoices(args); + return choices !== undefined && choices.length > 0; + } + argsContainKey(args, key, negable) { + const argsContains = (s) => args.indexOf((/^[^0-9]$/.test(s) ? '-' : '--') + s) !== -1; + if (argsContains(key)) + return true; + if (negable && argsContains(`no-${key}`)) + return true; + if (this.aliases) { + for (const alias of this.aliases[key]) { + if (argsContains(alias)) + return true; + } + } + return false; + } + completeOptionKey(key, completions, current, negable) { + var _a, _b, _c, _d; + let keyWithDesc = key; + if (this.zshShell) { + const descs = this.usage.getDescriptions(); + const aliasKey = (_b = (_a = this === null || this === void 0 ? void 0 : this.aliases) === null || _a === void 0 ? void 0 : _a[key]) === null || _b === void 0 ? void 0 : _b.find(alias => { + const desc = descs[alias]; + return typeof desc === 'string' && desc.length > 0; + }); + const descFromAlias = aliasKey ? descs[aliasKey] : undefined; + const desc = (_d = (_c = descs[key]) !== null && _c !== void 0 ? _c : descFromAlias) !== null && _d !== void 0 ? _d : ''; + keyWithDesc = `${key.replace(/:/g, '\\:')}:${desc + .replace('__yargsString__:', '') + .replace(/(\r\n|\n|\r)/gm, ' ')}`; + } + const startsByTwoDashes = (s) => /^--/.test(s); + const isShortOption = (s) => /^[^0-9]$/.test(s); + const dashes = !startsByTwoDashes(current) && isShortOption(key) ? '-' : '--'; + completions.push(dashes + keyWithDesc); + if (negable) { + completions.push(dashes + 'no-' + keyWithDesc); + } + } + customCompletion(args, argv, current, done) { + assertNotStrictEqual(this.customCompletionFunction, null, this.shim); + if (isSyncCompletionFunction(this.customCompletionFunction)) { + const result = this.customCompletionFunction(current, argv); + if (isPromise(result)) { + return result + .then(list => { + this.shim.process.nextTick(() => { + done(null, list); + }); + }) + .catch(err => { + this.shim.process.nextTick(() => { + done(err, undefined); + }); + }); + } + return done(null, result); + } + else if (isFallbackCompletionFunction(this.customCompletionFunction)) { + return this.customCompletionFunction(current, argv, (onCompleted = done) => this.defaultCompletion(args, argv, current, onCompleted), completions => { + done(null, completions); + }); + } + else { + return this.customCompletionFunction(current, argv, completions => { + done(null, completions); + }); + } + } + getCompletion(args, done) { + const current = args.length ? args[args.length - 1] : ''; + const argv = this.yargs.parse(args, true); + const completionFunction = this.customCompletionFunction + ? (argv) => this.customCompletion(args, argv, current, done) + : (argv) => this.defaultCompletion(args, argv, current, done); + return isPromise(argv) + ? argv.then(completionFunction) + : completionFunction(argv); + } + generateCompletionScript($0, cmd) { + let script = this.zshShell + ? templates.completionZshTemplate + : templates.completionShTemplate; + const name = this.shim.path.basename($0); + if ($0.match(/\.js$/)) + $0 = `./${$0}`; + script = script.replace(/{{app_name}}/g, name); + script = script.replace(/{{completion_command}}/g, cmd); + return script.replace(/{{app_path}}/g, $0); + } + registerFunction(fn) { + this.customCompletionFunction = fn; + } + setParsed(parsed) { + this.aliases = parsed.aliases; + } +} +export function completion(yargs, usage, command, shim) { + return new Completion(yargs, usage, command, shim); +} +function isSyncCompletionFunction(completionFunction) { + return completionFunction.length < 3; +} +function isFallbackCompletionFunction(completionFunction) { + return completionFunction.length > 3; +} diff --git a/node_modules/yargs/build/lib/middleware.js b/node_modules/yargs/build/lib/middleware.js new file mode 100644 index 0000000..4e561a7 --- /dev/null +++ b/node_modules/yargs/build/lib/middleware.js @@ -0,0 +1,88 @@ +import { argsert } from './argsert.js'; +import { isPromise } from './utils/is-promise.js'; +export class GlobalMiddleware { + constructor(yargs) { + this.globalMiddleware = []; + this.frozens = []; + this.yargs = yargs; + } + addMiddleware(callback, applyBeforeValidation, global = true, mutates = false) { + argsert(' [boolean] [boolean] [boolean]', [callback, applyBeforeValidation, global], arguments.length); + if (Array.isArray(callback)) { + for (let i = 0; i < callback.length; i++) { + if (typeof callback[i] !== 'function') { + throw Error('middleware must be a function'); + } + const m = callback[i]; + m.applyBeforeValidation = applyBeforeValidation; + m.global = global; + } + Array.prototype.push.apply(this.globalMiddleware, callback); + } + else if (typeof callback === 'function') { + const m = callback; + m.applyBeforeValidation = applyBeforeValidation; + m.global = global; + m.mutates = mutates; + this.globalMiddleware.push(callback); + } + return this.yargs; + } + addCoerceMiddleware(callback, option) { + const aliases = this.yargs.getAliases(); + this.globalMiddleware = this.globalMiddleware.filter(m => { + const toCheck = [...(aliases[option] || []), option]; + if (!m.option) + return true; + else + return !toCheck.includes(m.option); + }); + callback.option = option; + return this.addMiddleware(callback, true, true, true); + } + getMiddleware() { + return this.globalMiddleware; + } + freeze() { + this.frozens.push([...this.globalMiddleware]); + } + unfreeze() { + const frozen = this.frozens.pop(); + if (frozen !== undefined) + this.globalMiddleware = frozen; + } + reset() { + this.globalMiddleware = this.globalMiddleware.filter(m => m.global); + } +} +export function commandMiddlewareFactory(commandMiddleware) { + if (!commandMiddleware) + return []; + return commandMiddleware.map(middleware => { + middleware.applyBeforeValidation = false; + return middleware; + }); +} +export function applyMiddleware(argv, yargs, middlewares, beforeValidation) { + return middlewares.reduce((acc, middleware) => { + if (middleware.applyBeforeValidation !== beforeValidation) { + return acc; + } + if (middleware.mutates) { + if (middleware.applied) + return acc; + middleware.applied = true; + } + if (isPromise(acc)) { + return acc + .then(initialObj => Promise.all([initialObj, middleware(initialObj, yargs)])) + .then(([initialObj, middlewareObj]) => Object.assign(initialObj, middlewareObj)); + } + else { + const result = middleware(acc, yargs); + return isPromise(result) + ? result.then(middlewareObj => Object.assign(acc, middlewareObj)) + : Object.assign(acc, result); + } + }, argv); +} diff --git a/node_modules/yargs/build/lib/parse-command.js b/node_modules/yargs/build/lib/parse-command.js new file mode 100644 index 0000000..4989f53 --- /dev/null +++ b/node_modules/yargs/build/lib/parse-command.js @@ -0,0 +1,32 @@ +export function parseCommand(cmd) { + const extraSpacesStrippedCommand = cmd.replace(/\s{2,}/g, ' '); + const splitCommand = extraSpacesStrippedCommand.split(/\s+(?![^[]*]|[^<]*>)/); + const bregex = /\.*[\][<>]/g; + const firstCommand = splitCommand.shift(); + if (!firstCommand) + throw new Error(`No command found in: ${cmd}`); + const parsedCommand = { + cmd: firstCommand.replace(bregex, ''), + demanded: [], + optional: [], + }; + splitCommand.forEach((cmd, i) => { + let variadic = false; + cmd = cmd.replace(/\s/g, ''); + if (/\.+[\]>]/.test(cmd) && i === splitCommand.length - 1) + variadic = true; + if (/^\[/.test(cmd)) { + parsedCommand.optional.push({ + cmd: cmd.replace(bregex, '').split('|'), + variadic, + }); + } + else { + parsedCommand.demanded.push({ + cmd: cmd.replace(bregex, '').split('|'), + variadic, + }); + } + }); + return parsedCommand; +} diff --git a/node_modules/yargs/build/lib/typings/common-types.js b/node_modules/yargs/build/lib/typings/common-types.js new file mode 100644 index 0000000..73e1773 --- /dev/null +++ b/node_modules/yargs/build/lib/typings/common-types.js @@ -0,0 +1,9 @@ +export function assertNotStrictEqual(actual, expected, shim, message) { + shim.assert.notStrictEqual(actual, expected, message); +} +export function assertSingleKey(actual, shim) { + shim.assert.strictEqual(typeof actual, 'string'); +} +export function objectKeys(object) { + return Object.keys(object); +} diff --git a/node_modules/yargs/build/lib/typings/yargs-parser-types.js b/node_modules/yargs/build/lib/typings/yargs-parser-types.js new file mode 100644 index 0000000..cb0ff5c --- /dev/null +++ b/node_modules/yargs/build/lib/typings/yargs-parser-types.js @@ -0,0 +1 @@ +export {}; diff --git a/node_modules/yargs/build/lib/usage.js b/node_modules/yargs/build/lib/usage.js new file mode 100644 index 0000000..0127c13 --- /dev/null +++ b/node_modules/yargs/build/lib/usage.js @@ -0,0 +1,584 @@ +import { objFilter } from './utils/obj-filter.js'; +import { YError } from './yerror.js'; +import setBlocking from './utils/set-blocking.js'; +function isBoolean(fail) { + return typeof fail === 'boolean'; +} +export function usage(yargs, shim) { + const __ = shim.y18n.__; + const self = {}; + const fails = []; + self.failFn = function failFn(f) { + fails.push(f); + }; + let failMessage = null; + let globalFailMessage = null; + let showHelpOnFail = true; + self.showHelpOnFail = function showHelpOnFailFn(arg1 = true, arg2) { + const [enabled, message] = typeof arg1 === 'string' ? [true, arg1] : [arg1, arg2]; + if (yargs.getInternalMethods().isGlobalContext()) { + globalFailMessage = message; + } + failMessage = message; + showHelpOnFail = enabled; + return self; + }; + let failureOutput = false; + self.fail = function fail(msg, err) { + const logger = yargs.getInternalMethods().getLoggerInstance(); + if (fails.length) { + for (let i = fails.length - 1; i >= 0; --i) { + const fail = fails[i]; + if (isBoolean(fail)) { + if (err) + throw err; + else if (msg) + throw Error(msg); + } + else { + fail(msg, err, self); + } + } + } + else { + if (yargs.getExitProcess()) + setBlocking(true); + if (!failureOutput) { + failureOutput = true; + if (showHelpOnFail) { + yargs.showHelp('error'); + logger.error(); + } + if (msg || err) + logger.error(msg || err); + const globalOrCommandFailMessage = failMessage || globalFailMessage; + if (globalOrCommandFailMessage) { + if (msg || err) + logger.error(''); + logger.error(globalOrCommandFailMessage); + } + } + err = err || new YError(msg); + if (yargs.getExitProcess()) { + return yargs.exit(1); + } + else if (yargs.getInternalMethods().hasParseCallback()) { + return yargs.exit(1, err); + } + else { + throw err; + } + } + }; + let usages = []; + let usageDisabled = false; + self.usage = (msg, description) => { + if (msg === null) { + usageDisabled = true; + usages = []; + return self; + } + usageDisabled = false; + usages.push([msg, description || '']); + return self; + }; + self.getUsage = () => { + return usages; + }; + self.getUsageDisabled = () => { + return usageDisabled; + }; + self.getPositionalGroupName = () => { + return __('Positionals:'); + }; + let examples = []; + self.example = (cmd, description) => { + examples.push([cmd, description || '']); + }; + let commands = []; + self.command = function command(cmd, description, isDefault, aliases, deprecated = false) { + if (isDefault) { + commands = commands.map(cmdArray => { + cmdArray[2] = false; + return cmdArray; + }); + } + commands.push([cmd, description || '', isDefault, aliases, deprecated]); + }; + self.getCommands = () => commands; + let descriptions = {}; + self.describe = function describe(keyOrKeys, desc) { + if (Array.isArray(keyOrKeys)) { + keyOrKeys.forEach(k => { + self.describe(k, desc); + }); + } + else if (typeof keyOrKeys === 'object') { + Object.keys(keyOrKeys).forEach(k => { + self.describe(k, keyOrKeys[k]); + }); + } + else { + descriptions[keyOrKeys] = desc; + } + }; + self.getDescriptions = () => descriptions; + let epilogs = []; + self.epilog = msg => { + epilogs.push(msg); + }; + let wrapSet = false; + let wrap; + self.wrap = cols => { + wrapSet = true; + wrap = cols; + }; + self.getWrap = () => { + if (shim.getEnv('YARGS_DISABLE_WRAP')) { + return null; + } + if (!wrapSet) { + wrap = windowWidth(); + wrapSet = true; + } + return wrap; + }; + const deferY18nLookupPrefix = '__yargsString__:'; + self.deferY18nLookup = str => deferY18nLookupPrefix + str; + self.help = function help() { + if (cachedHelpMessage) + return cachedHelpMessage; + normalizeAliases(); + const base$0 = yargs.customScriptName + ? yargs.$0 + : shim.path.basename(yargs.$0); + const demandedOptions = yargs.getDemandedOptions(); + const demandedCommands = yargs.getDemandedCommands(); + const deprecatedOptions = yargs.getDeprecatedOptions(); + const groups = yargs.getGroups(); + const options = yargs.getOptions(); + let keys = []; + keys = keys.concat(Object.keys(descriptions)); + keys = keys.concat(Object.keys(demandedOptions)); + keys = keys.concat(Object.keys(demandedCommands)); + keys = keys.concat(Object.keys(options.default)); + keys = keys.filter(filterHiddenOptions); + keys = Object.keys(keys.reduce((acc, key) => { + if (key !== '_') + acc[key] = true; + return acc; + }, {})); + const theWrap = self.getWrap(); + const ui = shim.cliui({ + width: theWrap, + wrap: !!theWrap, + }); + if (!usageDisabled) { + if (usages.length) { + usages.forEach(usage => { + ui.div({ text: `${usage[0].replace(/\$0/g, base$0)}` }); + if (usage[1]) { + ui.div({ text: `${usage[1]}`, padding: [1, 0, 0, 0] }); + } + }); + ui.div(); + } + else if (commands.length) { + let u = null; + if (demandedCommands._) { + u = `${base$0} <${__('command')}>\n`; + } + else { + u = `${base$0} [${__('command')}]\n`; + } + ui.div(`${u}`); + } + } + if (commands.length > 1 || (commands.length === 1 && !commands[0][2])) { + ui.div(__('Commands:')); + const context = yargs.getInternalMethods().getContext(); + const parentCommands = context.commands.length + ? `${context.commands.join(' ')} ` + : ''; + if (yargs.getInternalMethods().getParserConfiguration()['sort-commands'] === + true) { + commands = commands.sort((a, b) => a[0].localeCompare(b[0])); + } + const prefix = base$0 ? `${base$0} ` : ''; + commands.forEach(command => { + const commandString = `${prefix}${parentCommands}${command[0].replace(/^\$0 ?/, '')}`; + ui.span({ + text: commandString, + padding: [0, 2, 0, 2], + width: maxWidth(commands, theWrap, `${base$0}${parentCommands}`) + 4, + }, { text: command[1] }); + const hints = []; + if (command[2]) + hints.push(`[${__('default')}]`); + if (command[3] && command[3].length) { + hints.push(`[${__('aliases:')} ${command[3].join(', ')}]`); + } + if (command[4]) { + if (typeof command[4] === 'string') { + hints.push(`[${__('deprecated: %s', command[4])}]`); + } + else { + hints.push(`[${__('deprecated')}]`); + } + } + if (hints.length) { + ui.div({ + text: hints.join(' '), + padding: [0, 0, 0, 2], + align: 'right', + }); + } + else { + ui.div(); + } + }); + ui.div(); + } + const aliasKeys = (Object.keys(options.alias) || []).concat(Object.keys(yargs.parsed.newAliases) || []); + keys = keys.filter(key => !yargs.parsed.newAliases[key] && + aliasKeys.every(alias => (options.alias[alias] || []).indexOf(key) === -1)); + const defaultGroup = __('Options:'); + if (!groups[defaultGroup]) + groups[defaultGroup] = []; + addUngroupedKeys(keys, options.alias, groups, defaultGroup); + const isLongSwitch = (sw) => /^--/.test(getText(sw)); + const displayedGroups = Object.keys(groups) + .filter(groupName => groups[groupName].length > 0) + .map(groupName => { + const normalizedKeys = groups[groupName] + .filter(filterHiddenOptions) + .map(key => { + if (aliasKeys.includes(key)) + return key; + for (let i = 0, aliasKey; (aliasKey = aliasKeys[i]) !== undefined; i++) { + if ((options.alias[aliasKey] || []).includes(key)) + return aliasKey; + } + return key; + }); + return { groupName, normalizedKeys }; + }) + .filter(({ normalizedKeys }) => normalizedKeys.length > 0) + .map(({ groupName, normalizedKeys }) => { + const switches = normalizedKeys.reduce((acc, key) => { + acc[key] = [key] + .concat(options.alias[key] || []) + .map(sw => { + if (groupName === self.getPositionalGroupName()) + return sw; + else { + return ((/^[0-9]$/.test(sw) + ? options.boolean.includes(key) + ? '-' + : '--' + : sw.length > 1 + ? '--' + : '-') + sw); + } + }) + .sort((sw1, sw2) => isLongSwitch(sw1) === isLongSwitch(sw2) + ? 0 + : isLongSwitch(sw1) + ? 1 + : -1) + .join(', '); + return acc; + }, {}); + return { groupName, normalizedKeys, switches }; + }); + const shortSwitchesUsed = displayedGroups + .filter(({ groupName }) => groupName !== self.getPositionalGroupName()) + .some(({ normalizedKeys, switches }) => !normalizedKeys.every(key => isLongSwitch(switches[key]))); + if (shortSwitchesUsed) { + displayedGroups + .filter(({ groupName }) => groupName !== self.getPositionalGroupName()) + .forEach(({ normalizedKeys, switches }) => { + normalizedKeys.forEach(key => { + if (isLongSwitch(switches[key])) { + switches[key] = addIndentation(switches[key], '-x, '.length); + } + }); + }); + } + displayedGroups.forEach(({ groupName, normalizedKeys, switches }) => { + ui.div(groupName); + normalizedKeys.forEach(key => { + const kswitch = switches[key]; + let desc = descriptions[key] || ''; + let type = null; + if (desc.includes(deferY18nLookupPrefix)) + desc = __(desc.substring(deferY18nLookupPrefix.length)); + if (options.boolean.includes(key)) + type = `[${__('boolean')}]`; + if (options.count.includes(key)) + type = `[${__('count')}]`; + if (options.string.includes(key)) + type = `[${__('string')}]`; + if (options.normalize.includes(key)) + type = `[${__('string')}]`; + if (options.array.includes(key)) + type = `[${__('array')}]`; + if (options.number.includes(key)) + type = `[${__('number')}]`; + const deprecatedExtra = (deprecated) => typeof deprecated === 'string' + ? `[${__('deprecated: %s', deprecated)}]` + : `[${__('deprecated')}]`; + const extra = [ + key in deprecatedOptions + ? deprecatedExtra(deprecatedOptions[key]) + : null, + type, + key in demandedOptions ? `[${__('required')}]` : null, + options.choices && options.choices[key] + ? `[${__('choices:')} ${self.stringifiedValues(options.choices[key])}]` + : null, + defaultString(options.default[key], options.defaultDescription[key]), + ] + .filter(Boolean) + .join(' '); + ui.span({ + text: getText(kswitch), + padding: [0, 2, 0, 2 + getIndentation(kswitch)], + width: maxWidth(switches, theWrap) + 4, + }, desc); + const shouldHideOptionExtras = yargs.getInternalMethods().getUsageConfiguration()['hide-types'] === + true; + if (extra && !shouldHideOptionExtras) + ui.div({ text: extra, padding: [0, 0, 0, 2], align: 'right' }); + else + ui.div(); + }); + ui.div(); + }); + if (examples.length) { + ui.div(__('Examples:')); + examples.forEach(example => { + example[0] = example[0].replace(/\$0/g, base$0); + }); + examples.forEach(example => { + if (example[1] === '') { + ui.div({ + text: example[0], + padding: [0, 2, 0, 2], + }); + } + else { + ui.div({ + text: example[0], + padding: [0, 2, 0, 2], + width: maxWidth(examples, theWrap) + 4, + }, { + text: example[1], + }); + } + }); + ui.div(); + } + if (epilogs.length > 0) { + const e = epilogs + .map(epilog => epilog.replace(/\$0/g, base$0)) + .join('\n'); + ui.div(`${e}\n`); + } + return ui.toString().replace(/\s*$/, ''); + }; + function maxWidth(table, theWrap, modifier) { + let width = 0; + if (!Array.isArray(table)) { + table = Object.values(table).map(v => [v]); + } + table.forEach(v => { + width = Math.max(shim.stringWidth(modifier ? `${modifier} ${getText(v[0])}` : getText(v[0])) + getIndentation(v[0]), width); + }); + if (theWrap) + width = Math.min(width, parseInt((theWrap * 0.5).toString(), 10)); + return width; + } + function normalizeAliases() { + const demandedOptions = yargs.getDemandedOptions(); + const options = yargs.getOptions(); + (Object.keys(options.alias) || []).forEach(key => { + options.alias[key].forEach(alias => { + if (descriptions[alias]) + self.describe(key, descriptions[alias]); + if (alias in demandedOptions) + yargs.demandOption(key, demandedOptions[alias]); + if (options.boolean.includes(alias)) + yargs.boolean(key); + if (options.count.includes(alias)) + yargs.count(key); + if (options.string.includes(alias)) + yargs.string(key); + if (options.normalize.includes(alias)) + yargs.normalize(key); + if (options.array.includes(alias)) + yargs.array(key); + if (options.number.includes(alias)) + yargs.number(key); + }); + }); + } + let cachedHelpMessage; + self.cacheHelpMessage = function () { + cachedHelpMessage = this.help(); + }; + self.clearCachedHelpMessage = function () { + cachedHelpMessage = undefined; + }; + self.hasCachedHelpMessage = function () { + return !!cachedHelpMessage; + }; + function addUngroupedKeys(keys, aliases, groups, defaultGroup) { + let groupedKeys = []; + let toCheck = null; + Object.keys(groups).forEach(group => { + groupedKeys = groupedKeys.concat(groups[group]); + }); + keys.forEach(key => { + toCheck = [key].concat(aliases[key]); + if (!toCheck.some(k => groupedKeys.indexOf(k) !== -1)) { + groups[defaultGroup].push(key); + } + }); + return groupedKeys; + } + function filterHiddenOptions(key) { + return (yargs.getOptions().hiddenOptions.indexOf(key) < 0 || + yargs.parsed.argv[yargs.getOptions().showHiddenOpt]); + } + self.showHelp = (level) => { + const logger = yargs.getInternalMethods().getLoggerInstance(); + if (!level) + level = 'error'; + const emit = typeof level === 'function' ? level : logger[level]; + emit(self.help()); + }; + self.functionDescription = fn => { + const description = fn.name + ? shim.Parser.decamelize(fn.name, '-') + : __('generated-value'); + return ['(', description, ')'].join(''); + }; + self.stringifiedValues = function stringifiedValues(values, separator) { + let string = ''; + const sep = separator || ', '; + const array = [].concat(values); + if (!values || !array.length) + return string; + array.forEach(value => { + if (string.length) + string += sep; + string += JSON.stringify(value); + }); + return string; + }; + function defaultString(value, defaultDescription) { + let string = `[${__('default:')} `; + if (value === undefined && !defaultDescription) + return null; + if (defaultDescription) { + string += defaultDescription; + } + else { + switch (typeof value) { + case 'string': + string += `"${value}"`; + break; + case 'object': + string += JSON.stringify(value); + break; + default: + string += value; + } + } + return `${string}]`; + } + function windowWidth() { + const maxWidth = 80; + if (shim.process.stdColumns) { + return Math.min(maxWidth, shim.process.stdColumns); + } + else { + return maxWidth; + } + } + let version = null; + self.version = ver => { + version = ver; + }; + self.showVersion = level => { + const logger = yargs.getInternalMethods().getLoggerInstance(); + if (!level) + level = 'error'; + const emit = typeof level === 'function' ? level : logger[level]; + emit(version); + }; + self.reset = function reset(localLookup) { + failMessage = null; + failureOutput = false; + usages = []; + usageDisabled = false; + epilogs = []; + examples = []; + commands = []; + descriptions = objFilter(descriptions, k => !localLookup[k]); + return self; + }; + const frozens = []; + self.freeze = function freeze() { + frozens.push({ + failMessage, + failureOutput, + usages, + usageDisabled, + epilogs, + examples, + commands, + descriptions, + }); + }; + self.unfreeze = function unfreeze(defaultCommand = false) { + const frozen = frozens.pop(); + if (!frozen) + return; + if (defaultCommand) { + descriptions = { ...frozen.descriptions, ...descriptions }; + commands = [...frozen.commands, ...commands]; + usages = [...frozen.usages, ...usages]; + examples = [...frozen.examples, ...examples]; + epilogs = [...frozen.epilogs, ...epilogs]; + } + else { + ({ + failMessage, + failureOutput, + usages, + usageDisabled, + epilogs, + examples, + commands, + descriptions, + } = frozen); + } + }; + return self; +} +function isIndentedText(text) { + return typeof text === 'object'; +} +function addIndentation(text, indent) { + return isIndentedText(text) + ? { text: text.text, indentation: text.indentation + indent } + : { text, indentation: indent }; +} +function getIndentation(text) { + return isIndentedText(text) ? text.indentation : 0; +} +function getText(text) { + return isIndentedText(text) ? text.text : text; +} diff --git a/node_modules/yargs/build/lib/utils/apply-extends.js b/node_modules/yargs/build/lib/utils/apply-extends.js new file mode 100644 index 0000000..0e593b4 --- /dev/null +++ b/node_modules/yargs/build/lib/utils/apply-extends.js @@ -0,0 +1,59 @@ +import { YError } from '../yerror.js'; +let previouslyVisitedConfigs = []; +let shim; +export function applyExtends(config, cwd, mergeExtends, _shim) { + shim = _shim; + let defaultConfig = {}; + if (Object.prototype.hasOwnProperty.call(config, 'extends')) { + if (typeof config.extends !== 'string') + return defaultConfig; + const isPath = /\.json|\..*rc$/.test(config.extends); + let pathToDefault = null; + if (!isPath) { + try { + pathToDefault = require.resolve(config.extends); + } + catch (_err) { + return config; + } + } + else { + pathToDefault = getPathToDefaultConfig(cwd, config.extends); + } + checkForCircularExtends(pathToDefault); + previouslyVisitedConfigs.push(pathToDefault); + defaultConfig = isPath + ? JSON.parse(shim.readFileSync(pathToDefault, 'utf8')) + : require(config.extends); + delete config.extends; + defaultConfig = applyExtends(defaultConfig, shim.path.dirname(pathToDefault), mergeExtends, shim); + } + previouslyVisitedConfigs = []; + return mergeExtends + ? mergeDeep(defaultConfig, config) + : Object.assign({}, defaultConfig, config); +} +function checkForCircularExtends(cfgPath) { + if (previouslyVisitedConfigs.indexOf(cfgPath) > -1) { + throw new YError(`Circular extended configurations: '${cfgPath}'.`); + } +} +function getPathToDefaultConfig(cwd, pathToExtend) { + return shim.path.resolve(cwd, pathToExtend); +} +function mergeDeep(config1, config2) { + const target = {}; + function isObject(obj) { + return obj && typeof obj === 'object' && !Array.isArray(obj); + } + Object.assign(target, config1); + for (const key of Object.keys(config2)) { + if (isObject(config2[key]) && isObject(target[key])) { + target[key] = mergeDeep(config1[key], config2[key]); + } + else { + target[key] = config2[key]; + } + } + return target; +} diff --git a/node_modules/yargs/build/lib/utils/is-promise.js b/node_modules/yargs/build/lib/utils/is-promise.js new file mode 100644 index 0000000..d250c08 --- /dev/null +++ b/node_modules/yargs/build/lib/utils/is-promise.js @@ -0,0 +1,5 @@ +export function isPromise(maybePromise) { + return (!!maybePromise && + !!maybePromise.then && + typeof maybePromise.then === 'function'); +} diff --git a/node_modules/yargs/build/lib/utils/levenshtein.js b/node_modules/yargs/build/lib/utils/levenshtein.js new file mode 100644 index 0000000..60575ef --- /dev/null +++ b/node_modules/yargs/build/lib/utils/levenshtein.js @@ -0,0 +1,34 @@ +export function levenshtein(a, b) { + if (a.length === 0) + return b.length; + if (b.length === 0) + return a.length; + const matrix = []; + let i; + for (i = 0; i <= b.length; i++) { + matrix[i] = [i]; + } + let j; + for (j = 0; j <= a.length; j++) { + matrix[0][j] = j; + } + for (i = 1; i <= b.length; i++) { + for (j = 1; j <= a.length; j++) { + if (b.charAt(i - 1) === a.charAt(j - 1)) { + matrix[i][j] = matrix[i - 1][j - 1]; + } + else { + if (i > 1 && + j > 1 && + b.charAt(i - 2) === a.charAt(j - 1) && + b.charAt(i - 1) === a.charAt(j - 2)) { + matrix[i][j] = matrix[i - 2][j - 2] + 1; + } + else { + matrix[i][j] = Math.min(matrix[i - 1][j - 1] + 1, Math.min(matrix[i][j - 1] + 1, matrix[i - 1][j] + 1)); + } + } + } + } + return matrix[b.length][a.length]; +} diff --git a/node_modules/yargs/build/lib/utils/maybe-async-result.js b/node_modules/yargs/build/lib/utils/maybe-async-result.js new file mode 100644 index 0000000..8c6a40c --- /dev/null +++ b/node_modules/yargs/build/lib/utils/maybe-async-result.js @@ -0,0 +1,17 @@ +import { isPromise } from './is-promise.js'; +export function maybeAsyncResult(getResult, resultHandler, errorHandler = (err) => { + throw err; +}) { + try { + const result = isFunction(getResult) ? getResult() : getResult; + return isPromise(result) + ? result.then((result) => resultHandler(result)) + : resultHandler(result); + } + catch (err) { + return errorHandler(err); + } +} +function isFunction(arg) { + return typeof arg === 'function'; +} diff --git a/node_modules/yargs/build/lib/utils/obj-filter.js b/node_modules/yargs/build/lib/utils/obj-filter.js new file mode 100644 index 0000000..cd68ad2 --- /dev/null +++ b/node_modules/yargs/build/lib/utils/obj-filter.js @@ -0,0 +1,10 @@ +import { objectKeys } from '../typings/common-types.js'; +export function objFilter(original = {}, filter = () => true) { + const obj = {}; + objectKeys(original).forEach(key => { + if (filter(key, original[key])) { + obj[key] = original[key]; + } + }); + return obj; +} diff --git a/node_modules/yargs/build/lib/utils/process-argv.js b/node_modules/yargs/build/lib/utils/process-argv.js new file mode 100644 index 0000000..74dc9e4 --- /dev/null +++ b/node_modules/yargs/build/lib/utils/process-argv.js @@ -0,0 +1,17 @@ +function getProcessArgvBinIndex() { + if (isBundledElectronApp()) + return 0; + return 1; +} +function isBundledElectronApp() { + return isElectronApp() && !process.defaultApp; +} +function isElectronApp() { + return !!process.versions.electron; +} +export function hideBin(argv) { + return argv.slice(getProcessArgvBinIndex() + 1); +} +export function getProcessArgvBin() { + return process.argv[getProcessArgvBinIndex()]; +} diff --git a/node_modules/yargs/build/lib/utils/set-blocking.js b/node_modules/yargs/build/lib/utils/set-blocking.js new file mode 100644 index 0000000..88fb806 --- /dev/null +++ b/node_modules/yargs/build/lib/utils/set-blocking.js @@ -0,0 +1,12 @@ +export default function setBlocking(blocking) { + if (typeof process === 'undefined') + return; + [process.stdout, process.stderr].forEach(_stream => { + const stream = _stream; + if (stream._handle && + stream.isTTY && + typeof stream._handle.setBlocking === 'function') { + stream._handle.setBlocking(blocking); + } + }); +} diff --git a/node_modules/yargs/build/lib/utils/which-module.js b/node_modules/yargs/build/lib/utils/which-module.js new file mode 100644 index 0000000..5974e22 --- /dev/null +++ b/node_modules/yargs/build/lib/utils/which-module.js @@ -0,0 +1,10 @@ +export default function whichModule(exported) { + if (typeof require === 'undefined') + return null; + for (let i = 0, files = Object.keys(require.cache), mod; i < files.length; i++) { + mod = require.cache[files[i]]; + if (mod.exports === exported) + return mod; + } + return null; +} diff --git a/node_modules/yargs/build/lib/validation.js b/node_modules/yargs/build/lib/validation.js new file mode 100644 index 0000000..bd2e1b8 --- /dev/null +++ b/node_modules/yargs/build/lib/validation.js @@ -0,0 +1,305 @@ +import { argsert } from './argsert.js'; +import { assertNotStrictEqual, } from './typings/common-types.js'; +import { levenshtein as distance } from './utils/levenshtein.js'; +import { objFilter } from './utils/obj-filter.js'; +const specialKeys = ['$0', '--', '_']; +export function validation(yargs, usage, shim) { + const __ = shim.y18n.__; + const __n = shim.y18n.__n; + const self = {}; + self.nonOptionCount = function nonOptionCount(argv) { + const demandedCommands = yargs.getDemandedCommands(); + const positionalCount = argv._.length + (argv['--'] ? argv['--'].length : 0); + const _s = positionalCount - yargs.getInternalMethods().getContext().commands.length; + if (demandedCommands._ && + (_s < demandedCommands._.min || _s > demandedCommands._.max)) { + if (_s < demandedCommands._.min) { + if (demandedCommands._.minMsg !== undefined) { + usage.fail(demandedCommands._.minMsg + ? demandedCommands._.minMsg + .replace(/\$0/g, _s.toString()) + .replace(/\$1/, demandedCommands._.min.toString()) + : null); + } + else { + usage.fail(__n('Not enough non-option arguments: got %s, need at least %s', 'Not enough non-option arguments: got %s, need at least %s', _s, _s.toString(), demandedCommands._.min.toString())); + } + } + else if (_s > demandedCommands._.max) { + if (demandedCommands._.maxMsg !== undefined) { + usage.fail(demandedCommands._.maxMsg + ? demandedCommands._.maxMsg + .replace(/\$0/g, _s.toString()) + .replace(/\$1/, demandedCommands._.max.toString()) + : null); + } + else { + usage.fail(__n('Too many non-option arguments: got %s, maximum of %s', 'Too many non-option arguments: got %s, maximum of %s', _s, _s.toString(), demandedCommands._.max.toString())); + } + } + } + }; + self.positionalCount = function positionalCount(required, observed) { + if (observed < required) { + usage.fail(__n('Not enough non-option arguments: got %s, need at least %s', 'Not enough non-option arguments: got %s, need at least %s', observed, observed + '', required + '')); + } + }; + self.requiredArguments = function requiredArguments(argv, demandedOptions) { + let missing = null; + for (const key of Object.keys(demandedOptions)) { + if (!Object.prototype.hasOwnProperty.call(argv, key) || + typeof argv[key] === 'undefined') { + missing = missing || {}; + missing[key] = demandedOptions[key]; + } + } + if (missing) { + const customMsgs = []; + for (const key of Object.keys(missing)) { + const msg = missing[key]; + if (msg && customMsgs.indexOf(msg) < 0) { + customMsgs.push(msg); + } + } + const customMsg = customMsgs.length ? `\n${customMsgs.join('\n')}` : ''; + usage.fail(__n('Missing required argument: %s', 'Missing required arguments: %s', Object.keys(missing).length, Object.keys(missing).join(', ') + customMsg)); + } + }; + self.unknownArguments = function unknownArguments(argv, aliases, positionalMap, isDefaultCommand, checkPositionals = true) { + var _a; + const commandKeys = yargs + .getInternalMethods() + .getCommandInstance() + .getCommands(); + const unknown = []; + const currentContext = yargs.getInternalMethods().getContext(); + Object.keys(argv).forEach(key => { + if (!specialKeys.includes(key) && + !Object.prototype.hasOwnProperty.call(positionalMap, key) && + !Object.prototype.hasOwnProperty.call(yargs.getInternalMethods().getParseContext(), key) && + !self.isValidAndSomeAliasIsNotNew(key, aliases)) { + unknown.push(key); + } + }); + if (checkPositionals && + (currentContext.commands.length > 0 || + commandKeys.length > 0 || + isDefaultCommand)) { + argv._.slice(currentContext.commands.length).forEach(key => { + if (!commandKeys.includes('' + key)) { + unknown.push('' + key); + } + }); + } + if (checkPositionals) { + const demandedCommands = yargs.getDemandedCommands(); + const maxNonOptDemanded = ((_a = demandedCommands._) === null || _a === void 0 ? void 0 : _a.max) || 0; + const expected = currentContext.commands.length + maxNonOptDemanded; + if (expected < argv._.length) { + argv._.slice(expected).forEach(key => { + key = String(key); + if (!currentContext.commands.includes(key) && + !unknown.includes(key)) { + unknown.push(key); + } + }); + } + } + if (unknown.length) { + usage.fail(__n('Unknown argument: %s', 'Unknown arguments: %s', unknown.length, unknown.map(s => (s.trim() ? s : `"${s}"`)).join(', '))); + } + }; + self.unknownCommands = function unknownCommands(argv) { + const commandKeys = yargs + .getInternalMethods() + .getCommandInstance() + .getCommands(); + const unknown = []; + const currentContext = yargs.getInternalMethods().getContext(); + if (currentContext.commands.length > 0 || commandKeys.length > 0) { + argv._.slice(currentContext.commands.length).forEach(key => { + if (!commandKeys.includes('' + key)) { + unknown.push('' + key); + } + }); + } + if (unknown.length > 0) { + usage.fail(__n('Unknown command: %s', 'Unknown commands: %s', unknown.length, unknown.join(', '))); + return true; + } + else { + return false; + } + }; + self.isValidAndSomeAliasIsNotNew = function isValidAndSomeAliasIsNotNew(key, aliases) { + if (!Object.prototype.hasOwnProperty.call(aliases, key)) { + return false; + } + const newAliases = yargs.parsed.newAliases; + return [key, ...aliases[key]].some(a => !Object.prototype.hasOwnProperty.call(newAliases, a) || !newAliases[key]); + }; + self.limitedChoices = function limitedChoices(argv) { + const options = yargs.getOptions(); + const invalid = {}; + if (!Object.keys(options.choices).length) + return; + Object.keys(argv).forEach(key => { + if (specialKeys.indexOf(key) === -1 && + Object.prototype.hasOwnProperty.call(options.choices, key)) { + [].concat(argv[key]).forEach(value => { + if (options.choices[key].indexOf(value) === -1 && + value !== undefined) { + invalid[key] = (invalid[key] || []).concat(value); + } + }); + } + }); + const invalidKeys = Object.keys(invalid); + if (!invalidKeys.length) + return; + let msg = __('Invalid values:'); + invalidKeys.forEach(key => { + msg += `\n ${__('Argument: %s, Given: %s, Choices: %s', key, usage.stringifiedValues(invalid[key]), usage.stringifiedValues(options.choices[key]))}`; + }); + usage.fail(msg); + }; + let implied = {}; + self.implies = function implies(key, value) { + argsert(' [array|number|string]', [key, value], arguments.length); + if (typeof key === 'object') { + Object.keys(key).forEach(k => { + self.implies(k, key[k]); + }); + } + else { + yargs.global(key); + if (!implied[key]) { + implied[key] = []; + } + if (Array.isArray(value)) { + value.forEach(i => self.implies(key, i)); + } + else { + assertNotStrictEqual(value, undefined, shim); + implied[key].push(value); + } + } + }; + self.getImplied = function getImplied() { + return implied; + }; + function keyExists(argv, val) { + const num = Number(val); + val = isNaN(num) ? val : num; + if (typeof val === 'number') { + val = argv._.length >= val; + } + else if (val.match(/^--no-.+/)) { + val = val.match(/^--no-(.+)/)[1]; + val = !Object.prototype.hasOwnProperty.call(argv, val); + } + else { + val = Object.prototype.hasOwnProperty.call(argv, val); + } + return val; + } + self.implications = function implications(argv) { + const implyFail = []; + Object.keys(implied).forEach(key => { + const origKey = key; + (implied[key] || []).forEach(value => { + let key = origKey; + const origValue = value; + key = keyExists(argv, key); + value = keyExists(argv, value); + if (key && !value) { + implyFail.push(` ${origKey} -> ${origValue}`); + } + }); + }); + if (implyFail.length) { + let msg = `${__('Implications failed:')}\n`; + implyFail.forEach(value => { + msg += value; + }); + usage.fail(msg); + } + }; + let conflicting = {}; + self.conflicts = function conflicts(key, value) { + argsert(' [array|string]', [key, value], arguments.length); + if (typeof key === 'object') { + Object.keys(key).forEach(k => { + self.conflicts(k, key[k]); + }); + } + else { + yargs.global(key); + if (!conflicting[key]) { + conflicting[key] = []; + } + if (Array.isArray(value)) { + value.forEach(i => self.conflicts(key, i)); + } + else { + conflicting[key].push(value); + } + } + }; + self.getConflicting = () => conflicting; + self.conflicting = function conflictingFn(argv) { + Object.keys(argv).forEach(key => { + if (conflicting[key]) { + conflicting[key].forEach(value => { + if (value && argv[key] !== undefined && argv[value] !== undefined) { + usage.fail(__('Arguments %s and %s are mutually exclusive', key, value)); + } + }); + } + }); + if (yargs.getInternalMethods().getParserConfiguration()['strip-dashed']) { + Object.keys(conflicting).forEach(key => { + conflicting[key].forEach(value => { + if (value && + argv[shim.Parser.camelCase(key)] !== undefined && + argv[shim.Parser.camelCase(value)] !== undefined) { + usage.fail(__('Arguments %s and %s are mutually exclusive', key, value)); + } + }); + }); + } + }; + self.recommendCommands = function recommendCommands(cmd, potentialCommands) { + const threshold = 3; + potentialCommands = potentialCommands.sort((a, b) => b.length - a.length); + let recommended = null; + let bestDistance = Infinity; + for (let i = 0, candidate; (candidate = potentialCommands[i]) !== undefined; i++) { + const d = distance(cmd, candidate); + if (d <= threshold && d < bestDistance) { + bestDistance = d; + recommended = candidate; + } + } + if (recommended) + usage.fail(__('Did you mean %s?', recommended)); + }; + self.reset = function reset(localLookup) { + implied = objFilter(implied, k => !localLookup[k]); + conflicting = objFilter(conflicting, k => !localLookup[k]); + return self; + }; + const frozens = []; + self.freeze = function freeze() { + frozens.push({ + implied, + conflicting, + }); + }; + self.unfreeze = function unfreeze() { + const frozen = frozens.pop(); + assertNotStrictEqual(frozen, undefined, shim); + ({ implied, conflicting } = frozen); + }; + return self; +} diff --git a/node_modules/yargs/build/lib/yargs-factory.js b/node_modules/yargs/build/lib/yargs-factory.js new file mode 100644 index 0000000..c4b1d50 --- /dev/null +++ b/node_modules/yargs/build/lib/yargs-factory.js @@ -0,0 +1,1512 @@ +var __classPrivateFieldSet = (this && this.__classPrivateFieldSet) || function (receiver, state, value, kind, f) { + if (kind === "m") throw new TypeError("Private method is not writable"); + if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter"); + if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it"); + return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value; +}; +var __classPrivateFieldGet = (this && this.__classPrivateFieldGet) || function (receiver, state, kind, f) { + if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter"); + if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it"); + return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver); +}; +var _YargsInstance_command, _YargsInstance_cwd, _YargsInstance_context, _YargsInstance_completion, _YargsInstance_completionCommand, _YargsInstance_defaultShowHiddenOpt, _YargsInstance_exitError, _YargsInstance_detectLocale, _YargsInstance_emittedWarnings, _YargsInstance_exitProcess, _YargsInstance_frozens, _YargsInstance_globalMiddleware, _YargsInstance_groups, _YargsInstance_hasOutput, _YargsInstance_helpOpt, _YargsInstance_isGlobalContext, _YargsInstance_logger, _YargsInstance_output, _YargsInstance_options, _YargsInstance_parentRequire, _YargsInstance_parserConfig, _YargsInstance_parseFn, _YargsInstance_parseContext, _YargsInstance_pkgs, _YargsInstance_preservedGroups, _YargsInstance_processArgs, _YargsInstance_recommendCommands, _YargsInstance_shim, _YargsInstance_strict, _YargsInstance_strictCommands, _YargsInstance_strictOptions, _YargsInstance_usage, _YargsInstance_usageConfig, _YargsInstance_versionOpt, _YargsInstance_validation; +import { command as Command, } from './command.js'; +import { assertNotStrictEqual, assertSingleKey, objectKeys, } from './typings/common-types.js'; +import { YError } from './yerror.js'; +import { usage as Usage } from './usage.js'; +import { argsert } from './argsert.js'; +import { completion as Completion, } from './completion.js'; +import { validation as Validation, } from './validation.js'; +import { objFilter } from './utils/obj-filter.js'; +import { applyExtends } from './utils/apply-extends.js'; +import { applyMiddleware, GlobalMiddleware, } from './middleware.js'; +import { isPromise } from './utils/is-promise.js'; +import { maybeAsyncResult } from './utils/maybe-async-result.js'; +import setBlocking from './utils/set-blocking.js'; +export function YargsFactory(_shim) { + return (processArgs = [], cwd = _shim.process.cwd(), parentRequire) => { + const yargs = new YargsInstance(processArgs, cwd, parentRequire, _shim); + Object.defineProperty(yargs, 'argv', { + get: () => { + return yargs.parse(); + }, + enumerable: true, + }); + yargs.help(); + yargs.version(); + return yargs; + }; +} +const kCopyDoubleDash = Symbol('copyDoubleDash'); +const kCreateLogger = Symbol('copyDoubleDash'); +const kDeleteFromParserHintObject = Symbol('deleteFromParserHintObject'); +const kEmitWarning = Symbol('emitWarning'); +const kFreeze = Symbol('freeze'); +const kGetDollarZero = Symbol('getDollarZero'); +const kGetParserConfiguration = Symbol('getParserConfiguration'); +const kGetUsageConfiguration = Symbol('getUsageConfiguration'); +const kGuessLocale = Symbol('guessLocale'); +const kGuessVersion = Symbol('guessVersion'); +const kParsePositionalNumbers = Symbol('parsePositionalNumbers'); +const kPkgUp = Symbol('pkgUp'); +const kPopulateParserHintArray = Symbol('populateParserHintArray'); +const kPopulateParserHintSingleValueDictionary = Symbol('populateParserHintSingleValueDictionary'); +const kPopulateParserHintArrayDictionary = Symbol('populateParserHintArrayDictionary'); +const kPopulateParserHintDictionary = Symbol('populateParserHintDictionary'); +const kSanitizeKey = Symbol('sanitizeKey'); +const kSetKey = Symbol('setKey'); +const kUnfreeze = Symbol('unfreeze'); +const kValidateAsync = Symbol('validateAsync'); +const kGetCommandInstance = Symbol('getCommandInstance'); +const kGetContext = Symbol('getContext'); +const kGetHasOutput = Symbol('getHasOutput'); +const kGetLoggerInstance = Symbol('getLoggerInstance'); +const kGetParseContext = Symbol('getParseContext'); +const kGetUsageInstance = Symbol('getUsageInstance'); +const kGetValidationInstance = Symbol('getValidationInstance'); +const kHasParseCallback = Symbol('hasParseCallback'); +const kIsGlobalContext = Symbol('isGlobalContext'); +const kPostProcess = Symbol('postProcess'); +const kRebase = Symbol('rebase'); +const kReset = Symbol('reset'); +const kRunYargsParserAndExecuteCommands = Symbol('runYargsParserAndExecuteCommands'); +const kRunValidation = Symbol('runValidation'); +const kSetHasOutput = Symbol('setHasOutput'); +const kTrackManuallySetKeys = Symbol('kTrackManuallySetKeys'); +export class YargsInstance { + constructor(processArgs = [], cwd, parentRequire, shim) { + this.customScriptName = false; + this.parsed = false; + _YargsInstance_command.set(this, void 0); + _YargsInstance_cwd.set(this, void 0); + _YargsInstance_context.set(this, { commands: [], fullCommands: [] }); + _YargsInstance_completion.set(this, null); + _YargsInstance_completionCommand.set(this, null); + _YargsInstance_defaultShowHiddenOpt.set(this, 'show-hidden'); + _YargsInstance_exitError.set(this, null); + _YargsInstance_detectLocale.set(this, true); + _YargsInstance_emittedWarnings.set(this, {}); + _YargsInstance_exitProcess.set(this, true); + _YargsInstance_frozens.set(this, []); + _YargsInstance_globalMiddleware.set(this, void 0); + _YargsInstance_groups.set(this, {}); + _YargsInstance_hasOutput.set(this, false); + _YargsInstance_helpOpt.set(this, null); + _YargsInstance_isGlobalContext.set(this, true); + _YargsInstance_logger.set(this, void 0); + _YargsInstance_output.set(this, ''); + _YargsInstance_options.set(this, void 0); + _YargsInstance_parentRequire.set(this, void 0); + _YargsInstance_parserConfig.set(this, {}); + _YargsInstance_parseFn.set(this, null); + _YargsInstance_parseContext.set(this, null); + _YargsInstance_pkgs.set(this, {}); + _YargsInstance_preservedGroups.set(this, {}); + _YargsInstance_processArgs.set(this, void 0); + _YargsInstance_recommendCommands.set(this, false); + _YargsInstance_shim.set(this, void 0); + _YargsInstance_strict.set(this, false); + _YargsInstance_strictCommands.set(this, false); + _YargsInstance_strictOptions.set(this, false); + _YargsInstance_usage.set(this, void 0); + _YargsInstance_usageConfig.set(this, {}); + _YargsInstance_versionOpt.set(this, null); + _YargsInstance_validation.set(this, void 0); + __classPrivateFieldSet(this, _YargsInstance_shim, shim, "f"); + __classPrivateFieldSet(this, _YargsInstance_processArgs, processArgs, "f"); + __classPrivateFieldSet(this, _YargsInstance_cwd, cwd, "f"); + __classPrivateFieldSet(this, _YargsInstance_parentRequire, parentRequire, "f"); + __classPrivateFieldSet(this, _YargsInstance_globalMiddleware, new GlobalMiddleware(this), "f"); + this.$0 = this[kGetDollarZero](); + this[kReset](); + __classPrivateFieldSet(this, _YargsInstance_command, __classPrivateFieldGet(this, _YargsInstance_command, "f"), "f"); + __classPrivateFieldSet(this, _YargsInstance_usage, __classPrivateFieldGet(this, _YargsInstance_usage, "f"), "f"); + __classPrivateFieldSet(this, _YargsInstance_validation, __classPrivateFieldGet(this, _YargsInstance_validation, "f"), "f"); + __classPrivateFieldSet(this, _YargsInstance_options, __classPrivateFieldGet(this, _YargsInstance_options, "f"), "f"); + __classPrivateFieldGet(this, _YargsInstance_options, "f").showHiddenOpt = __classPrivateFieldGet(this, _YargsInstance_defaultShowHiddenOpt, "f"); + __classPrivateFieldSet(this, _YargsInstance_logger, this[kCreateLogger](), "f"); + } + addHelpOpt(opt, msg) { + const defaultHelpOpt = 'help'; + argsert('[string|boolean] [string]', [opt, msg], arguments.length); + if (__classPrivateFieldGet(this, _YargsInstance_helpOpt, "f")) { + this[kDeleteFromParserHintObject](__classPrivateFieldGet(this, _YargsInstance_helpOpt, "f")); + __classPrivateFieldSet(this, _YargsInstance_helpOpt, null, "f"); + } + if (opt === false && msg === undefined) + return this; + __classPrivateFieldSet(this, _YargsInstance_helpOpt, typeof opt === 'string' ? opt : defaultHelpOpt, "f"); + this.boolean(__classPrivateFieldGet(this, _YargsInstance_helpOpt, "f")); + this.describe(__classPrivateFieldGet(this, _YargsInstance_helpOpt, "f"), msg || __classPrivateFieldGet(this, _YargsInstance_usage, "f").deferY18nLookup('Show help')); + return this; + } + help(opt, msg) { + return this.addHelpOpt(opt, msg); + } + addShowHiddenOpt(opt, msg) { + argsert('[string|boolean] [string]', [opt, msg], arguments.length); + if (opt === false && msg === undefined) + return this; + const showHiddenOpt = typeof opt === 'string' ? opt : __classPrivateFieldGet(this, _YargsInstance_defaultShowHiddenOpt, "f"); + this.boolean(showHiddenOpt); + this.describe(showHiddenOpt, msg || __classPrivateFieldGet(this, _YargsInstance_usage, "f").deferY18nLookup('Show hidden options')); + __classPrivateFieldGet(this, _YargsInstance_options, "f").showHiddenOpt = showHiddenOpt; + return this; + } + showHidden(opt, msg) { + return this.addShowHiddenOpt(opt, msg); + } + alias(key, value) { + argsert(' [string|array]', [key, value], arguments.length); + this[kPopulateParserHintArrayDictionary](this.alias.bind(this), 'alias', key, value); + return this; + } + array(keys) { + argsert('', [keys], arguments.length); + this[kPopulateParserHintArray]('array', keys); + this[kTrackManuallySetKeys](keys); + return this; + } + boolean(keys) { + argsert('', [keys], arguments.length); + this[kPopulateParserHintArray]('boolean', keys); + this[kTrackManuallySetKeys](keys); + return this; + } + check(f, global) { + argsert(' [boolean]', [f, global], arguments.length); + this.middleware((argv, _yargs) => { + return maybeAsyncResult(() => { + return f(argv, _yargs.getOptions()); + }, (result) => { + if (!result) { + __classPrivateFieldGet(this, _YargsInstance_usage, "f").fail(__classPrivateFieldGet(this, _YargsInstance_shim, "f").y18n.__('Argument check failed: %s', f.toString())); + } + else if (typeof result === 'string' || result instanceof Error) { + __classPrivateFieldGet(this, _YargsInstance_usage, "f").fail(result.toString(), result); + } + return argv; + }, (err) => { + __classPrivateFieldGet(this, _YargsInstance_usage, "f").fail(err.message ? err.message : err.toString(), err); + return argv; + }); + }, false, global); + return this; + } + choices(key, value) { + argsert(' [string|array]', [key, value], arguments.length); + this[kPopulateParserHintArrayDictionary](this.choices.bind(this), 'choices', key, value); + return this; + } + coerce(keys, value) { + argsert(' [function]', [keys, value], arguments.length); + if (Array.isArray(keys)) { + if (!value) { + throw new YError('coerce callback must be provided'); + } + for (const key of keys) { + this.coerce(key, value); + } + return this; + } + else if (typeof keys === 'object') { + for (const key of Object.keys(keys)) { + this.coerce(key, keys[key]); + } + return this; + } + if (!value) { + throw new YError('coerce callback must be provided'); + } + __classPrivateFieldGet(this, _YargsInstance_options, "f").key[keys] = true; + __classPrivateFieldGet(this, _YargsInstance_globalMiddleware, "f").addCoerceMiddleware((argv, yargs) => { + let aliases; + const shouldCoerce = Object.prototype.hasOwnProperty.call(argv, keys); + if (!shouldCoerce) { + return argv; + } + return maybeAsyncResult(() => { + aliases = yargs.getAliases(); + return value(argv[keys]); + }, (result) => { + argv[keys] = result; + const stripAliased = yargs + .getInternalMethods() + .getParserConfiguration()['strip-aliased']; + if (aliases[keys] && stripAliased !== true) { + for (const alias of aliases[keys]) { + argv[alias] = result; + } + } + return argv; + }, (err) => { + throw new YError(err.message); + }); + }, keys); + return this; + } + conflicts(key1, key2) { + argsert(' [string|array]', [key1, key2], arguments.length); + __classPrivateFieldGet(this, _YargsInstance_validation, "f").conflicts(key1, key2); + return this; + } + config(key = 'config', msg, parseFn) { + argsert('[object|string] [string|function] [function]', [key, msg, parseFn], arguments.length); + if (typeof key === 'object' && !Array.isArray(key)) { + key = applyExtends(key, __classPrivateFieldGet(this, _YargsInstance_cwd, "f"), this[kGetParserConfiguration]()['deep-merge-config'] || false, __classPrivateFieldGet(this, _YargsInstance_shim, "f")); + __classPrivateFieldGet(this, _YargsInstance_options, "f").configObjects = (__classPrivateFieldGet(this, _YargsInstance_options, "f").configObjects || []).concat(key); + return this; + } + if (typeof msg === 'function') { + parseFn = msg; + msg = undefined; + } + this.describe(key, msg || __classPrivateFieldGet(this, _YargsInstance_usage, "f").deferY18nLookup('Path to JSON config file')); + (Array.isArray(key) ? key : [key]).forEach(k => { + __classPrivateFieldGet(this, _YargsInstance_options, "f").config[k] = parseFn || true; + }); + return this; + } + completion(cmd, desc, fn) { + argsert('[string] [string|boolean|function] [function]', [cmd, desc, fn], arguments.length); + if (typeof desc === 'function') { + fn = desc; + desc = undefined; + } + __classPrivateFieldSet(this, _YargsInstance_completionCommand, cmd || __classPrivateFieldGet(this, _YargsInstance_completionCommand, "f") || 'completion', "f"); + if (!desc && desc !== false) { + desc = 'generate completion script'; + } + this.command(__classPrivateFieldGet(this, _YargsInstance_completionCommand, "f"), desc); + if (fn) + __classPrivateFieldGet(this, _YargsInstance_completion, "f").registerFunction(fn); + return this; + } + command(cmd, description, builder, handler, middlewares, deprecated) { + argsert(' [string|boolean] [function|object] [function] [array] [boolean|string]', [cmd, description, builder, handler, middlewares, deprecated], arguments.length); + __classPrivateFieldGet(this, _YargsInstance_command, "f").addHandler(cmd, description, builder, handler, middlewares, deprecated); + return this; + } + commands(cmd, description, builder, handler, middlewares, deprecated) { + return this.command(cmd, description, builder, handler, middlewares, deprecated); + } + commandDir(dir, opts) { + argsert(' [object]', [dir, opts], arguments.length); + const req = __classPrivateFieldGet(this, _YargsInstance_parentRequire, "f") || __classPrivateFieldGet(this, _YargsInstance_shim, "f").require; + __classPrivateFieldGet(this, _YargsInstance_command, "f").addDirectory(dir, req, __classPrivateFieldGet(this, _YargsInstance_shim, "f").getCallerFile(), opts); + return this; + } + count(keys) { + argsert('', [keys], arguments.length); + this[kPopulateParserHintArray]('count', keys); + this[kTrackManuallySetKeys](keys); + return this; + } + default(key, value, defaultDescription) { + argsert(' [*] [string]', [key, value, defaultDescription], arguments.length); + if (defaultDescription) { + assertSingleKey(key, __classPrivateFieldGet(this, _YargsInstance_shim, "f")); + __classPrivateFieldGet(this, _YargsInstance_options, "f").defaultDescription[key] = defaultDescription; + } + if (typeof value === 'function') { + assertSingleKey(key, __classPrivateFieldGet(this, _YargsInstance_shim, "f")); + if (!__classPrivateFieldGet(this, _YargsInstance_options, "f").defaultDescription[key]) + __classPrivateFieldGet(this, _YargsInstance_options, "f").defaultDescription[key] = + __classPrivateFieldGet(this, _YargsInstance_usage, "f").functionDescription(value); + value = value.call(); + } + this[kPopulateParserHintSingleValueDictionary](this.default.bind(this), 'default', key, value); + return this; + } + defaults(key, value, defaultDescription) { + return this.default(key, value, defaultDescription); + } + demandCommand(min = 1, max, minMsg, maxMsg) { + argsert('[number] [number|string] [string|null|undefined] [string|null|undefined]', [min, max, minMsg, maxMsg], arguments.length); + if (typeof max !== 'number') { + minMsg = max; + max = Infinity; + } + this.global('_', false); + __classPrivateFieldGet(this, _YargsInstance_options, "f").demandedCommands._ = { + min, + max, + minMsg, + maxMsg, + }; + return this; + } + demand(keys, max, msg) { + if (Array.isArray(max)) { + max.forEach(key => { + assertNotStrictEqual(msg, true, __classPrivateFieldGet(this, _YargsInstance_shim, "f")); + this.demandOption(key, msg); + }); + max = Infinity; + } + else if (typeof max !== 'number') { + msg = max; + max = Infinity; + } + if (typeof keys === 'number') { + assertNotStrictEqual(msg, true, __classPrivateFieldGet(this, _YargsInstance_shim, "f")); + this.demandCommand(keys, max, msg, msg); + } + else if (Array.isArray(keys)) { + keys.forEach(key => { + assertNotStrictEqual(msg, true, __classPrivateFieldGet(this, _YargsInstance_shim, "f")); + this.demandOption(key, msg); + }); + } + else { + if (typeof msg === 'string') { + this.demandOption(keys, msg); + } + else if (msg === true || typeof msg === 'undefined') { + this.demandOption(keys); + } + } + return this; + } + demandOption(keys, msg) { + argsert(' [string]', [keys, msg], arguments.length); + this[kPopulateParserHintSingleValueDictionary](this.demandOption.bind(this), 'demandedOptions', keys, msg); + return this; + } + deprecateOption(option, message) { + argsert(' [string|boolean]', [option, message], arguments.length); + __classPrivateFieldGet(this, _YargsInstance_options, "f").deprecatedOptions[option] = message; + return this; + } + describe(keys, description) { + argsert(' [string]', [keys, description], arguments.length); + this[kSetKey](keys, true); + __classPrivateFieldGet(this, _YargsInstance_usage, "f").describe(keys, description); + return this; + } + detectLocale(detect) { + argsert('', [detect], arguments.length); + __classPrivateFieldSet(this, _YargsInstance_detectLocale, detect, "f"); + return this; + } + env(prefix) { + argsert('[string|boolean]', [prefix], arguments.length); + if (prefix === false) + delete __classPrivateFieldGet(this, _YargsInstance_options, "f").envPrefix; + else + __classPrivateFieldGet(this, _YargsInstance_options, "f").envPrefix = prefix || ''; + return this; + } + epilogue(msg) { + argsert('', [msg], arguments.length); + __classPrivateFieldGet(this, _YargsInstance_usage, "f").epilog(msg); + return this; + } + epilog(msg) { + return this.epilogue(msg); + } + example(cmd, description) { + argsert(' [string]', [cmd, description], arguments.length); + if (Array.isArray(cmd)) { + cmd.forEach(exampleParams => this.example(...exampleParams)); + } + else { + __classPrivateFieldGet(this, _YargsInstance_usage, "f").example(cmd, description); + } + return this; + } + exit(code, err) { + __classPrivateFieldSet(this, _YargsInstance_hasOutput, true, "f"); + __classPrivateFieldSet(this, _YargsInstance_exitError, err, "f"); + if (__classPrivateFieldGet(this, _YargsInstance_exitProcess, "f")) + __classPrivateFieldGet(this, _YargsInstance_shim, "f").process.exit(code); + } + exitProcess(enabled = true) { + argsert('[boolean]', [enabled], arguments.length); + __classPrivateFieldSet(this, _YargsInstance_exitProcess, enabled, "f"); + return this; + } + fail(f) { + argsert('', [f], arguments.length); + if (typeof f === 'boolean' && f !== false) { + throw new YError("Invalid first argument. Expected function or boolean 'false'"); + } + __classPrivateFieldGet(this, _YargsInstance_usage, "f").failFn(f); + return this; + } + getAliases() { + return this.parsed ? this.parsed.aliases : {}; + } + async getCompletion(args, done) { + argsert(' [function]', [args, done], arguments.length); + if (!done) { + return new Promise((resolve, reject) => { + __classPrivateFieldGet(this, _YargsInstance_completion, "f").getCompletion(args, (err, completions) => { + if (err) + reject(err); + else + resolve(completions); + }); + }); + } + else { + return __classPrivateFieldGet(this, _YargsInstance_completion, "f").getCompletion(args, done); + } + } + getDemandedOptions() { + argsert([], 0); + return __classPrivateFieldGet(this, _YargsInstance_options, "f").demandedOptions; + } + getDemandedCommands() { + argsert([], 0); + return __classPrivateFieldGet(this, _YargsInstance_options, "f").demandedCommands; + } + getDeprecatedOptions() { + argsert([], 0); + return __classPrivateFieldGet(this, _YargsInstance_options, "f").deprecatedOptions; + } + getDetectLocale() { + return __classPrivateFieldGet(this, _YargsInstance_detectLocale, "f"); + } + getExitProcess() { + return __classPrivateFieldGet(this, _YargsInstance_exitProcess, "f"); + } + getGroups() { + return Object.assign({}, __classPrivateFieldGet(this, _YargsInstance_groups, "f"), __classPrivateFieldGet(this, _YargsInstance_preservedGroups, "f")); + } + getHelp() { + __classPrivateFieldSet(this, _YargsInstance_hasOutput, true, "f"); + if (!__classPrivateFieldGet(this, _YargsInstance_usage, "f").hasCachedHelpMessage()) { + if (!this.parsed) { + const parse = this[kRunYargsParserAndExecuteCommands](__classPrivateFieldGet(this, _YargsInstance_processArgs, "f"), undefined, undefined, 0, true); + if (isPromise(parse)) { + return parse.then(() => { + return __classPrivateFieldGet(this, _YargsInstance_usage, "f").help(); + }); + } + } + const builderResponse = __classPrivateFieldGet(this, _YargsInstance_command, "f").runDefaultBuilderOn(this); + if (isPromise(builderResponse)) { + return builderResponse.then(() => { + return __classPrivateFieldGet(this, _YargsInstance_usage, "f").help(); + }); + } + } + return Promise.resolve(__classPrivateFieldGet(this, _YargsInstance_usage, "f").help()); + } + getOptions() { + return __classPrivateFieldGet(this, _YargsInstance_options, "f"); + } + getStrict() { + return __classPrivateFieldGet(this, _YargsInstance_strict, "f"); + } + getStrictCommands() { + return __classPrivateFieldGet(this, _YargsInstance_strictCommands, "f"); + } + getStrictOptions() { + return __classPrivateFieldGet(this, _YargsInstance_strictOptions, "f"); + } + global(globals, global) { + argsert(' [boolean]', [globals, global], arguments.length); + globals = [].concat(globals); + if (global !== false) { + __classPrivateFieldGet(this, _YargsInstance_options, "f").local = __classPrivateFieldGet(this, _YargsInstance_options, "f").local.filter(l => globals.indexOf(l) === -1); + } + else { + globals.forEach(g => { + if (!__classPrivateFieldGet(this, _YargsInstance_options, "f").local.includes(g)) + __classPrivateFieldGet(this, _YargsInstance_options, "f").local.push(g); + }); + } + return this; + } + group(opts, groupName) { + argsert(' ', [opts, groupName], arguments.length); + const existing = __classPrivateFieldGet(this, _YargsInstance_preservedGroups, "f")[groupName] || __classPrivateFieldGet(this, _YargsInstance_groups, "f")[groupName]; + if (__classPrivateFieldGet(this, _YargsInstance_preservedGroups, "f")[groupName]) { + delete __classPrivateFieldGet(this, _YargsInstance_preservedGroups, "f")[groupName]; + } + const seen = {}; + __classPrivateFieldGet(this, _YargsInstance_groups, "f")[groupName] = (existing || []).concat(opts).filter(key => { + if (seen[key]) + return false; + return (seen[key] = true); + }); + return this; + } + hide(key) { + argsert('', [key], arguments.length); + __classPrivateFieldGet(this, _YargsInstance_options, "f").hiddenOptions.push(key); + return this; + } + implies(key, value) { + argsert(' [number|string|array]', [key, value], arguments.length); + __classPrivateFieldGet(this, _YargsInstance_validation, "f").implies(key, value); + return this; + } + locale(locale) { + argsert('[string]', [locale], arguments.length); + if (locale === undefined) { + this[kGuessLocale](); + return __classPrivateFieldGet(this, _YargsInstance_shim, "f").y18n.getLocale(); + } + __classPrivateFieldSet(this, _YargsInstance_detectLocale, false, "f"); + __classPrivateFieldGet(this, _YargsInstance_shim, "f").y18n.setLocale(locale); + return this; + } + middleware(callback, applyBeforeValidation, global) { + return __classPrivateFieldGet(this, _YargsInstance_globalMiddleware, "f").addMiddleware(callback, !!applyBeforeValidation, global); + } + nargs(key, value) { + argsert(' [number]', [key, value], arguments.length); + this[kPopulateParserHintSingleValueDictionary](this.nargs.bind(this), 'narg', key, value); + return this; + } + normalize(keys) { + argsert('', [keys], arguments.length); + this[kPopulateParserHintArray]('normalize', keys); + return this; + } + number(keys) { + argsert('', [keys], arguments.length); + this[kPopulateParserHintArray]('number', keys); + this[kTrackManuallySetKeys](keys); + return this; + } + option(key, opt) { + argsert(' [object]', [key, opt], arguments.length); + if (typeof key === 'object') { + Object.keys(key).forEach(k => { + this.options(k, key[k]); + }); + } + else { + if (typeof opt !== 'object') { + opt = {}; + } + this[kTrackManuallySetKeys](key); + if (__classPrivateFieldGet(this, _YargsInstance_versionOpt, "f") && (key === 'version' || (opt === null || opt === void 0 ? void 0 : opt.alias) === 'version')) { + this[kEmitWarning]([ + '"version" is a reserved word.', + 'Please do one of the following:', + '- Disable version with `yargs.version(false)` if using "version" as an option', + '- Use the built-in `yargs.version` method instead (if applicable)', + '- Use a different option key', + 'https://yargs.js.org/docs/#api-reference-version', + ].join('\n'), undefined, 'versionWarning'); + } + __classPrivateFieldGet(this, _YargsInstance_options, "f").key[key] = true; + if (opt.alias) + this.alias(key, opt.alias); + const deprecate = opt.deprecate || opt.deprecated; + if (deprecate) { + this.deprecateOption(key, deprecate); + } + const demand = opt.demand || opt.required || opt.require; + if (demand) { + this.demand(key, demand); + } + if (opt.demandOption) { + this.demandOption(key, typeof opt.demandOption === 'string' ? opt.demandOption : undefined); + } + if (opt.conflicts) { + this.conflicts(key, opt.conflicts); + } + if ('default' in opt) { + this.default(key, opt.default); + } + if (opt.implies !== undefined) { + this.implies(key, opt.implies); + } + if (opt.nargs !== undefined) { + this.nargs(key, opt.nargs); + } + if (opt.config) { + this.config(key, opt.configParser); + } + if (opt.normalize) { + this.normalize(key); + } + if (opt.choices) { + this.choices(key, opt.choices); + } + if (opt.coerce) { + this.coerce(key, opt.coerce); + } + if (opt.group) { + this.group(key, opt.group); + } + if (opt.boolean || opt.type === 'boolean') { + this.boolean(key); + if (opt.alias) + this.boolean(opt.alias); + } + if (opt.array || opt.type === 'array') { + this.array(key); + if (opt.alias) + this.array(opt.alias); + } + if (opt.number || opt.type === 'number') { + this.number(key); + if (opt.alias) + this.number(opt.alias); + } + if (opt.string || opt.type === 'string') { + this.string(key); + if (opt.alias) + this.string(opt.alias); + } + if (opt.count || opt.type === 'count') { + this.count(key); + } + if (typeof opt.global === 'boolean') { + this.global(key, opt.global); + } + if (opt.defaultDescription) { + __classPrivateFieldGet(this, _YargsInstance_options, "f").defaultDescription[key] = opt.defaultDescription; + } + if (opt.skipValidation) { + this.skipValidation(key); + } + const desc = opt.describe || opt.description || opt.desc; + const descriptions = __classPrivateFieldGet(this, _YargsInstance_usage, "f").getDescriptions(); + if (!Object.prototype.hasOwnProperty.call(descriptions, key) || + typeof desc === 'string') { + this.describe(key, desc); + } + if (opt.hidden) { + this.hide(key); + } + if (opt.requiresArg) { + this.requiresArg(key); + } + } + return this; + } + options(key, opt) { + return this.option(key, opt); + } + parse(args, shortCircuit, _parseFn) { + argsert('[string|array] [function|boolean|object] [function]', [args, shortCircuit, _parseFn], arguments.length); + this[kFreeze](); + if (typeof args === 'undefined') { + args = __classPrivateFieldGet(this, _YargsInstance_processArgs, "f"); + } + if (typeof shortCircuit === 'object') { + __classPrivateFieldSet(this, _YargsInstance_parseContext, shortCircuit, "f"); + shortCircuit = _parseFn; + } + if (typeof shortCircuit === 'function') { + __classPrivateFieldSet(this, _YargsInstance_parseFn, shortCircuit, "f"); + shortCircuit = false; + } + if (!shortCircuit) + __classPrivateFieldSet(this, _YargsInstance_processArgs, args, "f"); + if (__classPrivateFieldGet(this, _YargsInstance_parseFn, "f")) + __classPrivateFieldSet(this, _YargsInstance_exitProcess, false, "f"); + const parsed = this[kRunYargsParserAndExecuteCommands](args, !!shortCircuit); + const tmpParsed = this.parsed; + __classPrivateFieldGet(this, _YargsInstance_completion, "f").setParsed(this.parsed); + if (isPromise(parsed)) { + return parsed + .then(argv => { + if (__classPrivateFieldGet(this, _YargsInstance_parseFn, "f")) + __classPrivateFieldGet(this, _YargsInstance_parseFn, "f").call(this, __classPrivateFieldGet(this, _YargsInstance_exitError, "f"), argv, __classPrivateFieldGet(this, _YargsInstance_output, "f")); + return argv; + }) + .catch(err => { + if (__classPrivateFieldGet(this, _YargsInstance_parseFn, "f")) { + __classPrivateFieldGet(this, _YargsInstance_parseFn, "f")(err, this.parsed.argv, __classPrivateFieldGet(this, _YargsInstance_output, "f")); + } + throw err; + }) + .finally(() => { + this[kUnfreeze](); + this.parsed = tmpParsed; + }); + } + else { + if (__classPrivateFieldGet(this, _YargsInstance_parseFn, "f")) + __classPrivateFieldGet(this, _YargsInstance_parseFn, "f").call(this, __classPrivateFieldGet(this, _YargsInstance_exitError, "f"), parsed, __classPrivateFieldGet(this, _YargsInstance_output, "f")); + this[kUnfreeze](); + this.parsed = tmpParsed; + } + return parsed; + } + parseAsync(args, shortCircuit, _parseFn) { + const maybePromise = this.parse(args, shortCircuit, _parseFn); + return !isPromise(maybePromise) + ? Promise.resolve(maybePromise) + : maybePromise; + } + parseSync(args, shortCircuit, _parseFn) { + const maybePromise = this.parse(args, shortCircuit, _parseFn); + if (isPromise(maybePromise)) { + throw new YError('.parseSync() must not be used with asynchronous builders, handlers, or middleware'); + } + return maybePromise; + } + parserConfiguration(config) { + argsert('', [config], arguments.length); + __classPrivateFieldSet(this, _YargsInstance_parserConfig, config, "f"); + return this; + } + pkgConf(key, rootPath) { + argsert(' [string]', [key, rootPath], arguments.length); + let conf = null; + const obj = this[kPkgUp](rootPath || __classPrivateFieldGet(this, _YargsInstance_cwd, "f")); + if (obj[key] && typeof obj[key] === 'object') { + conf = applyExtends(obj[key], rootPath || __classPrivateFieldGet(this, _YargsInstance_cwd, "f"), this[kGetParserConfiguration]()['deep-merge-config'] || false, __classPrivateFieldGet(this, _YargsInstance_shim, "f")); + __classPrivateFieldGet(this, _YargsInstance_options, "f").configObjects = (__classPrivateFieldGet(this, _YargsInstance_options, "f").configObjects || []).concat(conf); + } + return this; + } + positional(key, opts) { + argsert(' ', [key, opts], arguments.length); + const supportedOpts = [ + 'default', + 'defaultDescription', + 'implies', + 'normalize', + 'choices', + 'conflicts', + 'coerce', + 'type', + 'describe', + 'desc', + 'description', + 'alias', + ]; + opts = objFilter(opts, (k, v) => { + if (k === 'type' && !['string', 'number', 'boolean'].includes(v)) + return false; + return supportedOpts.includes(k); + }); + const fullCommand = __classPrivateFieldGet(this, _YargsInstance_context, "f").fullCommands[__classPrivateFieldGet(this, _YargsInstance_context, "f").fullCommands.length - 1]; + const parseOptions = fullCommand + ? __classPrivateFieldGet(this, _YargsInstance_command, "f").cmdToParseOptions(fullCommand) + : { + array: [], + alias: {}, + default: {}, + demand: {}, + }; + objectKeys(parseOptions).forEach(pk => { + const parseOption = parseOptions[pk]; + if (Array.isArray(parseOption)) { + if (parseOption.indexOf(key) !== -1) + opts[pk] = true; + } + else { + if (parseOption[key] && !(pk in opts)) + opts[pk] = parseOption[key]; + } + }); + this.group(key, __classPrivateFieldGet(this, _YargsInstance_usage, "f").getPositionalGroupName()); + return this.option(key, opts); + } + recommendCommands(recommend = true) { + argsert('[boolean]', [recommend], arguments.length); + __classPrivateFieldSet(this, _YargsInstance_recommendCommands, recommend, "f"); + return this; + } + required(keys, max, msg) { + return this.demand(keys, max, msg); + } + require(keys, max, msg) { + return this.demand(keys, max, msg); + } + requiresArg(keys) { + argsert(' [number]', [keys], arguments.length); + if (typeof keys === 'string' && __classPrivateFieldGet(this, _YargsInstance_options, "f").narg[keys]) { + return this; + } + else { + this[kPopulateParserHintSingleValueDictionary](this.requiresArg.bind(this), 'narg', keys, NaN); + } + return this; + } + showCompletionScript($0, cmd) { + argsert('[string] [string]', [$0, cmd], arguments.length); + $0 = $0 || this.$0; + __classPrivateFieldGet(this, _YargsInstance_logger, "f").log(__classPrivateFieldGet(this, _YargsInstance_completion, "f").generateCompletionScript($0, cmd || __classPrivateFieldGet(this, _YargsInstance_completionCommand, "f") || 'completion')); + return this; + } + showHelp(level) { + argsert('[string|function]', [level], arguments.length); + __classPrivateFieldSet(this, _YargsInstance_hasOutput, true, "f"); + if (!__classPrivateFieldGet(this, _YargsInstance_usage, "f").hasCachedHelpMessage()) { + if (!this.parsed) { + const parse = this[kRunYargsParserAndExecuteCommands](__classPrivateFieldGet(this, _YargsInstance_processArgs, "f"), undefined, undefined, 0, true); + if (isPromise(parse)) { + parse.then(() => { + __classPrivateFieldGet(this, _YargsInstance_usage, "f").showHelp(level); + }); + return this; + } + } + const builderResponse = __classPrivateFieldGet(this, _YargsInstance_command, "f").runDefaultBuilderOn(this); + if (isPromise(builderResponse)) { + builderResponse.then(() => { + __classPrivateFieldGet(this, _YargsInstance_usage, "f").showHelp(level); + }); + return this; + } + } + __classPrivateFieldGet(this, _YargsInstance_usage, "f").showHelp(level); + return this; + } + scriptName(scriptName) { + this.customScriptName = true; + this.$0 = scriptName; + return this; + } + showHelpOnFail(enabled, message) { + argsert('[boolean|string] [string]', [enabled, message], arguments.length); + __classPrivateFieldGet(this, _YargsInstance_usage, "f").showHelpOnFail(enabled, message); + return this; + } + showVersion(level) { + argsert('[string|function]', [level], arguments.length); + __classPrivateFieldGet(this, _YargsInstance_usage, "f").showVersion(level); + return this; + } + skipValidation(keys) { + argsert('', [keys], arguments.length); + this[kPopulateParserHintArray]('skipValidation', keys); + return this; + } + strict(enabled) { + argsert('[boolean]', [enabled], arguments.length); + __classPrivateFieldSet(this, _YargsInstance_strict, enabled !== false, "f"); + return this; + } + strictCommands(enabled) { + argsert('[boolean]', [enabled], arguments.length); + __classPrivateFieldSet(this, _YargsInstance_strictCommands, enabled !== false, "f"); + return this; + } + strictOptions(enabled) { + argsert('[boolean]', [enabled], arguments.length); + __classPrivateFieldSet(this, _YargsInstance_strictOptions, enabled !== false, "f"); + return this; + } + string(keys) { + argsert('', [keys], arguments.length); + this[kPopulateParserHintArray]('string', keys); + this[kTrackManuallySetKeys](keys); + return this; + } + terminalWidth() { + argsert([], 0); + return __classPrivateFieldGet(this, _YargsInstance_shim, "f").process.stdColumns; + } + updateLocale(obj) { + return this.updateStrings(obj); + } + updateStrings(obj) { + argsert('', [obj], arguments.length); + __classPrivateFieldSet(this, _YargsInstance_detectLocale, false, "f"); + __classPrivateFieldGet(this, _YargsInstance_shim, "f").y18n.updateLocale(obj); + return this; + } + usage(msg, description, builder, handler) { + argsert(' [string|boolean] [function|object] [function]', [msg, description, builder, handler], arguments.length); + if (description !== undefined) { + assertNotStrictEqual(msg, null, __classPrivateFieldGet(this, _YargsInstance_shim, "f")); + if ((msg || '').match(/^\$0( |$)/)) { + return this.command(msg, description, builder, handler); + } + else { + throw new YError('.usage() description must start with $0 if being used as alias for .command()'); + } + } + else { + __classPrivateFieldGet(this, _YargsInstance_usage, "f").usage(msg); + return this; + } + } + usageConfiguration(config) { + argsert('', [config], arguments.length); + __classPrivateFieldSet(this, _YargsInstance_usageConfig, config, "f"); + return this; + } + version(opt, msg, ver) { + const defaultVersionOpt = 'version'; + argsert('[boolean|string] [string] [string]', [opt, msg, ver], arguments.length); + if (__classPrivateFieldGet(this, _YargsInstance_versionOpt, "f")) { + this[kDeleteFromParserHintObject](__classPrivateFieldGet(this, _YargsInstance_versionOpt, "f")); + __classPrivateFieldGet(this, _YargsInstance_usage, "f").version(undefined); + __classPrivateFieldSet(this, _YargsInstance_versionOpt, null, "f"); + } + if (arguments.length === 0) { + ver = this[kGuessVersion](); + opt = defaultVersionOpt; + } + else if (arguments.length === 1) { + if (opt === false) { + return this; + } + ver = opt; + opt = defaultVersionOpt; + } + else if (arguments.length === 2) { + ver = msg; + msg = undefined; + } + __classPrivateFieldSet(this, _YargsInstance_versionOpt, typeof opt === 'string' ? opt : defaultVersionOpt, "f"); + msg = msg || __classPrivateFieldGet(this, _YargsInstance_usage, "f").deferY18nLookup('Show version number'); + __classPrivateFieldGet(this, _YargsInstance_usage, "f").version(ver || undefined); + this.boolean(__classPrivateFieldGet(this, _YargsInstance_versionOpt, "f")); + this.describe(__classPrivateFieldGet(this, _YargsInstance_versionOpt, "f"), msg); + return this; + } + wrap(cols) { + argsert('', [cols], arguments.length); + __classPrivateFieldGet(this, _YargsInstance_usage, "f").wrap(cols); + return this; + } + [(_YargsInstance_command = new WeakMap(), _YargsInstance_cwd = new WeakMap(), _YargsInstance_context = new WeakMap(), _YargsInstance_completion = new WeakMap(), _YargsInstance_completionCommand = new WeakMap(), _YargsInstance_defaultShowHiddenOpt = new WeakMap(), _YargsInstance_exitError = new WeakMap(), _YargsInstance_detectLocale = new WeakMap(), _YargsInstance_emittedWarnings = new WeakMap(), _YargsInstance_exitProcess = new WeakMap(), _YargsInstance_frozens = new WeakMap(), _YargsInstance_globalMiddleware = new WeakMap(), _YargsInstance_groups = new WeakMap(), _YargsInstance_hasOutput = new WeakMap(), _YargsInstance_helpOpt = new WeakMap(), _YargsInstance_isGlobalContext = new WeakMap(), _YargsInstance_logger = new WeakMap(), _YargsInstance_output = new WeakMap(), _YargsInstance_options = new WeakMap(), _YargsInstance_parentRequire = new WeakMap(), _YargsInstance_parserConfig = new WeakMap(), _YargsInstance_parseFn = new WeakMap(), _YargsInstance_parseContext = new WeakMap(), _YargsInstance_pkgs = new WeakMap(), _YargsInstance_preservedGroups = new WeakMap(), _YargsInstance_processArgs = new WeakMap(), _YargsInstance_recommendCommands = new WeakMap(), _YargsInstance_shim = new WeakMap(), _YargsInstance_strict = new WeakMap(), _YargsInstance_strictCommands = new WeakMap(), _YargsInstance_strictOptions = new WeakMap(), _YargsInstance_usage = new WeakMap(), _YargsInstance_usageConfig = new WeakMap(), _YargsInstance_versionOpt = new WeakMap(), _YargsInstance_validation = new WeakMap(), kCopyDoubleDash)](argv) { + if (!argv._ || !argv['--']) + return argv; + argv._.push.apply(argv._, argv['--']); + try { + delete argv['--']; + } + catch (_err) { } + return argv; + } + [kCreateLogger]() { + return { + log: (...args) => { + if (!this[kHasParseCallback]()) + console.log(...args); + __classPrivateFieldSet(this, _YargsInstance_hasOutput, true, "f"); + if (__classPrivateFieldGet(this, _YargsInstance_output, "f").length) + __classPrivateFieldSet(this, _YargsInstance_output, __classPrivateFieldGet(this, _YargsInstance_output, "f") + '\n', "f"); + __classPrivateFieldSet(this, _YargsInstance_output, __classPrivateFieldGet(this, _YargsInstance_output, "f") + args.join(' '), "f"); + }, + error: (...args) => { + if (!this[kHasParseCallback]()) + console.error(...args); + __classPrivateFieldSet(this, _YargsInstance_hasOutput, true, "f"); + if (__classPrivateFieldGet(this, _YargsInstance_output, "f").length) + __classPrivateFieldSet(this, _YargsInstance_output, __classPrivateFieldGet(this, _YargsInstance_output, "f") + '\n', "f"); + __classPrivateFieldSet(this, _YargsInstance_output, __classPrivateFieldGet(this, _YargsInstance_output, "f") + args.join(' '), "f"); + }, + }; + } + [kDeleteFromParserHintObject](optionKey) { + objectKeys(__classPrivateFieldGet(this, _YargsInstance_options, "f")).forEach((hintKey) => { + if (((key) => key === 'configObjects')(hintKey)) + return; + const hint = __classPrivateFieldGet(this, _YargsInstance_options, "f")[hintKey]; + if (Array.isArray(hint)) { + if (hint.includes(optionKey)) + hint.splice(hint.indexOf(optionKey), 1); + } + else if (typeof hint === 'object') { + delete hint[optionKey]; + } + }); + delete __classPrivateFieldGet(this, _YargsInstance_usage, "f").getDescriptions()[optionKey]; + } + [kEmitWarning](warning, type, deduplicationId) { + if (!__classPrivateFieldGet(this, _YargsInstance_emittedWarnings, "f")[deduplicationId]) { + __classPrivateFieldGet(this, _YargsInstance_shim, "f").process.emitWarning(warning, type); + __classPrivateFieldGet(this, _YargsInstance_emittedWarnings, "f")[deduplicationId] = true; + } + } + [kFreeze]() { + __classPrivateFieldGet(this, _YargsInstance_frozens, "f").push({ + options: __classPrivateFieldGet(this, _YargsInstance_options, "f"), + configObjects: __classPrivateFieldGet(this, _YargsInstance_options, "f").configObjects.slice(0), + exitProcess: __classPrivateFieldGet(this, _YargsInstance_exitProcess, "f"), + groups: __classPrivateFieldGet(this, _YargsInstance_groups, "f"), + strict: __classPrivateFieldGet(this, _YargsInstance_strict, "f"), + strictCommands: __classPrivateFieldGet(this, _YargsInstance_strictCommands, "f"), + strictOptions: __classPrivateFieldGet(this, _YargsInstance_strictOptions, "f"), + completionCommand: __classPrivateFieldGet(this, _YargsInstance_completionCommand, "f"), + output: __classPrivateFieldGet(this, _YargsInstance_output, "f"), + exitError: __classPrivateFieldGet(this, _YargsInstance_exitError, "f"), + hasOutput: __classPrivateFieldGet(this, _YargsInstance_hasOutput, "f"), + parsed: this.parsed, + parseFn: __classPrivateFieldGet(this, _YargsInstance_parseFn, "f"), + parseContext: __classPrivateFieldGet(this, _YargsInstance_parseContext, "f"), + }); + __classPrivateFieldGet(this, _YargsInstance_usage, "f").freeze(); + __classPrivateFieldGet(this, _YargsInstance_validation, "f").freeze(); + __classPrivateFieldGet(this, _YargsInstance_command, "f").freeze(); + __classPrivateFieldGet(this, _YargsInstance_globalMiddleware, "f").freeze(); + } + [kGetDollarZero]() { + let $0 = ''; + let default$0; + if (/\b(node|iojs|electron)(\.exe)?$/.test(__classPrivateFieldGet(this, _YargsInstance_shim, "f").process.argv()[0])) { + default$0 = __classPrivateFieldGet(this, _YargsInstance_shim, "f").process.argv().slice(1, 2); + } + else { + default$0 = __classPrivateFieldGet(this, _YargsInstance_shim, "f").process.argv().slice(0, 1); + } + $0 = default$0 + .map(x => { + const b = this[kRebase](__classPrivateFieldGet(this, _YargsInstance_cwd, "f"), x); + return x.match(/^(\/|([a-zA-Z]:)?\\)/) && b.length < x.length ? b : x; + }) + .join(' ') + .trim(); + if (__classPrivateFieldGet(this, _YargsInstance_shim, "f").getEnv('_') && + __classPrivateFieldGet(this, _YargsInstance_shim, "f").getProcessArgvBin() === __classPrivateFieldGet(this, _YargsInstance_shim, "f").getEnv('_')) { + $0 = __classPrivateFieldGet(this, _YargsInstance_shim, "f") + .getEnv('_') + .replace(`${__classPrivateFieldGet(this, _YargsInstance_shim, "f").path.dirname(__classPrivateFieldGet(this, _YargsInstance_shim, "f").process.execPath())}/`, ''); + } + return $0; + } + [kGetParserConfiguration]() { + return __classPrivateFieldGet(this, _YargsInstance_parserConfig, "f"); + } + [kGetUsageConfiguration]() { + return __classPrivateFieldGet(this, _YargsInstance_usageConfig, "f"); + } + [kGuessLocale]() { + if (!__classPrivateFieldGet(this, _YargsInstance_detectLocale, "f")) + return; + const locale = __classPrivateFieldGet(this, _YargsInstance_shim, "f").getEnv('LC_ALL') || + __classPrivateFieldGet(this, _YargsInstance_shim, "f").getEnv('LC_MESSAGES') || + __classPrivateFieldGet(this, _YargsInstance_shim, "f").getEnv('LANG') || + __classPrivateFieldGet(this, _YargsInstance_shim, "f").getEnv('LANGUAGE') || + 'en_US'; + this.locale(locale.replace(/[.:].*/, '')); + } + [kGuessVersion]() { + const obj = this[kPkgUp](); + return obj.version || 'unknown'; + } + [kParsePositionalNumbers](argv) { + const args = argv['--'] ? argv['--'] : argv._; + for (let i = 0, arg; (arg = args[i]) !== undefined; i++) { + if (__classPrivateFieldGet(this, _YargsInstance_shim, "f").Parser.looksLikeNumber(arg) && + Number.isSafeInteger(Math.floor(parseFloat(`${arg}`)))) { + args[i] = Number(arg); + } + } + return argv; + } + [kPkgUp](rootPath) { + const npath = rootPath || '*'; + if (__classPrivateFieldGet(this, _YargsInstance_pkgs, "f")[npath]) + return __classPrivateFieldGet(this, _YargsInstance_pkgs, "f")[npath]; + let obj = {}; + try { + let startDir = rootPath || __classPrivateFieldGet(this, _YargsInstance_shim, "f").mainFilename; + if (!rootPath && __classPrivateFieldGet(this, _YargsInstance_shim, "f").path.extname(startDir)) { + startDir = __classPrivateFieldGet(this, _YargsInstance_shim, "f").path.dirname(startDir); + } + const pkgJsonPath = __classPrivateFieldGet(this, _YargsInstance_shim, "f").findUp(startDir, (dir, names) => { + if (names.includes('package.json')) { + return 'package.json'; + } + else { + return undefined; + } + }); + assertNotStrictEqual(pkgJsonPath, undefined, __classPrivateFieldGet(this, _YargsInstance_shim, "f")); + obj = JSON.parse(__classPrivateFieldGet(this, _YargsInstance_shim, "f").readFileSync(pkgJsonPath, 'utf8')); + } + catch (_noop) { } + __classPrivateFieldGet(this, _YargsInstance_pkgs, "f")[npath] = obj || {}; + return __classPrivateFieldGet(this, _YargsInstance_pkgs, "f")[npath]; + } + [kPopulateParserHintArray](type, keys) { + keys = [].concat(keys); + keys.forEach(key => { + key = this[kSanitizeKey](key); + __classPrivateFieldGet(this, _YargsInstance_options, "f")[type].push(key); + }); + } + [kPopulateParserHintSingleValueDictionary](builder, type, key, value) { + this[kPopulateParserHintDictionary](builder, type, key, value, (type, key, value) => { + __classPrivateFieldGet(this, _YargsInstance_options, "f")[type][key] = value; + }); + } + [kPopulateParserHintArrayDictionary](builder, type, key, value) { + this[kPopulateParserHintDictionary](builder, type, key, value, (type, key, value) => { + __classPrivateFieldGet(this, _YargsInstance_options, "f")[type][key] = (__classPrivateFieldGet(this, _YargsInstance_options, "f")[type][key] || []).concat(value); + }); + } + [kPopulateParserHintDictionary](builder, type, key, value, singleKeyHandler) { + if (Array.isArray(key)) { + key.forEach(k => { + builder(k, value); + }); + } + else if (((key) => typeof key === 'object')(key)) { + for (const k of objectKeys(key)) { + builder(k, key[k]); + } + } + else { + singleKeyHandler(type, this[kSanitizeKey](key), value); + } + } + [kSanitizeKey](key) { + if (key === '__proto__') + return '___proto___'; + return key; + } + [kSetKey](key, set) { + this[kPopulateParserHintSingleValueDictionary](this[kSetKey].bind(this), 'key', key, set); + return this; + } + [kUnfreeze]() { + var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m; + const frozen = __classPrivateFieldGet(this, _YargsInstance_frozens, "f").pop(); + assertNotStrictEqual(frozen, undefined, __classPrivateFieldGet(this, _YargsInstance_shim, "f")); + let configObjects; + (_a = this, _b = this, _c = this, _d = this, _e = this, _f = this, _g = this, _h = this, _j = this, _k = this, _l = this, _m = this, { + options: ({ set value(_o) { __classPrivateFieldSet(_a, _YargsInstance_options, _o, "f"); } }).value, + configObjects, + exitProcess: ({ set value(_o) { __classPrivateFieldSet(_b, _YargsInstance_exitProcess, _o, "f"); } }).value, + groups: ({ set value(_o) { __classPrivateFieldSet(_c, _YargsInstance_groups, _o, "f"); } }).value, + output: ({ set value(_o) { __classPrivateFieldSet(_d, _YargsInstance_output, _o, "f"); } }).value, + exitError: ({ set value(_o) { __classPrivateFieldSet(_e, _YargsInstance_exitError, _o, "f"); } }).value, + hasOutput: ({ set value(_o) { __classPrivateFieldSet(_f, _YargsInstance_hasOutput, _o, "f"); } }).value, + parsed: this.parsed, + strict: ({ set value(_o) { __classPrivateFieldSet(_g, _YargsInstance_strict, _o, "f"); } }).value, + strictCommands: ({ set value(_o) { __classPrivateFieldSet(_h, _YargsInstance_strictCommands, _o, "f"); } }).value, + strictOptions: ({ set value(_o) { __classPrivateFieldSet(_j, _YargsInstance_strictOptions, _o, "f"); } }).value, + completionCommand: ({ set value(_o) { __classPrivateFieldSet(_k, _YargsInstance_completionCommand, _o, "f"); } }).value, + parseFn: ({ set value(_o) { __classPrivateFieldSet(_l, _YargsInstance_parseFn, _o, "f"); } }).value, + parseContext: ({ set value(_o) { __classPrivateFieldSet(_m, _YargsInstance_parseContext, _o, "f"); } }).value, + } = frozen); + __classPrivateFieldGet(this, _YargsInstance_options, "f").configObjects = configObjects; + __classPrivateFieldGet(this, _YargsInstance_usage, "f").unfreeze(); + __classPrivateFieldGet(this, _YargsInstance_validation, "f").unfreeze(); + __classPrivateFieldGet(this, _YargsInstance_command, "f").unfreeze(); + __classPrivateFieldGet(this, _YargsInstance_globalMiddleware, "f").unfreeze(); + } + [kValidateAsync](validation, argv) { + return maybeAsyncResult(argv, result => { + validation(result); + return result; + }); + } + getInternalMethods() { + return { + getCommandInstance: this[kGetCommandInstance].bind(this), + getContext: this[kGetContext].bind(this), + getHasOutput: this[kGetHasOutput].bind(this), + getLoggerInstance: this[kGetLoggerInstance].bind(this), + getParseContext: this[kGetParseContext].bind(this), + getParserConfiguration: this[kGetParserConfiguration].bind(this), + getUsageConfiguration: this[kGetUsageConfiguration].bind(this), + getUsageInstance: this[kGetUsageInstance].bind(this), + getValidationInstance: this[kGetValidationInstance].bind(this), + hasParseCallback: this[kHasParseCallback].bind(this), + isGlobalContext: this[kIsGlobalContext].bind(this), + postProcess: this[kPostProcess].bind(this), + reset: this[kReset].bind(this), + runValidation: this[kRunValidation].bind(this), + runYargsParserAndExecuteCommands: this[kRunYargsParserAndExecuteCommands].bind(this), + setHasOutput: this[kSetHasOutput].bind(this), + }; + } + [kGetCommandInstance]() { + return __classPrivateFieldGet(this, _YargsInstance_command, "f"); + } + [kGetContext]() { + return __classPrivateFieldGet(this, _YargsInstance_context, "f"); + } + [kGetHasOutput]() { + return __classPrivateFieldGet(this, _YargsInstance_hasOutput, "f"); + } + [kGetLoggerInstance]() { + return __classPrivateFieldGet(this, _YargsInstance_logger, "f"); + } + [kGetParseContext]() { + return __classPrivateFieldGet(this, _YargsInstance_parseContext, "f") || {}; + } + [kGetUsageInstance]() { + return __classPrivateFieldGet(this, _YargsInstance_usage, "f"); + } + [kGetValidationInstance]() { + return __classPrivateFieldGet(this, _YargsInstance_validation, "f"); + } + [kHasParseCallback]() { + return !!__classPrivateFieldGet(this, _YargsInstance_parseFn, "f"); + } + [kIsGlobalContext]() { + return __classPrivateFieldGet(this, _YargsInstance_isGlobalContext, "f"); + } + [kPostProcess](argv, populateDoubleDash, calledFromCommand, runGlobalMiddleware) { + if (calledFromCommand) + return argv; + if (isPromise(argv)) + return argv; + if (!populateDoubleDash) { + argv = this[kCopyDoubleDash](argv); + } + const parsePositionalNumbers = this[kGetParserConfiguration]()['parse-positional-numbers'] || + this[kGetParserConfiguration]()['parse-positional-numbers'] === undefined; + if (parsePositionalNumbers) { + argv = this[kParsePositionalNumbers](argv); + } + if (runGlobalMiddleware) { + argv = applyMiddleware(argv, this, __classPrivateFieldGet(this, _YargsInstance_globalMiddleware, "f").getMiddleware(), false); + } + return argv; + } + [kReset](aliases = {}) { + __classPrivateFieldSet(this, _YargsInstance_options, __classPrivateFieldGet(this, _YargsInstance_options, "f") || {}, "f"); + const tmpOptions = {}; + tmpOptions.local = __classPrivateFieldGet(this, _YargsInstance_options, "f").local || []; + tmpOptions.configObjects = __classPrivateFieldGet(this, _YargsInstance_options, "f").configObjects || []; + const localLookup = {}; + tmpOptions.local.forEach(l => { + localLookup[l] = true; + (aliases[l] || []).forEach(a => { + localLookup[a] = true; + }); + }); + Object.assign(__classPrivateFieldGet(this, _YargsInstance_preservedGroups, "f"), Object.keys(__classPrivateFieldGet(this, _YargsInstance_groups, "f")).reduce((acc, groupName) => { + const keys = __classPrivateFieldGet(this, _YargsInstance_groups, "f")[groupName].filter(key => !(key in localLookup)); + if (keys.length > 0) { + acc[groupName] = keys; + } + return acc; + }, {})); + __classPrivateFieldSet(this, _YargsInstance_groups, {}, "f"); + const arrayOptions = [ + 'array', + 'boolean', + 'string', + 'skipValidation', + 'count', + 'normalize', + 'number', + 'hiddenOptions', + ]; + const objectOptions = [ + 'narg', + 'key', + 'alias', + 'default', + 'defaultDescription', + 'config', + 'choices', + 'demandedOptions', + 'demandedCommands', + 'deprecatedOptions', + ]; + arrayOptions.forEach(k => { + tmpOptions[k] = (__classPrivateFieldGet(this, _YargsInstance_options, "f")[k] || []).filter((k) => !localLookup[k]); + }); + objectOptions.forEach((k) => { + tmpOptions[k] = objFilter(__classPrivateFieldGet(this, _YargsInstance_options, "f")[k], k => !localLookup[k]); + }); + tmpOptions.envPrefix = __classPrivateFieldGet(this, _YargsInstance_options, "f").envPrefix; + __classPrivateFieldSet(this, _YargsInstance_options, tmpOptions, "f"); + __classPrivateFieldSet(this, _YargsInstance_usage, __classPrivateFieldGet(this, _YargsInstance_usage, "f") + ? __classPrivateFieldGet(this, _YargsInstance_usage, "f").reset(localLookup) + : Usage(this, __classPrivateFieldGet(this, _YargsInstance_shim, "f")), "f"); + __classPrivateFieldSet(this, _YargsInstance_validation, __classPrivateFieldGet(this, _YargsInstance_validation, "f") + ? __classPrivateFieldGet(this, _YargsInstance_validation, "f").reset(localLookup) + : Validation(this, __classPrivateFieldGet(this, _YargsInstance_usage, "f"), __classPrivateFieldGet(this, _YargsInstance_shim, "f")), "f"); + __classPrivateFieldSet(this, _YargsInstance_command, __classPrivateFieldGet(this, _YargsInstance_command, "f") + ? __classPrivateFieldGet(this, _YargsInstance_command, "f").reset() + : Command(__classPrivateFieldGet(this, _YargsInstance_usage, "f"), __classPrivateFieldGet(this, _YargsInstance_validation, "f"), __classPrivateFieldGet(this, _YargsInstance_globalMiddleware, "f"), __classPrivateFieldGet(this, _YargsInstance_shim, "f")), "f"); + if (!__classPrivateFieldGet(this, _YargsInstance_completion, "f")) + __classPrivateFieldSet(this, _YargsInstance_completion, Completion(this, __classPrivateFieldGet(this, _YargsInstance_usage, "f"), __classPrivateFieldGet(this, _YargsInstance_command, "f"), __classPrivateFieldGet(this, _YargsInstance_shim, "f")), "f"); + __classPrivateFieldGet(this, _YargsInstance_globalMiddleware, "f").reset(); + __classPrivateFieldSet(this, _YargsInstance_completionCommand, null, "f"); + __classPrivateFieldSet(this, _YargsInstance_output, '', "f"); + __classPrivateFieldSet(this, _YargsInstance_exitError, null, "f"); + __classPrivateFieldSet(this, _YargsInstance_hasOutput, false, "f"); + this.parsed = false; + return this; + } + [kRebase](base, dir) { + return __classPrivateFieldGet(this, _YargsInstance_shim, "f").path.relative(base, dir); + } + [kRunYargsParserAndExecuteCommands](args, shortCircuit, calledFromCommand, commandIndex = 0, helpOnly = false) { + let skipValidation = !!calledFromCommand || helpOnly; + args = args || __classPrivateFieldGet(this, _YargsInstance_processArgs, "f"); + __classPrivateFieldGet(this, _YargsInstance_options, "f").__ = __classPrivateFieldGet(this, _YargsInstance_shim, "f").y18n.__; + __classPrivateFieldGet(this, _YargsInstance_options, "f").configuration = this[kGetParserConfiguration](); + const populateDoubleDash = !!__classPrivateFieldGet(this, _YargsInstance_options, "f").configuration['populate--']; + const config = Object.assign({}, __classPrivateFieldGet(this, _YargsInstance_options, "f").configuration, { + 'populate--': true, + }); + const parsed = __classPrivateFieldGet(this, _YargsInstance_shim, "f").Parser.detailed(args, Object.assign({}, __classPrivateFieldGet(this, _YargsInstance_options, "f"), { + configuration: { 'parse-positional-numbers': false, ...config }, + })); + const argv = Object.assign(parsed.argv, __classPrivateFieldGet(this, _YargsInstance_parseContext, "f")); + let argvPromise = undefined; + const aliases = parsed.aliases; + let helpOptSet = false; + let versionOptSet = false; + Object.keys(argv).forEach(key => { + if (key === __classPrivateFieldGet(this, _YargsInstance_helpOpt, "f") && argv[key]) { + helpOptSet = true; + } + else if (key === __classPrivateFieldGet(this, _YargsInstance_versionOpt, "f") && argv[key]) { + versionOptSet = true; + } + }); + argv.$0 = this.$0; + this.parsed = parsed; + if (commandIndex === 0) { + __classPrivateFieldGet(this, _YargsInstance_usage, "f").clearCachedHelpMessage(); + } + try { + this[kGuessLocale](); + if (shortCircuit) { + return this[kPostProcess](argv, populateDoubleDash, !!calledFromCommand, false); + } + if (__classPrivateFieldGet(this, _YargsInstance_helpOpt, "f")) { + const helpCmds = [__classPrivateFieldGet(this, _YargsInstance_helpOpt, "f")] + .concat(aliases[__classPrivateFieldGet(this, _YargsInstance_helpOpt, "f")] || []) + .filter(k => k.length > 1); + if (helpCmds.includes('' + argv._[argv._.length - 1])) { + argv._.pop(); + helpOptSet = true; + } + } + __classPrivateFieldSet(this, _YargsInstance_isGlobalContext, false, "f"); + const handlerKeys = __classPrivateFieldGet(this, _YargsInstance_command, "f").getCommands(); + const requestCompletions = __classPrivateFieldGet(this, _YargsInstance_completion, "f").completionKey in argv; + const skipRecommendation = helpOptSet || requestCompletions || helpOnly; + if (argv._.length) { + if (handlerKeys.length) { + let firstUnknownCommand; + for (let i = commandIndex || 0, cmd; argv._[i] !== undefined; i++) { + cmd = String(argv._[i]); + if (handlerKeys.includes(cmd) && cmd !== __classPrivateFieldGet(this, _YargsInstance_completionCommand, "f")) { + const innerArgv = __classPrivateFieldGet(this, _YargsInstance_command, "f").runCommand(cmd, this, parsed, i + 1, helpOnly, helpOptSet || versionOptSet || helpOnly); + return this[kPostProcess](innerArgv, populateDoubleDash, !!calledFromCommand, false); + } + else if (!firstUnknownCommand && + cmd !== __classPrivateFieldGet(this, _YargsInstance_completionCommand, "f")) { + firstUnknownCommand = cmd; + break; + } + } + if (!__classPrivateFieldGet(this, _YargsInstance_command, "f").hasDefaultCommand() && + __classPrivateFieldGet(this, _YargsInstance_recommendCommands, "f") && + firstUnknownCommand && + !skipRecommendation) { + __classPrivateFieldGet(this, _YargsInstance_validation, "f").recommendCommands(firstUnknownCommand, handlerKeys); + } + } + if (__classPrivateFieldGet(this, _YargsInstance_completionCommand, "f") && + argv._.includes(__classPrivateFieldGet(this, _YargsInstance_completionCommand, "f")) && + !requestCompletions) { + if (__classPrivateFieldGet(this, _YargsInstance_exitProcess, "f")) + setBlocking(true); + this.showCompletionScript(); + this.exit(0); + } + } + if (__classPrivateFieldGet(this, _YargsInstance_command, "f").hasDefaultCommand() && !skipRecommendation) { + const innerArgv = __classPrivateFieldGet(this, _YargsInstance_command, "f").runCommand(null, this, parsed, 0, helpOnly, helpOptSet || versionOptSet || helpOnly); + return this[kPostProcess](innerArgv, populateDoubleDash, !!calledFromCommand, false); + } + if (requestCompletions) { + if (__classPrivateFieldGet(this, _YargsInstance_exitProcess, "f")) + setBlocking(true); + args = [].concat(args); + const completionArgs = args.slice(args.indexOf(`--${__classPrivateFieldGet(this, _YargsInstance_completion, "f").completionKey}`) + 1); + __classPrivateFieldGet(this, _YargsInstance_completion, "f").getCompletion(completionArgs, (err, completions) => { + if (err) + throw new YError(err.message); + (completions || []).forEach(completion => { + __classPrivateFieldGet(this, _YargsInstance_logger, "f").log(completion); + }); + this.exit(0); + }); + return this[kPostProcess](argv, !populateDoubleDash, !!calledFromCommand, false); + } + if (!__classPrivateFieldGet(this, _YargsInstance_hasOutput, "f")) { + if (helpOptSet) { + if (__classPrivateFieldGet(this, _YargsInstance_exitProcess, "f")) + setBlocking(true); + skipValidation = true; + this.showHelp('log'); + this.exit(0); + } + else if (versionOptSet) { + if (__classPrivateFieldGet(this, _YargsInstance_exitProcess, "f")) + setBlocking(true); + skipValidation = true; + __classPrivateFieldGet(this, _YargsInstance_usage, "f").showVersion('log'); + this.exit(0); + } + } + if (!skipValidation && __classPrivateFieldGet(this, _YargsInstance_options, "f").skipValidation.length > 0) { + skipValidation = Object.keys(argv).some(key => __classPrivateFieldGet(this, _YargsInstance_options, "f").skipValidation.indexOf(key) >= 0 && argv[key] === true); + } + if (!skipValidation) { + if (parsed.error) + throw new YError(parsed.error.message); + if (!requestCompletions) { + const validation = this[kRunValidation](aliases, {}, parsed.error); + if (!calledFromCommand) { + argvPromise = applyMiddleware(argv, this, __classPrivateFieldGet(this, _YargsInstance_globalMiddleware, "f").getMiddleware(), true); + } + argvPromise = this[kValidateAsync](validation, argvPromise !== null && argvPromise !== void 0 ? argvPromise : argv); + if (isPromise(argvPromise) && !calledFromCommand) { + argvPromise = argvPromise.then(() => { + return applyMiddleware(argv, this, __classPrivateFieldGet(this, _YargsInstance_globalMiddleware, "f").getMiddleware(), false); + }); + } + } + } + } + catch (err) { + if (err instanceof YError) + __classPrivateFieldGet(this, _YargsInstance_usage, "f").fail(err.message, err); + else + throw err; + } + return this[kPostProcess](argvPromise !== null && argvPromise !== void 0 ? argvPromise : argv, populateDoubleDash, !!calledFromCommand, true); + } + [kRunValidation](aliases, positionalMap, parseErrors, isDefaultCommand) { + const demandedOptions = { ...this.getDemandedOptions() }; + return (argv) => { + if (parseErrors) + throw new YError(parseErrors.message); + __classPrivateFieldGet(this, _YargsInstance_validation, "f").nonOptionCount(argv); + __classPrivateFieldGet(this, _YargsInstance_validation, "f").requiredArguments(argv, demandedOptions); + let failedStrictCommands = false; + if (__classPrivateFieldGet(this, _YargsInstance_strictCommands, "f")) { + failedStrictCommands = __classPrivateFieldGet(this, _YargsInstance_validation, "f").unknownCommands(argv); + } + if (__classPrivateFieldGet(this, _YargsInstance_strict, "f") && !failedStrictCommands) { + __classPrivateFieldGet(this, _YargsInstance_validation, "f").unknownArguments(argv, aliases, positionalMap, !!isDefaultCommand); + } + else if (__classPrivateFieldGet(this, _YargsInstance_strictOptions, "f")) { + __classPrivateFieldGet(this, _YargsInstance_validation, "f").unknownArguments(argv, aliases, {}, false, false); + } + __classPrivateFieldGet(this, _YargsInstance_validation, "f").limitedChoices(argv); + __classPrivateFieldGet(this, _YargsInstance_validation, "f").implications(argv); + __classPrivateFieldGet(this, _YargsInstance_validation, "f").conflicting(argv); + }; + } + [kSetHasOutput]() { + __classPrivateFieldSet(this, _YargsInstance_hasOutput, true, "f"); + } + [kTrackManuallySetKeys](keys) { + if (typeof keys === 'string') { + __classPrivateFieldGet(this, _YargsInstance_options, "f").key[keys] = true; + } + else { + for (const k of keys) { + __classPrivateFieldGet(this, _YargsInstance_options, "f").key[k] = true; + } + } + } +} +export function isYargsInstance(y) { + return !!y && typeof y.getInternalMethods === 'function'; +} diff --git a/node_modules/yargs/build/lib/yerror.js b/node_modules/yargs/build/lib/yerror.js new file mode 100644 index 0000000..7a36684 --- /dev/null +++ b/node_modules/yargs/build/lib/yerror.js @@ -0,0 +1,9 @@ +export class YError extends Error { + constructor(msg) { + super(msg || 'yargs error'); + this.name = 'YError'; + if (Error.captureStackTrace) { + Error.captureStackTrace(this, YError); + } + } +} diff --git a/node_modules/yargs/helpers/helpers.mjs b/node_modules/yargs/helpers/helpers.mjs new file mode 100644 index 0000000..3f96b3d --- /dev/null +++ b/node_modules/yargs/helpers/helpers.mjs @@ -0,0 +1,10 @@ +import {applyExtends as _applyExtends} from '../build/lib/utils/apply-extends.js'; +import {hideBin} from '../build/lib/utils/process-argv.js'; +import Parser from 'yargs-parser'; +import shim from '../lib/platform-shims/esm.mjs'; + +const applyExtends = (config, cwd, mergeExtends) => { + return _applyExtends(config, cwd, mergeExtends, shim); +}; + +export {applyExtends, hideBin, Parser}; diff --git a/node_modules/yargs/helpers/index.js b/node_modules/yargs/helpers/index.js new file mode 100644 index 0000000..8ab79a3 --- /dev/null +++ b/node_modules/yargs/helpers/index.js @@ -0,0 +1,14 @@ +const { + applyExtends, + cjsPlatformShim, + Parser, + processArgv, +} = require('../build/index.cjs'); + +module.exports = { + applyExtends: (config, cwd, mergeExtends) => { + return applyExtends(config, cwd, mergeExtends, cjsPlatformShim); + }, + hideBin: processArgv.hideBin, + Parser, +}; diff --git a/node_modules/yargs/helpers/package.json b/node_modules/yargs/helpers/package.json new file mode 100644 index 0000000..5bbefff --- /dev/null +++ b/node_modules/yargs/helpers/package.json @@ -0,0 +1,3 @@ +{ + "type": "commonjs" +} diff --git a/node_modules/yargs/index.cjs b/node_modules/yargs/index.cjs new file mode 100644 index 0000000..d1eee82 --- /dev/null +++ b/node_modules/yargs/index.cjs @@ -0,0 +1,53 @@ +'use strict'; +// classic singleton yargs API, to use yargs +// without running as a singleton do: +// require('yargs/yargs')(process.argv.slice(2)) +const {Yargs, processArgv} = require('./build/index.cjs'); + +Argv(processArgv.hideBin(process.argv)); + +module.exports = Argv; + +function Argv(processArgs, cwd) { + const argv = Yargs(processArgs, cwd, require); + singletonify(argv); + // TODO(bcoe): warn if argv.parse() or argv.argv is used directly. + return argv; +} + +function defineGetter(obj, key, getter) { + Object.defineProperty(obj, key, { + configurable: true, + enumerable: true, + get: getter, + }); +} +function lookupGetter(obj, key) { + const desc = Object.getOwnPropertyDescriptor(obj, key); + if (typeof desc !== 'undefined') { + return desc.get; + } +} + +/* Hack an instance of Argv with process.argv into Argv + so people can do + require('yargs')(['--beeble=1','-z','zizzle']).argv + to parse a list of args and + require('yargs').argv + to get a parsed version of process.argv. +*/ +function singletonify(inst) { + [ + ...Object.keys(inst), + ...Object.getOwnPropertyNames(inst.constructor.prototype), + ].forEach(key => { + if (key === 'argv') { + defineGetter(Argv, key, lookupGetter(inst, key)); + } else if (typeof inst[key] === 'function') { + Argv[key] = inst[key].bind(inst); + } else { + defineGetter(Argv, '$0', () => inst.$0); + defineGetter(Argv, 'parsed', () => inst.parsed); + } + }); +} diff --git a/node_modules/yargs/index.mjs b/node_modules/yargs/index.mjs new file mode 100644 index 0000000..c6440b9 --- /dev/null +++ b/node_modules/yargs/index.mjs @@ -0,0 +1,8 @@ +'use strict'; + +// Bootstraps yargs for ESM: +import esmPlatformShim from './lib/platform-shims/esm.mjs'; +import {YargsFactory} from './build/lib/yargs-factory.js'; + +const Yargs = YargsFactory(esmPlatformShim); +export default Yargs; diff --git a/node_modules/yargs/lib/platform-shims/browser.mjs b/node_modules/yargs/lib/platform-shims/browser.mjs new file mode 100644 index 0000000..5f8ec61 --- /dev/null +++ b/node_modules/yargs/lib/platform-shims/browser.mjs @@ -0,0 +1,95 @@ +/* eslint-disable no-unused-vars */ +'use strict'; + +import cliui from 'https://unpkg.com/cliui@7.0.1/index.mjs'; // eslint-disable-line +import Parser from 'https://unpkg.com/yargs-parser@19.0.0/browser.js'; // eslint-disable-line +import {getProcessArgvBin} from '../../build/lib/utils/process-argv.js'; +import {YError} from '../../build/lib/yerror.js'; + +const REQUIRE_ERROR = 'require is not supported in browser'; +const REQUIRE_DIRECTORY_ERROR = + 'loading a directory of commands is not supported in browser'; + +export default { + assert: { + notStrictEqual: (a, b) => { + // noop. + }, + strictEqual: (a, b) => { + // noop. + }, + }, + cliui, + findUp: () => undefined, + getEnv: key => { + // There is no environment in browser: + return undefined; + }, + inspect: console.log, + getCallerFile: () => { + throw new YError(REQUIRE_DIRECTORY_ERROR); + }, + getProcessArgvBin, + mainFilename: 'yargs', + Parser, + path: { + basename: str => str, + dirname: str => str, + extname: str => str, + relative: str => str, + }, + process: { + argv: () => [], + cwd: () => '', + emitWarning: (warning, name) => {}, + execPath: () => '', + // exit is noop browser: + exit: () => {}, + nextTick: cb => { + // eslint-disable-next-line no-undef + window.setTimeout(cb, 1); + }, + stdColumns: 80, + }, + readFileSync: () => { + return ''; + }, + require: () => { + throw new YError(REQUIRE_ERROR); + }, + requireDirectory: () => { + throw new YError(REQUIRE_DIRECTORY_ERROR); + }, + stringWidth: str => { + return [...str].length; + }, + // TODO: replace this with y18n once it's ported to ESM: + y18n: { + __: (...str) => { + if (str.length === 0) return ''; + const args = str.slice(1); + return sprintf(str[0], ...args); + }, + __n: (str1, str2, count, ...args) => { + if (count === 1) { + return sprintf(str1, ...args); + } else { + return sprintf(str2, ...args); + } + }, + getLocale: () => { + return 'en_US'; + }, + setLocale: () => {}, + updateLocale: () => {}, + }, +}; + +function sprintf(_str, ...args) { + let str = ''; + const split = _str.split('%s'); + split.forEach((token, i) => { + str += `${token}${split[i + 1] !== undefined && args[i] ? args[i] : ''}`; + }); + return str; +} diff --git a/node_modules/yargs/lib/platform-shims/esm.mjs b/node_modules/yargs/lib/platform-shims/esm.mjs new file mode 100644 index 0000000..c25baa5 --- /dev/null +++ b/node_modules/yargs/lib/platform-shims/esm.mjs @@ -0,0 +1,73 @@ +'use strict' + +import { notStrictEqual, strictEqual } from 'assert' +import cliui from 'cliui' +import escalade from 'escalade/sync' +import { inspect } from 'util' +import { readFileSync } from 'fs' +import { fileURLToPath } from 'url'; +import Parser from 'yargs-parser' +import { basename, dirname, extname, relative, resolve } from 'path' +import { getProcessArgvBin } from '../../build/lib/utils/process-argv.js' +import { YError } from '../../build/lib/yerror.js' +import y18n from 'y18n' + +const REQUIRE_ERROR = 'require is not supported by ESM' +const REQUIRE_DIRECTORY_ERROR = 'loading a directory of commands is not supported yet for ESM' + +let __dirname; +try { + __dirname = fileURLToPath(import.meta.url); +} catch (e) { + __dirname = process.cwd(); +} +const mainFilename = __dirname.substring(0, __dirname.lastIndexOf('node_modules')); + +export default { + assert: { + notStrictEqual, + strictEqual + }, + cliui, + findUp: escalade, + getEnv: (key) => { + return process.env[key] + }, + inspect, + getCallerFile: () => { + throw new YError(REQUIRE_DIRECTORY_ERROR) + }, + getProcessArgvBin, + mainFilename: mainFilename || process.cwd(), + Parser, + path: { + basename, + dirname, + extname, + relative, + resolve + }, + process: { + argv: () => process.argv, + cwd: process.cwd, + emitWarning: (warning, type) => process.emitWarning(warning, type), + execPath: () => process.execPath, + exit: process.exit, + nextTick: process.nextTick, + stdColumns: typeof process.stdout.columns !== 'undefined' ? process.stdout.columns : null + }, + readFileSync, + require: () => { + throw new YError(REQUIRE_ERROR) + }, + requireDirectory: () => { + throw new YError(REQUIRE_DIRECTORY_ERROR) + }, + stringWidth: (str) => { + return [...str].length + }, + y18n: y18n({ + directory: resolve(__dirname, '../../../locales'), + updateFiles: false + }) +} diff --git a/node_modules/yargs/locales/be.json b/node_modules/yargs/locales/be.json new file mode 100644 index 0000000..e28fa30 --- /dev/null +++ b/node_modules/yargs/locales/be.json @@ -0,0 +1,46 @@ +{ + "Commands:": "Каманды:", + "Options:": "Опцыі:", + "Examples:": "Прыклады:", + "boolean": "булевы тып", + "count": "падлік", + "string": "радковы тып", + "number": "лік", + "array": "масіў", + "required": "неабходна", + "default": "па змаўчанні", + "default:": "па змаўчанні:", + "choices:": "магчымасці:", + "aliases:": "аліасы:", + "generated-value": "згенераванае значэнне", + "Not enough non-option arguments: got %s, need at least %s": { + "one": "Недастаткова неапцыйных аргументаў: ёсць %s, трэба як мінімум %s", + "other": "Недастаткова неапцыйных аргументаў: ёсць %s, трэба як мінімум %s" + }, + "Too many non-option arguments: got %s, maximum of %s": { + "one": "Занадта шмат неапцыйных аргументаў: ёсць %s, максімум дапушчальна %s", + "other": "Занадта шмат неапцыйных аргументаў: ёсць %s, максімум дапушчальна %s" + }, + "Missing argument value: %s": { + "one": "Не хапае значэння аргументу: %s", + "other": "Не хапае значэнняў аргументаў: %s" + }, + "Missing required argument: %s": { + "one": "Не хапае неабходнага аргументу: %s", + "other": "Не хапае неабходных аргументаў: %s" + }, + "Unknown argument: %s": { + "one": "Невядомы аргумент: %s", + "other": "Невядомыя аргументы: %s" + }, + "Invalid values:": "Несапраўдныя значэння:", + "Argument: %s, Given: %s, Choices: %s": "Аргумент: %s, Дадзенае значэнне: %s, Магчымасці: %s", + "Argument check failed: %s": "Праверка аргументаў не ўдалася: %s", + "Implications failed:": "Дадзены аргумент патрабуе наступны дадатковы аргумент:", + "Not enough arguments following: %s": "Недастаткова наступных аргументаў: %s", + "Invalid JSON config file: %s": "Несапраўдны файл канфігурацыі JSON: %s", + "Path to JSON config file": "Шлях да файла канфігурацыі JSON", + "Show help": "Паказаць дапамогу", + "Show version number": "Паказаць нумар версіі", + "Did you mean %s?": "Вы мелі на ўвазе %s?" +} diff --git a/node_modules/yargs/locales/cs.json b/node_modules/yargs/locales/cs.json new file mode 100644 index 0000000..6394875 --- /dev/null +++ b/node_modules/yargs/locales/cs.json @@ -0,0 +1,51 @@ +{ + "Commands:": "Příkazy:", + "Options:": "Možnosti:", + "Examples:": "Příklady:", + "boolean": "logická hodnota", + "count": "počet", + "string": "řetězec", + "number": "číslo", + "array": "pole", + "required": "povinné", + "default": "výchozí", + "default:": "výchozí:", + "choices:": "volby:", + "aliases:": "aliasy:", + "generated-value": "generovaná-hodnota", + "Not enough non-option arguments: got %s, need at least %s": { + "one": "Nedostatek argumentů: zadáno %s, je potřeba alespoň %s", + "other": "Nedostatek argumentů: zadáno %s, je potřeba alespoň %s" + }, + "Too many non-option arguments: got %s, maximum of %s": { + "one": "Příliš mnoho argumentů: zadáno %s, maximálně %s", + "other": "Příliš mnoho argumentů: zadáno %s, maximálně %s" + }, + "Missing argument value: %s": { + "one": "Chybí hodnota argumentu: %s", + "other": "Chybí hodnoty argumentů: %s" + }, + "Missing required argument: %s": { + "one": "Chybí požadovaný argument: %s", + "other": "Chybí požadované argumenty: %s" + }, + "Unknown argument: %s": { + "one": "Neznámý argument: %s", + "other": "Neznámé argumenty: %s" + }, + "Invalid values:": "Neplatné hodnoty:", + "Argument: %s, Given: %s, Choices: %s": "Argument: %s, Zadáno: %s, Možnosti: %s", + "Argument check failed: %s": "Kontrola argumentů se nezdařila: %s", + "Implications failed:": "Chybí závislé argumenty:", + "Not enough arguments following: %s": "Následuje nedostatek argumentů: %s", + "Invalid JSON config file: %s": "Neplatný konfigurační soubor JSON: %s", + "Path to JSON config file": "Cesta ke konfiguračnímu souboru JSON", + "Show help": "Zobrazit nápovědu", + "Show version number": "Zobrazit číslo verze", + "Did you mean %s?": "Měl jste na mysli %s?", + "Arguments %s and %s are mutually exclusive" : "Argumenty %s a %s se vzájemně vylučují", + "Positionals:": "Poziční:", + "command": "příkaz", + "deprecated": "zastaralé", + "deprecated: %s": "zastaralé: %s" +} diff --git a/node_modules/yargs/locales/de.json b/node_modules/yargs/locales/de.json new file mode 100644 index 0000000..dc73ec3 --- /dev/null +++ b/node_modules/yargs/locales/de.json @@ -0,0 +1,46 @@ +{ + "Commands:": "Kommandos:", + "Options:": "Optionen:", + "Examples:": "Beispiele:", + "boolean": "boolean", + "count": "Zähler", + "string": "string", + "number": "Zahl", + "array": "array", + "required": "erforderlich", + "default": "Standard", + "default:": "Standard:", + "choices:": "Möglichkeiten:", + "aliases:": "Aliase:", + "generated-value": "Generierter-Wert", + "Not enough non-option arguments: got %s, need at least %s": { + "one": "Nicht genügend Argumente ohne Optionen: %s vorhanden, mindestens %s benötigt", + "other": "Nicht genügend Argumente ohne Optionen: %s vorhanden, mindestens %s benötigt" + }, + "Too many non-option arguments: got %s, maximum of %s": { + "one": "Zu viele Argumente ohne Optionen: %s vorhanden, maximal %s erlaubt", + "other": "Zu viele Argumente ohne Optionen: %s vorhanden, maximal %s erlaubt" + }, + "Missing argument value: %s": { + "one": "Fehlender Argumentwert: %s", + "other": "Fehlende Argumentwerte: %s" + }, + "Missing required argument: %s": { + "one": "Fehlendes Argument: %s", + "other": "Fehlende Argumente: %s" + }, + "Unknown argument: %s": { + "one": "Unbekanntes Argument: %s", + "other": "Unbekannte Argumente: %s" + }, + "Invalid values:": "Unzulässige Werte:", + "Argument: %s, Given: %s, Choices: %s": "Argument: %s, Gegeben: %s, Möglichkeiten: %s", + "Argument check failed: %s": "Argumente-Check fehlgeschlagen: %s", + "Implications failed:": "Fehlende abhängige Argumente:", + "Not enough arguments following: %s": "Nicht genügend Argumente nach: %s", + "Invalid JSON config file: %s": "Fehlerhafte JSON-Config Datei: %s", + "Path to JSON config file": "Pfad zur JSON-Config Datei", + "Show help": "Hilfe anzeigen", + "Show version number": "Version anzeigen", + "Did you mean %s?": "Meintest du %s?" +} diff --git a/node_modules/yargs/locales/en.json b/node_modules/yargs/locales/en.json new file mode 100644 index 0000000..af096a1 --- /dev/null +++ b/node_modules/yargs/locales/en.json @@ -0,0 +1,55 @@ +{ + "Commands:": "Commands:", + "Options:": "Options:", + "Examples:": "Examples:", + "boolean": "boolean", + "count": "count", + "string": "string", + "number": "number", + "array": "array", + "required": "required", + "default": "default", + "default:": "default:", + "choices:": "choices:", + "aliases:": "aliases:", + "generated-value": "generated-value", + "Not enough non-option arguments: got %s, need at least %s": { + "one": "Not enough non-option arguments: got %s, need at least %s", + "other": "Not enough non-option arguments: got %s, need at least %s" + }, + "Too many non-option arguments: got %s, maximum of %s": { + "one": "Too many non-option arguments: got %s, maximum of %s", + "other": "Too many non-option arguments: got %s, maximum of %s" + }, + "Missing argument value: %s": { + "one": "Missing argument value: %s", + "other": "Missing argument values: %s" + }, + "Missing required argument: %s": { + "one": "Missing required argument: %s", + "other": "Missing required arguments: %s" + }, + "Unknown argument: %s": { + "one": "Unknown argument: %s", + "other": "Unknown arguments: %s" + }, + "Unknown command: %s": { + "one": "Unknown command: %s", + "other": "Unknown commands: %s" + }, + "Invalid values:": "Invalid values:", + "Argument: %s, Given: %s, Choices: %s": "Argument: %s, Given: %s, Choices: %s", + "Argument check failed: %s": "Argument check failed: %s", + "Implications failed:": "Missing dependent arguments:", + "Not enough arguments following: %s": "Not enough arguments following: %s", + "Invalid JSON config file: %s": "Invalid JSON config file: %s", + "Path to JSON config file": "Path to JSON config file", + "Show help": "Show help", + "Show version number": "Show version number", + "Did you mean %s?": "Did you mean %s?", + "Arguments %s and %s are mutually exclusive" : "Arguments %s and %s are mutually exclusive", + "Positionals:": "Positionals:", + "command": "command", + "deprecated": "deprecated", + "deprecated: %s": "deprecated: %s" +} diff --git a/node_modules/yargs/locales/es.json b/node_modules/yargs/locales/es.json new file mode 100644 index 0000000..d77b461 --- /dev/null +++ b/node_modules/yargs/locales/es.json @@ -0,0 +1,46 @@ +{ + "Commands:": "Comandos:", + "Options:": "Opciones:", + "Examples:": "Ejemplos:", + "boolean": "booleano", + "count": "cuenta", + "string": "cadena de caracteres", + "number": "número", + "array": "tabla", + "required": "requerido", + "default": "defecto", + "default:": "defecto:", + "choices:": "selección:", + "aliases:": "alias:", + "generated-value": "valor-generado", + "Not enough non-option arguments: got %s, need at least %s": { + "one": "Hacen falta argumentos no-opcionales: Número recibido %s, necesita por lo menos %s", + "other": "Hacen falta argumentos no-opcionales: Número recibido %s, necesita por lo menos %s" + }, + "Too many non-option arguments: got %s, maximum of %s": { + "one": "Demasiados argumentos no-opcionales: Número recibido %s, máximo es %s", + "other": "Demasiados argumentos no-opcionales: Número recibido %s, máximo es %s" + }, + "Missing argument value: %s": { + "one": "Falta argumento: %s", + "other": "Faltan argumentos: %s" + }, + "Missing required argument: %s": { + "one": "Falta argumento requerido: %s", + "other": "Faltan argumentos requeridos: %s" + }, + "Unknown argument: %s": { + "one": "Argumento desconocido: %s", + "other": "Argumentos desconocidos: %s" + }, + "Invalid values:": "Valores inválidos:", + "Argument: %s, Given: %s, Choices: %s": "Argumento: %s, Recibido: %s, Seleccionados: %s", + "Argument check failed: %s": "Verificación de argumento ha fallado: %s", + "Implications failed:": "Implicaciones fallidas:", + "Not enough arguments following: %s": "No hay suficientes argumentos después de: %s", + "Invalid JSON config file: %s": "Archivo de configuración JSON inválido: %s", + "Path to JSON config file": "Ruta al archivo de configuración JSON", + "Show help": "Muestra ayuda", + "Show version number": "Muestra número de versión", + "Did you mean %s?": "Quisiste decir %s?" +} diff --git a/node_modules/yargs/locales/fi.json b/node_modules/yargs/locales/fi.json new file mode 100644 index 0000000..481feb7 --- /dev/null +++ b/node_modules/yargs/locales/fi.json @@ -0,0 +1,49 @@ +{ + "Commands:": "Komennot:", + "Options:": "Valinnat:", + "Examples:": "Esimerkkejä:", + "boolean": "totuusarvo", + "count": "lukumäärä", + "string": "merkkijono", + "number": "numero", + "array": "taulukko", + "required": "pakollinen", + "default": "oletusarvo", + "default:": "oletusarvo:", + "choices:": "vaihtoehdot:", + "aliases:": "aliakset:", + "generated-value": "generoitu-arvo", + "Not enough non-option arguments: got %s, need at least %s": { + "one": "Liian vähän argumentteja, jotka eivät ole valintoja: annettu %s, vaaditaan vähintään %s", + "other": "Liian vähän argumentteja, jotka eivät ole valintoja: annettu %s, vaaditaan vähintään %s" + }, + "Too many non-option arguments: got %s, maximum of %s": { + "one": "Liikaa argumentteja, jotka eivät ole valintoja: annettu %s, sallitaan enintään %s", + "other": "Liikaa argumentteja, jotka eivät ole valintoja: annettu %s, sallitaan enintään %s" + }, + "Missing argument value: %s": { + "one": "Argumentin arvo puuttuu: %s", + "other": "Argumentin arvot puuttuvat: %s" + }, + "Missing required argument: %s": { + "one": "Pakollinen argumentti puuttuu: %s", + "other": "Pakollisia argumentteja puuttuu: %s" + }, + "Unknown argument: %s": { + "one": "Tuntematon argumentti: %s", + "other": "Tuntemattomia argumentteja: %s" + }, + "Invalid values:": "Virheelliset arvot:", + "Argument: %s, Given: %s, Choices: %s": "Argumentti: %s, Annettu: %s, Vaihtoehdot: %s", + "Argument check failed: %s": "Argumentin tarkistus epäonnistui: %s", + "Implications failed:": "Riippuvia argumentteja puuttuu:", + "Not enough arguments following: %s": "Argumentin perässä ei ole tarpeeksi argumentteja: %s", + "Invalid JSON config file: %s": "Epävalidi JSON-asetustiedosto: %s", + "Path to JSON config file": "JSON-asetustiedoston polku", + "Show help": "Näytä ohje", + "Show version number": "Näytä versionumero", + "Did you mean %s?": "Tarkoititko %s?", + "Arguments %s and %s are mutually exclusive" : "Argumentit %s ja %s eivät ole yhteensopivat", + "Positionals:": "Sijaintiparametrit:", + "command": "komento" +} diff --git a/node_modules/yargs/locales/fr.json b/node_modules/yargs/locales/fr.json new file mode 100644 index 0000000..edd743f --- /dev/null +++ b/node_modules/yargs/locales/fr.json @@ -0,0 +1,53 @@ +{ + "Commands:": "Commandes :", + "Options:": "Options :", + "Examples:": "Exemples :", + "boolean": "booléen", + "count": "compteur", + "string": "chaîne de caractères", + "number": "nombre", + "array": "tableau", + "required": "requis", + "default": "défaut", + "default:": "défaut :", + "choices:": "choix :", + "aliases:": "alias :", + "generated-value": "valeur générée", + "Not enough non-option arguments: got %s, need at least %s": { + "one": "Pas assez d'arguments (hors options) : reçu %s, besoin d'au moins %s", + "other": "Pas assez d'arguments (hors options) : reçus %s, besoin d'au moins %s" + }, + "Too many non-option arguments: got %s, maximum of %s": { + "one": "Trop d'arguments (hors options) : reçu %s, maximum de %s", + "other": "Trop d'arguments (hors options) : reçus %s, maximum de %s" + }, + "Missing argument value: %s": { + "one": "Argument manquant : %s", + "other": "Arguments manquants : %s" + }, + "Missing required argument: %s": { + "one": "Argument requis manquant : %s", + "other": "Arguments requis manquants : %s" + }, + "Unknown argument: %s": { + "one": "Argument inconnu : %s", + "other": "Arguments inconnus : %s" + }, + "Unknown command: %s": { + "one": "Commande inconnue : %s", + "other": "Commandes inconnues : %s" + }, + "Invalid values:": "Valeurs invalides :", + "Argument: %s, Given: %s, Choices: %s": "Argument : %s, donné : %s, choix : %s", + "Argument check failed: %s": "Echec de la vérification de l'argument : %s", + "Implications failed:": "Arguments dépendants manquants :", + "Not enough arguments following: %s": "Pas assez d'arguments après : %s", + "Invalid JSON config file: %s": "Fichier de configuration JSON invalide : %s", + "Path to JSON config file": "Chemin du fichier de configuration JSON", + "Show help": "Affiche l'aide", + "Show version number": "Affiche le numéro de version", + "Did you mean %s?": "Vouliez-vous dire %s ?", + "Arguments %s and %s are mutually exclusive" : "Les arguments %s et %s sont mutuellement exclusifs", + "Positionals:": "Arguments positionnels :", + "command": "commande" +} diff --git a/node_modules/yargs/locales/hi.json b/node_modules/yargs/locales/hi.json new file mode 100644 index 0000000..a9de77c --- /dev/null +++ b/node_modules/yargs/locales/hi.json @@ -0,0 +1,49 @@ +{ + "Commands:": "आदेश:", + "Options:": "विकल्प:", + "Examples:": "उदाहरण:", + "boolean": "सत्यता", + "count": "संख्या", + "string": "वर्णों का तार ", + "number": "अंक", + "array": "सरणी", + "required": "आवश्यक", + "default": "डिफॉल्ट", + "default:": "डिफॉल्ट:", + "choices:": "विकल्प:", + "aliases:": "उपनाम:", + "generated-value": "उत्पन्न-मूल्य", + "Not enough non-option arguments: got %s, need at least %s": { + "one": "पर्याप्त गैर-विकल्प तर्क प्राप्त नहीं: %s प्राप्त, कम से कम %s की आवश्यकता है", + "other": "पर्याप्त गैर-विकल्प तर्क प्राप्त नहीं: %s प्राप्त, कम से कम %s की आवश्यकता है" + }, + "Too many non-option arguments: got %s, maximum of %s": { + "one": "बहुत सारे गैर-विकल्प तर्क: %s प्राप्त, अधिकतम %s मान्य", + "other": "बहुत सारे गैर-विकल्प तर्क: %s प्राप्त, अधिकतम %s मान्य" + }, + "Missing argument value: %s": { + "one": "कुछ तर्को के मूल्य गुम हैं: %s", + "other": "कुछ तर्को के मूल्य गुम हैं: %s" + }, + "Missing required argument: %s": { + "one": "आवश्यक तर्क गुम हैं: %s", + "other": "आवश्यक तर्क गुम हैं: %s" + }, + "Unknown argument: %s": { + "one": "अज्ञात तर्क प्राप्त: %s", + "other": "अज्ञात तर्क प्राप्त: %s" + }, + "Invalid values:": "अमान्य मूल्य:", + "Argument: %s, Given: %s, Choices: %s": "तर्क: %s, प्राप्त: %s, विकल्प: %s", + "Argument check failed: %s": "तर्क जांच विफल: %s", + "Implications failed:": "दिए गए तर्क के लिए अतिरिक्त तर्क की अपेक्षा है:", + "Not enough arguments following: %s": "निम्नलिखित के बाद पर्याप्त तर्क नहीं प्राप्त: %s", + "Invalid JSON config file: %s": "अमान्य JSON config फाइल: %s", + "Path to JSON config file": "JSON config फाइल का पथ", + "Show help": "सहायता दिखाएँ", + "Show version number": "Version संख्या दिखाएँ", + "Did you mean %s?": "क्या आपका मतलब है %s?", + "Arguments %s and %s are mutually exclusive" : "तर्क %s और %s परस्पर अनन्य हैं", + "Positionals:": "स्थानीय:", + "command": "आदेश" +} diff --git a/node_modules/yargs/locales/hu.json b/node_modules/yargs/locales/hu.json new file mode 100644 index 0000000..21492d0 --- /dev/null +++ b/node_modules/yargs/locales/hu.json @@ -0,0 +1,46 @@ +{ + "Commands:": "Parancsok:", + "Options:": "Opciók:", + "Examples:": "Példák:", + "boolean": "boolean", + "count": "számláló", + "string": "szöveg", + "number": "szám", + "array": "tömb", + "required": "kötelező", + "default": "alapértelmezett", + "default:": "alapértelmezett:", + "choices:": "lehetőségek:", + "aliases:": "aliaszok:", + "generated-value": "generált-érték", + "Not enough non-option arguments: got %s, need at least %s": { + "one": "Nincs elég nem opcionális argumentum: %s van, legalább %s kell", + "other": "Nincs elég nem opcionális argumentum: %s van, legalább %s kell" + }, + "Too many non-option arguments: got %s, maximum of %s": { + "one": "Túl sok nem opciánlis argumentum van: %s van, maximum %s lehet", + "other": "Túl sok nem opciánlis argumentum van: %s van, maximum %s lehet" + }, + "Missing argument value: %s": { + "one": "Hiányzó argumentum érték: %s", + "other": "Hiányzó argumentum értékek: %s" + }, + "Missing required argument: %s": { + "one": "Hiányzó kötelező argumentum: %s", + "other": "Hiányzó kötelező argumentumok: %s" + }, + "Unknown argument: %s": { + "one": "Ismeretlen argumentum: %s", + "other": "Ismeretlen argumentumok: %s" + }, + "Invalid values:": "Érvénytelen érték:", + "Argument: %s, Given: %s, Choices: %s": "Argumentum: %s, Megadott: %s, Lehetőségek: %s", + "Argument check failed: %s": "Argumentum ellenőrzés sikertelen: %s", + "Implications failed:": "Implikációk sikertelenek:", + "Not enough arguments following: %s": "Nem elég argumentum követi: %s", + "Invalid JSON config file: %s": "Érvénytelen JSON konfigurációs file: %s", + "Path to JSON config file": "JSON konfigurációs file helye", + "Show help": "Súgo megjelenítése", + "Show version number": "Verziószám megjelenítése", + "Did you mean %s?": "Erre gondoltál %s?" +} diff --git a/node_modules/yargs/locales/id.json b/node_modules/yargs/locales/id.json new file mode 100644 index 0000000..125867c --- /dev/null +++ b/node_modules/yargs/locales/id.json @@ -0,0 +1,50 @@ + +{ + "Commands:": "Perintah:", + "Options:": "Pilihan:", + "Examples:": "Contoh:", + "boolean": "boolean", + "count": "jumlah", + "number": "nomor", + "string": "string", + "array": "larik", + "required": "diperlukan", + "default": "bawaan", + "default:": "bawaan:", + "aliases:": "istilah lain:", + "choices:": "pilihan:", + "generated-value": "nilai-yang-dihasilkan", + "Not enough non-option arguments: got %s, need at least %s": { + "one": "Argumen wajib kurang: hanya %s, minimal %s", + "other": "Argumen wajib kurang: hanya %s, minimal %s" + }, + "Too many non-option arguments: got %s, maximum of %s": { + "one": "Terlalu banyak argumen wajib: ada %s, maksimal %s", + "other": "Terlalu banyak argumen wajib: ada %s, maksimal %s" + }, + "Missing argument value: %s": { + "one": "Kurang argumen: %s", + "other": "Kurang argumen: %s" + }, + "Missing required argument: %s": { + "one": "Kurang argumen wajib: %s", + "other": "Kurang argumen wajib: %s" + }, + "Unknown argument: %s": { + "one": "Argumen tak diketahui: %s", + "other": "Argumen tak diketahui: %s" + }, + "Invalid values:": "Nilai-nilai tidak valid:", + "Argument: %s, Given: %s, Choices: %s": "Argumen: %s, Diberikan: %s, Pilihan: %s", + "Argument check failed: %s": "Pemeriksaan argument gagal: %s", + "Implications failed:": "Implikasi gagal:", + "Not enough arguments following: %s": "Kurang argumen untuk: %s", + "Invalid JSON config file: %s": "Berkas konfigurasi JSON tidak valid: %s", + "Path to JSON config file": "Alamat berkas konfigurasi JSON", + "Show help": "Lihat bantuan", + "Show version number": "Lihat nomor versi", + "Did you mean %s?": "Maksud Anda: %s?", + "Arguments %s and %s are mutually exclusive" : "Argumen %s dan %s saling eksklusif", + "Positionals:": "Posisional-posisional:", + "command": "perintah" +} diff --git a/node_modules/yargs/locales/it.json b/node_modules/yargs/locales/it.json new file mode 100644 index 0000000..fde5756 --- /dev/null +++ b/node_modules/yargs/locales/it.json @@ -0,0 +1,46 @@ +{ + "Commands:": "Comandi:", + "Options:": "Opzioni:", + "Examples:": "Esempi:", + "boolean": "booleano", + "count": "contatore", + "string": "stringa", + "number": "numero", + "array": "vettore", + "required": "richiesto", + "default": "predefinito", + "default:": "predefinito:", + "choices:": "scelte:", + "aliases:": "alias:", + "generated-value": "valore generato", + "Not enough non-option arguments: got %s, need at least %s": { + "one": "Numero insufficiente di argomenti non opzione: inseriti %s, richiesti almeno %s", + "other": "Numero insufficiente di argomenti non opzione: inseriti %s, richiesti almeno %s" + }, + "Too many non-option arguments: got %s, maximum of %s": { + "one": "Troppi argomenti non opzione: inseriti %s, massimo possibile %s", + "other": "Troppi argomenti non opzione: inseriti %s, massimo possibile %s" + }, + "Missing argument value: %s": { + "one": "Argomento mancante: %s", + "other": "Argomenti mancanti: %s" + }, + "Missing required argument: %s": { + "one": "Argomento richiesto mancante: %s", + "other": "Argomenti richiesti mancanti: %s" + }, + "Unknown argument: %s": { + "one": "Argomento sconosciuto: %s", + "other": "Argomenti sconosciuti: %s" + }, + "Invalid values:": "Valori non validi:", + "Argument: %s, Given: %s, Choices: %s": "Argomento: %s, Richiesto: %s, Scelte: %s", + "Argument check failed: %s": "Controllo dell'argomento fallito: %s", + "Implications failed:": "Argomenti dipendenti mancanti:", + "Not enough arguments following: %s": "Argomenti insufficienti dopo: %s", + "Invalid JSON config file: %s": "File di configurazione JSON non valido: %s", + "Path to JSON config file": "Percorso del file di configurazione JSON", + "Show help": "Mostra la schermata di aiuto", + "Show version number": "Mostra il numero di versione", + "Did you mean %s?": "Intendi forse %s?" +} diff --git a/node_modules/yargs/locales/ja.json b/node_modules/yargs/locales/ja.json new file mode 100644 index 0000000..3954ae6 --- /dev/null +++ b/node_modules/yargs/locales/ja.json @@ -0,0 +1,51 @@ +{ + "Commands:": "コマンド:", + "Options:": "オプション:", + "Examples:": "例:", + "boolean": "真偽", + "count": "カウント", + "string": "文字列", + "number": "数値", + "array": "配列", + "required": "必須", + "default": "デフォルト", + "default:": "デフォルト:", + "choices:": "選択してください:", + "aliases:": "エイリアス:", + "generated-value": "生成された値", + "Not enough non-option arguments: got %s, need at least %s": { + "one": "オプションではない引数が %s 個では不足しています。少なくとも %s 個の引数が必要です:", + "other": "オプションではない引数が %s 個では不足しています。少なくとも %s 個の引数が必要です:" + }, + "Too many non-option arguments: got %s, maximum of %s": { + "one": "オプションではない引数が %s 個では多すぎます。最大で %s 個までです:", + "other": "オプションではない引数が %s 個では多すぎます。最大で %s 個までです:" + }, + "Missing argument value: %s": { + "one": "引数の値が見つかりません: %s", + "other": "引数の値が見つかりません: %s" + }, + "Missing required argument: %s": { + "one": "必須の引数が見つかりません: %s", + "other": "必須の引数が見つかりません: %s" + }, + "Unknown argument: %s": { + "one": "未知の引数です: %s", + "other": "未知の引数です: %s" + }, + "Invalid values:": "不正な値です:", + "Argument: %s, Given: %s, Choices: %s": "引数は %s です。与えられた値: %s, 選択してください: %s", + "Argument check failed: %s": "引数のチェックに失敗しました: %s", + "Implications failed:": "オプションの組み合わせで不正が生じました:", + "Not enough arguments following: %s": "次の引数が不足しています。: %s", + "Invalid JSON config file: %s": "JSONの設定ファイルが不正です: %s", + "Path to JSON config file": "JSONの設定ファイルまでのpath", + "Show help": "ヘルプを表示", + "Show version number": "バージョンを表示", + "Did you mean %s?": "もしかして %s?", + "Arguments %s and %s are mutually exclusive" : "引数 %s と %s は同時に指定できません", + "Positionals:": "位置:", + "command": "コマンド", + "deprecated": "非推奨", + "deprecated: %s": "非推奨: %s" +} diff --git a/node_modules/yargs/locales/ko.json b/node_modules/yargs/locales/ko.json new file mode 100644 index 0000000..746bc89 --- /dev/null +++ b/node_modules/yargs/locales/ko.json @@ -0,0 +1,49 @@ +{ + "Commands:": "명령:", + "Options:": "옵션:", + "Examples:": "예시:", + "boolean": "불리언", + "count": "개수", + "string": "문자열", + "number": "숫자", + "array": "배열", + "required": "필수", + "default": "기본값", + "default:": "기본값:", + "choices:": "선택지:", + "aliases:": "별칭:", + "generated-value": "생성된 값", + "Not enough non-option arguments: got %s, need at least %s": { + "one": "옵션이 아닌 인수가 충분하지 않습니다: %s개 입력받음, 최소 %s개 입력 필요", + "other": "옵션이 아닌 인수가 충분하지 않습니다: %s개 입력받음, 최소 %s개 입력 필요" + }, + "Too many non-option arguments: got %s, maximum of %s": { + "one": "옵션이 아닌 인수가 너무 많습니다: %s개 입력받음, 최대 %s개 입력 가능", + "other": "옵션이 아닌 인수가 너무 많습니다: %s개 입력받음, 최대 %s개 입력 가능" + }, + "Missing argument value: %s": { + "one": "인수가 주어지지 않았습니다: %s", + "other": "인수가 주어지지 않았습니다: %s" + }, + "Missing required argument: %s": { + "one": "필수 인수가 주어지지 않았습니다: %s", + "other": "필수 인수가 주어지지 않았습니다: %s" + }, + "Unknown argument: %s": { + "one": "알 수 없는 인수입니다: %s", + "other": "알 수 없는 인수입니다: %s" + }, + "Invalid values:": "유효하지 않은 값:", + "Argument: %s, Given: %s, Choices: %s": "인수: %s, 주어진 값: %s, 선택지: %s", + "Argument check failed: %s": "인수 체크에 실패했습니다: %s", + "Implications failed:": "주어진 인수에 필요한 추가 인수가 주어지지 않았습니다:", + "Not enough arguments following: %s": "다음 인수가 주어지지 않았습니다: %s", + "Invalid JSON config file: %s": "유효하지 않은 JSON 설정 파일: %s", + "Path to JSON config file": "JSON 설정 파일 경로", + "Show help": "도움말 표시", + "Show version number": "버전 표시", + "Did you mean %s?": "%s을(를) 찾으시나요?", + "Arguments %s and %s are mutually exclusive" : "인수 %s과(와) %s은(는) 동시에 지정할 수 없습니다", + "Positionals:": "위치:", + "command": "명령" +} diff --git a/node_modules/yargs/locales/nb.json b/node_modules/yargs/locales/nb.json new file mode 100644 index 0000000..6f410ed --- /dev/null +++ b/node_modules/yargs/locales/nb.json @@ -0,0 +1,44 @@ +{ + "Commands:": "Kommandoer:", + "Options:": "Alternativer:", + "Examples:": "Eksempler:", + "boolean": "boolsk", + "count": "antall", + "string": "streng", + "number": "nummer", + "array": "matrise", + "required": "obligatorisk", + "default": "standard", + "default:": "standard:", + "choices:": "valg:", + "generated-value": "generert-verdi", + "Not enough non-option arguments: got %s, need at least %s": { + "one": "Ikke nok ikke-alternativ argumenter: fikk %s, trenger minst %s", + "other": "Ikke nok ikke-alternativ argumenter: fikk %s, trenger minst %s" + }, + "Too many non-option arguments: got %s, maximum of %s": { + "one": "For mange ikke-alternativ argumenter: fikk %s, maksimum %s", + "other": "For mange ikke-alternativ argumenter: fikk %s, maksimum %s" + }, + "Missing argument value: %s": { + "one": "Mangler argument verdi: %s", + "other": "Mangler argument verdier: %s" + }, + "Missing required argument: %s": { + "one": "Mangler obligatorisk argument: %s", + "other": "Mangler obligatoriske argumenter: %s" + }, + "Unknown argument: %s": { + "one": "Ukjent argument: %s", + "other": "Ukjente argumenter: %s" + }, + "Invalid values:": "Ugyldige verdier:", + "Argument: %s, Given: %s, Choices: %s": "Argument: %s, Gitt: %s, Valg: %s", + "Argument check failed: %s": "Argumentsjekk mislyktes: %s", + "Implications failed:": "Konsekvensene mislyktes:", + "Not enough arguments following: %s": "Ikke nok følgende argumenter: %s", + "Invalid JSON config file: %s": "Ugyldig JSON konfigurasjonsfil: %s", + "Path to JSON config file": "Bane til JSON konfigurasjonsfil", + "Show help": "Vis hjelp", + "Show version number": "Vis versjonsnummer" +} diff --git a/node_modules/yargs/locales/nl.json b/node_modules/yargs/locales/nl.json new file mode 100644 index 0000000..9ff95c5 --- /dev/null +++ b/node_modules/yargs/locales/nl.json @@ -0,0 +1,49 @@ +{ + "Commands:": "Commando's:", + "Options:": "Opties:", + "Examples:": "Voorbeelden:", + "boolean": "booleaans", + "count": "aantal", + "string": "string", + "number": "getal", + "array": "lijst", + "required": "verplicht", + "default": "standaard", + "default:": "standaard:", + "choices:": "keuzes:", + "aliases:": "aliassen:", + "generated-value": "gegenereerde waarde", + "Not enough non-option arguments: got %s, need at least %s": { + "one": "Niet genoeg niet-optie-argumenten: %s gekregen, minstens %s nodig", + "other": "Niet genoeg niet-optie-argumenten: %s gekregen, minstens %s nodig" + }, + "Too many non-option arguments: got %s, maximum of %s": { + "one": "Te veel niet-optie-argumenten: %s gekregen, maximum is %s", + "other": "Te veel niet-optie-argumenten: %s gekregen, maximum is %s" + }, + "Missing argument value: %s": { + "one": "Missende argumentwaarde: %s", + "other": "Missende argumentwaarden: %s" + }, + "Missing required argument: %s": { + "one": "Missend verplicht argument: %s", + "other": "Missende verplichte argumenten: %s" + }, + "Unknown argument: %s": { + "one": "Onbekend argument: %s", + "other": "Onbekende argumenten: %s" + }, + "Invalid values:": "Ongeldige waarden:", + "Argument: %s, Given: %s, Choices: %s": "Argument: %s, Gegeven: %s, Keuzes: %s", + "Argument check failed: %s": "Argumentcontrole mislukt: %s", + "Implications failed:": "Ontbrekende afhankelijke argumenten:", + "Not enough arguments following: %s": "Niet genoeg argumenten na: %s", + "Invalid JSON config file: %s": "Ongeldig JSON-config-bestand: %s", + "Path to JSON config file": "Pad naar JSON-config-bestand", + "Show help": "Toon help", + "Show version number": "Toon versienummer", + "Did you mean %s?": "Bedoelde u misschien %s?", + "Arguments %s and %s are mutually exclusive": "Argumenten %s en %s kunnen niet tegelijk gebruikt worden", + "Positionals:": "Positie-afhankelijke argumenten", + "command": "commando" +} diff --git a/node_modules/yargs/locales/nn.json b/node_modules/yargs/locales/nn.json new file mode 100644 index 0000000..24479ac --- /dev/null +++ b/node_modules/yargs/locales/nn.json @@ -0,0 +1,44 @@ +{ + "Commands:": "Kommandoar:", + "Options:": "Alternativ:", + "Examples:": "Døme:", + "boolean": "boolsk", + "count": "mengd", + "string": "streng", + "number": "nummer", + "array": "matrise", + "required": "obligatorisk", + "default": "standard", + "default:": "standard:", + "choices:": "val:", + "generated-value": "generert-verdi", + "Not enough non-option arguments: got %s, need at least %s": { + "one": "Ikkje nok ikkje-alternativ argument: fekk %s, treng minst %s", + "other": "Ikkje nok ikkje-alternativ argument: fekk %s, treng minst %s" + }, + "Too many non-option arguments: got %s, maximum of %s": { + "one": "For mange ikkje-alternativ argument: fekk %s, maksimum %s", + "other": "For mange ikkje-alternativ argument: fekk %s, maksimum %s" + }, + "Missing argument value: %s": { + "one": "Manglar argumentverdi: %s", + "other": "Manglar argumentverdiar: %s" + }, + "Missing required argument: %s": { + "one": "Manglar obligatorisk argument: %s", + "other": "Manglar obligatoriske argument: %s" + }, + "Unknown argument: %s": { + "one": "Ukjent argument: %s", + "other": "Ukjende argument: %s" + }, + "Invalid values:": "Ugyldige verdiar:", + "Argument: %s, Given: %s, Choices: %s": "Argument: %s, Gjeve: %s, Val: %s", + "Argument check failed: %s": "Argumentsjekk mislukkast: %s", + "Implications failed:": "Konsekvensane mislukkast:", + "Not enough arguments following: %s": "Ikkje nok fylgjande argument: %s", + "Invalid JSON config file: %s": "Ugyldig JSON konfigurasjonsfil: %s", + "Path to JSON config file": "Bane til JSON konfigurasjonsfil", + "Show help": "Vis hjelp", + "Show version number": "Vis versjonsnummer" +} diff --git a/node_modules/yargs/locales/pirate.json b/node_modules/yargs/locales/pirate.json new file mode 100644 index 0000000..dcb5cb7 --- /dev/null +++ b/node_modules/yargs/locales/pirate.json @@ -0,0 +1,13 @@ +{ + "Commands:": "Choose yer command:", + "Options:": "Options for me hearties!", + "Examples:": "Ex. marks the spot:", + "required": "requi-yar-ed", + "Missing required argument: %s": { + "one": "Ye be havin' to set the followin' argument land lubber: %s", + "other": "Ye be havin' to set the followin' arguments land lubber: %s" + }, + "Show help": "Parlay this here code of conduct", + "Show version number": "'Tis the version ye be askin' fer", + "Arguments %s and %s are mutually exclusive" : "Yon scurvy dogs %s and %s be as bad as rum and a prudish wench" +} diff --git a/node_modules/yargs/locales/pl.json b/node_modules/yargs/locales/pl.json new file mode 100644 index 0000000..a41d4bd --- /dev/null +++ b/node_modules/yargs/locales/pl.json @@ -0,0 +1,49 @@ +{ + "Commands:": "Polecenia:", + "Options:": "Opcje:", + "Examples:": "Przykłady:", + "boolean": "boolean", + "count": "ilość", + "string": "ciąg znaków", + "number": "liczba", + "array": "tablica", + "required": "wymagany", + "default": "domyślny", + "default:": "domyślny:", + "choices:": "dostępne:", + "aliases:": "aliasy:", + "generated-value": "wygenerowana-wartość", + "Not enough non-option arguments: got %s, need at least %s": { + "one": "Niewystarczająca ilość argumentów: otrzymano %s, wymagane co najmniej %s", + "other": "Niewystarczająca ilość argumentów: otrzymano %s, wymagane co najmniej %s" + }, + "Too many non-option arguments: got %s, maximum of %s": { + "one": "Zbyt duża ilość argumentów: otrzymano %s, wymagane co najwyżej %s", + "other": "Zbyt duża ilość argumentów: otrzymano %s, wymagane co najwyżej %s" + }, + "Missing argument value: %s": { + "one": "Brak wartości dla argumentu: %s", + "other": "Brak wartości dla argumentów: %s" + }, + "Missing required argument: %s": { + "one": "Brak wymaganego argumentu: %s", + "other": "Brak wymaganych argumentów: %s" + }, + "Unknown argument: %s": { + "one": "Nieznany argument: %s", + "other": "Nieznane argumenty: %s" + }, + "Invalid values:": "Nieprawidłowe wartości:", + "Argument: %s, Given: %s, Choices: %s": "Argument: %s, Otrzymano: %s, Dostępne: %s", + "Argument check failed: %s": "Weryfikacja argumentów nie powiodła się: %s", + "Implications failed:": "Założenia nie zostały spełnione:", + "Not enough arguments following: %s": "Niewystarczająca ilość argumentów następujących po: %s", + "Invalid JSON config file: %s": "Nieprawidłowy plik konfiguracyjny JSON: %s", + "Path to JSON config file": "Ścieżka do pliku konfiguracyjnego JSON", + "Show help": "Pokaż pomoc", + "Show version number": "Pokaż numer wersji", + "Did you mean %s?": "Czy chodziło Ci o %s?", + "Arguments %s and %s are mutually exclusive": "Argumenty %s i %s wzajemnie się wykluczają", + "Positionals:": "Pozycyjne:", + "command": "polecenie" +} diff --git a/node_modules/yargs/locales/pt.json b/node_modules/yargs/locales/pt.json new file mode 100644 index 0000000..0c8ac99 --- /dev/null +++ b/node_modules/yargs/locales/pt.json @@ -0,0 +1,45 @@ +{ + "Commands:": "Comandos:", + "Options:": "Opções:", + "Examples:": "Exemplos:", + "boolean": "boolean", + "count": "contagem", + "string": "cadeia de caracteres", + "number": "número", + "array": "arranjo", + "required": "requerido", + "default": "padrão", + "default:": "padrão:", + "choices:": "escolhas:", + "generated-value": "valor-gerado", + "Not enough non-option arguments: got %s, need at least %s": { + "one": "Argumentos insuficientes não opcionais: Argumento %s, necessário pelo menos %s", + "other": "Argumentos insuficientes não opcionais: Argumento %s, necessário pelo menos %s" + }, + "Too many non-option arguments: got %s, maximum of %s": { + "one": "Excesso de argumentos não opcionais: recebido %s, máximo de %s", + "other": "Excesso de argumentos não opcionais: recebido %s, máximo de %s" + }, + "Missing argument value: %s": { + "one": "Falta valor de argumento: %s", + "other": "Falta valores de argumento: %s" + }, + "Missing required argument: %s": { + "one": "Falta argumento obrigatório: %s", + "other": "Faltando argumentos obrigatórios: %s" + }, + "Unknown argument: %s": { + "one": "Argumento desconhecido: %s", + "other": "Argumentos desconhecidos: %s" + }, + "Invalid values:": "Valores inválidos:", + "Argument: %s, Given: %s, Choices: %s": "Argumento: %s, Dado: %s, Escolhas: %s", + "Argument check failed: %s": "Verificação de argumento falhou: %s", + "Implications failed:": "Implicações falharam:", + "Not enough arguments following: %s": "Insuficientes argumentos a seguir: %s", + "Invalid JSON config file: %s": "Arquivo de configuração em JSON esta inválido: %s", + "Path to JSON config file": "Caminho para o arquivo de configuração em JSON", + "Show help": "Mostra ajuda", + "Show version number": "Mostra número de versão", + "Arguments %s and %s are mutually exclusive" : "Argumentos %s e %s são mutualmente exclusivos" +} diff --git a/node_modules/yargs/locales/pt_BR.json b/node_modules/yargs/locales/pt_BR.json new file mode 100644 index 0000000..eae1ec6 --- /dev/null +++ b/node_modules/yargs/locales/pt_BR.json @@ -0,0 +1,48 @@ +{ + "Commands:": "Comandos:", + "Options:": "Opções:", + "Examples:": "Exemplos:", + "boolean": "booleano", + "count": "contagem", + "string": "string", + "number": "número", + "array": "array", + "required": "obrigatório", + "default:": "padrão:", + "choices:": "opções:", + "aliases:": "sinônimos:", + "generated-value": "valor-gerado", + "Not enough non-option arguments: got %s, need at least %s": { + "one": "Argumentos insuficientes: Argumento %s, necessário pelo menos %s", + "other": "Argumentos insuficientes: Argumento %s, necessário pelo menos %s" + }, + "Too many non-option arguments: got %s, maximum of %s": { + "one": "Excesso de argumentos: recebido %s, máximo de %s", + "other": "Excesso de argumentos: recebido %s, máximo de %s" + }, + "Missing argument value: %s": { + "one": "Falta valor de argumento: %s", + "other": "Falta valores de argumento: %s" + }, + "Missing required argument: %s": { + "one": "Falta argumento obrigatório: %s", + "other": "Faltando argumentos obrigatórios: %s" + }, + "Unknown argument: %s": { + "one": "Argumento desconhecido: %s", + "other": "Argumentos desconhecidos: %s" + }, + "Invalid values:": "Valores inválidos:", + "Argument: %s, Given: %s, Choices: %s": "Argumento: %s, Dado: %s, Opções: %s", + "Argument check failed: %s": "Verificação de argumento falhou: %s", + "Implications failed:": "Implicações falharam:", + "Not enough arguments following: %s": "Argumentos insuficientes a seguir: %s", + "Invalid JSON config file: %s": "Arquivo JSON de configuração inválido: %s", + "Path to JSON config file": "Caminho para o arquivo JSON de configuração", + "Show help": "Exibe ajuda", + "Show version number": "Exibe a versão", + "Did you mean %s?": "Você quis dizer %s?", + "Arguments %s and %s are mutually exclusive" : "Argumentos %s e %s são mutualmente exclusivos", + "Positionals:": "Posicionais:", + "command": "comando" +} diff --git a/node_modules/yargs/locales/ru.json b/node_modules/yargs/locales/ru.json new file mode 100644 index 0000000..d5c9e32 --- /dev/null +++ b/node_modules/yargs/locales/ru.json @@ -0,0 +1,51 @@ +{ + "Commands:": "Команды:", + "Options:": "Опции:", + "Examples:": "Примеры:", + "boolean": "булевый тип", + "count": "подсчет", + "string": "строковой тип", + "number": "число", + "array": "массив", + "required": "необходимо", + "default": "по умолчанию", + "default:": "по умолчанию:", + "choices:": "возможности:", + "aliases:": "алиасы:", + "generated-value": "генерированное значение", + "Not enough non-option arguments: got %s, need at least %s": { + "one": "Недостаточно неопционных аргументов: есть %s, нужно как минимум %s", + "other": "Недостаточно неопционных аргументов: есть %s, нужно как минимум %s" + }, + "Too many non-option arguments: got %s, maximum of %s": { + "one": "Слишком много неопционных аргументов: есть %s, максимум допустимо %s", + "other": "Слишком много неопционных аргументов: есть %s, максимум допустимо %s" + }, + "Missing argument value: %s": { + "one": "Не хватает значения аргумента: %s", + "other": "Не хватает значений аргументов: %s" + }, + "Missing required argument: %s": { + "one": "Не хватает необходимого аргумента: %s", + "other": "Не хватает необходимых аргументов: %s" + }, + "Unknown argument: %s": { + "one": "Неизвестный аргумент: %s", + "other": "Неизвестные аргументы: %s" + }, + "Invalid values:": "Недействительные значения:", + "Argument: %s, Given: %s, Choices: %s": "Аргумент: %s, Данное значение: %s, Возможности: %s", + "Argument check failed: %s": "Проверка аргументов не удалась: %s", + "Implications failed:": "Данный аргумент требует следующий дополнительный аргумент:", + "Not enough arguments following: %s": "Недостаточно следующих аргументов: %s", + "Invalid JSON config file: %s": "Недействительный файл конфигурации JSON: %s", + "Path to JSON config file": "Путь к файлу конфигурации JSON", + "Show help": "Показать помощь", + "Show version number": "Показать номер версии", + "Did you mean %s?": "Вы имели в виду %s?", + "Arguments %s and %s are mutually exclusive": "Аргументы %s и %s являются взаимоисключающими", + "Positionals:": "Позиционные аргументы:", + "command": "команда", + "deprecated": "устар.", + "deprecated: %s": "устар.: %s" +} diff --git a/node_modules/yargs/locales/th.json b/node_modules/yargs/locales/th.json new file mode 100644 index 0000000..33b048e --- /dev/null +++ b/node_modules/yargs/locales/th.json @@ -0,0 +1,46 @@ +{ + "Commands:": "คอมมาน", + "Options:": "ออฟชั่น", + "Examples:": "ตัวอย่าง", + "boolean": "บูลีน", + "count": "นับ", + "string": "สตริง", + "number": "ตัวเลข", + "array": "อาเรย์", + "required": "จำเป็น", + "default": "ค่าเริ่มต้", + "default:": "ค่าเริ่มต้น", + "choices:": "ตัวเลือก", + "aliases:": "เอเลียส", + "generated-value": "ค่าที่ถูกสร้างขึ้น", + "Not enough non-option arguments: got %s, need at least %s": { + "one": "ใส่อาร์กิวเมนต์ไม่ครบตามจำนวนที่กำหนด: ใส่ค่ามาจำนวน %s ค่า, แต่ต้องการอย่างน้อย %s ค่า", + "other": "ใส่อาร์กิวเมนต์ไม่ครบตามจำนวนที่กำหนด: ใส่ค่ามาจำนวน %s ค่า, แต่ต้องการอย่างน้อย %s ค่า" + }, + "Too many non-option arguments: got %s, maximum of %s": { + "one": "ใส่อาร์กิวเมนต์เกินจำนวนที่กำหนด: ใส่ค่ามาจำนวน %s ค่า, แต่ต้องการมากที่สุด %s ค่า", + "other": "ใส่อาร์กิวเมนต์เกินจำนวนที่กำหนด: ใส่ค่ามาจำนวน %s ค่า, แต่ต้องการมากที่สุด %s ค่า" + }, + "Missing argument value: %s": { + "one": "ค่าอาร์กิวเมนต์ที่ขาดไป: %s", + "other": "ค่าอาร์กิวเมนต์ที่ขาดไป: %s" + }, + "Missing required argument: %s": { + "one": "อาร์กิวเมนต์จำเป็นที่ขาดไป: %s", + "other": "อาร์กิวเมนต์จำเป็นที่ขาดไป: %s" + }, + "Unknown argument: %s": { + "one": "อาร์กิวเมนต์ที่ไม่รู้จัก: %s", + "other": "อาร์กิวเมนต์ที่ไม่รู้จัก: %s" + }, + "Invalid values:": "ค่าไม่ถูกต้อง:", + "Argument: %s, Given: %s, Choices: %s": "อาร์กิวเมนต์: %s, ได้รับ: %s, ตัวเลือก: %s", + "Argument check failed: %s": "ตรวจสอบพบอาร์กิวเมนต์ที่ไม่ถูกต้อง: %s", + "Implications failed:": "Implications ไม่สำเร็จ:", + "Not enough arguments following: %s": "ใส่อาร์กิวเมนต์ไม่ครบ: %s", + "Invalid JSON config file: %s": "ไฟล์คอนฟิค JSON ไม่ถูกต้อง: %s", + "Path to JSON config file": "พาทไฟล์คอนฟิค JSON", + "Show help": "ขอความช่วยเหลือ", + "Show version number": "แสดงตัวเลขเวอร์ชั่น", + "Did you mean %s?": "คุณหมายถึง %s?" +} diff --git a/node_modules/yargs/locales/tr.json b/node_modules/yargs/locales/tr.json new file mode 100644 index 0000000..0d0d2cc --- /dev/null +++ b/node_modules/yargs/locales/tr.json @@ -0,0 +1,48 @@ +{ + "Commands:": "Komutlar:", + "Options:": "Seçenekler:", + "Examples:": "Örnekler:", + "boolean": "boolean", + "count": "sayı", + "string": "string", + "number": "numara", + "array": "array", + "required": "zorunlu", + "default": "varsayılan", + "default:": "varsayılan:", + "choices:": "seçimler:", + "aliases:": "takma adlar:", + "generated-value": "oluşturulan-değer", + "Not enough non-option arguments: got %s, need at least %s": { + "one": "Seçenek dışı argümanlar yetersiz: %s bulundu, %s gerekli", + "other": "Seçenek dışı argümanlar yetersiz: %s bulundu, %s gerekli" + }, + "Too many non-option arguments: got %s, maximum of %s": { + "one": "Seçenek dışı argümanlar gereğinden fazla: %s bulundu, azami %s", + "other": "Seçenek dışı argümanlar gereğinden fazla: %s bulundu, azami %s" + }, + "Missing argument value: %s": { + "one": "Eksik argüman değeri: %s", + "other": "Eksik argüman değerleri: %s" + }, + "Missing required argument: %s": { + "one": "Eksik zorunlu argüman: %s", + "other": "Eksik zorunlu argümanlar: %s" + }, + "Unknown argument: %s": { + "one": "Bilinmeyen argüman: %s", + "other": "Bilinmeyen argümanlar: %s" + }, + "Invalid values:": "Geçersiz değerler:", + "Argument: %s, Given: %s, Choices: %s": "Argüman: %s, Verilen: %s, Seçimler: %s", + "Argument check failed: %s": "Argüman kontrolü başarısız oldu: %s", + "Implications failed:": "Sonuçlar başarısız oldu:", + "Not enough arguments following: %s": "%s için yeterli argüman bulunamadı", + "Invalid JSON config file: %s": "Geçersiz JSON yapılandırma dosyası: %s", + "Path to JSON config file": "JSON yapılandırma dosya konumu", + "Show help": "Yardım detaylarını göster", + "Show version number": "Versiyon detaylarını göster", + "Did you mean %s?": "Bunu mu demek istediniz: %s?", + "Positionals:": "Sıralılar:", + "command": "komut" +} diff --git a/node_modules/yargs/locales/uk_UA.json b/node_modules/yargs/locales/uk_UA.json new file mode 100644 index 0000000..0af0e99 --- /dev/null +++ b/node_modules/yargs/locales/uk_UA.json @@ -0,0 +1,51 @@ +{ + "Commands:": "Команди:", + "Options:": "Опції:", + "Examples:": "Приклади:", + "boolean": "boolean", + "count": "кількість", + "string": "строка", + "number": "число", + "array": "масива", + "required": "обов'язково", + "default": "за замовчуванням", + "default:": "за замовчуванням:", + "choices:": "доступні варіанти:", + "aliases:": "псевдоніми:", + "generated-value": "згенероване значення", + "Not enough non-option arguments: got %s, need at least %s": { + "one": "Недостатньо аргументів: наразі %s, потрібно %s або більше", + "other": "Недостатньо аргументів: наразі %s, потрібно %s або більше" + }, + "Too many non-option arguments: got %s, maximum of %s": { + "one": "Забагато аргументів: наразі %s, максимум %s", + "other": "Too many non-option arguments: наразі %s, максимум of %s" + }, + "Missing argument value: %s": { + "one": "Відсутнє значення для аргументу: %s", + "other": "Відсутні значення для аргументу: %s" + }, + "Missing required argument: %s": { + "one": "Відсутній обов'язковий аргумент: %s", + "other": "Відсутні обов'язкові аргументи: %s" + }, + "Unknown argument: %s": { + "one": "Аргумент %s не підтримується", + "other": "Аргументи %s не підтримуються" + }, + "Invalid values:": "Некоректні значення:", + "Argument: %s, Given: %s, Choices: %s": "Аргумент: %s, Введено: %s, Доступні варіанти: %s", + "Argument check failed: %s": "Аргумент не пройшов перевірку: %s", + "Implications failed:": "Відсутні залежні аргументи:", + "Not enough arguments following: %s": "Не достатньо аргументів після: %s", + "Invalid JSON config file: %s": "Некоректний JSON-файл конфігурації: %s", + "Path to JSON config file": "Шлях до JSON-файлу конфігурації", + "Show help": "Показати довідку", + "Show version number": "Показати версію", + "Did you mean %s?": "Можливо, ви мали на увазі %s?", + "Arguments %s and %s are mutually exclusive" : "Аргументи %s та %s взаємовиключні", + "Positionals:": "Позиційні:", + "command": "команда", + "deprecated": "застарілий", + "deprecated: %s": "застарілий: %s" +} diff --git a/node_modules/yargs/locales/uz.json b/node_modules/yargs/locales/uz.json new file mode 100644 index 0000000..0d07168 --- /dev/null +++ b/node_modules/yargs/locales/uz.json @@ -0,0 +1,52 @@ +{ + "Commands:": "Buyruqlar:", + "Options:": "Imkoniyatlar:", + "Examples:": "Misollar:", + "boolean": "boolean", + "count": "sanoq", + "string": "satr", + "number": "raqam", + "array": "massiv", + "required": "majburiy", + "default": "boshlang'ich", + "default:": "boshlang'ich:", + "choices:": "tanlovlar:", + "aliases:": "taxalluslar:", + "generated-value": "yaratilgan-qiymat", + "Not enough non-option arguments: got %s, need at least %s": { + "one": "No-imkoniyat argumentlar yetarli emas: berilgan %s, minimum %s", + "other": "No-imkoniyat argumentlar yetarli emas: berilgan %s, minimum %s" + }, + "Too many non-option arguments: got %s, maximum of %s": { + "one": "No-imkoniyat argumentlar juda ko'p: berilgan %s, maksimum %s", + "other": "No-imkoniyat argumentlar juda ko'p: got %s, maksimum %s" + }, + "Missing argument value: %s": { + "one": "Argument qiymati berilmagan: %s", + "other": "Argument qiymatlari berilmagan: %s" + }, + "Missing required argument: %s": { + "one": "Majburiy argument berilmagan: %s", + "other": "Majburiy argumentlar berilmagan: %s" + }, + "Unknown argument: %s": { + "one": "Noma'lum argument berilmagan: %s", + "other": "Noma'lum argumentlar berilmagan: %s" + }, + "Invalid values:": "Nosoz qiymatlar:", + "Argument: %s, Given: %s, Choices: %s": "Argument: %s, Berilgan: %s, Tanlovlar: %s", + "Argument check failed: %s": "Muvaffaqiyatsiz argument tekshiruvi: %s", + "Implications failed:": "Bog'liq argumentlar berilmagan:", + "Not enough arguments following: %s": "Quyidagi argumentlar yetarli emas: %s", + "Invalid JSON config file: %s": "Nosoz JSON konfiguratsiya fayli: %s", + "Path to JSON config file": "JSON konfiguratsiya fayli joylashuvi", + "Show help": "Yordam ko'rsatish", + "Show version number": "Versiyani ko'rsatish", + "Did you mean %s?": "%s ni nazarda tutyapsizmi?", + "Arguments %s and %s are mutually exclusive" : "%s va %s argumentlari alohida", + "Positionals:": "Positsionallar:", + "command": "buyruq", + "deprecated": "eskirgan", + "deprecated: %s": "eskirgan: %s" + } + \ No newline at end of file diff --git a/node_modules/yargs/locales/zh_CN.json b/node_modules/yargs/locales/zh_CN.json new file mode 100644 index 0000000..257d26b --- /dev/null +++ b/node_modules/yargs/locales/zh_CN.json @@ -0,0 +1,48 @@ +{ + "Commands:": "命令:", + "Options:": "选项:", + "Examples:": "示例:", + "boolean": "布尔", + "count": "计数", + "string": "字符串", + "number": "数字", + "array": "数组", + "required": "必需", + "default": "默认值", + "default:": "默认值:", + "choices:": "可选值:", + "generated-value": "生成的值", + "Not enough non-option arguments: got %s, need at least %s": { + "one": "缺少 non-option 参数:传入了 %s 个, 至少需要 %s 个", + "other": "缺少 non-option 参数:传入了 %s 个, 至少需要 %s 个" + }, + "Too many non-option arguments: got %s, maximum of %s": { + "one": "non-option 参数过多:传入了 %s 个, 最大允许 %s 个", + "other": "non-option 参数过多:传入了 %s 个, 最大允许 %s 个" + }, + "Missing argument value: %s": { + "one": "没有给此选项指定值:%s", + "other": "没有给这些选项指定值:%s" + }, + "Missing required argument: %s": { + "one": "缺少必须的选项:%s", + "other": "缺少这些必须的选项:%s" + }, + "Unknown argument: %s": { + "one": "无法识别的选项:%s", + "other": "无法识别这些选项:%s" + }, + "Invalid values:": "无效的选项值:", + "Argument: %s, Given: %s, Choices: %s": "选项名称: %s, 传入的值: %s, 可选的值:%s", + "Argument check failed: %s": "选项值验证失败:%s", + "Implications failed:": "缺少依赖的选项:", + "Not enough arguments following: %s": "没有提供足够的值给此选项:%s", + "Invalid JSON config file: %s": "无效的 JSON 配置文件:%s", + "Path to JSON config file": "JSON 配置文件的路径", + "Show help": "显示帮助信息", + "Show version number": "显示版本号", + "Did you mean %s?": "是指 %s?", + "Arguments %s and %s are mutually exclusive" : "选项 %s 和 %s 是互斥的", + "Positionals:": "位置:", + "command": "命令" +} diff --git a/node_modules/yargs/locales/zh_TW.json b/node_modules/yargs/locales/zh_TW.json new file mode 100644 index 0000000..e38495d --- /dev/null +++ b/node_modules/yargs/locales/zh_TW.json @@ -0,0 +1,51 @@ +{ + "Commands:": "命令:", + "Options:": "選項:", + "Examples:": "範例:", + "boolean": "布林", + "count": "次數", + "string": "字串", + "number": "數字", + "array": "陣列", + "required": "必填", + "default": "預設值", + "default:": "預設值:", + "choices:": "可選值:", + "aliases:": "別名:", + "generated-value": "生成的值", + "Not enough non-option arguments: got %s, need at least %s": { + "one": "non-option 引數不足:只傳入了 %s 個, 至少要 %s 個", + "other": "non-option 引數不足:只傳入了 %s 個, 至少要 %s 個" + }, + "Too many non-option arguments: got %s, maximum of %s": { + "one": "non-option 引數過多:傳入了 %s 個, 但最多 %s 個", + "other": "non-option 引數過多:傳入了 %s 個, 但最多 %s 個" + }, + "Missing argument value: %s": { + "one": "此引數無指定值:%s", + "other": "這些引數無指定值:%s" + }, + "Missing required argument: %s": { + "one": "缺少必須的引數:%s", + "other": "缺少這些必須的引數:%s" + }, + "Unknown argument: %s": { + "one": "未知的引數:%s", + "other": "未知的引數:%s" + }, + "Invalid values:": "無效的選項值:", + "Argument: %s, Given: %s, Choices: %s": "引數名稱: %s, 傳入的值: %s, 可選的值:%s", + "Argument check failed: %s": "引數驗證失敗:%s", + "Implications failed:": "缺少依賴引數:", + "Not enough arguments following: %s": "沒有提供足夠的值給此引數:%s", + "Invalid JSON config file: %s": "無效的 JSON 設置文件:%s", + "Path to JSON config file": "JSON 設置文件的路徑", + "Show help": "顯示說明", + "Show version number": "顯示版本", + "Did you mean %s?": "您是指 %s 嗎?", + "Arguments %s and %s are mutually exclusive" : "引數 %s 和 %s 互斥", + "Positionals:": "位置:", + "command": "命令", + "deprecated": "已淘汰", + "deprecated: %s": "已淘汰:%s" + } diff --git a/node_modules/yargs/package.json b/node_modules/yargs/package.json new file mode 100644 index 0000000..389cc6b --- /dev/null +++ b/node_modules/yargs/package.json @@ -0,0 +1,123 @@ +{ + "name": "yargs", + "version": "17.7.2", + "description": "yargs the modern, pirate-themed, successor to optimist.", + "main": "./index.cjs", + "exports": { + "./package.json": "./package.json", + ".": [ + { + "import": "./index.mjs", + "require": "./index.cjs" + }, + "./index.cjs" + ], + "./helpers": { + "import": "./helpers/helpers.mjs", + "require": "./helpers/index.js" + }, + "./browser": { + "import": "./browser.mjs", + "types": "./browser.d.ts" + }, + "./yargs": [ + { + "import": "./yargs.mjs", + "require": "./yargs" + }, + "./yargs" + ] + }, + "type": "module", + "module": "./index.mjs", + "contributors": [ + { + "name": "Yargs Contributors", + "url": "https://github.com/yargs/yargs/graphs/contributors" + } + ], + "files": [ + "browser.mjs", + "browser.d.ts", + "index.cjs", + "helpers/*.js", + "helpers/*", + "index.mjs", + "yargs", + "yargs.mjs", + "build", + "locales", + "LICENSE", + "lib/platform-shims/*.mjs", + "!*.d.ts", + "!**/*.d.ts" + ], + "dependencies": { + "cliui": "^8.0.1", + "escalade": "^3.1.1", + "get-caller-file": "^2.0.5", + "require-directory": "^2.1.1", + "string-width": "^4.2.3", + "y18n": "^5.0.5", + "yargs-parser": "^21.1.1" + }, + "devDependencies": { + "@types/chai": "^4.2.11", + "@types/mocha": "^9.0.0", + "@types/node": "^18.0.0", + "c8": "^7.7.0", + "chai": "^4.2.0", + "chalk": "^4.0.0", + "coveralls": "^3.0.9", + "cpr": "^3.0.1", + "cross-env": "^7.0.2", + "cross-spawn": "^7.0.0", + "eslint": "^7.23.0", + "gts": "^3.0.0", + "hashish": "0.0.4", + "mocha": "^9.0.0", + "rimraf": "^3.0.2", + "rollup": "^2.23.0", + "rollup-plugin-cleanup": "^3.1.1", + "rollup-plugin-terser": "^7.0.2", + "rollup-plugin-ts": "^2.0.4", + "typescript": "^4.0.2", + "which": "^2.0.0", + "yargs-test-extends": "^1.0.1" + }, + "scripts": { + "fix": "gts fix && npm run fix:js", + "fix:js": "eslint . --ext cjs --ext mjs --ext js --fix", + "posttest": "npm run check", + "test": "c8 mocha --enable-source-maps ./test/*.cjs --require ./test/before.cjs --timeout=12000 --check-leaks", + "test:esm": "c8 mocha --enable-source-maps ./test/esm/*.mjs --check-leaks", + "coverage": "c8 report --check-coverage", + "prepare": "npm run compile", + "pretest": "npm run compile -- -p tsconfig.test.json && cross-env NODE_ENV=test npm run build:cjs", + "compile": "rimraf build && tsc", + "postcompile": "npm run build:cjs", + "build:cjs": "rollup -c rollup.config.cjs", + "postbuild:cjs": "rimraf ./build/index.cjs.d.ts", + "check": "gts lint && npm run check:js", + "check:js": "eslint . --ext cjs --ext mjs --ext js", + "clean": "gts clean" + }, + "repository": { + "type": "git", + "url": "https://github.com/yargs/yargs.git" + }, + "homepage": "https://yargs.js.org/", + "keywords": [ + "argument", + "args", + "option", + "parser", + "parsing", + "cli", + "command" + ], + "license": "MIT", + "engines": { + "node": ">=12" + } +} diff --git a/node_modules/yargs/yargs b/node_modules/yargs/yargs new file mode 100644 index 0000000..8460d10 --- /dev/null +++ b/node_modules/yargs/yargs @@ -0,0 +1,9 @@ +// TODO: consolidate on using a helpers file at some point in the future, which +// is the approach currently used to export Parser and applyExtends for ESM: +const {applyExtends, cjsPlatformShim, Parser, Yargs, processArgv} = require('./build/index.cjs') +Yargs.applyExtends = (config, cwd, mergeExtends) => { + return applyExtends(config, cwd, mergeExtends, cjsPlatformShim) +} +Yargs.hideBin = processArgv.hideBin +Yargs.Parser = Parser +module.exports = Yargs diff --git a/node_modules/yargs/yargs.mjs b/node_modules/yargs/yargs.mjs new file mode 100644 index 0000000..6d9f390 --- /dev/null +++ b/node_modules/yargs/yargs.mjs @@ -0,0 +1,10 @@ +// TODO: consolidate on using a helpers file at some point in the future, which +// is the approach currently used to export Parser and applyExtends for ESM: +import pkg from './build/index.cjs'; +const {applyExtends, cjsPlatformShim, Parser, processArgv, Yargs} = pkg; +Yargs.applyExtends = (config, cwd, mergeExtends) => { + return applyExtends(config, cwd, mergeExtends, cjsPlatformShim); +}; +Yargs.hideBin = processArgv.hideBin; +Yargs.Parser = Parser; +export default Yargs; diff --git a/package-lock.json b/package-lock.json new file mode 100644 index 0000000..110d83e --- /dev/null +++ b/package-lock.json @@ -0,0 +1,316 @@ +{ + "name": "grpc", + "version": "1.0.0", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "name": "grpc", + "version": "1.0.0", + "license": "MIT", + "dependencies": { + "@grpc/grpc-js": "^1.10.8", + "@grpc/proto-loader": "^0.7.13" + } + }, + "node_modules/@grpc/grpc-js": { + "version": "1.10.8", + "resolved": "https://registry.npmjs.org/@grpc/grpc-js/-/grpc-js-1.10.8.tgz", + "integrity": "sha512-vYVqYzHicDqyKB+NQhAc54I1QWCBLCrYG6unqOIcBTHx+7x8C9lcoLj3KVJXs2VB4lUbpWY+Kk9NipcbXYWmvg==", + "dependencies": { + "@grpc/proto-loader": "^0.7.13", + "@js-sdsl/ordered-map": "^4.4.2" + }, + "engines": { + "node": ">=12.10.0" + } + }, + "node_modules/@grpc/proto-loader": { + "version": "0.7.13", + "resolved": "https://registry.npmjs.org/@grpc/proto-loader/-/proto-loader-0.7.13.tgz", + "integrity": "sha512-AiXO/bfe9bmxBjxxtYxFAXGZvMaN5s8kO+jBHAJCON8rJoB5YS/D6X7ZNc6XQkuHNmyl4CYaMI1fJ/Gn27RGGw==", + "dependencies": { + "lodash.camelcase": "^4.3.0", + "long": "^5.0.0", + "protobufjs": "^7.2.5", + "yargs": "^17.7.2" + }, + "bin": { + "proto-loader-gen-types": "build/bin/proto-loader-gen-types.js" + }, + "engines": { + "node": ">=6" + } + }, + "node_modules/@js-sdsl/ordered-map": { + "version": "4.4.2", + "resolved": "https://registry.npmjs.org/@js-sdsl/ordered-map/-/ordered-map-4.4.2.tgz", + "integrity": "sha512-iUKgm52T8HOE/makSxjqoWhe95ZJA1/G1sYsGev2JDKUSS14KAgg1LHb+Ba+IPow0xflbnSkOsZcO08C7w1gYw==", + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/js-sdsl" + } + }, + "node_modules/@protobufjs/aspromise": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/@protobufjs/aspromise/-/aspromise-1.1.2.tgz", + "integrity": "sha512-j+gKExEuLmKwvz3OgROXtrJ2UG2x8Ch2YZUxahh+s1F2HZ+wAceUNLkvy6zKCPVRkU++ZWQrdxsUeQXmcg4uoQ==" + }, + "node_modules/@protobufjs/base64": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/@protobufjs/base64/-/base64-1.1.2.tgz", + "integrity": "sha512-AZkcAA5vnN/v4PDqKyMR5lx7hZttPDgClv83E//FMNhR2TMcLUhfRUBHCmSl0oi9zMgDDqRUJkSxO3wm85+XLg==" + }, + "node_modules/@protobufjs/codegen": { + "version": "2.0.4", + "resolved": "https://registry.npmjs.org/@protobufjs/codegen/-/codegen-2.0.4.tgz", + "integrity": "sha512-YyFaikqM5sH0ziFZCN3xDC7zeGaB/d0IUb9CATugHWbd1FRFwWwt4ld4OYMPWu5a3Xe01mGAULCdqhMlPl29Jg==" + }, + "node_modules/@protobufjs/eventemitter": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@protobufjs/eventemitter/-/eventemitter-1.1.0.tgz", + "integrity": "sha512-j9ednRT81vYJ9OfVuXG6ERSTdEL1xVsNgqpkxMsbIabzSo3goCjDIveeGv5d03om39ML71RdmrGNjG5SReBP/Q==" + }, + "node_modules/@protobufjs/fetch": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@protobufjs/fetch/-/fetch-1.1.0.tgz", + "integrity": "sha512-lljVXpqXebpsijW71PZaCYeIcE5on1w5DlQy5WH6GLbFryLUrBD4932W/E2BSpfRJWseIL4v/KPgBFxDOIdKpQ==", + "dependencies": { + "@protobufjs/aspromise": "^1.1.1", + "@protobufjs/inquire": "^1.1.0" + } + }, + "node_modules/@protobufjs/float": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/@protobufjs/float/-/float-1.0.2.tgz", + "integrity": "sha512-Ddb+kVXlXst9d+R9PfTIxh1EdNkgoRe5tOX6t01f1lYWOvJnSPDBlG241QLzcyPdoNTsblLUdujGSE4RzrTZGQ==" + }, + "node_modules/@protobufjs/inquire": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@protobufjs/inquire/-/inquire-1.1.0.tgz", + "integrity": "sha512-kdSefcPdruJiFMVSbn801t4vFK7KB/5gd2fYvrxhuJYg8ILrmn9SKSX2tZdV6V+ksulWqS7aXjBcRXl3wHoD9Q==" + }, + "node_modules/@protobufjs/path": { + "version": "1.1.2", + "resolved": "https://registry.npmjs.org/@protobufjs/path/-/path-1.1.2.tgz", + "integrity": "sha512-6JOcJ5Tm08dOHAbdR3GrvP+yUUfkjG5ePsHYczMFLq3ZmMkAD98cDgcT2iA1lJ9NVwFd4tH/iSSoe44YWkltEA==" + }, + "node_modules/@protobufjs/pool": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@protobufjs/pool/-/pool-1.1.0.tgz", + "integrity": "sha512-0kELaGSIDBKvcgS4zkjz1PeddatrjYcmMWOlAuAPwAeccUrPHdUqo/J6LiymHHEiJT5NrF1UVwxY14f+fy4WQw==" + }, + "node_modules/@protobufjs/utf8": { + "version": "1.1.0", + "resolved": "https://registry.npmjs.org/@protobufjs/utf8/-/utf8-1.1.0.tgz", + "integrity": "sha512-Vvn3zZrhQZkkBE8LSuW3em98c0FwgO4nxzv6OdSxPKJIEKY2bGbHn+mhGIPerzI4twdxaP8/0+06HBpwf345Lw==" + }, + "node_modules/@types/node": { + "version": "20.14.1", + "resolved": "https://registry.npmjs.org/@types/node/-/node-20.14.1.tgz", + "integrity": "sha512-T2MzSGEu+ysB/FkWfqmhV3PLyQlowdptmmgD20C6QxsS8Fmv5SjpZ1ayXaEC0S21/h5UJ9iA6W/5vSNU5l00OA==", + "dependencies": { + "undici-types": "~5.26.4" + } + }, + "node_modules/ansi-regex": { + "version": "5.0.1", + "resolved": "https://registry.npmjs.org/ansi-regex/-/ansi-regex-5.0.1.tgz", + "integrity": "sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==", + "engines": { + "node": ">=8" + } + }, + "node_modules/ansi-styles": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/ansi-styles/-/ansi-styles-4.3.0.tgz", + "integrity": "sha512-zbB9rCJAT1rbjiVDb2hqKFHNYLxgtk8NURxZ3IZwD3F6NtxbXZQCnnSi1Lkx+IDohdPlFp222wVALIheZJQSEg==", + "dependencies": { + "color-convert": "^2.0.1" + }, + "engines": { + "node": ">=8" + }, + "funding": { + "url": "https://github.com/chalk/ansi-styles?sponsor=1" + } + }, + "node_modules/cliui": { + "version": "8.0.1", + "resolved": "https://registry.npmjs.org/cliui/-/cliui-8.0.1.tgz", + "integrity": "sha512-BSeNnyus75C4//NQ9gQt1/csTXyo/8Sb+afLAkzAptFuMsod9HFokGNudZpi/oQV73hnVK+sR+5PVRMd+Dr7YQ==", + "dependencies": { + "string-width": "^4.2.0", + "strip-ansi": "^6.0.1", + "wrap-ansi": "^7.0.0" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/color-convert": { + "version": "2.0.1", + "resolved": "https://registry.npmjs.org/color-convert/-/color-convert-2.0.1.tgz", + "integrity": "sha512-RRECPsj7iu/xb5oKYcsFHSppFNnsj/52OVTRKb4zP5onXwVF3zVmmToNcOfGC+CRDpfK/U584fMg38ZHCaElKQ==", + "dependencies": { + "color-name": "~1.1.4" + }, + "engines": { + "node": ">=7.0.0" + } + }, + "node_modules/color-name": { + "version": "1.1.4", + "resolved": "https://registry.npmjs.org/color-name/-/color-name-1.1.4.tgz", + "integrity": "sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==" + }, + "node_modules/emoji-regex": { + "version": "8.0.0", + "resolved": "https://registry.npmjs.org/emoji-regex/-/emoji-regex-8.0.0.tgz", + "integrity": "sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==" + }, + "node_modules/escalade": { + "version": "3.1.2", + "resolved": "https://registry.npmjs.org/escalade/-/escalade-3.1.2.tgz", + "integrity": "sha512-ErCHMCae19vR8vQGe50xIsVomy19rg6gFu3+r3jkEO46suLMWBksvVyoGgQV+jOfl84ZSOSlmv6Gxa89PmTGmA==", + "engines": { + "node": ">=6" + } + }, + "node_modules/get-caller-file": { + "version": "2.0.5", + "resolved": "https://registry.npmjs.org/get-caller-file/-/get-caller-file-2.0.5.tgz", + "integrity": "sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg==", + "engines": { + "node": "6.* || 8.* || >= 10.*" + } + }, + "node_modules/is-fullwidth-code-point": { + "version": "3.0.0", + "resolved": "https://registry.npmjs.org/is-fullwidth-code-point/-/is-fullwidth-code-point-3.0.0.tgz", + "integrity": "sha512-zymm5+u+sCsSWyD9qNaejV3DFvhCKclKdizYaJUuHA83RLjb7nSuGnddCHGv0hk+KY7BMAlsWeK4Ueg6EV6XQg==", + "engines": { + "node": ">=8" + } + }, + "node_modules/lodash.camelcase": { + "version": "4.3.0", + "resolved": "https://registry.npmjs.org/lodash.camelcase/-/lodash.camelcase-4.3.0.tgz", + "integrity": "sha512-TwuEnCnxbc3rAvhf/LbG7tJUDzhqXyFnv3dtzLOPgCG/hODL7WFnsbwktkD7yUV0RrreP/l1PALq/YSg6VvjlA==" + }, + "node_modules/long": { + "version": "5.2.3", + "resolved": "https://registry.npmjs.org/long/-/long-5.2.3.tgz", + "integrity": "sha512-lcHwpNoggQTObv5apGNCTdJrO69eHOZMi4BNC+rTLER8iHAqGrUVeLh/irVIM7zTw2bOXA8T6uNPeujwOLg/2Q==" + }, + "node_modules/protobufjs": { + "version": "7.3.0", + "resolved": "https://registry.npmjs.org/protobufjs/-/protobufjs-7.3.0.tgz", + "integrity": "sha512-YWD03n3shzV9ImZRX3ccbjqLxj7NokGN0V/ESiBV5xWqrommYHYiihuIyavq03pWSGqlyvYUFmfoMKd+1rPA/g==", + "hasInstallScript": true, + "dependencies": { + "@protobufjs/aspromise": "^1.1.2", + "@protobufjs/base64": "^1.1.2", + "@protobufjs/codegen": "^2.0.4", + "@protobufjs/eventemitter": "^1.1.0", + "@protobufjs/fetch": "^1.1.0", + "@protobufjs/float": "^1.0.2", + "@protobufjs/inquire": "^1.1.0", + "@protobufjs/path": "^1.1.2", + "@protobufjs/pool": "^1.1.0", + "@protobufjs/utf8": "^1.1.0", + "@types/node": ">=13.7.0", + "long": "^5.0.0" + }, + "engines": { + "node": ">=12.0.0" + } + }, + "node_modules/require-directory": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/require-directory/-/require-directory-2.1.1.tgz", + "integrity": "sha512-fGxEI7+wsG9xrvdjsrlmL22OMTTiHRwAMroiEeMgq8gzoLC/PQr7RsRDSTLUg/bZAZtF+TVIkHc6/4RIKrui+Q==", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/string-width": { + "version": "4.2.3", + "resolved": "https://registry.npmjs.org/string-width/-/string-width-4.2.3.tgz", + "integrity": "sha512-wKyQRQpjJ0sIp62ErSZdGsjMJWsap5oRNihHhu6G7JVO/9jIB6UyevL+tXuOqrng8j/cxKTWyWUwvSTriiZz/g==", + "dependencies": { + "emoji-regex": "^8.0.0", + "is-fullwidth-code-point": "^3.0.0", + "strip-ansi": "^6.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/strip-ansi": { + "version": "6.0.1", + "resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz", + "integrity": "sha512-Y38VPSHcqkFrCpFnQ9vuSXmquuv5oXOKpGeT6aGrr3o3Gc9AlVa6JBfUSOCnbxGGZF+/0ooI7KrPuUSztUdU5A==", + "dependencies": { + "ansi-regex": "^5.0.1" + }, + "engines": { + "node": ">=8" + } + }, + "node_modules/undici-types": { + "version": "5.26.5", + "resolved": "https://registry.npmjs.org/undici-types/-/undici-types-5.26.5.tgz", + "integrity": "sha512-JlCMO+ehdEIKqlFxk6IfVoAUVmgz7cU7zD/h9XZ0qzeosSHmUJVOzSQvvYSYWXkFXC+IfLKSIffhv0sVZup6pA==" + }, + "node_modules/wrap-ansi": { + "version": "7.0.0", + "resolved": "https://registry.npmjs.org/wrap-ansi/-/wrap-ansi-7.0.0.tgz", + "integrity": "sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q==", + "dependencies": { + "ansi-styles": "^4.0.0", + "string-width": "^4.1.0", + "strip-ansi": "^6.0.0" + }, + "engines": { + "node": ">=10" + }, + "funding": { + "url": "https://github.com/chalk/wrap-ansi?sponsor=1" + } + }, + "node_modules/y18n": { + "version": "5.0.8", + "resolved": "https://registry.npmjs.org/y18n/-/y18n-5.0.8.tgz", + "integrity": "sha512-0pfFzegeDWJHJIAmTLRP2DwHjdF5s7jo9tuztdQxAhINCdvS+3nGINqPd00AphqJR/0LhANUS6/+7SCb98YOfA==", + "engines": { + "node": ">=10" + } + }, + "node_modules/yargs": { + "version": "17.7.2", + "resolved": "https://registry.npmjs.org/yargs/-/yargs-17.7.2.tgz", + "integrity": "sha512-7dSzzRQ++CKnNI/krKnYRV7JKKPUXMEh61soaHKg9mrWEhzFWhFnxPxGl+69cD1Ou63C13NUPCnmIcrvqCuM6w==", + "dependencies": { + "cliui": "^8.0.1", + "escalade": "^3.1.1", + "get-caller-file": "^2.0.5", + "require-directory": "^2.1.1", + "string-width": "^4.2.3", + "y18n": "^5.0.5", + "yargs-parser": "^21.1.1" + }, + "engines": { + "node": ">=12" + } + }, + "node_modules/yargs-parser": { + "version": "21.1.1", + "resolved": "https://registry.npmjs.org/yargs-parser/-/yargs-parser-21.1.1.tgz", + "integrity": "sha512-tVpsJW7DdjecAiFpbIB1e3qxIQsE6NoPc5/eTdrbbIC4h0LVsWhnoa3g+m2HclBIujHzsxZ4VJVA+GUuc2/LBw==", + "engines": { + "node": ">=12" + } + } + } +} diff --git a/package.json b/package.json new file mode 100644 index 0000000..628eb29 --- /dev/null +++ b/package.json @@ -0,0 +1,17 @@ +{ + "name": "grpc", + "version": "1.0.0", + "description": "", + "main": "index.js", + "type": "module", + "scripts": { + "test": "echo \"Error: no test specified\" && exit 1" + }, + "keywords": [], + "author": "Luiz Picolo ", + "license": "MIT", + "dependencies": { + "@grpc/grpc-js": "^1.10.8", + "@grpc/proto-loader": "^0.7.13" + } +} diff --git a/server.js b/server.js new file mode 100644 index 0000000..7c79579 --- /dev/null +++ b/server.js @@ -0,0 +1,20 @@ +import { Server, loadPackageDefinition } from "@grpc/grpc-js"; +import { loadSync } from "@grpc/proto-loader"; + +// Ler as definições do protobuffer +const tasksDefs = loadSync("./tasks.proto"); +const tasksProto = loadPackageDefinition(tasksDefs); + +const tasks = [ + { id: 1, title: "Tarefa 01", type: "IFMS" } +] + +// Criando nosso objeto Servidor +const grpcServer = new Server(); +grpcServer.addService(tasksProto.TaskService.service, { + findAll: (call, callBack) => { + callBack(null, { tasks: tasks }) + } +}) + +const serverAddress = '0.0.0.0:5050'; \ No newline at end of file diff --git a/tasks.proto b/tasks.proto new file mode 100644 index 0000000..bcbadbb --- /dev/null +++ b/tasks.proto @@ -0,0 +1,21 @@ +syntax = "proto3"; + +// Serviços (Service) +// Métodos que serão invocados remotamente +service TaskService { + rpc FindAll( Empty ) returns ( TaskList ); +} + +// Mensagem (Message) +// Entidades +message Empty {} + +message Task { + int32 id = 1; + string title = 2; + string type = 3; +} + +message TaskList { + repeated Task tasks = 1; +}